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.

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