1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BeyondCode\LaravelWebSockets\API; |
4
|
|
|
|
5
|
|
|
use BeyondCode\LaravelWebSockets\Channels\Channel; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
use stdClass; |
9
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException; |
10
|
|
|
|
11
|
|
|
class FetchChannels extends Controller |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Handle the incoming request. |
15
|
|
|
* |
16
|
|
|
* @param \Illuminate\Http\Request $request |
17
|
|
|
* @return \Illuminate\Http\Response |
18
|
|
|
*/ |
19
|
|
|
public function __invoke(Request $request) |
20
|
|
|
{ |
21
|
|
|
$attributes = []; |
22
|
|
|
|
23
|
|
|
if ($request->has('info')) { |
24
|
|
|
$attributes = explode(',', trim($request->info)); |
25
|
|
|
|
26
|
|
|
if (in_array('user_count', $attributes) && ! Str::startsWith($request->filter_by_prefix, 'presence-')) { |
27
|
|
|
throw new HttpException(400, 'Request must be limited to presence channels in order to fetch user_count'); |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
return $this->channelManager |
32
|
|
|
->getGlobalChannels($request->appId) |
33
|
|
|
->then(function ($channels) use ($request, $attributes) { |
34
|
|
|
$channels = collect($channels)->keyBy(function ($channel) { |
35
|
|
|
return $channel instanceof Channel |
36
|
|
|
? $channel->getName() |
37
|
|
|
: $channel; |
38
|
|
|
}); |
39
|
|
|
|
40
|
|
|
if ($request->has('filter_by_prefix')) { |
41
|
|
|
$channels = $channels->filter(function ($channel, $channelName) use ($request) { |
42
|
|
|
return Str::startsWith($channelName, $request->filter_by_prefix); |
43
|
|
|
}); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$channelNames = $channels->map(function ($channel) { |
47
|
|
|
return $channel instanceof Channel |
48
|
|
|
? $channel->getName() |
49
|
|
|
: $channel; |
50
|
|
|
})->toArray(); |
51
|
|
|
|
52
|
|
|
return $this->channelManager |
53
|
|
|
->getChannelsMembersCount($request->appId, $channelNames) |
54
|
|
|
->then(function ($counts) use ($channels, $attributes) { |
55
|
|
|
$channels = $channels->map(function ($channel) use ($counts, $attributes) { |
56
|
|
|
$info = new stdClass; |
57
|
|
|
|
58
|
|
|
$channelName = $channel instanceof Channel |
59
|
|
|
? $channel->getName() |
60
|
|
|
: $channel; |
61
|
|
|
|
62
|
|
|
if (in_array('user_count', $attributes)) { |
63
|
|
|
$info->user_count = $counts[$channelName]; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $info; |
67
|
|
|
})->sortBy(function ($content, $name) { |
68
|
|
|
return $name; |
69
|
|
|
})->all(); |
70
|
|
|
|
71
|
|
|
return [ |
72
|
|
|
'channels' => $channels ?: new stdClass, |
73
|
|
|
]; |
74
|
|
|
}); |
75
|
|
|
}); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|