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.

336 lines
11 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;
  6. use Quartz;
  7. use Log;
  8. use DateTime, DateTimeZone, DateInterval;
  9. use App\Jobs\TripComplete;
  10. use App\Jobs\NotifyOfNewLocations;
  11. class Api extends BaseController
  12. {
  13. public function account(Request $request) {
  14. $token = $request->input('token');
  15. if(!$token)
  16. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  17. $db = DB::table('databases')->where('write_token','=',$token)->first();
  18. if(!$db)
  19. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  20. return response(json_encode(['name' => $db->name]))->header('Content-Type', 'application/json');
  21. }
  22. public function query(Request $request) {
  23. $token = $request->input('token');
  24. if(!$token)
  25. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  26. $db = DB::table('databases')->where('read_token','=',$token)->first();
  27. if(!$db)
  28. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  29. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  30. if($request->input('tz')) {
  31. $tz = $request->input('tz');
  32. } else {
  33. $tz = 'UTC';
  34. }
  35. if($date=$request->input('date')) {
  36. $start = DateTime::createFromFormat('Y-m-d H:i:s', $date.' 00:00:00', new DateTimeZone($tz));
  37. $end = DateTime::createFromFormat('Y-m-d H:i:s', $date.' 23:59:59', new DateTimeZone($tz));
  38. } elseif(($start=$request->input('start')) && ($end=$request->input('end'))) {
  39. $start = new DateTime($start, new DateTimeZone($tz));
  40. $end = new DateTime($end, new DateTimeZone($tz));
  41. } else {
  42. return response(json_encode(['error' => 'no date provided']))->header('Content-Type', 'application/json');
  43. }
  44. $results = $qz->queryRange($start, $end);
  45. $locations = [];
  46. $properties = [];
  47. $events = [];
  48. if($request->input('format') == 'linestring') {
  49. foreach($results as $id=>$record) {
  50. // When returning a linestring, separate out the "event" records from the "location" records
  51. if($record->data) {
  52. if(property_exists($record->data->properties, 'action')) {
  53. $rec = $record->data;
  54. # add a unixtime property
  55. $rec->properties->unixtime = (int)$record->date->format('U');
  56. $events[] = $rec;
  57. } else {
  58. #$record->date->format('U.u');
  59. // Ignore super inaccurate locations
  60. if(!property_exists($record->data->properties, 'horizontal_accuracy')
  61. || $record->data->properties->horizontal_accuracy <= 5000) {
  62. $locations[] = $record->data;
  63. $props = $record->data->properties;
  64. $date = $record->date;
  65. $date->setTimeZone(new DateTimeZone($tz));
  66. $props->timestamp = $date->format('c');
  67. $props->unixtime = (int)$date->format('U');
  68. $properties[] = $props;
  69. }
  70. }
  71. }
  72. }
  73. $linestring = array(
  74. 'type' => 'LineString',
  75. 'coordinates' => [],
  76. 'properties' => $properties
  77. );
  78. foreach($locations as $loc) {
  79. if(property_exists($loc, 'geometry'))
  80. $linestring['coordinates'][] = $loc->geometry->coordinates;
  81. else
  82. $linestring['coordinates'][] = null;
  83. }
  84. $response = array(
  85. 'linestring' => $linestring,
  86. 'events' => $events
  87. );
  88. } else {
  89. foreach($results as $id=>$record) {
  90. if($record->data) {
  91. $locations[] = $record->data;
  92. }
  93. }
  94. $response = [
  95. 'locations' => $locations
  96. ];
  97. }
  98. return response(json_encode($response))->header('Content-Type', 'application/json');
  99. }
  100. public function last(Request $request) {
  101. $token = $request->input('token');
  102. if(!$token)
  103. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  104. $db = DB::table('databases')->where('read_token','=',$token)->first();
  105. if(!$db)
  106. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  107. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  108. if($request->input('tz')) {
  109. $tz = $request->input('tz');
  110. } else {
  111. $tz = 'UTC';
  112. }
  113. if($input=$request->input('before')) {
  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. } else {
  126. $date = new DateTime();
  127. }
  128. /* ********************************************** */
  129. // TODO: move this logic into QuartzDB
  130. // Load the shard for the given date
  131. $shard = $qz->shardForDate($date);
  132. // If the shard doesn't exist, check one day before
  133. if(!$shard->exists()) {
  134. $date = $date->sub(new DateInterval('PT86400S'));
  135. $shard = $qz->shardForDate($date);
  136. }
  137. // Now if the shard doesn't exist, return an empty result
  138. if(!$shard->exists()) {
  139. return response(json_encode([
  140. 'data'=>null
  141. ]));
  142. }
  143. // Start iterating through the shard and look for the last line that is before the given date
  144. $shard->init();
  145. $record = false;
  146. foreach($shard as $r) {
  147. if($r->date > $date)
  148. break;
  149. $record = $r;
  150. }
  151. /* ********************************************** */
  152. if(!$record) {
  153. return response(json_encode([
  154. 'data'=>null
  155. ]));
  156. }
  157. $response = [
  158. 'data' => $record->data
  159. ];
  160. if($request->input('geocode') && property_exists($record->data, 'geometry') && property_exists($record->data->geometry, 'coordinates')) {
  161. $coords = $record->data->geometry->coordinates;
  162. $params = [
  163. 'latitude' => $coords[1],
  164. 'longitude' => $coords[0],
  165. 'date' => $record->data->properties->timestamp
  166. ];
  167. $geocode = self::geocode($params);
  168. if($geocode) {
  169. $response['geocode'] = $geocode;
  170. } else {
  171. $response['geocode'] = null;
  172. }
  173. }
  174. return response(json_encode($response))->header('Content-Type', 'application/json');;
  175. }
  176. public function input(Request $request) {
  177. $token = $request->input('token');
  178. if(!$token)
  179. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  180. $db = DB::table('databases')->where('write_token','=',$token)->first();
  181. if(!$db)
  182. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  183. if(!is_array($request->input('locations')))
  184. 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');
  185. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'w');
  186. $num = 0;
  187. $trips = 0;
  188. $last_location = false;
  189. foreach($request->input('locations') as $loc) {
  190. if(array_key_exists('properties', $loc)) {
  191. if(array_key_exists('timestamp', $loc['properties'])) {
  192. try {
  193. if(preg_match('/^\d+\.\d+$/', $loc['properties']['timestamp']))
  194. $date = DateTime::createFromFormat('U.u', $loc['properties']['timestamp']);
  195. elseif(preg_match('/^\d+$/', $loc['properties']['timestamp']))
  196. $date = DateTime::createFromFormat('U', $loc['properties']['timestamp']);
  197. else
  198. $date = new DateTime($loc['properties']['timestamp']);
  199. if($date) {
  200. $num++;
  201. $qz->add($date, $loc);
  202. $last_location = $loc;
  203. if(array_key_exists('type', $loc['properties']) && $loc['properties']['type'] == 'trip') {
  204. try {
  205. $job = (new TripComplete($db->id, $loc))->onQueue('compass');
  206. $this->dispatch($job);
  207. $trips++;
  208. Log::info('Got a trip record');
  209. } catch(Exception $e) {
  210. Log::warning('Received invalid trip');
  211. }
  212. }
  213. } else {
  214. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  215. }
  216. } catch(Exception $e) {
  217. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  218. }
  219. }
  220. }
  221. }
  222. $response = [
  223. 'result' => 'ok',
  224. 'saved' => $num,
  225. 'trips' => $trips
  226. ];
  227. if($last_location) {
  228. $geocode = self::geocode(['latitude'=>$last_location['geometry']['coordinates'][1], 'longitude'=>$last_location['geometry']['coordinates'][0]]);
  229. $response['geocode'] = [
  230. 'full_name' => $geocode->full_name,
  231. 'locality' => $geocode->locality,
  232. 'country' => $geocode->country
  233. ];
  234. #$response['geocode'] = null;
  235. // Notify subscribers that new data is available
  236. if($db->ping_urls) {
  237. $job = (new NotifyOfNewLocations($db->id))->onQueue('compass');
  238. $this->dispatch($job);
  239. }
  240. }
  241. return response(json_encode($response))->header('Content-Type', 'application/json');
  242. }
  243. public function trip_complete(Request $request) {
  244. $token = $request->input('token');
  245. if(!$token)
  246. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  247. $db = DB::table('databases')->where('write_token','=',$token)->first();
  248. if(!$db)
  249. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  250. if($request->input('tz')) {
  251. $tz = new DateTimeZone($request->input('tz'));
  252. } else {
  253. $tz = new DateTimeZone('UTC');
  254. }
  255. $start = new DateTime($request->input('start'), $tz);
  256. $end = new DateTime($request->input('end'), $tz);
  257. $loc = [
  258. 'properties' => [
  259. 'mode' => $request->input('mode'),
  260. 'start' => $start->format('c'),
  261. 'end' => $end->format('c'),
  262. ]
  263. ];
  264. try {
  265. $job = (new TripComplete($db->id, $loc))->onQueue('compass');
  266. $this->dispatch($job);
  267. Log::info('Got a manual trip record: '.$start->format('c').' '.$end->format('c'));
  268. } catch(Exception $e) {
  269. Log::warning('Received invalid trip');
  270. }
  271. return response(json_encode(['result' => 'ok']))->header('Content-Type', 'application/json');
  272. }
  273. public static function geocode($params) {
  274. $ch = curl_init(env('ATLAS_BASE').'api/geocode?'.http_build_query($params));
  275. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  276. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  277. $response = curl_exec($ch);
  278. if($response) {
  279. return json_decode($response);
  280. }
  281. }
  282. }