-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathRoomController.php
More file actions
432 lines (360 loc) · 15.6 KB
/
RoomController.php
File metadata and controls
432 lines (360 loc) · 15.6 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
<?php
namespace App\Http\Controllers\api\v1;
use App\Enums\CustomStatusCodes;
use App\Enums\RoomSortingType;
use App\Enums\RoomUserRole;
use App\Enums\RoomVisibility;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateRoom;
use App\Http\Requests\JoinMeeting;
use App\Http\Requests\ShowRoomsRequest;
use App\Http\Requests\StartMeeting;
use App\Http\Requests\TransferOwnershipRequest;
use App\Http\Requests\UpdateRoomDescription;
use App\Http\Requests\UpdateRoomSettings;
use App\Http\Resources\RoomSettings;
use App\Models\Room;
use App\Models\RoomType;
use App\Models\User;
use App\Services\RoomAuthService;
use App\Services\RoomService;
use App\Settings\GeneralSettings;
use Auth;
use DB;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Log;
class RoomController extends Controller
{
public function __construct()
{
$this->authorizeResource(Room::class, 'room');
}
/**
* Return a json array with all rooms the user owners or is member of
*
* @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection|\Illuminate\Http\Response
*/
public function index(ShowRoomsRequest $request)
{
$additionalMeta = [];
if ($request->only_favorites) {
// list if room favorites
$roomFavorites = Auth::user()->roomFavorites->modelKeys();
$collection = Room::whereIn('rooms.id', $roomFavorites);
} else {
// all rooms without limitation (always include own rooms, shared rooms and public rooms)
if ($request->filter_all && Auth::user()->can('viewAll', Room::class)) {
$collection = Room::query();
} else {
$collection = Room::where(function (Builder $query) use ($request) {
// own rooms
if ($request->filter_own) {
$query->orWhere('user_id', '=', Auth::user()->id);
}
// rooms where the user is member
if ($request->filter_shared) {
// list of room ids where the user is member
$roomMemberships = Auth::user()->sharedRooms->modelKeys();
$query->orWhereIn('rooms.id', $roomMemberships);
}
// all rooms that are public
if ($request->filter_public) {
$query->orWhere(function (Builder $subQuery) {
$roomTypesWithListingEnforced = RoomType::where('visibility_enforced', true)->where('visibility_default', RoomVisibility::PUBLIC)->get('id');
$roomTypesWithNoListingEnforced = RoomType::where('visibility_enforced', true)->where('visibility_default', RoomVisibility::PRIVATE)->get('id');
$roomTypesWithListingDefault = RoomType::where('visibility_enforced', false)->where('visibility_default', RoomVisibility::PUBLIC)->get('id');
$subQuery
// Room has a room type where the visibility public is enforced
->whereIn('room_type_id', $roomTypesWithListingEnforced)
// Room where expert mode is deactivated where the visibility public is the default value
->orWhere(function (Builder $subSubQuery) use ($roomTypesWithListingDefault) {
$subSubQuery
->where('expert_mode', false)
->whereIn('room_type_id', $roomTypesWithListingDefault);
})
// Room where expert mode is activated and visibility is set to public
->orWhere(function (Builder $subSubQuery) use ($roomTypesWithNoListingEnforced) {
$subSubQuery
->where('expert_mode', true)
->where('visibility', RoomVisibility::PUBLIC)
->whereNotIn('room_type_id', $roomTypesWithNoListingEnforced);
});
});
}
// prevent request with no filter (would return all rooms)
if (! $request->filter_own && ! $request->filter_shared && ! $request->filter_public) {
abort(400);
}
});
}
}
// join relationship table to allow sorting by relationship columns
$collection->leftJoin('meetings', 'rooms.meeting_id', '=', 'meetings.id');
$collection->join('room_types', 'rooms.room_type_id', '=', 'room_types.id');
$collection->join('users', 'rooms.user_id', '=', 'users.id');
// only select columns from rooms table to prevent duplicate column names
$collection->select('rooms.*');
// eager load relationships
$collection->with(['owner', 'roomType', 'latestMeeting']);
// count all available rooms before search
$additionalMeta['meta']['total_no_filter'] = $collection->count();
// filter by specific room Type if not only favorites
if ($request->has('room_type') && ! $request->only_favorites) {
$collection->where('room_type_id', $request->room_type);
}
// rooms that can be found with the search
if ($request->has('search') && trim($request->search) != '') {
$searchQueries = explode(' ', preg_replace('/\s\s+/', ' ', $request->search));
foreach ($searchQueries as $searchQuery) {
$collection = $collection->where(function ($query) use ($searchQuery) {
$query->whereLike('rooms.name', '%'.$searchQuery.'%')
->orWhereHas('owner', function ($query2) use ($searchQuery) {
$query2->whereLike('users.firstname', '%'.$searchQuery.'%')
->orWhereLike('users.lastname', '%'.$searchQuery.'%');
});
});
}
}
// sort rooms by different strategies
$collection = match ($request->sort_by) {
RoomSortingType::ALPHA->value => $collection->orderByRaw('LOWER(rooms.name)'),
RoomSortingType::ROOM_TYPE->value => $collection->orderByRaw('LOWER(room_types.name)')->orderByRaw('LOWER(rooms.name)'),
default => $collection->orderByRaw('meetings.start IS NULL ASC')->orderByRaw('meetings.end IS NULL DESC')->orderByDesc('meetings.start')->orderByRaw('LOWER(rooms.name)'),
};
// Add secondary sort by id to ensure consistent ordering
$collection = $collection->orderBy('rooms.id');
// count own rooms
$additionalMeta['meta']['total_own'] = Auth::user()->myRooms()->count();
$collection = $collection->paginate($request->per_page);
return \App\Http\Resources\Room::collection($collection)->additional($additionalMeta);
}
/**
* Store a new created room
*
* @param \Illuminate\Http\Request $request
* @return \App\Http\Resources\Room|JsonResponse
*/
public function store(CreateRoom $request)
{
if (Auth::user()->hasRoomLimitExceeded()) {
abort(CustomStatusCodes::ROOM_LIMIT_EXCEEDED->value, __('app.errors.room_limit_exceeded'));
}
$room = new Room;
$room->name = $request->name;
$room->roomType()->associate($request->room_type);
$room->owner()->associate(Auth::user());
$room->save();
// Create access code if activated for this room type
if ($room->roomType->has_access_code_default) {
$room->access_code = random_int(111111111, 999999999);
}
// Create dialin pin if activated for this room type
if ($room->roomType->dialin_pin_default) {
$room->dialin_pin = random_int(11111, 99999);
}
// Apply non-expert settings of the room type
foreach (Room::ROOM_SETTINGS_DEFINITION as $setting => $config) {
if (! $config['expert']) {
$room[$setting] = $room->roomType[$setting.'_default'];
}
}
$room->save();
Log::info('Created new room {room}', ['room' => $room->getLogLabel()]);
return new \App\Http\Resources\Room($room);
}
/**
* Return all general room details
*
* @return \App\Http\Resources\Room
*/
public function show(Room $room, RoomAuthService $roomAuthService)
{
return (new \App\Http\Resources\Room($room))->withDetails();
}
/**
* Return all room settings
*
* @return RoomSettings
*/
public function getSettings(Room $room)
{
$this->authorize('viewSettings', $room);
return new RoomSettings($room);
}
/**
* Start a new meeting
*
* @return JsonResponse
*
* @throws AuthorizationException
*/
public function start(Room $room, StartMeeting $request)
{
$roomService = new RoomService($room);
$url = $roomService->start()->getJoinUrl($request);
return response()->json(['url' => $url]);
}
public function getStartRequirements(Room $room)
{
$features = [
'recording' => $room->getRoomSetting('record'),
'attendance_recording' => $room->getRoomSetting('record_attendance'),
'streaming' => $room->streaming->enabled,
];
return response()->json(['data' => ['features' => $features]]);
}
public function getJoinRequirements(Room $room)
{
$meeting = $room->latestMeeting;
$features = [
'recording' => $meeting?->record ?? false,
'attendance_recording' => $meeting?->record_attendance ?? false,
'streaming' => $meeting ? $room->streaming->enabled_for_current_meeting : false,
];
return response()->json(['data' => ['features' => $features]]);
}
/**
* Join a running meeting
*
* @return JsonResponse
*/
public function join(Room $room, JoinMeeting $request)
{
$roomService = new RoomService($room);
$url = $roomService->join()->getJoinUrl($request);
return response()->json(['url' => $url]);
}
/**
* Update room settings
*
* @return RoomSettings
*/
public function update(UpdateRoomSettings $request, Room $room)
{
$room->name = $request->name;
$room->expert_mode = $request->expert_mode;
$room->short_description = $request->short_description;
$room->access_code = $request->access_code;
$room->dialin_pin = $request->dialin_pin;
foreach (Room::ROOM_SETTINGS_DEFINITION as $setting => $config) {
// Expert mode for room is deactivated and setting is an expert setting: do not update setting
if (! $room->expert_mode && $config['expert']) {
continue;
}
$room[$setting] = $request[$setting];
}
// Save welcome message if expert mode enabled, otherwise clear
$room->welcome = $room->expert_mode ? $request->welcome : null;
$room->roomType()->associate($request->room_type);
$room->save();
Log::info('Changed settings for room {room}', ['room' => $room->getLogLabel()]);
return new RoomSettings($room);
}
/**
* Update room description
*
* @return \Illuminate\Http\Response
*/
public function updateDescription(UpdateRoomDescription $request, Room $room)
{
$room->description = $request->description;
// Remove empty paragraph (tiptop editor always outputs at least one empty paragraph)
if ($room->description == '<p></p>') {
$room->description = null;
}
$room->save();
$room->refresh();
Log::info('Changed description for room {room}', ['room' => $room->getLogLabel()]);
return response()->noContent();
}
/**
* Delete a room and all related data
*
* @return \Illuminate\Http\Response
*/
public function destroy(Room $room)
{
$room->delete();
Log::info('Deleted room {room}', ['room' => $room->getLogLabel()]);
return response()->noContent();
}
/**
* List of all meeting of the given room
*
* @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
*
* @throws AuthorizationException
*/
public function meetings(Room $room, Request $request)
{
$this->authorize('viewStatistics', $room);
// Sort by column, fallback/default is start time
$sortBy = match ($request->query('sort_by')) {
default => 'start',
};
// Sort direction, fallback/default is asc
$sortOrder = match ($request->query('sort_direction')) {
'desc' => 'DESC',
default => 'ASC',
};
// Get all meeting of the room and sort them, only meetings that are not in the starting phase
$resource = $room->meetings()->orderByRaw($sortBy.' '.$sortOrder)->whereNotNull('start');
return \App\Http\Resources\Meeting::collection($resource->paginate(app(GeneralSettings::class)->pagination_page_size));
}
/**
* add a room to the users favorites
*
* @return \Illuminate\Http\Response
*/
public function addToFavorites(Room $room)
{
Auth::user()->roomFavorites()->syncWithoutDetaching([$room->id]);
return response()->noContent();
}
/**
* delete a room from the users favorites
*
* @return \Illuminate\Http\Response
*/
public function deleteFromFavorites(Room $room)
{
Auth::user()->roomFavorites()->detach($room);
return response()->noContent();
}
/**
* transfer the room ownership to another user
*
* @return \Illuminate\Http\Response
*/
public function transferOwnership(Room $room, TransferOwnershipRequest $request)
{
$oldOwner = $room->owner;
$newOwner = User::findOrFail($request->user);
DB::beginTransaction();
try {
// delete the new owner from the members if he is a member of the room
if ($room->members->contains($newOwner)) {
$room->members()->detach($newOwner);
}
$room->owner()->associate($newOwner);
$room->save();
// add old owner to the members
if ($request->role) {
$room->members()->attach($oldOwner, ['role' => $request->role]);
}
DB::commit();
Log::info('Transferred room ownership of the room {room} from previous owner {oldOwner} to new owner {newOwner}', ['room' => $room->getLogLabel(), 'oldOwner' => $oldOwner->getLogLabel(), 'newOwner' => $newOwner->getLogLabel()]);
if ($request->role) {
Log::info('Changed role of previous owner {oldOwner} of the room {room} to the role {role}', ['oldOwner' => $oldOwner->getLogLabel(), 'room' => $room->getLogLabel(), 'role' => RoomUserRole::from($request->role)->label()]);
}
return response()->noContent();
} catch (\Exception $e) {
DB::rollBack();
Log::error('Failed to transfer ownership of the room {room} from previous owner {oldOwner} to new owner {newOwner}', ['room' => $room->getLogLabel(), 'oldOwner' => $oldOwner->getLogLabel(), 'newOwner' => $newOwner->getLogLabel()]);
return abort(500);
}
}
}