Where-in-the-World-is-Ben/routes/web.php

68 lines
2.5 KiB
PHP

<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Client;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/past-trips', function () {
return view('past-trips');
});
Route::get('/{tripId?}/{showAll?}', function ($tripId = null, $showAll = false) {
if (!$tripId && !config('app.current_trip_id')) return view('no-trip');
/*
* If there is a file in the local cache that is less than 5 hours old,
* use that.
*/
$tripFileName = $tripId ?? config('app.current_trip_id') . '.json';
if (Storage::disk('local')->exists($tripFileName)) {
$cachedData = json_decode(Storage::disk('local')->get($tripFileName));
$cachedDataUpdatedAt = new DateTime($cachedData->trip->updated_at);
$now = new DateTime();
if (intval(($now->getTimestamp() - $cachedDataUpdatedAt->getTimestamp()) / 3600) <= 5) {
return view('tracker', ['trip' => $cachedData->trip, 'showAllCheckins' => ($showAll === 'all')]);
}
}
/*
* Otherwise, download the latest tracking data.
*/
$client = new Client([
'base_uri' => 'https://app.wayward.travel/',
'timeout' => 3.0
]);
$response = $client->get('trip/'.($tripId ?? config('app.current_trip_id')).'/user/zmld8ko6qy7d9j3xvq10/json');
if ($response->getStatusCode() == 200) {
$data = json_decode($response->getBody());
// Cache the downloaded file if it does not exist locally.
if (Storage::disk('local')->missing($tripFileName)) {
Storage::disk('local')->put($tripFileName, json_encode($data));
} else {
$cachedData = json_decode(Storage::disk('local')->get($tripFileName));
if ($data->trip->updated_at !== $cachedData->trip->updated_at) {
Storage::disk('local')->put($tripFileName, json_encode($data));
// TODO: Cache photos locally
} else {
$data = $cachedData;
}
}
return view('tracker', ['trip' => $data->trip, 'showAllCheckins' => ($showAll === 'all')]);
} else {
return 'Something went wrong';
}
});