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.

305 lines
10 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. //////////////////////////////////
  27. // Web Hooks
  28. // Don't run the web hooks for manually created trips
  29. if(isset($this->_data['properties']['end_location'])) {
  30. $urls = preg_split('/\s+/', $db->ping_urls);
  31. // Build a trip object that looks like the active trip format from Overland
  32. $trip = [
  33. 'trip' => [
  34. 'mode' => $this->_data['properties']['mode'],
  35. 'start_location' => $this->_data['properties']['start_location'],
  36. 'end_location' => $this->_data['properties']['end_location'],
  37. 'distance' => $this->_data['properties']['distance'],
  38. 'start' => $this->_data['properties']['start'],
  39. 'end' => $this->_data['properties']['end']
  40. ]
  41. ];
  42. $trip = json_encode($trip, JSON_UNESCAPED_SLASHES);
  43. foreach($urls as $url) {
  44. if(trim($url)) {
  45. $ch = curl_init($url);
  46. curl_setopt($ch, CURLOPT_POST, true);
  47. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  48. 'Content-Type: application/json',
  49. 'Authorization: Bearer '.$db->read_token,
  50. 'Compass-Url: '.env('BASE_URL').'api/trip?token='.$db->read_token
  51. ]);
  52. curl_setopt($ch, CURLOPT_POSTFIELDS, $trip);
  53. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  54. curl_exec($ch);
  55. Log::info("Notifying ".$url." of a completed trip");
  56. }
  57. }
  58. }
  59. //////////////////////////////////
  60. // Micropub
  61. if(!$db->micropub_endpoint) {
  62. Log::info('No micropub endpoint configured for database ' . $db->name);
  63. return;
  64. }
  65. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  66. // Load the data from the start and end times
  67. $start = new DateTime($this->_data['properties']['start']);
  68. $end = new DateTime($this->_data['properties']['end']);
  69. if($end->format('U') - $start->format('U') < 15) {
  70. Log::info("Skipping trip since it was too short");
  71. return;
  72. }
  73. $results = $qz->queryRange($start, $end);
  74. $features = [];
  75. foreach($results as $id=>$record) {
  76. // Don't include app action tracking data
  77. if(!property_exists($record->data->properties, 'action')) {
  78. // Ignore locations with accuracy worse than 5000m
  79. if(property_exists($record->data->properties, 'horizontal_accuracy') && $record->data->properties->horizontal_accuracy <= 5000) {
  80. $record->data->properties = array_filter((array)$record->data->properties, function($k){
  81. // Remove some of the app-specific tracking keys from each record
  82. return !in_array($k, ['locations_in_payload','desired_accuracy','significant_change','pauses','deferred']);
  83. }, ARRAY_FILTER_USE_KEY);
  84. $features[] = $record->data;
  85. }
  86. }
  87. }
  88. // Build the GeoJSON for this trip
  89. $geojson = [
  90. 'type' => 'FeatureCollection',
  91. 'features' => $features
  92. ];
  93. $file_path = tempnam(sys_get_temp_dir(), 'compass');
  94. file_put_contents($file_path, json_encode($geojson));
  95. // If there are no start/end coordinates in the request, use the first and last coordinates
  96. if(count($features)) {
  97. if(!array_key_exists('start_location', $this->_data['properties'])) {
  98. $this->_data['properties']['start_location'] = json_decode(json_encode($features[0]), true);
  99. }
  100. if(!array_key_exists('end_location', $this->_data['properties'])) {
  101. $this->_data['properties']['end_location'] = json_decode(json_encode($features[count($features)-1]), true);
  102. }
  103. }
  104. $startAdr = false;
  105. if(array_key_exists('start_location', $this->_data['properties'])) {
  106. // Reverse geocode the start and end location to get an h-adr
  107. $startAdr = [
  108. 'type' => 'h-adr',
  109. 'properties' => [
  110. 'latitude' => $this->_data['properties']['start_location']['geometry']['coordinates'][1],
  111. 'longitude' => $this->_data['properties']['start_location']['geometry']['coordinates'][0],
  112. ]
  113. ];
  114. Log::info('Looking up start location');
  115. $start = self::geocode($startAdr['properties']['latitude'], $startAdr['properties']['longitude']);
  116. if($start && property_exists($start, 'locality')) {
  117. $startAdr['properties']['locality'] = $start->locality;
  118. $startAdr['properties']['region'] = $start->region;
  119. $startAdr['properties']['country'] = $start->country;
  120. Log::info('Found start: '.$start->full_name.' '.$start->timezone);
  121. }
  122. } else {
  123. $start = false;
  124. }
  125. $endAdr = false;
  126. if(array_key_exists('end_location', $this->_data['properties'])) {
  127. $endAdr = [
  128. 'type' => 'h-adr',
  129. 'properties' => [
  130. 'latitude' => $this->_data['properties']['end_location']['geometry']['coordinates'][1],
  131. 'longitude' => $this->_data['properties']['end_location']['geometry']['coordinates'][0],
  132. ]
  133. ];
  134. Log::info('Looking up end location');
  135. $end = self::geocode($endAdr['properties']['latitude'], $endAdr['properties']['longitude']);
  136. if($end && property_exists($end, 'locality')) {
  137. $endAdr['properties']['locality'] = $end->locality;
  138. $endAdr['properties']['region'] = $end->region;
  139. $endAdr['properties']['country'] = $end->country;
  140. Log::info('Found end: '.$end->full_name.' '.$end->timezone);
  141. }
  142. } else {
  143. $end = false;
  144. }
  145. // Set the timezone of the dates based on the location
  146. $startDate = new DateTime($this->_data['properties']['start']);
  147. if($start && $start->timezone) {
  148. $startDate->setTimeZone(new DateTimeZone($start->timezone));
  149. }
  150. $endDate = new DateTime($this->_data['properties']['end']);
  151. if($end && $end->timezone) {
  152. $endDate->setTimeZone(new DateTimeZone($end->timezone));
  153. }
  154. $params = [
  155. 'h' => 'entry',
  156. 'published' => $endDate->format('c'),
  157. 'trip' => [
  158. 'type' => 'h-trip',
  159. 'properties' => [
  160. 'mode-of-transport' => $this->_data['properties']['mode'],
  161. 'start' => $startDate->format('c'),
  162. 'end' => $endDate->format('c'),
  163. 'route' => 'route.json'
  164. ]
  165. ]
  166. ];
  167. if($startAdr) {
  168. $params['trip']['properties']['start-location'] = $startAdr;
  169. }
  170. if($endAdr) {
  171. $params['trip']['properties']['end-location'] = $endAdr;
  172. }
  173. if(array_key_exists('distance', $this->_data['properties'])) {
  174. $params['trip']['properties']['distance'] = [
  175. 'type' => 'h-measure',
  176. 'properties' => [
  177. 'num' => round($this->_data['properties']['distance']),
  178. 'unit' => 'meter'
  179. ]
  180. ];
  181. }
  182. if(array_key_exists('duration', $this->_data['properties'])) {
  183. $params['trip']['properties']['duration'] = [
  184. 'type' => 'h-measure',
  185. 'properties' => [
  186. 'num' => round($this->_data['properties']['duration']),
  187. 'unit' => 'second'
  188. ]
  189. ];
  190. }
  191. if(array_key_exists('cost', $this->_data['properties'])) {
  192. $params['trip']['properties']['cost'] = [
  193. 'type' => 'h-measure',
  194. 'properties' => [
  195. 'num' => round($this->_data['properties']['cost'], 2),
  196. 'unit' => 'USD'
  197. ]
  198. ];
  199. }
  200. // If there is trip data, recalculate the distance and duration based on the actual data
  201. if(count($features)) {
  202. $startTime = strtotime($features[0]->properties['timestamp']);
  203. $endTime = strtotime($features[count($features)-1]->properties['timestamp']);
  204. $duration = $endTime - $startTime;
  205. $params['trip']['properties']['duration']['type'] = 'h-measure';
  206. $params['trip']['properties']['duration']['properties']['num'] = $duration;
  207. $params['trip']['properties']['duration']['properties']['unit'] = 'second';
  208. Log::debug("Overriding duration to $duration");
  209. $points = array_map(function($f){
  210. return $f->geometry->coordinates;
  211. }, $features);
  212. $simple = \p3k\geo\ramerDouglasPeucker($points, 0.0001);
  213. $last = false;
  214. $distance = 0;
  215. foreach($simple as $p) {
  216. if($last) {
  217. $distance += \p3k\geo\gc_distance($p[1], $p[0], $last[1], $last[0]);
  218. }
  219. $last = $p;
  220. }
  221. if($distance) {
  222. $params['trip']['properties']['distance']['type'] = 'h-measure';
  223. $params['trip']['properties']['distance']['properties']['num'] = $distance;
  224. $params['trip']['properties']['distance']['properties']['unit'] = 'meter';
  225. Log::debug("Overriding distance to $distance");
  226. }
  227. }
  228. // TODO: avgpace for runs
  229. // TODO: avgspeed for bike rides
  230. // TODO: avg heart rate if available
  231. // echo "Micropub Params\n";
  232. // print_r($params);
  233. $multipart = new Multipart();
  234. $multipart->addArray($params);
  235. $multipart->addFile('route.json', $file_path, 'application/json');
  236. $httpheaders = [
  237. 'Authorization: Bearer ' . $db->micropub_token,
  238. 'Content-type: ' . $multipart->contentType()
  239. ];
  240. Log::info('Sending to the Micropub endpoint: '.$db->micropub_endpoint);
  241. // Post to the Micropub endpoint
  242. $ch = curl_init($db->micropub_endpoint);
  243. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  244. curl_setopt($ch, CURLOPT_POST, true);
  245. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
  246. curl_setopt($ch, CURLOPT_POSTFIELDS, $multipart->data());
  247. curl_setopt($ch, CURLOPT_HEADER, true);
  248. $response = curl_exec($ch);
  249. Log::info("Done!");
  250. if(preg_match('/Location: (.+)/', $response, $match)) {
  251. Log::info($match[1]);
  252. }
  253. // echo "========\n";
  254. // echo $response."\n========\n";
  255. //
  256. // echo "\n";
  257. }
  258. public static function geocode($lat, $lng) {
  259. $ch = curl_init(env('ATLAS_BASE').'api/geocode?latitude='.$lat.'&longitude='.$lng);
  260. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  261. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  262. $response = curl_exec($ch);
  263. if($response) {
  264. return json_decode($response);
  265. }
  266. }
  267. }