-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathYoutubeScraper.php
269 lines (244 loc) · 8.16 KB
/
YoutubeScraper.php
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
<?php
namespace App\Services;
use App\Models\Channel;
use App\Models\Statistic;
use App\Models\Tag;
use App\Models\Video;
class YoutubeScraper
{
const URI = 'https://www.googleapis.com/youtube/v3/';
const MAX_RESULTS = 50;
private Channel $channel;
private Video $video;
private Statistic $statistic;
private Tag $tag;
public function __construct(Channel $channel, Video $video, Statistic $statistic, Tag $tag)
{
$this->channel = $channel;
$this->video = $video;
$this->statistic = $statistic;
$this->tag = $tag;
}
/**
* @param string $channelId
* @param string|null $pageToken
*
* @return array
*/
public function scrapeChannel(string $channelId, string $pageToken = null)
{
$channelContent = file_get_contents(
self::URI
. 'search'
. '?part=snippet'
. '&channelId=' . $channelId
. '&maxResults=' . self::MAX_RESULTS
. '&pageToken=' . $pageToken
. '&order=date'
. '&type=video'
. '&key=' . env('YOUTUBE_API_KEY')
);
return json_decode($channelContent, true);
}
/**
* @param string $ids
* @return array
*/
public function scrapeVideos(string $ids)
{
$videos = file_get_contents(
self::URI
. 'videos'
. '?part=snippet,statistics'
. '&id=' . $ids
. '&key=' . env('YOUTUBE_API_KEY')
);
return json_decode($videos, true);
}
/**
* @param array $channelContent
* @return string
*/
public function makeVideoIds(array $channelContent)
{
$ids = [];
foreach ($channelContent['items'] as $item) {
$ids[] = $item['id']['videoId'];
}
return implode(',', $ids);
}
/**
* @param string $channelId
* @param array $channelContent
*/
public function saveChannel(string $channelId, array $channelContent)
{
$channel = $this->channel->find($channelId);
if (!$channel) {
$this->channel->create(
[
'id' => $channelId,
'title' => $channelContent['items'][0]['snippet']['channelTitle'],
]
);
}
}
/**
* @param array $videoContent
*/
public function saveVideos(array $videoContent)
{
foreach ($videoContent['items'] as $item) {
$video = $this->video->where('video_id', $item['id'])->first();
if (!$video) {
$video = $this->video->create(
[
'video_id' => $item['id'],
'channel_id' => $item['snippet']['channelId'],
'title' => $item['snippet']['title'],
'description' => $item['snippet']['description'],
]
);
}
if (isset($item['snippet']['tags'])) {
$this->saveVideoTags($video, $item['snippet']['tags']);
}
if (isset($item['statistics'])) {
$this->saveVideoStatistics($video, $item['statistics']);
}
}
}
/**
* @param Video $video
* @param array $statistics
*/
private function saveVideoStatistics(Video $video, array $statistics)
{
$this->statistic->create(
[
'video_id' => $video->id,
'views' => $statistics['viewCount'],
'likes' => $statistics['likeCount'],
'dislikes' => $statistics['dislikeCount'],
'favorites' => $statistics['favoriteCount'],
'comments' => $statistics['commentCount'],
]
);
}
/**
* @param Video $video
* @param array $tags
*/
private function saveVideoTags(Video $video, array $tags)
{
foreach ($tags as $name) {
$tag = $this->tag->where('name', $name)->first();
if (!$tag) {
$tag = $this->tag->create(['name' => $name]);
}
$video->tags()->syncWithoutDetaching($tag);
}
}
/**
* TODO: experimental code
*
* @param string $order {date|rating|relevance|title|videoCount|viewCount }
*
* This method allows us to scrape as many channels as API allows
* Currently it shows about 1M channels available
* In order to scrape even more channels we can variate with ordering thru $order param
* This approach should scrape more or less all Youtube channels
* The only problem is quota available :)
*/
public function scrapeChannelsMassively(string $order)
{
$channelsContent = $this->searchChannels($order);
$this->processChannels($channelsContent);
$totalChannelsScrapped = count($channelsContent['items']);
while (
$totalChannelsScrapped < $channelsContent['pageInfo']['totalResults']
&& isset($channelsContent['nextPageToken'])
) {
$channelsContent = $this->searchChannels(
$order,
$channelsContent['nextPageToken']
);
$this->processChannels($channelsContent);
$totalChannelsScrapped += count($channelsContent['items']);
}
}
/**
* TODO: experimental code
*
* @param array $channelsContent
*/
private function processChannels(array $channelsContent)
{
foreach ($channelsContent['items'] as $channel) {
$channelId = $channel['snippet']['channelId'];
// TODO: proceed with $channelId according to needs - scrape videos, statistics
}
}
/**
* TODO: experimental code
*
* @param string $order
* @param string|null $pageToken
*
* @return array Example API response:
{
"kind": "youtube#searchListResponse",
"etag": "\"xwzn9fn_LczrfK9QS3iZcGzqRGs/qHAKWpatdr_yUt4QRoXkjSx8LLA\"",
"nextPageToken": "CAEQAA",
"regionCode": "LT",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": N
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"xwzn9fn_LczrfK9QS3iZcGzqRGs/b7zszVbkH9MiAYE0IOwAHA_9HPc\"",
"id": {
"kind": "youtube#channel",
"channelId": "UC2OacIzd2UxGHRGhdHl1Rhw"
},
"snippet": {
"publishedAt": "2019-06-26T09:40:35.000Z",
"channelId": "UC2OacIzd2UxGHRGhdHl1Rhw",
"title": "早瀬 走 / Hayase Sou【にじさんじ所属】",
"description": "にじさんじ所属のバーチャルライバー早瀬 走(ハヤセ ソウ)です! 多趣味の陽キャです! どうぞ皆さんよろしくお願いします。 【早瀬 走】...",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/-BF5rMquYDjc/AAAAAAAAAAI/AAAAAAAAAAA/aa3jpBEKeZ8/s88-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"medium": {
"url": "https://yt3.ggpht.com/-BF5rMquYDjc/AAAAAAAAAAI/AAAAAAAAAAA/aa3jpBEKeZ8/s240-c-k-no-mo-rj-c0xffffff/photo.jpg"
},
"high": {
"url": "https://yt3.ggpht.com/-BF5rMquYDjc/AAAAAAAAAAI/AAAAAAAAAAA/aa3jpBEKeZ8/s800-c-k-no-mo-rj-c0xffffff/photo.jpg"
}
},
"channelTitle": "早瀬 走 / Hayase Sou【にじさんじ所属】",
"liveBroadcastContent": "upcoming"
}
}
],
... N items
}
*/
private function searchChannels(string $order, string $pageToken = null)
{
$channelContent = file_get_contents(
self::URI
. 'search'
. '?part=snippet'
. '&maxResults=' . self::MAX_RESULTS
. '&pageToken=' . $pageToken
. '&order=' . $order
. '&type=channel'
. '&key=' . env('YOUTUBE_API_KEY')
);
return json_decode($channelContent, true);
}
}