-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyoutube.php
More file actions
338 lines (312 loc) · 12.2 KB
/
Copy pathyoutube.php
File metadata and controls
338 lines (312 loc) · 12.2 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
<?php
namespace App\Meltir;
use App\Entity\GoogleTokenStorage;
use App\Entity\YtCategories;
use App\Entity\YtChannels;
use App\Entity\YtVideos;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Google_Client;
use Google_Service_YouTube;
use Doctrine\ORM\EntityManagerInterface;
/**
* Class youtube
* Import channels and vidoes using the youtube API
* Provides helpers for login functions
*
* @package App\Meltir
*/
class youtube {
public function __construct(Stopwatch $stopwatch,
LoggerInterface $logger,
Google_Client $google,
SessionInterface $session,
RequestStack $request,
RouterInterface $router,
EntityManagerInterface $manager)
{
$this->logger = $logger;
$this->stopwatch = $stopwatch;
$this->google = $google;
$this->session = $session;
$this->router = $router;
$this->manager = $manager;
if ($request->getCurrentRequest()) $this->current_route = $request->getCurrentRequest()->get('_route');
$this->google->setApplicationName('my website');
$this->google->setAccessType('offline');
$this->google->setIncludeGrantedScopes(true);
$this->google->addScope([
'https://www.googleapis.com/auth/youtube.readonly'
]);
$this->google->setRedirectUri($this->router->generate('youtube_auth',[],UrlGeneratorInterface::ABSOLUTE_URL));
$this->google_session = $session->get('google',[]);
}
/**
* @var EntityManagerInterface
*/
private $manager;
/**
* Current route is used when we need to authenticate and go back to the calling page
* @var string
*/
private $current_route = '';
/**
* @var UrlGeneratorInterface
*/
private $router;
/**
* array of
* code - return auth code recieved directly from google
* token - token generated by google from auth code
* return_route - when authorising, return to this url (this is the url that called for authorization initially)
* @var array|mixed
*/
private $google_session = [];
/**
* @var SessionInterface
*/
private $session;
/**
* @var Stopwatch
*/
private $stopwatch;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var Google_Client|null
*/
private $google = null;
/**
* @var Google_Service_YouTube|null
*/
private $youtube = null;
/**
* Check if you need to log into google or can use an existing code/token
* Returns false if you do not need to log in and can reuse existing auth
* Returns a string, which is the url of google authorization
*
* @param string $auth_route
* @return bool|string
* @todo handle errors and exceptions when processing login
*/
public function login($auth_route) {
if ($this->youtube) return false;
if ($this->checkExistingToken()) {
$this->logger->info('Refreshed or reused token');
}
$this->logger->info('Google session info:'.print_r($this->google_session,true));
if (empty($this->google_session['code']) && empty($this->google_session['token']) ) {
$this->logger->info('Google - no code or token found');
$this->google->setRedirectUri($this->router->generate($auth_route,[],UrlGeneratorInterface::ABSOLUTE_URL));
$this->google_session['return_route'] = $this->current_route;
$this->session->set('google',$this->google_session);
return $this->google->createAuthUrl();
}
if (!empty($this->google_session['token'])) {
$this->logger->info('Google - token found, authorising');
$this->google->setAccessToken($this->google_session['token']);
$this->youtube = new Google_Service_YouTube($this->google);
}
if (!empty($this->google_session['code']) && empty($this->google_session['token'])) {
$this->logger->info('Google - code found, generating token');
$this->google_session['token'] = $this->google->fetchAccessTokenWithAuthCode($this->google_session['code']);
$this->logger->info('Google - generated token'.print_r($this->google_session['token'],true));
$this->google->setAccessToken($this->google_session['token']);
$this->youtube = new Google_Service_YouTube($this->google);
$this->session->set('google',$this->google_session);
$this->storeToken($this->google_session['token']);
}
return false;
}
/**
* Put the token from google into the db
* @param $token
*/
private function storeToken($token) {
$db_token = new GoogleTokenStorage();
$db_token->setToken($token);
$db_token->setScope($token['scope']);
$this->manager->persist($db_token);
$this->manager->flush();
}
/**
* Try to fetch a token from the database, refresh it if it has expired
*
* @return bool true if token found, false if token failed to be generated
*/
private function checkExistingToken() {
if (!empty($this->google_session['token'])) return true;
$token_repo = $this->manager->getRepository(GoogleTokenStorage::class);
$last_token = $token_repo->getLastToken();
if (!$last_token) {
$this->logger->info('Have not found an existing token');
return false;
}
$this->logger->info('Found token of '.print_r($last_token->getToken(),true));
try {
$this->google->setAccessToken($last_token->getToken());
$this->youtube = new Google_Service_YouTube($this->google);
$this->google_session['token'] = $last_token->getToken();
$this->session->set('google',$this->google_session);
return true;
} catch (\Exception $e) {
try {
$refresh_token = $last_token->getToken()['refresh_token'];
$this->logger->info('Trying to refresh token with '.$refresh_token);
$token = $this->google->refreshToken($refresh_token);
$this->google_session['token'] = $token;
$this->google->setAccessToken($token);
$this->youtube = new Google_Service_YouTube($this->google);
$this->storeToken($token);
return true;
} catch (\Exception $e) {
$this->logger->error('Failed to refresh token with'.$e->getMessage());
}
}
return false;
}
/**
* Set the auth code in the session
* @param string $code
*/
public function setAuthCode($code) {
$this->logger->info('Google code set to:'.$code);
$this->google_session['code'] = $code;
$this->google_session['token'] = null;
$this->session->set('google',$this->google_session);
}
/**
* Return the route of the calling component
* @return string
*/
public function getReturnRoute() {
return $this->google_session['return_route'];
}
/**
* Read a list of subscribed channels and store them in the db,
* does not duplicate existing channels in the database
* if $nextPageToken is supplied, use this to get the particular page of the replies
* if not supplied fetches the first page of subscribed channels
* Returns null if this is the last (or only) page
*
* @param null|string $nextPageToken
* @return string|null
*/
public function updateChannelListFromYoutube($nextPageToken = null) {
$queryParams = [
'mine' => 'true',
'maxResults' => 50
];
if ($nextPageToken) {
$queryParams['pageToken'] = $nextPageToken;
}
$this->stopwatch->start('Google','listSubscriptions');
$response = $this->
youtube->
subscriptions->
listSubscriptions('snippet',$queryParams);
$this->stopwatch->stop('Google','listSubscriptions');
foreach ($response->getItems() as $item) {
$this->insertChannel($item->snippet);
}
$this->manager->flush();
$nextPageToken = $response->getNextPageToken();
return $nextPageToken;
}
/**
* Insert channel into db if does not already exists from youtube results snippet
* Fetches additional channel info (uploads playlist from youtube api)
*
* @param $snippet
* @return bool false if not inserted, true if inserted
*/
private function insertChannel($snippet) {
$chan_id = $snippet->resourceId->channelId;
$repository = $this->manager->getRepository(YtChannels::class);
$old_channel = $repository->findOneBy(['chan_id'=>$chan_id]);
if ($old_channel) return false;
$this->stopwatch->start('Google');
$contentDetails = $this->
youtube->
channels->
listChannels('contentDetails',['id'=>$chan_id]);
$this->stopwatch->stop('Google');
$upload_playlist = $contentDetails->
getItems()[0]->
contentDetails->
relatedPlaylists->
uploads;
$noneCat = $this->
manager->
getRepository(YtCategories::class)->
findOneBy(['slug'=>'todo']);
$channel = new YtChannels();
$channel->setCategory($noneCat);
$channel->setThumb($snippet->thumbnails->high->url);
$channel->setChanName($snippet->title);
$channel->setChanId($chan_id);
$channel->setUploadPlaylist($upload_playlist);
$channel->setChanDescription($snippet->description);
$this->manager->persist($channel);
return true;
}
/**
* Fetch latest videos for active youtube channels, starting from $page
*
* @param int $page
* @return bool true if there are more batches to process, false if this is the last batch to process
*/
public function addLatestVideos(int $page = 1) {
$channels_repo = $this->manager->getRepository(YtChannels::class);
$per_page = 10;
if ($page == 1) $startRow = 0;
else $startRow = ($page-1)*$per_page;
$channels = $channels_repo->findActiveChannels($startRow,$per_page);
foreach ($channels as $channel) {
$this->addLatestVideosForChannel($channel);
}
if (count($channels) < $per_page) return false;
return true;
}
/**
* Add videos to specified channel from youtube API
* Does not create duplicate videos
*
* @param YtChannels $channel
* @throws \Exception
*/
public function addLatestVideosForChannel(YtChannels $channel) {
$this->stopwatch->start('Google');
$playlist = $this->
youtube->
playlistItems->
listPlaylistItems('snippet',[
'playlistId'=>$channel->getUploadPlaylist(),
'maxResults'=>30
]);
$this->stopwatch->stop('Google');
$video_repository = $this->manager->getRepository(YtVideos::class);
foreach ($playlist->getItems() as $item) {
if (!$video_repository->findBy(['videoid'=>$item->snippet->resourceId->videoId])) {
$video = new YtVideos();
$img_url = $item->snippet->thumbnails->high->url;
if ($item->snippet->thumbnails->standard) $img_url = $item->snippet->thumbnails->standard->url;
$video->setThumb($img_url);
$video->setChannel($channel);
$video->setTitle($item->snippet->title);
$video->setVideoid($item->snippet->resourceId->videoId);
$video->setActive(true);
$video->setDatePublished(new \DateTime($item->snippet->publishedAt));
$video->setLiked(false);
$this->manager->persist($video);
}
}
$this->manager->flush();
}
}