You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

349 lines
12 KiB

  1. <?php
  2. namespace App\Jobs;
  3. use DB;
  4. use Log;
  5. use Quartz;
  6. use p3k\Multipart;
  7. use App\Jobs\Job;
  8. use Illuminate\Contracts\Bus\SelfHandling;
  9. use Illuminate\Contracts\Queue\ShouldQueue;
  10. use DateTime, DateTimeZone;
  11. class TripComplete extends Job implements SelfHandling, ShouldQueue
  12. {
  13. private $_dbid;
  14. private $_data;
  15. public function __construct($dbid, $data) {
  16. $this->_dbid = $dbid;
  17. $this->_data = $data;
  18. }
  19. public function handle() {
  20. // echo "Job Data\n";
  21. // echo json_encode($this->_data)."\n";
  22. if(!is_array($this->_data)) return;
  23. $db = DB::table('databases')->where('id','=',$this->_dbid)->first();
  24. Log::info("Starting job for ".$db->name);
  25. Log::debug(json_encode($this->_data));
  26. if(!$db->micropub_endpoint) {
  27. Log::info('No micropub endpoint configured for database ' . $db->name);
  28. return;
  29. }
  30. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  31. // Load the data from the start and end times
  32. $start = new DateTime($this->_data['properties']['start']);
  33. $end = new DateTime($this->_data['properties']['end']);
  34. $results = $qz->queryRange($start, $end);
  35. $features = [];
  36. foreach($results as $id=>$record) {
  37. // Don't include app action tracking data
  38. if(!property_exists($record->data->properties, 'action')) {
  39. $record->data->properties = array_filter((array)$record->data->properties, function($k){
  40. // Remove some of the app-specific tracking keys from each record
  41. return !in_array($k, ['locations_in_payload','desired_accuracy','significant_change','pauses','deferred']);
  42. }, ARRAY_FILTER_USE_KEY);
  43. $features[] = $record->data;
  44. }
  45. }
  46. // Build the GeoJSON for this trip
  47. $geojson = [
  48. 'type' => 'FeatureCollection',
  49. 'features' => $features
  50. ];
  51. $file_path = tempnam(sys_get_temp_dir(), 'compass');
  52. file_put_contents($file_path, json_encode($geojson));
  53. // If there are no start/end coordinates in the request, use the first and last coordinates
  54. if(count($features)) {
  55. if(!array_key_exists('start-coordinates', $this->_data['properties'])) {
  56. $this->_data['properties']['start-coordinates'] = $features[0]->geometry->coordinates;
  57. }
  58. if(!array_key_exists('end-coordinates', $this->_data['properties'])) {
  59. $this->_data['properties']['end-coordinates'] = $features[count($features)-1]->geometry->coordinates;
  60. }
  61. }
  62. $startAdr = false;
  63. if(array_key_exists('start-coordinates', $this->_data['properties'])) {
  64. // Reverse geocode the start and end location to get an h-adr
  65. $startAdr = [
  66. 'type' => 'h-adr',
  67. 'properties' => [
  68. 'latitude' => $this->_data['properties']['start-coordinates'][1],
  69. 'longitude' => $this->_data['properties']['start-coordinates'][0],
  70. ]
  71. ];
  72. Log::info('Looking up start location');
  73. $start = self::geocode($this->_data['properties']['start-coordinates'][1], $this->_data['properties']['start-coordinates'][0]);
  74. if($start) {
  75. $startAdr['properties']['locality'] = $start->locality;
  76. $startAdr['properties']['region'] = $start->region;
  77. $startAdr['properties']['country'] = $start->country;
  78. Log::info('Found start: '.$start->full_name.' '.$start->timezone);
  79. }
  80. } else {
  81. $start = false;
  82. }
  83. $endAdr = false;
  84. if(array_key_exists('end-coordinates', $this->_data['properties'])) {
  85. $endAdr = [
  86. 'type' => 'h-adr',
  87. 'properties' => [
  88. 'latitude' => $this->_data['properties']['end-coordinates'][1],
  89. 'longitude' => $this->_data['properties']['end-coordinates'][0],
  90. ]
  91. ];
  92. Log::info('Looking up end location');
  93. $end = self::geocode($this->_data['properties']['end-coordinates'][1], $this->_data['properties']['end-coordinates'][0]);
  94. if($end) {
  95. $endAdr['properties']['locality'] = $end->locality;
  96. $endAdr['properties']['region'] = $end->region;
  97. $endAdr['properties']['country'] = $end->country;
  98. Log::info('Found end: '.$end->full_name.' '.$end->timezone);
  99. }
  100. } else {
  101. $end = false;
  102. }
  103. // Set the timezone of the dates based on the location
  104. $startDate = new DateTime($this->_data['properties']['start']);
  105. if($start && $start->timezone) {
  106. $startDate->setTimeZone(new DateTimeZone($start->timezone));
  107. }
  108. $endDate = new DateTime($this->_data['properties']['end']);
  109. if($end && $end->timezone) {
  110. $endDate->setTimeZone(new DateTimeZone($end->timezone));
  111. }
  112. $params = [
  113. 'h' => 'entry',
  114. 'created' => $endDate->format('c'),
  115. 'trip' => [
  116. 'type' => 'h-trip',
  117. 'properties' => [
  118. 'mode-of-transport' => $this->_data['properties']['mode'],
  119. 'start' => $startDate->format('c'),
  120. 'end' => $endDate->format('c'),
  121. 'route' => 'route.json'
  122. // TODO: avgpace for runs
  123. // TODO: avgspeed for bike rides
  124. // TODO: avg heart rate if available
  125. ]
  126. ]
  127. ];
  128. if($startAdr) {
  129. $params['trip']['properties']['start-location'] = $startAdr;
  130. }
  131. if($endAdr) {
  132. $params['trip']['properties']['end-location'] = $endAdr;
  133. }
  134. if(array_key_exists('distance', $this->_data['properties'])) {
  135. $params['trip']['properties']['distance'] = [
  136. 'type' => 'h-measure',
  137. 'properties' => [
  138. 'num' => round($this->_data['properties']['distance']),
  139. 'unit' => 'meter'
  140. ]
  141. ];
  142. }
  143. if(array_key_exists('duration', $this->_data['properties'])) {
  144. $params['trip']['properties']['duration'] = [
  145. 'type' => 'h-measure',
  146. 'properties' => [
  147. 'num' => round($this->_data['properties']['duration']),
  148. 'unit' => 'second'
  149. ]
  150. ];
  151. }
  152. if(array_key_exists('cost', $this->_data['properties'])) {
  153. $params['trip']['properties']['cost'] = [
  154. 'type' => 'h-measure',
  155. 'properties' => [
  156. 'num' => round($this->_data['properties']['cost'], 2),
  157. 'unit' => 'USD'
  158. ]
  159. ];
  160. }
  161. // If there is trip data, recalculate the distance and duration based on the actual data
  162. if(count($features)) {
  163. $startTime = strtotime($features[0]->properties['timestamp']);
  164. $endTime = strtotime($features[count($features)-1]->properties['timestamp']);
  165. $duration = $endTime - $startTime;
  166. $params['trip']['properties']['duration']['type'] = 'h-measure';
  167. $params['trip']['properties']['duration']['properties']['num'] = $duration;
  168. $params['trip']['properties']['duration']['properties']['unit'] = 'second';
  169. Log::debug("Overriding duration to $duration");
  170. $points = array_map(function($f){
  171. return $f->geometry->coordinates;
  172. }, $features);
  173. $simple = $this->_ramerDouglasPeucker($points, 0.0001);
  174. $last = false;
  175. $distance = 0;
  176. foreach($simple as $p) {
  177. if($last) {
  178. $distance += $this->_gc_distance($p[1], $p[0], $last[1], $last[0]);
  179. }
  180. $last = $p;
  181. }
  182. if($distance) {
  183. $params['trip']['properties']['distance']['type'] = 'h-measure';
  184. $params['trip']['properties']['distance']['properties']['num'] = $distance;
  185. $params['trip']['properties']['distance']['properties']['unit'] = 'meter';
  186. Log::debug("Overriding distance to $distance");
  187. }
  188. }
  189. // echo "Micropub Params\n";
  190. // print_r($params);
  191. $multipart = new Multipart();
  192. $multipart->addArray($params);
  193. $multipart->addFile('route.json', $file_path, 'application/json');
  194. $httpheaders = [
  195. 'Authorization: Bearer ' . $db->micropub_token,
  196. 'Content-type: ' . $multipart->contentType()
  197. ];
  198. Log::info('Sending to the Micropub endpoint: '.$db->micropub_endpoint);
  199. // Post to the Micropub endpoint
  200. $ch = curl_init($db->micropub_endpoint);
  201. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  202. curl_setopt($ch, CURLOPT_POST, true);
  203. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  204. curl_setopt($ch, CURLOPT_POSTFIELDS, $multipart->data());
  205. curl_setopt($ch, CURLOPT_HEADER, true);
  206. $response = curl_exec($ch);
  207. Log::info("Done!");
  208. Log::info($response);
  209. // echo "========\n";
  210. // echo $response."\n========\n";
  211. //
  212. // echo "\n";
  213. }
  214. public static function geocode($lat, $lng) {
  215. $ch = curl_init(env('ATLAS_BASE').'api/geocode?latitude='.$lat.'&longitude='.$lng);
  216. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  217. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  218. $response = curl_exec($ch);
  219. if($response) {
  220. return json_decode($response);
  221. }
  222. }
  223. // TODO: move this to a library p3k/Geo
  224. // http://www.loughrigg.org/rdp/
  225. //The author has placed this work in the Public Domain, thereby relinquishing all copyrights.
  226. //You may use, modify, republish, sell or give away this work without prior consent.
  227. //This implementation comes with no warranty or guarantee of fitness for any purpose.
  228. //=========================================================================
  229. //An implementation of the Ramer-Douglas-Peucker algorithm for reducing
  230. //the number of points on a polyline
  231. //see http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
  232. //=========================================================================
  233. //Finds the perpendicular distance from a point to a straight line.
  234. //The coordinates of the point are specified as $ptX and $ptY.
  235. //The line passes through points l1 and l2, specified respectively with their
  236. //coordinates $l1x and $l1y, and $l2x and $l2y
  237. public function _perpendicularDistance($ptX, $ptY, $l1x, $l1y, $l2x, $l2y)
  238. {
  239. $result = 0;
  240. if ($l2x == $l1x)
  241. {
  242. //vertical lines - treat this case specially to avoid divide by zero
  243. $result = abs($ptX - $l2x);
  244. }
  245. else
  246. {
  247. $slope = (($l2y-$l1y) / ($l2x-$l1x));
  248. $passThroughY = (0-$l1x)*$slope + $l1y;
  249. $result = (abs(($slope * $ptX) - $ptY + $passThroughY)) / (sqrt($slope*$slope + 1));
  250. }
  251. return $result;
  252. }
  253. //RamerDouglasPeucker
  254. //Reduces the number of points on a polyline by removing those that are closer to the line
  255. //than the distance $epsilon.
  256. //The polyline is provided as an array of arrays, where each internal array is one point on the polyline,
  257. //specified by easting (x-coordinate) with key "0" and northing (y-coordinate) with key "1".
  258. //It is assumed that the coordinates and distance $epsilon are given in the same units.
  259. //The result is returned as an array in a similar format.
  260. //Each point returned in the result array will retain all its original data, including its E and N
  261. //values along with any others.
  262. public function _ramerDouglasPeucker($pointList, $epsilon)
  263. {
  264. if(count($pointList) == 0)
  265. return array();
  266. // Find the point with the maximum distance
  267. $dmax = 0;
  268. $index = 0;
  269. $totalPoints = count($pointList);
  270. for ($i = 1; $i < ($totalPoints - 1); $i++)
  271. {
  272. $d = $this->_perpendicularDistance($pointList[$i][0], $pointList[$i][1],
  273. $pointList[0][0], $pointList[0][1],
  274. $pointList[$totalPoints-1][0], $pointList[$totalPoints-1][1]);
  275. if ($d > $dmax)
  276. {
  277. $index = $i;
  278. $dmax = $d;
  279. }
  280. }
  281. $resultList = array();
  282. // If max distance is greater than epsilon, recursively simplify
  283. if ($dmax >= $epsilon)
  284. {
  285. // Recursive call
  286. $recResults1 = $this->_ramerDouglasPeucker(array_slice($pointList, 0, $index + 1), $epsilon);
  287. $recResults2 = $this->_ramerDouglasPeucker(array_slice($pointList, $index, $totalPoints - $index), $epsilon);
  288. // Build the result list
  289. $resultList = array_merge(array_slice($recResults1, 0, count($recResults1) - 1),
  290. array_slice($recResults2, 0, count($recResults2)));
  291. }
  292. else
  293. {
  294. $resultList = array($pointList[0], $pointList[$totalPoints-1]);
  295. }
  296. // Return the result
  297. return $resultList;
  298. }
  299. function _gc_distance($lat1, $lng1, $lat2, $lng2) {
  300. return ( 6378100 * acos( cos( deg2rad($lat1) ) * cos( deg2rad($lat2) ) * cos( deg2rad($lng2) - deg2rad($lng1) ) + sin( deg2rad($lat1) ) * sin( deg2rad($lat2) ) ) );
  301. }
  302. }