-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessPodcastSubscriptions.module
More file actions
588 lines (496 loc) · 16.5 KB
/
ProcessPodcastSubscriptions.module
File metadata and controls
588 lines (496 loc) · 16.5 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
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
<?php
/**
* COPYRIGHT NOTICE
* Copyright (c) 2023 Neue Rituale GbR
* @author NR <code@neuerituale.com>
*/
namespace ProcessWire;
use Lukaswhite\PodcastFeedParser\Exceptions\FileNotFoundException;
use Lukaswhite\PodcastFeedParser\Exceptions\InvalidXmlException;
use Lukaswhite\PodcastFeedParser\Parser;
use Lukaswhite\PodcastFeedParser\Podcast;
/**
* @method void processPodcast(WireData $feed, Podcast $podcast)
* @method array filterDbFeedInput(string $feedUrl, Podcast $podcast)
* @method array filterDbFeedUpdate(int $id, Podcast $podcast)
* @method Parser getFeedParserInstance($args = null)
*/
class ProcessPodcastSubscriptions extends Process implements Module, ConfigurableModule {
const dbTableName = 'podcast_subscriptions';
const logFileName = 'podcast-subscriptions';
const SCHEMA_VERSION = 2;
private ?WireArray $feedsCache = null;
public static function getModuleInfo(): array {
return [
'title' => 'Process Podcast Subscriptions',
'version' => 104,
'summary' => 'Subscribe Podcast RSS feed and save as new page',
'icon' => 'clock-o',
'requires' => ['LazyCron'],
'permission' => 'podcast-subscriptions',
'singular' => true,
'autoload' => true,
'page' => [
'name' => 'podcast-subscriptions',
'parent' => 'admin',
'title' => __('Podcasts'),
],
];
}
/**
* Init
* @return void
* @throws WireException
*/
public function init() {
// set initial schema version
if(!$this->schemaVersion) $this->schemaVersion = 1;
// update the database schema (if not the latest one yet)
if($this->schemaVersion < self::SCHEMA_VERSION) $this->updateDatabaseSchema();
// build subscription links array
$subscriptionLinks = [];
if(!empty($this->subscriptionLinksConfig)) {
$links = explode("\n", $this->subscriptionLinksConfig);
foreach($links as $link) {
list($name, $label) = array_map('trim', explode('=', $link, 2));
$subscriptionLinks[$name] = $label;
}
}
$this->subscriptionLinks = $subscriptionLinks;
// find hookname and init lazy cron hook
$hookName = $this->timeFuncs[$this->cronSchedule] ?? false;
if($hookName && $this->modules->isInstalled('LazyCron')) $this->addHook('LazyCron::' . $hookName, $this, 'updateAllFeeds');
}
/**
* Ready
* @return void
*/
public function ready() {
// add css in Backend
if($this->page->template->name === 'admin') $this->config->styles->add($this->config->urls->ProcessPodcastSubscriptions . "ProcessPodcastSubscriptions.css");
// hook field options for field podcast
if($this->modules->isInstalled('FieldtypeDynamicOptions') && $this->fields->has('podcast')) {
$this->wire->addHookAfter('FieldtypeDynamicOptions::getSelectableOptions', $this, 'hookPodcastFieldOptions');
}
}
/** VIEWS */
/**
* Show table
* @return array|null
* @throws WirePermissionException|WireException
*/
public function ___execute() : ?array {
// Add new feed
if($this->session->CSRF->hasValidToken()) {
// submit feed
if($this->input->post('submit')) {
$feedUrl = $this->input->post('feed_url', 'url');
try {
$this->addFeed($feedUrl);
} catch(\Exception $exception) {
$this->error($exception->getMessage());
}
}
// update feed info
elseif($this->input->post('feedmeta')) {
$feedId = $this->input->post('feedId', 'int');
$meta = $this->processMetaInput();
$feed = $this->getFeeds('id='.$feedId)->first();
if($feed instanceof Feed) $this->updateFeedMeta($feed, $meta);
}
}
return [
'feeds' => $this->getFeeds(),
'subscriptionLinks' => $this->subscriptionLinks,
'meta' => $this->meta
];
}
/**
* Manual update
* @return void
* @throws WireException
* @throws FileNotFoundException
* @throws InvalidXmlException
*/
public function ___executeUpdate() {
$id = $this->sanitizer->int($this->input->urlSegment2);
$feed = $this->updateFeed($id);
$this->message(sprintf($this->_('Podcast "%s" updated'), $feed->title));
$this->session->redirect($this->page->url);
}
/**
* Delete Feed
* @return void
* @throws WireException
*/
public function ___executeDelete() {
$id = $this->sanitizer->int($this->input->urlSegment2);
if($this->deleteFeed($id)) $this->message($this->_('Podcast deleted'));
$this->session->redirect($this->page->url);
}
/** CONTROL */
/**
* @param string $feedUrl
* @return Podcast
* @throws WireException
* @throws FileNotFoundException
* @throws InvalidXmlException
*/
public function addFeed(string $feedUrl = '') : Podcast {
// check url
if(empty($feedUrl)) throw new \Exception($this->_('Empty feed url'));
// duplication check
$checkStatement = $this->database->prepare('SELECT * FROM ' . self::dbTableName . ' WHERE feed_url=:feedUrl');
$checkStatement->execute(['feedUrl' => $feedUrl]);
if($checkStatement->fetchColumn(0)) throw new \Exception($this->_('Feed already exists'));
// check feed
$podcast = $this->fetchAndParseFeed($feedUrl);
if(!$podcast) throw new \Exception($this->_('Invalid feed, no type found.'));
// add to db
$addStatement = $this->database->prepare('INSERT INTO ' . self::dbTableName . ' (title,description,artwork_url,feed_url,media_count) VALUE (:title,:description,:artwork_url,:feed_url,:media_count)');
$dbFeedInput = $this->filterDbFeedInput($feedUrl, $podcast);
$addStatement->execute($dbFeedInput);
$this->message(sprintf($this->_('Podcast "%s" added'), $dbFeedInput['title']));
// processPodcast
$feed = $this->getFeeds('feed_url=' . $feedUrl)->first();
if($feed) $this->processPodcast($feed, $podcast);
return $podcast;
}
/**
* @param int $id
* @param bool $flushFeedCache
* @return bool|mixed|Wire
* @throws WireException
* @throws FileNotFoundException
* @throws InvalidXmlException
*/
public function updateFeed(int $id, bool $flushFeedCache = true) {
// find feed
$feed = $this->getFeeds('id=' . $id)->first();
if(!$feed) throw new \Exception($this->_('Invalid feed id'));
$podcast = $this->fetchAndParseFeed($feed->feed_url);
// Update feed in db and the wireData for return
$updateStatement = $this->database->prepare('UPDATE '.self::dbTableName.' SET title=:title, description=:description, artwork_url=:artwork_url, media_count=:media_count, modified=:modified WHERE id=:id;');
$dbFeedUpdate = $this->filterDbFeedUpdate($id, $podcast);
$updateStatement->execute($dbFeedUpdate);
$feed->setArray($dbFeedUpdate);
// flush feedcache
if($flushFeedCache) $this->feedsCache = null;
// process podcast
$this->processPodcast($feed, $podcast);
return $feed;
}
/**
* Update all feeds
* @return $this
* @throws WireException
* @throws FileNotFoundException
* @throws InvalidXmlException
*/
public function updateAllFeeds() : ProcessPodcastSubscriptions {
$feeds = $this->getFeeds('', true);
foreach($feeds as $feed) {
try { $this->updateFeed($feed->id, false); }
catch ( \Exception $exception ) { $this->log('Error:' . $exception->getMessage(), ['name' => self::logFileName]); }
}
$this->feedsCache = null;
return $this;
}
/**
* @param string $selector
* @param bool $fresh
* @return WireArray
*/
public function getFeeds(string $selector = '', bool $fresh = false) : ?WireArray {
$result = $this->feedsCache;
if($fresh || !($result instanceof WireArray)) {
$result = new WireArray();
// Get from database
$statement = $this->database->prepare('SELECT * FROM ' . self::dbTableName);
$statement->execute();
$items = $statement->fetchAll(\PDO::FETCH_CLASS, Feed::class);
if(!is_array($items)) {
$this->feedsCache = null;
return $result;
}
$result = WireArray::newInstance($items);
$this->feedsCache = $result;
}
return empty($selector) ? $result : $result->find($selector);
}
/**
* Delete feed by id
* @param int $id
* @return bool
* @throws WireException|\Exception
*/
public function deleteFeed(int $id) : bool {
$feed = $this->getFeeds('id=' . $id)->first();
if(!$feed) throw new \Exception($this->_('Invalid feed id'));
$statement = $this->database->prepare('DELETE FROM '.self::dbTableName.' WHERE id=:id');
$statement->bindValue('id', $feed->id, \PDO::PARAM_INT);
return $statement->execute();
}
/**
* @param Feed $feed
* @param array $meta
* @return Feed
*/
public function updateFeedMeta(Feed $feed, array $meta = []): Feed {
$json = count($meta)
? json_encode($meta, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)
: 'null'
;
$updateStatement = $this->database->prepare('UPDATE '.self::dbTableName.' SET meta=:meta WHERE id=:id;');
$updateStatement->execute([
'id' => $feed->id,
'meta' => $json
]);
// decode in Feed::class because of same behavior of data
return $feed->set('meta', $json);
}
/**
* @param $feedUrl
* @return Podcast|null
* @throws InvalidXmlException
*/
public function fetchAndParseFeed($feedUrl) : ?Podcast {
$fileContent = $this->files->fileGetContents($feedUrl);
if(!$fileContent) throw new \Exception(sprintf($this->_("Invalid feed url: %s"), $feedUrl ?: ''));
libxml_use_internal_errors(true);
$parser = $this->getFeedParserInstance();
$parser->setContent($fileContent);
$podcast = $parser->run();
return $podcast->getTitle() ? $podcast : null;
}
/**
* @param WireData $feed
* @param Podcast $podcast
* @return void
*/
public function ___processPodcast(WireData $feed, Podcast $podcast) {
$this->log('Process podcast done', ['name' => self::logFileName]);
}
/** HELPER */
/**
* Filter database input
* for hooks
*
* @param string $feedUrl
* @param Podcast $podcast
* @return array
* @throws WireException
*/
public function ___filterDbFeedInput(string $feedUrl, Podcast $podcast) : array {
return [
'title' => $this->sanitizer->text(htmlspecialchars_decode($podcast->getTitle())),
'description' => $this->sanitizer->text(htmlspecialchars_decode($podcast->getDescription()), ['maxLength' => 65535]),
'artwork_url' => $this->sanitizer->url($podcast->getArtwork()->getUri()),
'feed_url' => $feedUrl,
'media_count' => $this->sanitizer->int($podcast->getEpisodes()->count())
];
}
/**
* Filter database update
* for hooks
*
* @param int $id
* @param Podcast $podcast
* @return array
* @throws WireException
*/
public function ___filterDbFeedUpdate(int $id, Podcast $podcast) : array {
return [
'title' => $this->sanitizer->text(htmlspecialchars_decode($podcast->getTitle())),
'description' => $this->sanitizer->text(htmlspecialchars_decode($podcast->getDescription()), ['maxLength' => 65535]),
'artwork_url' => $this->sanitizer->url($podcast->getArtwork()->getUri()),
'media_count' => $this->sanitizer->int($podcast->getEpisodes()->count()),
'modified' => date('Y-m-d H:i:s'),
'id' =>$id
];
}
/**
* Collect data from input or somewhere else to save as additional metadata to the feed
* @return array
* @throws WireException
*/
public function processMetaInput(): array {
$meta = [];
// Subscription links
$meta['subscriptionLinks'] = [];
foreach($this->subscriptionLinks as $subscriptionLink => $label) {
if($url = $this->input->post($subscriptionLink, 'url')) $meta['subscriptionLinks'][$subscriptionLink] = $url;
}
// other stuff
// ...
return $meta;
}
/**
* Install
* Add field
*/
public function install() {
// Create Database
wire()->database->exec("
CREATE TABLE ".self::dbTableName." (
`id` int(11) NOT NULL,
`title` tinytext NOT NULL,
`description` text NOT NULL,
`artwork_url` text NOT NULL,
`feed_url` varchar(2000) NOT NULL,
`media_count` int(11) NOT NULL DEFAULT '0',
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE ".self::dbTableName." ADD PRIMARY KEY (`id`);
ALTER TABLE ".self::dbTableName." MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
");
// Create process page
$pageInfo = self::getModuleInfo()['page'];
$page = new Page($this->templates->get('admin'));
$page->name = $pageInfo['name'];
$page->title = $pageInfo['title'];
$page->parent = $this->pages->get($this->config->adminRootPageID);
$page->process = $this->className;
$page->save();
}
/**
* @return void
*/
public function uninstall() {
try {
wire()->database->exec('DROP TABLE ' . self::dbTableName);
} catch(\Exception $exception) {
$this->error($exception->getMessage());
}
}
/**
* Update database schema
* @see https://github.com/teppokoivula/ProcessChangelog/
* from Teppo Koivula
*
* This method applies incremental updates until latest schema version is
* reached, while also keeping schemaVersion config setting up to date.
*
* @throws WireException if database schema version isn't recognized
*/
public function updateDatabaseSchema() {
while ($this->schemaVersion < self::SCHEMA_VERSION) {
// increment; defaults to 1, but in some cases we may be able to skip over a specific schema update
$increment = 1;
// first we need to figure out which update we're going to trigger, and whether it's one that can be
switch ($this->schemaVersion) {
case 1:
$sql = [
"ALTER TABLE `" . self::dbTableName . "` ADD `meta` JSON NOT NULL AFTER `media_count`;",
];
break;
default:
throw new WireException("Unrecognized database schema version: {$this->schemaVersion}");
}
// we're ready to execute this update
foreach ($sql as $sqlQuery) {
$schemaUpdated = $this->executeDatabaseSchemaUpdate($sqlQuery);
if (!$schemaUpdated) {
break;
}
}
// if update fails: log, show notice (if current user is superuser) and continue
if (!$schemaUpdated) {
$message = sprintf(
$this->_("Running database schema update %d failed"),
$this->schemaVersion
);
$this->log->save(self::logFileName, $message);
if ($this->user->isSuperuser()) $this->message($message);
return;
}
// all's well that ends well
$this->schemaVersion += $increment;
$configData = $this->modules->getModuleConfigData($this);
$configData['schemaVersion'] = $this->schemaVersion;
$this->modules->saveModuleConfigData($this, $configData);
if ($this->user->isSuperuser()) {
$this->message(sprintf(
$this->_('ProcessChangelog database schema update applied (#%d).'),
$this->schemaVersion - 1
));
}
}
}
/**
* Execute database schema update
*
* @param string $sql
* @return bool
*/
protected function executeDatabaseSchemaUpdate(string $sql): bool {
try {
$updatedRows = $this->database->exec($sql);
return $updatedRows !== false;
} catch (\PDOException $e) {
if (isset($e->errorInfo[1]) && in_array($e->errorInfo[1], [1060, 1061, 1091])) {
// 1060 (column already exists), 1061 (duplicate key name), and 1091 (can't drop index) are errors that
// can be safely ignored here; the most likely issue would be that this update has already been applied
return true;
}
// another type of error; log, show notice (if current user is superuser) and return false
$message = sprintf(
'Error updating schema: %s (%s)',
$e->getMessage(),
$e->getCode()
);
$this->log->save(self::logFileName, $message);
if ($this->user->isSuperuser()) {
$this->error($message);
}
return false;
}
}
/**
* Add all Podcast to dynamic podcast field
* @param HookEvent $event
* @return void
*/
public function hookPodcastFieldOptions(HookEvent $event) {
// The page being edited
$page = $event->arguments(0);
// The Dynamic Options field
$field = $event->arguments(1);
if($field->name !== 'podcast') return;
// Feeds
$feeds = $this->getFeeds();
// Add options
$result = [];
foreach($feeds as $feed) $result[$feed->id] = $feed->title;
$event->return = $result;
}
/**
* Get Parser Instance
* @param $args
* @return Parser
* @throws \Exception
*/
public function ___getFeedParserInstance($args = null): Parser {
$this->loadFeedParserLib();
return new Parser($args);
}
/**
* Load PodcastFeedParser Library
* @return void
* @throws \Exception
*/
public function loadFeedParserLib() {
if(!class_exists("\Lukaswhite\PodcastFeedParser\Parser")) {
if(!file_exists(__DIR__ . '/vendor/autoload.php')) throw new \Exception("Please install the PodcastFeedParser library via `composer install` in the ProcessPodcastSubscriptions module directory.");
require_once(/*NoCompile*/__DIR__ . '/vendor/autoload.php');
}
}
}
class Feed extends WireData {
public function set($key, $value) {
if($key === 'id' || $key === 'media_count') $value = (int) $value;
elseif($key === 'meta' && is_string($value)) $value = json_decode($value);
return parent::set($key, $value);
}
}