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.

255 lines
8.5 KiB

  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. 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. } else {
  38. return response(json_encode(['error' => 'no date provided']))->header('Content-Type', 'application/json');
  39. }
  40. $results = $qz->queryRange($start, $end);
  41. $locations = [];
  42. $properties = [];
  43. $events = [];
  44. if($request->input('format') == 'linestring') {
  45. foreach($results as $id=>$record) {
  46. // When returning a linestring, separate out the "event" records from the "location" records
  47. if(property_exists($record->data->properties, 'action')) {
  48. $rec = $record->data;
  49. # add a unixtime property
  50. $rec->properties->unixtime = (int)$record->date->format('U');
  51. $events[] = $rec;
  52. } else {
  53. #$record->date->format('U.u');
  54. $locations[] = $record->data;
  55. $props = $record->data->properties;
  56. $date = $record->date;
  57. $date->setTimeZone(new DateTimeZone($tz));
  58. $props->timestamp = $date->format('c');
  59. $props->unixtime = (int)$date->format('U');
  60. $properties[] = $props;
  61. }
  62. }
  63. $linestring = array(
  64. 'type' => 'LineString',
  65. 'coordinates' => [],
  66. 'properties' => $properties
  67. );
  68. foreach($locations as $loc) {
  69. if(property_exists($loc, 'geometry'))
  70. $linestring['coordinates'][] = $loc->geometry->coordinates;
  71. else
  72. $linestring['coordinates'][] = null;
  73. }
  74. $response = array(
  75. 'linestring' => $linestring,
  76. 'events' => $events
  77. );
  78. } else {
  79. foreach($results as $id=>$record) {
  80. $locations[] = $record->data;
  81. }
  82. $response = [
  83. 'locations' => $locations
  84. ];
  85. }
  86. return response(json_encode($response))->header('Content-Type', 'application/json');
  87. }
  88. public function last(Request $request) {
  89. $token = $request->input('token');
  90. if(!$token)
  91. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  92. $db = DB::table('databases')->where('read_token','=',$token)->first();
  93. if(!$db)
  94. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  95. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'r');
  96. if($request->input('tz')) {
  97. $tz = $request->input('tz');
  98. } else {
  99. $tz = 'UTC';
  100. }
  101. if($input=$request->input('before')) {
  102. if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $input)) {
  103. // If the input date is given in YYYY-mm-dd HH:mm:ss format, interpret it in the timezone given
  104. $date = DateTime::createFromFormat('Y-m-d H:i:s', $input, new DateTimeZone($tz));
  105. } else {
  106. // Otherwise, parse the string and use the timezone in the input
  107. $date = new DateTime($input);
  108. $date->setTimeZone(new DateTimeZone($tz));
  109. }
  110. if(!$date) {
  111. return response(json_encode(['error' => 'invalid date provided']))->header('Content-Type', 'application/json');
  112. }
  113. } else {
  114. $date = new DateTime();
  115. }
  116. /* ********************************************** */
  117. // TODO: move this logic into QuartzDB
  118. // Load the shard for the given date
  119. $shard = $qz->shardForDate($date);
  120. // If the shard doesn't exist, check one day before
  121. if(!$shard->exists()) {
  122. $date = $date->sub(new DateInterval('PT86400S'));
  123. $shard = $qz->shardForDate($date);
  124. }
  125. // Now if the shard doesn't exist, return an empty result
  126. if(!$shard->exists()) {
  127. return response(json_encode([
  128. 'data'=>null
  129. ]));
  130. }
  131. // Start iterating through the shard and look for the last line that is before the given date
  132. $shard->init();
  133. $record = false;
  134. foreach($shard as $r) {
  135. if($r->date > $date)
  136. break;
  137. $record = $r;
  138. }
  139. /* ********************************************** */
  140. if(!$record) {
  141. return response(json_encode([
  142. 'data'=>null
  143. ]));
  144. }
  145. $response = [
  146. 'data' => $record->data
  147. ];
  148. if($request->input('geocode') && property_exists($record->data, 'geometry') && property_exists($record->data->geometry, 'coordinates')) {
  149. $coords = $record->data->geometry->coordinates;
  150. $params = [
  151. 'latitude' => $coords[1],
  152. 'longitude' => $coords[0]
  153. ];
  154. $ch = curl_init(env('ATLAS_BASE').'api/geocode?'.http_build_query($params));
  155. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  156. curl_setopt($ch, CURLOPT_TIMEOUT, 8);
  157. $geocode = json_decode(curl_exec($ch));
  158. if($geocode) {
  159. $response['geocode'] = $geocode;
  160. } else {
  161. $response['geocode'] = null;
  162. }
  163. }
  164. return response(json_encode($response));
  165. }
  166. public function input(Request $request) {
  167. $token = $request->input('token');
  168. if(!$token)
  169. return response(json_encode(['error' => 'no token provided']))->header('Content-Type', 'application/json');
  170. $db = DB::table('databases')->where('write_token','=',$token)->first();
  171. if(!$db)
  172. return response(json_encode(['error' => 'invalid token']))->header('Content-Type', 'application/json');
  173. if(!is_array($request->input('locations')))
  174. 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');
  175. $qz = new Quartz\DB(env('STORAGE_DIR').$db->name, 'w');
  176. $num = 0;
  177. $trips = 0;
  178. foreach($request->input('locations') as $loc) {
  179. if(array_key_exists('properties', $loc)) {
  180. if(array_key_exists('timestamp', $loc['properties'])) {
  181. try {
  182. if(preg_match('/^\d+\.\d+$/', $loc['properties']['timestamp']))
  183. $date = DateTime::createFromFormat('U.u', $loc['properties']['timestamp']);
  184. elseif(preg_match('/^\d+$/', $loc['properties']['timestamp']))
  185. $date = DateTime::createFromFormat('U', $loc['properties']['timestamp']);
  186. else
  187. $date = new DateTime($loc['properties']['timestamp']);
  188. if($date) {
  189. $num++;
  190. $qz->add($date, $loc);
  191. if(array_key_exists('type', $loc['properties']) && $loc['properties']['type'] == 'trip') {
  192. try {
  193. $job = (new TripComplete($db->id, $loc))->onQueue('compass');
  194. $this->dispatch($job);
  195. $trips++;
  196. Log::info('Got a trip record');
  197. } catch(Exception $e) {
  198. Log::warning('Received invalid trip');
  199. }
  200. }
  201. } else {
  202. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  203. }
  204. } catch(Exception $e) {
  205. Log::warning('Received invalid date: ' . $loc['properties']['timestamp']);
  206. }
  207. }
  208. }
  209. }
  210. return response(json_encode(['result' => 'ok', 'saved' => $num, 'trips' => $trips]))->header('Content-Type', 'application/json');
  211. }
  212. }