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.

104 lines
2.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. class Share extends BaseController
  8. {
  9. private function _databaseFromToken($token) {
  10. $share = DB::table('shares')
  11. ->where('token', $token)
  12. ->where('expires_at', '>', date('Y-m-d H:i:s'))
  13. ->first();
  14. if(!$share) return false;
  15. $database = DB::table('databases')->where('id', $share->database_id)->first();
  16. return $database;
  17. }
  18. public function view(Request $request, $token) {
  19. $database = $this->_databaseFromToken($token);
  20. if(!$database) {
  21. return view('share-expired');
  22. }
  23. return view('share', [
  24. 'database' => $database,
  25. 'share_token' => $token,
  26. ]);
  27. }
  28. public function current_location(Request $request) {
  29. $database = $this->_databaseFromToken($request->input('token'));
  30. if(!$database) {
  31. return response(json_encode(['error' => 'invalid']))->header('Content-Type', 'application/json');
  32. }
  33. $response = [
  34. 'data' => json_decode($database->last_location),
  35. ];
  36. return response(json_encode($response))->header('Content-Type', 'application/json');
  37. }
  38. public function history(Request $request) {
  39. $database = $this->_databaseFromToken($request->input('token'));
  40. if(!$database) {
  41. return response(json_encode(['error' => 'invalid']))->header('Content-Type', 'application/json');
  42. }
  43. $share = DB::table('shares')
  44. ->where('token', $request->input('token'))
  45. ->first();
  46. $share_date = strtotime($share->created_at);
  47. $locations = [];
  48. $db = new Quartz\DB(env('STORAGE_DIR').$database->name, 'r');
  49. $results = $db->queryLast(100);
  50. foreach($results as $id=>$record) {
  51. if(!is_object($record) || !$record->data)
  52. continue;
  53. if(!property_exists($record->data->properties, 'horizontal_accuracy')
  54. || $record->data->properties->horizontal_accuracy >= 5000)
  55. continue;
  56. // Make sure this is from after the share was created
  57. $record_date = $record->date->format('U');
  58. if($record_date < $share_date)
  59. continue;
  60. $locations[] = $record->data;
  61. }
  62. $linestring = array(
  63. 'type' => 'LineString',
  64. 'coordinates' => [],
  65. );
  66. foreach($locations as $loc) {
  67. if(property_exists($loc, 'geometry'))
  68. $linestring['coordinates'][] = $loc->geometry->coordinates;
  69. else
  70. $linestring['coordinates'][] = null;
  71. }
  72. $response = array(
  73. 'linestring' => $linestring,
  74. );
  75. return response(json_encode($response))->header('Content-Type', 'application/json');
  76. }
  77. }