-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShowManager.php
641 lines (577 loc) · 18.6 KB
/
ShowManager.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
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
<?php
namespace Drupal\kcts9_media_manager;
use DateTime;
use DateTimeZone;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LoggerChannelInterface;
use Drupal\Core\Queue\QueueFactory;
use Drupal\Core\State\StateInterface;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Drupal\node\NodeInterface;
use Drupal\taxonomy\Entity\Term;
use Exception;
use stdClass;
/**
* Class ShowManager.
*
* @package Drupal\kcts9_media_manager
*/
class ShowManager extends ApiContentManagerBase {
/**
* Genre term bundle machine name.
*/
const GENRE_BUNDLE = 'genre';
/**
* State key for the last update DateTime.
*/
const LAST_UPDATE_KEY = 'kcts9_media_manager.shows.last_update';
/**
* All Genre taxonomy term entities.
*
* @var array
*/
private $genres;
/**
* ApiQueueController constructor.
*
* @param \Drupal\kcts9_media_manager\ApiClient $client
* Media Manager API client service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Entity type manager service.
* @param \Drupal\Core\Logger\LoggerChannelInterface $logger
* Logger channel service.
* @param \Drupal\Core\Queue\QueueFactory $queue_factory
* Queue factory service.
* @param \Drupal\Core\State\StateInterface $state
* State service.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function __construct(
ApiClient $client,
EntityTypeManagerInterface $entity_type_manager,
LoggerChannelInterface $logger,
QueueFactory $queue_factory,
StateInterface $state
) {
parent::__construct($client, $entity_type_manager, $logger, $queue_factory, $state);
$this->genres = $this->getGenres();
}
/**
* {@inheritdoc}
*/
public static function getEntityTypeId(): string {
return 'node';
}
/**
* {@inheritdoc}
*/
public static function getBundleId(): string {
return 'show';
}
/**
* {@inheritdoc}
*/
public static function getQueueName(): string {
return 'kcts9_media_manager.queue.shows';
}
/**
* {@inheritdoc}
*/
public function getLastUpdateTime(): DateTime {
return $this->state->get(
self::LAST_UPDATE_KEY,
new DateTime('@1')
);
}
/**
* {@inheritdoc}
*/
public function setLastUpdateTime(DateTime $time): void {
$this->state->set(self::LAST_UPDATE_KEY, $time);
}
/**
* {@inheritdoc}
*/
public function resetLastUpdateTime(): void {
$this->state->delete(self::LAST_UPDATE_KEY);
}
/**
* {@inheritdoc}
*/
public static function getAutoUpdateConfigName(): string {
return 'shows.queue.autoupdate';
}
/**
* {@inheritdoc}
*/
public static function getAutoUpdateIntervalConfigName(): string {
return 'shows.queue.autoupdate_interval';
}
/**
* Gets all existing Genre entities from the database.
*
* @return array
* Genre entities keyed by Media Manager GUID.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
private function getGenres(): array {
$definition = $this->entityTypeManager->getDefinition('taxonomy_term');
$storage = $this->entityTypeManager->getStorage('taxonomy_term');
/** @var \Drupal\taxonomy\Entity\Term[] $entities */
$entities = $storage->loadByProperties([
$definition->getKey('bundle') => self::GENRE_BUNDLE,
]);
// Re-key by Media Manager GUID.
$genres = [];
foreach ($entities as $entity) {
$genres[$entity->get(self::GUID_FIELD_NAME)->value] = $entity;
}
return $genres;
}
/**
* Gets an existing Genre term (creating a new one if necessary).
*
* This method also adds the newly created genre to the self::genres array so
* it can be reused with further objects processed by this class.
*
* @param string $guid
* Media Manager GUID for the Genre.
* @param string $name
* Genre name.
* @param string $slug
* Genre slug.
*
* @return \Drupal\Core\Entity\EntityInterface
* A Genre term.
*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityStorageException
*/
private function getOrAddGenre(string $guid, string $name, string $slug): EntityInterface {
if (isset($this->genres[$guid])) {
$genre = $this->genres[$guid];
}
else {
$definition = $this->entityTypeManager->getDefinition('taxonomy_term');
$genre = Term::create([
$definition->getKey('bundle') => self::GENRE_BUNDLE,
]);
$genre->setName($name);
$genre->set(self::GUID_FIELD_NAME, $guid);
$genre->set('field_slug', $slug);
$genre->save();
$this->genres[$guid] = $genre;
}
return $genre;
}
/**
* {@inheritdoc}
*
* @throws \Exception
*/
public function updateQueue(DateTime $since = NULL): bool {
$dt_start = new DateTime();
if (empty($since)) {
$since = $this->getLastUpdateTime();
}
// This query cannot sort by update time. Results must be fully traversed.
$shows = $this->client->getShows(['fetch-related' => FALSE]);
foreach ($shows as $show) {
$updated_at = self::getLatestUpdatedAt($show);
if ($updated_at > $since) {
$this->getQueue()->createItem($show);
}
}
$this->setLastUpdateTime($dt_start);
return TRUE;
}
/**
* Gets an API response for a single Show.
*
* @param string $guid
* GUID of the Show to get.
*
* @return object|null
* Show item data from the API or NULL.
*/
public function getShow(string $guid): ?stdClass {
return $this->client->getShow($guid);
}
/**
* Get Show nodes with optional properties.
*
* @param array $properties
* Properties to filter Show nodes.
*
* @return \Drupal\node\NodeInterface[]
* Shows nodes.
*/
public function getShowNodes(array $properties = []): array {
try {
$definition = $this->entityTypeManager->getDefinition(self::getEntityTypeId());
$storage = $this->entityTypeManager->getStorage(self::getEntityTypeId());
$nodes = $storage->loadByProperties([
$definition->getKey('bundle') => self::getBundleId(),
] + $properties);
}
catch (Exception $e) {
// Let NULL fall through.
$nodes = [];
}
return $nodes;
}
/**
* Gets a Show node by TMS ID.
*
* @param string $id
* TMS ID to query with.
*
* @return \Drupal\node\NodeInterface|null
* Show node with TMS ID or NULL if none found.
*/
public function getShowNodeByTmsId(string $id): ?NodeInterface {
$nodes = $this->getShowNodes(['field_show_tms_id' => $id]);
$node = NULL;
if (!empty($nodes)) {
$node = reset($nodes);
if (count($nodes) > 1) {
$this->logger->error('Multiple nodes found for Media Manager
TMS ID {id}. Node IDs found: {nid_list}. Using node {nid}.', [
'id' => $id,
'nid_list' => implode(', ', array_keys($nodes)),
'nid' => $node->id(),
]);
}
}
return $node;
}
/**
* Gets a Show node by slug.
*
* @param string $slug
* Slug to query with.
*
* @return \Drupal\node\NodeInterface|null
* Show node with the slug or NULL if none found.
*/
public function getShowNodeBySlug(string $slug): ?NodeInterface {
$nodes = $this->getShowNodes(['field_show_slug' => $slug]);
$node = NULL;
if (!empty($nodes)) {
$node = reset($nodes);
}
return $node;
}
/**
* Adds or updates a Show node based on API data.
*
* @param object $item
* An API response object for the Show.
*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityStorageException
* @throws \Exception
*/
public function addOrUpdateShow(object $item): void {
$node = $this->getOrCreateNode($item->id, self::getBundleId());
$attributes = $item->attributes;
$updated_at = self::getLatestUpdatedAt($item);
$updated_at->setTimezone(new DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
$images = $this->parseImages($attributes->images);
$node->setTitle($attributes->title);
$node->set('field_show_slug', $attributes->slug);
$node->set(self::GUID_FIELD_NAME, $item->id);
$node->set('field_show_tms_id', $attributes->tms_id);
$node->set(
'field_show_updated',
$updated_at->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT)
);
$node->set('field_description', [
'value' => $attributes->description_long,
'summary' => $attributes->description_short,
]);
$node->set('field_episode_count', $attributes->episodes_count);
// Capture the _first_ recognized audience scope based on the field's
// allowed values list. Multiple scopes are possible, but for now this
// functionality is really only used as a method to catch and disable Shows
// with an audience of "kids".
if (!empty($attributes->audience)) {
$audience_scope = $node->getFieldDefinition('field_audience_scope');
$allowed_values = $audience_scope->getSetting('allowed_values');
foreach ($attributes->audience as $audience) {
if (isset($allowed_values[$audience->scope])) {
$node->set('field_audience_scope', $audience->scope);
break;
}
}
}
if (!empty($attributes->genre)) {
$node->set('field_genre', $this->getOrAddGenre(
$attributes->genre->id,
$attributes->genre->title,
$attributes->genre->slug
));
}
else {
$node->set('field_genre', NULL);
}
if (!empty($attributes->premiered_on)) {
$node->set('field_premiere_date', $attributes->premiered_on);
}
else {
$node->set('field_premiere_date', NULL);
}
if (!empty($attributes->franchise)) {
$node->set('field_show_franchise_id', $attributes->franchise->id);
}
else {
$node->set('field_show_franchise_id', NULL);
}
if (isset($images['show-mezzanine16x9'])) {
$node->set('field_show_mezzanine', $images['show-mezzanine16x9']);
$node->set('field_show_mezz_original', $images['show-mezzanine16x9']);
}
elseif (isset($images['show-kids-16x9'])) {
$node->set('field_show_mezzanine', $images['show-kids-16x9']);
$node->set('field_show_mezz_original', $images['show-kids-16x9']);
}
else {
$node->set('field_show_mezzanine', NULL);
$node->set('field_show_mezz_original', NULL);
}
// Attempt to replace the default mezzanine with the latest episode/video.
$this->updateShowMezzanine($node);
$node->set(
'field_latest_episode',
['target_id' => $this->getLatestEpisodeId($node)]
);
if (isset($images['show-poster2x3'])) {
$node->set('field_show_poster', $images['show-poster2x3']);
}
else {
$node->set('field_show_poster', NULL);
}
// _All_ content with a "kids" audience scope will be unpublished. This data
// is in the API primarily to support PBS's own pbskids.org website and the
// Assets related to these Shows are never available for embed (despite what
// other API data says). Note: the computed field "publishable" is not used
// here because it will not work for newly added (unsaved) nodes.
if ($node->get('field_audience_scope')->value === 'kids') {
$node->setUnpublished();
}
// If no Video Content related to this Show is available or scheduled to be
// available, unpublish it.
elseif (empty($this->getVideoContent($node, TRUE))) {
$node->setUnpublished();
}
else {
$node->setPublished();
}
$node->save();
}
/**
* Updates a Show node mezzanine from the latest Video Content child node.
*
* This method modifies the `field_show_mezzanine` field on the Show node, but
* _does not_ save the modified node.
*
* @param \Drupal\node\NodeInterface &$show
* Show node to update.
*
* @return bool
* TRUE if the Show node was updated, FALSE otherwise.
*/
public function updateShowMezzanine(NodeInterface &$show): bool {
$node_updated = FALSE;
// Get the latest full length episode to feature on the show mezzanine.
if (!$latestEpisode = $this->getLatestEpisodeId($show)) {
// Get the latest video of any type if a full episode is not available.
$latestEpisode = $this->getLatestVideoWithImage($show);
}
if (!empty($latestEpisode)) {
// Set show mezzanine to use the image from the latest episode or video.
/** @var \Drupal\node\NodeInterface $video_content */
$video_content = $this->initStorage($show)->load($latestEpisode);
$show->set(
'field_show_mezzanine',
$video_content->get('field_video_image')->value
);
$node_updated = TRUE;
}
return $node_updated;
}
/**
* Gets the NID of the latest episode of a Show.
*
* Identifies the latest Video Content node that is a published, full length
* episode.
*
* @param \Drupal\node\NodeInterface $show
* The show being updated.
*
* @return int
* The node id of the latest episode or an empty string.
*/
public function getLatestEpisodeId(NodeInterface $show) {
// Initialize the query object. Exit early if there are any problems.
if (!$query = $this->initQuery($show)) {
return '';
}
// Fetch the most recent full length episode by season and ordinal.
$query->condition('type', VideoContentManager::getBundleId())
->condition('status', 1)
->condition('field_show_ref', $show->id())
->condition('field_video_type', 'episode')
->condition('field_video_object_type', 'full_length')
->sort('field_video_content_season', 'DESC')
->sort('field_ordinal_number', 'DESC')
->range(0, 1);
// Query results return an array of node ids or an empty string.
$results = $query->execute();
$nid = reset($results);
return $nid ? $nid : '';
}
/**
* Gets the NID of the latest video _with an image_ for a Show.
*
* Identifies the latest Video Content node that is a published item of any
* type.
*
* @param \Drupal\node\NodeInterface $show
* The show being updated.
*
* @return int
* The node id of the latest episode or an empty string.
*/
protected function getLatestVideoWithImage(NodeInterface $show) {
// Initialize the query object. Exit early if there are any problems.
if (!$query = $this->initQuery($show)) {
return '';
}
// Fetch the most recent video that includes a image by field_premiere_date.
// This video may be a clip or a preview.
$query->condition('type', VideoContentManager::getBundleId())
->condition('status', 1)
->condition('field_show_ref', $show->id())
->exists('field_video_image')
->sort('field_video_content_season', 'DESC')
->sort('field_ordinal_number', 'DESC')
->sort('field_last_updated', 'DESC')
->range(0, 1);
// Query results return an array of node ids or an empty string.
$results = $query->execute();
$nid = reset($results);
return $nid ? $nid : '';
}
/**
* Get an instance of the entity storage object for a content type.
*
* @param \Drupal\node\NodeInterface $show
* The show being updated.
*
* @return \Drupal\Core\Entity\EntityStorageInterface|null
* An instance of an entity storage object.
*/
protected function initStorage(NodeInterface $show) {
$storage = NULL;
if ($show->bundle() != $this->getBundleId()) {
$this->logger->notice($this->t(
'Invalid Show node bundle: @bundle.', ['@bundle' => $show->bundle()]
));
return $storage;
}
try {
$storage = $this->entityTypeManager
->getStorage(VideoContentManager::getEntityTypeId());
}
catch (Exception $e) {
watchdog_exception('kcts9_media_manager', $e);
}
return $storage;
}
/**
* Get an instance of the entity query object for a content type.
*
* @param \Drupal\node\NodeInterface $show
* The show being updated.
*
* @return \Drupal\Core\Entity\Query\QueryInterface|null
* An instance of an entity query object.
*/
protected function initQuery(NodeInterface $show) {
$query = NULL;
if ($storage = $this->initStorage($show)) {
$query = $storage->getQuery();
}
return $query;
}
/**
* Gets IDs of available (published) Video Content nodes related to a Show.
*
* @param \Drupal\node\NodeInterface $show
* Show node.
* @param bool $include_scheduled
* Whether to include include Video Content scheduled in the future (via the
* contrib module Scheduler).
*
* @return array
* Node IDs of related Video Content nodes.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function getVideoContent(
NodeInterface $show,
bool $include_scheduled = FALSE
): array {
$definition = $this->entityTypeManager
->getDefinition(VideoContentManager::getEntityTypeId());
$query = $this->entityTypeManager
->getStorage(VideoContentManager::getEntityTypeId())
->getQuery();
$query
->condition($definition->getKey('bundle'), VideoContentManager::getBundleId())
->condition('field_show_ref', $show->id());
if ($include_scheduled) {
$now = new DrupalDateTime();
$now->setTimezone(new DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
$or = $query->orConditionGroup();
$or->condition('status', 1);
$or->condition('publish_on', $now->getTimestamp(), '>');
$query->condition($or);
}
else {
$query->condition('status', 1);
}
return $query->execute();
}
/**
* Determines if a Show is suitable for publishing consideration.
*
* Note: This method does not determine whether or not a Show should be
* published. It determines if the Show should be _considered_ for publishing.
*
* Currently, the only requirement for a Show to be publishable is that it
* does not have an audience scope of "kids".
*
* @param \Drupal\node\NodeInterface $show
* Show node.
*
* @return bool
* TRUE if the Show is publishable, FALSE otherwise.
*/
public static function showIsPublishable(NodeInterface $show): bool {
$field = 'field_audience_scope';
if ($show->hasField($field) && !$show->get($field)->isEmpty()
&& $show->get($field)->value === 'kids') {
return FALSE;
}
return TRUE;
}
}