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.

346 lines
12 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. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  107. if($request->input('tz')) {
  108. $tz = $request->input('tz');
  109. } else {
  110. $tz = 'UTC';
  111. }
  112. if($input=$request->input('before')) {
  113. if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $input)) {
  114. // If the input date is given in YYYY-mm-dd HH:mm:ss format, interpret it in the timezone given
  115. $date = DateTime::createFromFormat('Y-m-d H:i:s', $input, new DateTimeZone($tz));
  116. } else {
  117. // Otherwise, parse the string and use the timezone in the input
  118. $date = new DateTime($input);
  119. $date->setTimeZone(new DateTimeZone($tz));
  120. }
  121. if(!$date) {
  122. return response(json_encode(['error' => 'invalid date provided']))->header('Content-Type', 'application/json');
  123. }
  124. } else {
  125. $date = new DateTime();
  126. }
  127. /* ********************************************** */
  128. // TODO: move this logic into QuartzDB
  129. // Load the shard for the given date
  130. $shard = $qz->shardForDate($date);
  131. // If the shard doesn't exist, check one day before
  132. if(!$shard->exists()) {
  133. $date = $date->sub(new DateInterval('PT86400S'));
  134. $shard = $qz->shardForDate($date);
  135. }
  136. // Now if the shard doesn't exist, return an empty result
  137. if(!$shard->exists()) {
  138. return response(json_encode([
  139. 'data'=>null
  140. ]));
  141. }
  142. // Start iterating through the shard and look for the last line that is before the given date
  143. $shard->init();
  144. $record = false;
  145. foreach($shard as $r) {
  146. if($r->date > $date)
  147. break;
  148. $record = $r;
  149. }
  150. /* ********************************************** */
  151. if(!$record) {
  152. return response(json_encode([
  153. 'data'=>null
  154. ]));
  155. }
  156. $response = [
  157. 'data' => $record->data
  158. ];
  159. if($request->input('geocode') && property_exists($record->data, 'geometry') && property_exists($record->data->geometry, 'coordinates')) {
  160. $coords = $record->data->geometry->coordinates;
  161. $params = [
  162. 'latitude' => $coords[1],
  163. 'longitude' => $coords[0],
  164. 'date' => $record->data->properties->timestamp
  165. ];
  166. $geocode = self::geocode($params);
  167. if($geocode) {
  168. $response['geocode'] = $geocode;
  169. } else {
  170. $response['geocode'] = null;
  171. }
  172. }
  173. return response(json_encode($response))->header('Content-Type', 'application/json');;
  174. }
  175. public function input(Request $request) {
  176. $token = $request->input('token');
  177. if(!$token)
  178. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  179. $db = DB::table('databases')->where('write_token','=',$token)->first();
  180. if(!$db)
  181. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  182. if(!is_array($request->input('locations')))
  183. 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');
  184. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'w');
  185. $num = 0;
  186. $trips = 0;
  187. $last_location = false;
  188. foreach($request->input('locations') as $loc) {
  189. if(array_key_exists('properties', $loc)) {
  190. if(array_key_exists('timestamp', $loc['properties'])) {
  191. try {
  192. if(preg_match('/^\d+\.\d+$/', $loc['properties']['timestamp']))
  193. $date = DateTime::createFromFormat('U.u', $loc['properties']['timestamp']);
  194. elseif(preg_match('/^\d+$/', $loc['properties']['timestamp']))
  195. $date = DateTime::createFromFormat('U', $loc['properties']['timestamp']);
  196. else
  197. $date = new DateTime($loc['properties']['timestamp']);
  198. if($date) {
  199. $cacheKey = 'compass::'.$db->name.'::'.$date->format('U');
  200. // Skip adding if the timestamp is already in the cache.
  201. // Helps prevent writing duplicate data when the HTTP request is interrupted.
  202. if(!env('CACHE_DRIVER') || !Cache::has($cacheKey)) {
  203. $num++;
  204. $qz->add($date, $loc);
  205. if(env('CACHE_DRIVER'))
  206. Cache::put($cacheKey, 1, 360); // cache this for 6 hours
  207. $last_location = $loc;
  208. }
  209. if(array_key_exists('type', $loc['properties']) && $loc['properties']['type'] == 'trip') {
  210. try {
  211. $job = (new TripComplete($db->id, $loc))->onQueue('compass');
  212. $this->dispatch($job);
  213. $trips++;
  214. Log::info('Got a trip record');
  215. } catch(Exception $e) {
  216. Log::warning('Received invalid trip');
  217. }
  218. }
  219. } else {
  220. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  221. }
  222. } catch(Exception $e) {
  223. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  224. }
  225. }
  226. }
  227. }
  228. $response = [
  229. 'result' => 'ok',
  230. 'saved' => $num,
  231. 'trips' => $trips
  232. ];
  233. if($last_location) {
  234. /*
  235. // 2017-08-22 Don't geocode cause it takes too long. Maybe make a separate route for this later.
  236. $geocode = self::geocode(['latitude'=>$last_location['geometry']['coordinates'][1], 'longitude'=>$last_location['geometry']['coordinates'][0]]);
  237. $response['geocode'] = [
  238. 'full_name' => $geocode->full_name,
  239. 'locality' => $geocode->locality,
  240. 'country' => $geocode->country
  241. ];
  242. */
  243. $response['geocode'] = null;
  244. // Notify subscribers that new data is available
  245. if($db->ping_urls) {
  246. $job = (new NotifyOfNewLocations($db->id))->onQueue('compass');
  247. $this->dispatch($job);
  248. }
  249. }
  250. return response(json_encode($response))->header('Content-Type', 'application/json');
  251. }
  252. public function trip_complete(Request $request) {
  253. $token = $request->input('token');
  254. if(!$token)
  255. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  256. $db = DB::table('databases')->where('write_token','=',$token)->first();
  257. if(!$db)
  258. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  259. if($request->input('tz')) {
  260. $tz = new DateTimeZone($request->input('tz'));
  261. } else {
  262. $tz = new DateTimeZone('UTC');
  263. }
  264. $start = new DateTime($request->input('start'), $tz);
  265. $end = new DateTime($request->input('end'), $tz);
  266. $loc = [
  267. 'properties' => [
  268. 'mode' => $request->input('mode'),
  269. 'start' => $start->format('c'),
  270. 'end' => $end->format('c'),
  271. ]
  272. ];
  273. try {
  274. $job = (new TripComplete($db->id, $loc))->onQueue('compass');
  275. $this->dispatch($job);
  276. Log::info('Got a manual trip record: '.$start->format('c').' '.$end->format('c'));
  277. } catch(Exception $e) {
  278. Log::warning('Received invalid trip');
  279. }
  280. return response(json_encode(['result' => 'ok']))->header('Content-Type', 'application/json');
  281. }
  282. public static function geocode($params) {
  283. $ch = curl_init(env('ATLAS_BASE').'api/geocode?'.http_build_query($params));
  284. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  285. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  286. $response = curl_exec($ch);
  287. if($response) {
  288. return json_decode($response);
  289. }
  290. }
  291. }