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.

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