-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathStatusController.php
More file actions
783 lines (738 loc) · 32 KB
/
StatusController.php
File metadata and controls
783 lines (738 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
<?php
namespace App\Http\Controllers\API\v1;
use App\Dto\GeoJson\Feature;
use App\Dto\GeoJson\FeatureCollection;
use App\Enum\Business;
use App\Enum\StatusVisibility;
use App\Events\StatusUpdateEvent;
use App\Http\Controllers\Backend\Support\LocationController;
use App\Http\Controllers\Backend\Transport\TrainCheckinController;
use App\Http\Controllers\Backend\User\DashboardController;
use App\Http\Controllers\StatusController as StatusBackend;
use App\Http\Controllers\UserController as UserBackend;
use App\Http\Resources\StatusResource;
use App\Http\Resources\StopoverResource;
use App\Models\Status;
use App\Models\Stopover;
use App\Models\Trip;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Enum;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use OpenApi\Attributes as OA;
#[OA\Schema(
schema: 'StatusUpdateBody',
title: 'StatusUpdateBody',
description: 'Status Update Body',
properties: [
new OA\Property(property: 'body', description: 'Status-Text to be displayed alongside the checkin', type: 'string', example: 'Wow. This train is extremely crowded!', nullable: true, maxLength: 280),
new OA\Property(property: 'business', ref: '#/components/schemas/Business'),
new OA\Property(property: 'visibility', ref: '#/components/schemas/StatusVisibility'),
new OA\Property(property: 'eventId', description: 'The ID of the event this status is related to - or null', type: 'string', example: '1', nullable: true),
new OA\Property(property: 'manualDeparture', description: 'Manual departure time set by the user', type: 'string', format: 'date', example: '2020-01-01 12:00:00', nullable: true),
new OA\Property(property: 'manualArrival', description: 'Manual arrival time set by the user', type: 'string', format: 'date', example: '2020-01-01 13:00:00', nullable: true),
new OA\Property(property: 'destinationId', description: 'Destination station id', type: 'string', example: '1', nullable: true),
new OA\Property(property: 'destinationArrivalPlanned', description: 'Destination arrival time', type: 'string', format: 'date', example: '2020-01-01 13:00:00', nullable: true),
],
)]
#[OA\Schema(
schema: 'Polyline',
title: 'Polyline',
description: 'Polyline of a single status as GeoJSON Feature',
properties: [
new OA\Property(property: 'type', type: 'string', example: 'Feature'),
new OA\Property(
property: 'geometry',
properties: [
new OA\Property(property: 'type', type: 'string', example: 'LineString'),
new OA\Property(property: 'coordinates', type: 'array', items: new OA\Items(example: '[[8.39767,49.01625],[8.45947,49.06576]]')),
],
type: 'object',
),
new OA\Property(
property: 'properties',
properties: [
new OA\Property(property: 'statusId', type: 'integer', example: 1337),
],
type: 'object',
),
],
)]
class StatusController extends Controller
{
#[OA\Get(
path: '/dashboard',
operationId: 'getDashboard',
description: 'Returns paginated statuses of personal dashboard',
summary: 'Get paginated statuses of personal dashboard',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Dashboard'],
parameters: [
new OA\Parameter(
name: 'page',
description: 'Page of pagination',
in: 'query',
required: false,
schema: new OA\Schema(type: 'integer'),
),
],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/StatusResource'),
),
new OA\Property(property: 'links', ref: '#/components/schemas/Links'),
new OA\Property(
property: 'meta',
ref: '#/components/schemas/PaginationMeta',
),
],
),
),
new OA\Response(response: 400, description: 'Bad request'),
new OA\Response(response: 401, description: 'Not logged in'),
],
)]
public static function getDashboard(): AnonymousResourceCollection
{
return StatusResource::collection(DashboardController::getPrivateDashboard(Auth::user()));
}
#[OA\Get(
path: '/dashboard/future',
operationId: 'getFutureDashboard',
description: 'Returns paginated statuses of the authenticated user, that are more than 20 minutes in the future',
summary: 'Get paginated future statuses of current user',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Dashboard'],
parameters: [
new OA\Parameter(
name: 'page',
description: 'Page of pagination',
in: 'query',
required: false,
schema: new OA\Schema(type: 'integer'),
),
],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/StatusResource'),
),
new OA\Property(property: 'links', ref: '#/components/schemas/Links'),
new OA\Property(
property: 'meta',
ref: '#/components/schemas/PaginationMeta',
),
],
),
),
new OA\Response(response: 400, description: 'Bad request'),
new OA\Response(response: 401, description: 'Not logged in'),
],
)]
public static function getFutureCheckins(): AnonymousResourceCollection
{
return StatusResource::collection(StatusBackend::getFutureCheckins());
}
#[OA\Get(
path: '/statuses',
operationId: 'getActiveStatuses',
description: 'Returns all currently active statuses that are visible to the (un)authenticated user',
summary: '[Auth optional] Get active statuses',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Status'],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/StatusResource'),
),
],
),
),
new OA\Response(response: 400, description: 'Bad request'),
],
)]
public function enRoute(): AnonymousResourceCollection
{
return StatusResource::collection(StatusBackend::getActiveStatuses());
}
#[OA\Get(
path: '/positions',
operationId: 'getLivePositionsForActiveStatuses',
description: 'Returns an array of live position objects for active statuses',
summary: '[Auth optional] get live positions for active statuses',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Status'],
responses: [
new OA\Response(
response: '200',
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/LivePointDto'),
),
],
),
),
new OA\Response(response: 403, description: 'User not authorized to access this status'),
],
)]
public function livePositions(): JsonResource
{
return JsonResource::collection(StatusBackend::getLivePositions());
}
#[OA\Get(
path: '/positions/{ids}',
operationId: 'getLivePositionsForStatuses',
description: 'Returns an array of live position objects for given status IDs',
summary: '[Auth optional] get live positions for given statuses',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Status'],
parameters: [
new OA\Parameter(
name: 'ids',
description: 'Status-IDs separated by comma',
in: 'path',
schema: new OA\Schema(type: 'string'),
example: '1337,1338',
),
],
responses: [
new OA\Response(
response: '200',
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/LivePointDto'),
),
],
),
),
new OA\Response(response: 403, description: 'User not authorized to access this status'),
],
)]
public function getLivePositionForStatus($ids): AnonymousResourceCollection
{
return JsonResource::collection(StatusBackend::getLivePositionForStatus($ids));
}
#[OA\Get(
path: '/status',
operationId: 'listStatuses',
description: 'Returns paginated list of statuses, filtered by given parameters',
summary: '[Auth optional] List and filter statuses',
tags: ['Status'],
parameters: [
new OA\Parameter(
name: 'body',
description: 'Filter by text in status body',
in: 'query',
schema: new OA\Schema(type: 'string'),
example: 'Having a great trip!',
),
new OA\Parameter(
name: 'user_id',
description: 'Filter by user ID',
in: 'query',
schema: new OA\Schema(type: 'integer'),
example: 42,
),
new OA\Parameter(
name: 'origin_text',
description: 'Filter by origin station name',
in: 'query',
schema: new OA\Schema(type: 'string'),
example: 'Central Station',
),
new OA\Parameter(
name: 'origin_id',
description: 'Filter by origin station ID',
in: 'query',
schema: new OA\Schema(type: 'integer'),
example: 5,
),
new OA\Parameter(
name: 'destination_text',
description: 'Filter by destination station name',
in: 'query',
schema: new OA\Schema(type: 'string'),
example: 'Main Square',
),
new OA\Parameter(
name: 'destination_id',
description: 'Filter by destination station ID',
in: 'query',
schema: new OA\Schema(type: 'integer'),
example: 10,
),
],
responses: [
new OA\Response(
response: 200,
description: 'list of matching statuses',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/StatusResource'),
),
],
),
),
],
)]
public function list(Request $request): AnonymousResourceCollection
{
$validated = $request->validate([
// generic filters
'body' => ['nullable', 'string', 'max:32'],
'user_id' => ['nullable', 'integer', 'exists:users,id'],
// Filters for origin/destination
'origin_text' => ['nullable', 'string', 'max:64'],
'origin_id' => ['nullable', 'integer', 'exists:train_stations,id'],
'destination_text' => ['nullable', 'string', 'max:64'],
'destination_id' => ['nullable', 'integer', 'exists:train_stations,id'],
]);
$user = auth()->user();
$query = Status::query()->orderByDesc('created_at');
if (isset($validated['body'])) {
$query->where('body', 'like', '%' . $validated['body'] . '%');
}
$query->join('train_checkins', 'train_checkins.status_id', '=', 'statuses.id')
->join('users', 'statuses.user_id', '=', 'users.id')
->join('train_stopovers as origin_stopover', 'train_checkins.origin_stopover_id', '=', 'origin_stopover.id')
->join('train_stations as origin_station', 'origin_stopover.train_station_id', '=', 'origin_station.id')
->join('train_stopovers as destination_stopover', 'train_checkins.destination_stopover_id', '=', 'destination_stopover.id')
->join('train_stations as destination_station', 'destination_stopover.train_station_id', '=', 'destination_station.id')
->when(isset($validated['origin_text']), function ($q) use ($validated) {
$q->where('origin_station.name', 'like', '%' . $validated['origin_text'] . '%');
})
->when(isset($validated['origin_id']), function ($q) use ($validated) {
$q->where('origin_station.id', $validated['origin_id']);
})
->when(isset($validated['destination_text']), function ($q) use ($validated) {
$q->where('destination_station.name', 'like', '%' . $validated['destination_text'] . '%');
})
->when(isset($validated['destination_id']), function ($q) use ($validated) {
$q->where('destination_station.id', $validated['destination_id']);
})
->when(isset($validated['user_id']), function ($q) use ($validated) {
$q->where('users.id', $validated['user_id']);
})
->where(\App\Http\Controllers\Backend\Transport\StatusController::filterStatusVisibility($user))
->where('train_checkins.departure', '<', now()->addMinutes(20))
->whereNotIn('statuses.user_id', $user->mutedUsers()->select('muted_id'))
->whereNotIn('statuses.user_id', $user->blockedUsers()->select('blocked_id'))
->whereNotIn('statuses.user_id', $user->blockedByUsers()->select('user_id'))
->select('statuses.*');
return StatusResource::collection($query->cursorPaginate(20));
}
#[OA\Get(
path: '/status/{id}',
operationId: 'getSingleStatus',
description: 'Returns a single status Object, if user is authorized to see it',
summary: '[Auth optional] Get single statuses',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Status'],
parameters: [
new OA\Parameter(
name: 'id',
description: 'Status-ID',
in: 'path',
schema: new OA\Schema(type: 'integer'),
example: 1337,
),
],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [new OA\Property(property: 'data', ref: '#/components/schemas/StatusResource')],
),
),
new OA\Response(response: 400, description: 'Bad request'),
new OA\Response(response: 404, description: 'No status found for this id'),
new OA\Response(response: 403, description: 'User not authorized to access this status'),
],
)]
public function show(int $id): StatusResource|JsonResponse
{
$status = StatusBackend::getStatus($id);
try {
$this->authorize('view', $status);
} catch (AuthorizationException) {
return response()->json(['message' => 'Status invisible to you.'], 403);
}
return new StatusResource($status);
}
#[OA\Delete(
path: '/status/{id}',
operationId: 'destroySingleStatus',
description: 'Deletes a single status Object, if user is authorized to',
summary: 'Destroy a status',
security: [['passport' => ['write-statuses']], ['token' => []]],
tags: ['Status'],
parameters: [
new OA\Parameter(
name: 'id',
description: 'Status-ID',
in: 'path',
schema: new OA\Schema(type: 'integer'),
example: 1337,
),
],
responses: [
new OA\Response(response: 204, description: 'Status deleted.'),
new OA\Response(response: 400, description: 'Bad request'),
new OA\Response(response: 404, description: 'No status found for this id'),
new OA\Response(
response: 403,
description: 'User not authorized to manipulate this status',
),
],
)]
public function destroy(int $statusId): JsonResponse
{
try {
StatusBackend::DeleteStatus(Auth::user(), $statusId);
return response()->json(null, 204);
} catch (AuthorizationException) {
return $this->sendError('You are not allowed to delete this status.', 403);
} catch (ModelNotFoundException) {
return $this->sendError('No status found for this id.');
}
}
/**
* @throws ValidationException
*/
#[OA\Put(
path: '/status/{id}',
operationId: 'updateSingleStatus',
description: 'Updates a single status Object, if user is authorized to',
summary: 'Update a status',
security: [['passport' => ['write-statuses']], ['token' => []]],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(ref: '#/components/schemas/StatusUpdateBody'),
),
tags: ['Status'],
parameters: [
new OA\Parameter(
name: 'id',
description: 'Status-ID',
in: 'path',
schema: new OA\Schema(type: 'integer'),
example: 1337,
),
],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [new OA\Property(property: 'data', ref: '#/components/schemas/StatusResource')],
),
),
new OA\Response(response: 400, description: 'Bad request'),
new OA\Response(response: 404, description: 'No status found for this id'),
new OA\Response(
response: 403,
description: 'User not authorized to manipulate this status',
),
],
)]
public function update(Request $request, int $statusId): JsonResponse
{
$validator = Validator::make($request->all(), [
// Just changing of metadata
'body' => ['nullable', 'max:280', 'nullable'],
'business' => [new Enum(Business::class)],
'visibility' => [new Enum(StatusVisibility::class)],
'eventId' => ['nullable', 'integer', 'exists:events,id'],
// Changing of Checkin-Metadata
'manualDeparture' => ['nullable', 'date'],
'manualArrival' => ['nullable', 'date'],
// Following attributes are needed, if user want's to change the destination
'destinationId' => ['required_with:destinationArrivalPlanned', 'exists:train_stations,id'],
'destinationArrivalPlanned' => ['required_with:destinationId', 'date'],
]);
if ($validator->fails()) {
return $this->sendError($validator->errors(), 400);
}
$validated = $validator->validate();
try {
$status = Status::findOrFail($statusId);
$this->authorize('update', $status);
// Check for disallowed status visibility changes
if (auth()->user()->can('disallow-status-visibility-change') && $validated['visibility'] !== StatusVisibility::PRIVATE->value) {
return $this->sendError('You are not allowed to change the visibility to anything else than private', 403);
}
DB::beginTransaction();
if (
isset($validated['destinationId'], $validated['destinationArrivalPlanned'])
&& (
((int) $validated['destinationId']) !== $status->checkin->destinationStopover->station->id
|| (Carbon::parse($validated['destinationArrivalPlanned'])->ne($status->checkin->destinationStopover->arrival_planned))
)
) {
$arrival = Carbon::parse($validated['destinationArrivalPlanned'])->timezone(config('app.timezone'));
$stopover = Stopover::where('train_station_id', $validated['destinationId'])
->where('arrival_planned', $arrival)
->where('trip_id', $status->checkin->trip_id)
->first();
if ($stopover === null) {
return $this->sendError('Invalid stopover given', 400);
}
TrainCheckinController::changeDestination(
checkin: $status->checkin,
newDestinationStopover: $stopover,
);
}
$updatePayload = [];
if (array_key_exists('body', $validated)) {
$updatePayload['body'] = $validated['body'] ?? null;
}
if (array_key_exists('business', $validated)) {
$updatePayload['business'] = Business::from($validated['business']);
}
if (!$status->lock_visibility && array_key_exists('visibility', $validated)) {
// If moderation has locked the visibility, prevent the user from changing it
$updatePayload['visibility'] = StatusVisibility::from($validated['visibility']);
}
if (array_key_exists('eventId', $validated)) { // don't use isset here as it would return false if eventId is null
$updatePayload['event_id'] = $validated['eventId'];
}
$status->update($updatePayload);
if (array_key_exists('manualDeparture', $validated)) {
$manualDeparture = isset($validated['manualDeparture'])
? Carbon::parse($validated['manualDeparture'], auth()->user()->timezone)->setSecond(0)->setMillisecond(0)
: null;
$status->checkin->update(['manual_departure' => $manualDeparture]);
}
if (array_key_exists('manualArrival', $validated)) {
$manualArrival = isset($validated['manualArrival'])
? Carbon::parse($validated['manualArrival'], auth()->user()->timezone)->setSecond(0)->setMillisecond(0)
: null;
$status->checkin->update(['manual_arrival' => $manualArrival]);
}
// check duration of manual arrival and departure
$arrivalDelayInHours = 0;
$departureDelayInHours = 0;
if (!empty($manualDeparture)) {
$departureDelayInHours = abs($manualDeparture->diffInHours($status->checkin->departure));
}
if (!empty($manualArrival)) {
$arrivalDelayInHours = abs($manualArrival->diffInHours($status->checkin->arrival));
}
if ($departureDelayInHours > config('trwl.max_delay_hours') || $arrivalDelayInHours > config('trwl.max_delay_hours')) {
DB::rollBack();
return $this->sendError('The delay of the manual arrival or departure is too high.', 400);
}
DB::commit();
$status = $status->fresh();
StatusUpdateEvent::dispatch($status);
return $this->sendResponse(new StatusResource($status));
} catch (ModelNotFoundException) {
DB::rollBack();
return $this->sendError('Status not found');
} catch (AuthorizationException) {
DB::rollBack();
return $this->sendError('You are not authorized to edit this status', 403);
} catch (InvalidArgumentException) {
DB::rollBack();
return $this->sendError('Invalid Arguments', 400);
}
}
/**
* @todo extract this to backend
* @todo does this conform to the private checkin-shit?
*/
#[OA\Get(
path: '/polyline/{ids}',
operationId: 'getPolylines',
description: 'Returns GeoJSON for all requested status IDs',
summary: '[Auth optional] Get GeoJSON for statuses',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Status'],
parameters: [
new OA\Parameter(
name: 'ids',
description: 'comma seperated status IDs',
in: 'path',
schema: new OA\Schema(type: 'string'),
example: '1337,1338',
),
],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
properties: [
new OA\Property(property: 'type', example: 'FeatureCollection'),
new OA\Property(
property: 'features',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/Polyline'),
),
],
type: 'object',
),
],
),
),
new OA\Response(response: 400, description: 'Bad request'),
new OA\Response(response: 404, description: 'No status found for this id'),
new OA\Response(response: 403, description: 'User not authorized to access this status'),
],
)]
public function getPolyline(string $parameters): JsonResource
{
$ids = explode(',', $parameters, 50);
$geoJsonFeatures = Status::whereIn('id', $ids)
->with('checkin.Trip.polyline')
->get()
->filter(function (Status $status) {
try {
$this->authorize('view', $status);
} catch (AuthorizationException) {
return false;
}
return true;
})
->map(function ($status) {
return new Feature(
LocationController::forStatus($status)->getMapLines(),
'LineString',
$status->id
);
});
$geoJson = new FeatureCollection($geoJsonFeatures);
return $ids ? new JsonResource($geoJson) : $this->sendError('');
}
#[OA\Get(
path: '/stopovers/{ids}',
operationId: 'getStopOvers',
description: 'Returns all underway-stops for stations',
summary: '[Auth optional] Get stopovers for statuses',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Status'],
parameters: [
new OA\Parameter(
name: 'ids',
description: 'comma seperated trip IDs',
in: 'path',
schema: new OA\Schema(type: 'string'),
example: '1,2',
),
],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
properties: [
new OA\Property(
property: '1',
description: 'Array of stopovers. Key describes trip id',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/StopoverResource'),
),
],
type: 'object',
),
],
),
),
new OA\Response(response: 400, description: 'Bad request'),
new OA\Response(response: 404, description: 'No status found for this id'),
new OA\Response(response: 403, description: 'User not authorized to access this status'),
],
)]
public function getStopovers(string $parameters): JsonResponse
{
$tripIds = array_unique(explode(',', $parameters, 50));
$trips = Trip::with('stopovers.station')->whereIn('id', $tripIds)->get()->mapWithKeys(function ($trip) {
return [$trip->id => StopoverResource::collection($trip->stopovers)];
});
return $this->sendResponse($trips);
}
#[OA\Get(
path: '/user/statuses/active',
operationId: 'userState',
description: 'This request returns whether the currently logged-in user has an active check-in or not.',
summary: 'User state',
security: [['passport' => ['read-statuses']], ['token' => []]],
tags: ['Auth'],
responses: [
new OA\Response(
response: 200,
description: 'successful operation',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'data',
ref: '#/components/schemas/StatusResource',
type: 'object',
),
],
),
),
new OA\Response(response: 401, description: 'Unauthorized'),
new OA\Response(response: 204, description: 'No active checkin'),
],
)]
public function getActiveStatus(): StatusResource|JsonResponse
{
$latestStatuses = UserBackend::statusesForUser(Auth::user());
if ($latestStatuses->count() > 0) {
foreach ($latestStatuses as $status) {
if ($status->checkin->originStopover->departure->isPast()
&& $status->checkin->destinationStopover->arrival->isFuture()) {
return new StatusResource($status);
}
}
}
return response()->json(null, 204);
}
}