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.

385 lines
13 KiB

7 years ago
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Laravel\Lumen\Routing\Controller as BaseController;
  4. use Illuminate\Http\Request;
  5. use DB, Log, Cache;
  6. use Quartz;
  7. use DateTime, DateTimeZone, DateInterval;
  8. use App\Jobs\TripComplete;
  9. use App\Jobs\NotifyOfNewLocations;
  10. class Api extends BaseController
  11. {
  12. public function account(Request $request) {
  13. $token = $request->input('token');
  14. if(!$token)
  15. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  16. $db = DB::table('databases')->where('write_token','=',$token)->first();
  17. if(!$db)
  18. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  19. return response(json_encode(['name' => $db->name]))->header('Content-Type', 'application/json');
  20. }
  21. public function query(Request $request) {
  22. $token = $request->input('token');
  23. if(!$token)
  24. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  25. $db = DB::table('databases')->where('read_token','=',$token)->first();
  26. if(!$db)
  27. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  28. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  29. if($request->input('tz')) {
  30. $tz = $request->input('tz');
  31. } else {
  32. $tz = 'UTC';
  33. }
  34. if($date=$request->input('date')) {
  35. $start = DateTime::createFromFormat('Y-m-d H:i:s', $date.' 00:00:00', new DateTimeZone($tz));
  36. $end = DateTime::createFromFormat('Y-m-d H:i:s', $date.' 23:59:59', new DateTimeZone($tz));
  37. } elseif(($start=$request->input('start')) && ($end=$request->input('end'))) {
  38. $start = new DateTime($start, new DateTimeZone($tz));
  39. $end = new DateTime($end, new DateTimeZone($tz));
  40. } else {
  41. return response(json_encode(['error' => 'no date provided']))->header('Content-Type', 'application/json');
  42. }
  43. $results = $qz->queryRange($start, $end);
  44. $locations = [];
  45. $properties = [];
  46. $events = [];
  47. if($request->input('format') == 'linestring') {
  48. foreach($results as $id=>$record) {
  49. // When returning a linestring, separate out the "event" records from the "location" records
  50. if($record->data) {
  51. if(property_exists($record->data->properties, 'action')) {
  52. $rec = $record->data;
  53. # add a unixtime property
  54. $rec->properties->unixtime = (int)$record->date->format('U');
  55. $events[] = $rec;
  56. } else {
  57. #$record->date->format('U.u');
  58. // Ignore super inaccurate locations
  59. if(!property_exists($record->data->properties, 'horizontal_accuracy')
  60. || $record->data->properties->horizontal_accuracy <= 5000) {
  61. $locations[] = $record->data;
  62. $props = $record->data->properties;
  63. $date = $record->date;
  64. $date->setTimeZone(new DateTimeZone($tz));
  65. $props->timestamp = $date->format('c');
  66. $props->unixtime = (int)$date->format('U');
  67. $properties[] = $props;
  68. }
  69. }
  70. }
  71. }
  72. $linestring = array(
  73. 'type' => 'LineString',
  74. 'coordinates' => [],
  75. 'properties' => $properties
  76. );
  77. foreach($locations as $loc) {
  78. if(property_exists($loc, 'geometry'))
  79. $linestring['coordinates'][] = $loc->geometry->coordinates;
  80. else
  81. $linestring['coordinates'][] = null;
  82. }
  83. $response = array(
  84. 'linestring' => $linestring,
  85. 'events' => $events
  86. );
  87. } else {
  88. foreach($results as $id=>$record) {
  89. if($record->data) {
  90. $locations[] = $record->data;
  91. }
  92. }
  93. $response = [
  94. 'locations' => $locations
  95. ];
  96. }
  97. return response(json_encode($response))->header('Content-Type', 'application/json');
  98. }
  99. public function last(Request $request) {
  100. $token = $request->input('token');
  101. if(!$token)
  102. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  103. $db = DB::table('databases')->where('read_token','=',$token)->first();
  104. if(!$db)
  105. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  106. if($request->input('tz')) {
  107. $tz = $request->input('tz');
  108. } else {
  109. $tz = 'UTC';
  110. }
  111. if($input=$request->input('before')) {
  112. // If a specific time was requested, look up the data in the filesystem
  113. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  114. if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $input)) {
  115. // If the input date is given in YYYY-mm-dd HH:mm:ss format, interpret it in the timezone given
  116. $date = DateTime::createFromFormat('Y-m-d H:i:s', $input, new DateTimeZone($tz));
  117. } else {
  118. // Otherwise, parse the string and use the timezone in the input
  119. $date = new DateTime($input);
  120. $date->setTimeZone(new DateTimeZone($tz));
  121. }
  122. if(!$date) {
  123. return response(json_encode(['error' => 'invalid date provided']))->header('Content-Type', 'application/json');
  124. }
  125. /* ********************************************** */
  126. // TODO: move this logic into QuartzDB
  127. // Load the shard for the given date
  128. $shard = $qz->shardForDate($date);
  129. // If the shard doesn't exist, check one day before
  130. if(!$shard->exists()) {
  131. $date = $date->sub(new DateInterval('PT86400S'));
  132. $shard = $qz->shardForDate($date);
  133. }
  134. // Now if the shard doesn't exist, return an empty result
  135. if(!$shard->exists()) {
  136. return response(json_encode([
  137. 'data'=>null
  138. ]));
  139. }
  140. // Start iterating through the shard and look for the last line that is before the given date
  141. $shard->init();
  142. $record = false;
  143. foreach($shard as $r) {
  144. if($r->date > $date)
  145. break;
  146. $record = $r;
  147. }
  148. /* ********************************************** */
  149. if(!$record) {
  150. return response(json_encode([
  151. 'data'=>null
  152. ]));
  153. }
  154. $response = [
  155. 'data' => $record->data,
  156. ];
  157. } else {
  158. // If no specific time was requested, use the cached location from the database
  159. $response = [
  160. 'data' => json_decode($db->last_location),
  161. ];
  162. }
  163. if($request->input('geocode') && property_exists($response['data'], 'geometry') && property_exists($response['data']->geometry, 'coordinates')) {
  164. $coords = $response['data']->geometry->coordinates;
  165. $params = [
  166. 'latitude' => $coords[1],
  167. 'longitude' => $coords[0],
  168. 'date' => $response['data']->properties->timestamp
  169. ];
  170. $geocode = self::geocode($params);
  171. if($geocode) {
  172. $response['geocode'] = $geocode;
  173. } else {
  174. $response['geocode'] = null;
  175. }
  176. }
  177. return response(json_encode($response))->header('Content-Type', 'application/json');;
  178. }
  179. public function input(Request $request) {
  180. $token = $request->input('token');
  181. if(!$token)
  182. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  183. $db = DB::table('databases')->where('write_token','=',$token)->first();
  184. if(!$db)
  185. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  186. if(!is_array($request->input('locations')))
  187. return response(json_encode(['error' => 'invalid input', 'error_description' => 'parameter "locations" must be an array of GeoJSON data with a "timestamp" property']))->header('Content-Type', 'application/json');
  188. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'w');
  189. $num = 0;
  190. $trips = 0;
  191. $last_location = false;
  192. foreach($request->input('locations') as $loc) {
  193. if(array_key_exists('properties', $loc)) {
  194. if(array_key_exists('timestamp', $loc['properties'])) {
  195. try {
  196. if(preg_match('/^\d+\.\d+$/', $loc['properties']['timestamp']))
  197. $date = DateTime::createFromFormat('U.u', $loc['properties']['timestamp']);
  198. elseif(preg_match('/^\d+$/', $loc['properties']['timestamp']))
  199. $date = DateTime::createFromFormat('U', $loc['properties']['timestamp']);
  200. else
  201. $date = new DateTime($loc['properties']['timestamp']);
  202. if($date) {
  203. $cacheKey = 'compass::'.$db->name.'::'.$date->format('U');
  204. // Skip adding if the timestamp is already in the cache.
  205. // Helps prevent writing duplicate data when the HTTP request is interrupted.
  206. if(!env('CACHE_DRIVER') || !Cache::has($cacheKey)) {
  207. $num++;
  208. $qz->add($date, $loc);
  209. if(env('CACHE_DRIVER'))
  210. Cache::put($cacheKey, 1, 360); // cache this for 6 hours
  211. $last_location = $loc;
  212. }
  213. if(array_key_exists('type', $loc['properties']) && $loc['properties']['type'] == 'trip') {
  214. try {
  215. $job = (new TripComplete($db->id, $loc))->onQueue('compass');
  216. $this->dispatch($job);
  217. $trips++;
  218. Log::info('Got a trip record');
  219. } catch(Exception $e) {
  220. Log::warning('Received invalid trip');
  221. }
  222. }
  223. } else {
  224. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  225. }
  226. } catch(Exception $e) {
  227. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  228. }
  229. }
  230. }
  231. }
  232. if($request->input('current')) {
  233. $last_location = $request->input('current');
  234. Log::info('Device sent current location');
  235. }
  236. $response = [
  237. 'result' => 'ok',
  238. 'saved' => $num,
  239. 'trips' => $trips
  240. ];
  241. if($last_location) {
  242. /*
  243. // 2017-08-22 Don't geocode cause it takes too long. Maybe make a separate route for this later.
  244. $geocode = self::geocode(['latitude'=>$last_location['geometry']['coordinates'][1], 'longitude'=>$last_location['geometry']['coordinates'][0]]);
  245. $response['geocode'] = [
  246. 'full_name' => $geocode->full_name,
  247. 'locality' => $geocode->locality,
  248. 'country' => $geocode->country
  249. ];
  250. */
  251. $response['geocode'] = null;
  252. // Cache the last location in the database
  253. if(isset($last_location['properties']['timestamp'])) {
  254. if(preg_match('/^\d+\.\d+$/', $last_location['properties']['timestamp']))
  255. $date = DateTime::createFromFormat('U.u', $last_location['properties']['timestamp']);
  256. elseif(preg_match('/^\d+$/', $last_location['properties']['timestamp']))
  257. $date = DateTime::createFromFormat('U', $last_location['properties']['timestamp']);
  258. else
  259. $date = new DateTime($last_location['properties']['timestamp']);
  260. $date->setTimeZone(new DateTimeZone('UTC'));
  261. $date = $date->format('Y-m-d H:i:s');
  262. } else {
  263. $date = null;
  264. }
  265. DB::table('databases')->where('id', $db->id)
  266. ->update([
  267. 'last_location' => json_encode($last_location, JSON_UNESCAPED_SLASHES+JSON_PRETTY_PRINT),
  268. 'last_location_date' => $date,
  269. ]);
  270. // Notify subscribers that new data is available
  271. if($db->ping_urls) {
  272. $job = (new NotifyOfNewLocations($db->id, $last_location))->onQueue('compass');
  273. $this->dispatch($job);
  274. }
  275. }
  276. if($request->input('trip')) {
  277. DB::table('databases')->where('id', $db->id)
  278. ->update([
  279. 'current_trip' => json_encode($request->input('trip'), JSON_UNESCAPED_SLASHES+JSON_PRETTY_PRINT)
  280. ]);
  281. } else {
  282. DB::table('databases')->where('id', $db->id)->update(['current_trip' => null]);
  283. }
  284. return response(json_encode($response))->header('Content-Type', 'application/json');
  285. }
  286. public function trip_complete(Request $request) {
  287. $token = $request->input('token');
  288. if(!$token)
  289. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  290. $db = DB::table('databases')->where('write_token','=',$token)->first();
  291. if(!$db)
  292. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  293. if($request->input('tz')) {
  294. $tz = new DateTimeZone($request->input('tz'));
  295. } else {
  296. $tz = new DateTimeZone('UTC');
  297. }
  298. $start = new DateTime($request->input('start'), $tz);
  299. $end = new DateTime($request->input('end'), $tz);
  300. $loc = [
  301. 'properties' => [
  302. 'mode' => $request->input('mode'),
  303. 'start' => $start->format('c'),
  304. 'end' => $end->format('c'),
  305. ]
  306. ];
  307. try {
  308. $job = (new TripComplete($db->id, $loc))->onQueue('compass');
  309. $this->dispatch($job);
  310. Log::info('Got a manual trip record: '.$start->format('c').' '.$end->format('c'));
  311. } catch(Exception $e) {
  312. Log::warning('Received invalid trip');
  313. }
  314. return response(json_encode(['result' => 'ok']))->header('Content-Type', 'application/json');
  315. }
  316. public static function geocode($params) {
  317. $ch = curl_init(env('ATLAS_BASE').'api/geocode?'.http_build_query($params));
  318. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  319. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  320. $response = curl_exec($ch);
  321. if($response) {
  322. return json_decode($response);
  323. }
  324. }
  325. }