-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessPodcastSubscriptionsEpisodes.module
More file actions
263 lines (220 loc) · 7.53 KB
/
ProcessPodcastSubscriptionsEpisodes.module
File metadata and controls
263 lines (220 loc) · 7.53 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
<?php
/**
* COPYRIGHT NOTICE
* Copyright (c) 2023 Neue Rituale GbR
* @author NR <code@neuerituale.com>
*/
namespace ProcessWire;
use Lukaswhite\PodcastFeedParser\Artwork;
use Lukaswhite\PodcastFeedParser\Episode;
use Lukaswhite\PodcastFeedParser\Podcast;
/**
* @method void updateOrCreatePodcastEpisode(Episode $episode, Podcast $podcast, WireData $feed)
* @method NullPage|Page getPodcastEpisodePageByIdOrCreateNew($episode_id, string $title = '')
* @method float parseDuration($duration)
*/
class ProcessPodcastSubscriptionsEpisodes extends WireData implements Module, ConfigurableModule
{
public static function getModuleInfo() {
return array(
'title' => 'Process Podcast Create Episode Pages',
'version' => 104,
'summary' => 'Example Module for creating podcast episodes pages with ProcessPodcastSubscriptions',
'icon' => 'clock-o',
'requires' => ['LazyCron', 'ProcessPodcastSubscriptions'],
'installs' => 'ProcessPodcastSubscriptions',
'singular' => true,
'autoload' => true,
);
}
public function init() {
$this->addHookBefore('ProcessPodcastSubscriptions::processPodcast', $this, 'hookProcessPodcast');
$this->episodeParent = $this->pages->get($this->episodeParentId);
if(!$this->episodeParent->id) $this->episodeParent = $this->pages->get('/');
}
/**
* @param HookEvent $event
* @return void
* @throws WireException
*/
public function hookProcessPodcast(HookEvent $event) {
/** @var WireData $feed */
$feed = $event->arguments(0);
/** @var Podcast $podcast */
$podcast = $event->arguments(1);
// process
foreach($podcast->getEpisodes() as $episode) $this->updateOrCreatePodcastEpisode($episode, $podcast, $feed);
}
/**
* @param Episode $episode
* @param Podcast $podcast
* @param WireData $feed
* @return void
* @throws WireException
*/
public function ___updateOrCreatePodcastEpisode(Episode $episode, Podcast $podcast, WireData $feed) {
$podcastId = $episode->getGuid();
if(!$podcastId) return;
$title = $episode->getTitle();
/** @var Page $podcastEpisode */
$podcastEpisode = $this->getPodcastEpisodePageByIdOrCreateNew($podcastId, $title);
// Set fields
$podcastEpisode->title = html_entity_decode($episode->getTitle());
$podcastEpisode->episode_description = html_entity_decode($episode->getDescription());
$podcastEpisode->episode_duration = $this->parseDuration($episode->getDuration());
$podcastEpisode->episode_media = $episode->getMedia()->getUri();
$podcastEpisode->episode_number = $episode->getEpisodeNumber();
// Add feed
// this is the linking property
$podcastEpisode->podcast_feed = $feed->feed_url;
// Add Artwork
$artwork = $episode->getArtwork() ?? $podcast->getArtwork();
if(($artwork instanceof Artwork) && !$podcastEpisode->episode_image->count()) {
// get Field
/** @var FieldtypeImage|FieldtypeFile $episodeImage */
$episodeImage = $podcastEpisode->getField('episode_image');
$allowedExtensions = explode(' ', $episodeImage->extensions);
// filename
// build filename from title or id
$filename = $podcastEpisode->title;
if(empty($filename)) $filename = $podcastId;
$filename = $this->sanitizer->snakeCase(strtolower( $filename ));
// download file and save in tmp folder
$imageContent = $this->files->fileGetContents($artwork->getUri());
$tempDir = $this->files->tempDir();
$path = $tempDir->get();
$pathToFile = $path . $filename;
$tmpFile = $this->files->filePutContents($pathToFile, $imageContent);
if($tmpFile) {
// find extension by mime type and check if is allowed in this field
$internalFileExtensionFromMimeType = strtolower(explode('/', mime_content_type($pathToFile))[1] ?? 'unknown');
if(
in_array($internalFileExtensionFromMimeType, $allowedExtensions) &&
$this->files->rename($pathToFile, $pathToFile . '.' . $internalFileExtensionFromMimeType)
) {
$pathToFile = $pathToFile . '.' . $internalFileExtensionFromMimeType;
$podcastEpisode->episode_image = null;
$podcastEpisode->episode_image->add($pathToFile);
}
}
}
// Update published date
if($podcastEpisode->published !== (int) $episode->getPublishedDate()->format('U')) {
$mysqlDateTime = $episode->getPublishedDate()->format('Y-m-d H:i:s');
$podcastEpisode->set('published', $mysqlDateTime);
$this->database->exec("UPDATE pages SET published='{$mysqlDateTime}', created='{$mysqlDateTime}' WHERE id={$podcastEpisode->id}");
}
// Update
$podcastEpisode->save();
}
/**
* Find or create and save new media Page
* @param $episode_id
* @param string $title
* @return NullPage|Page
* @throws WireException
*/
public function ___getPodcastEpisodePageByIdOrCreateNew($episode_id, string $title = '') {
$podcast_episode = $this->pages->findOne('template=podcast-episode,episode_id=' . $episode_id);
if(!$podcast_episode->id) {
$podcast_episode = new Page($this->templates->get('podcast-episode'));
$podcast_episode
->set('episode_id', $episode_id)
->set('title', $title)
->set('parent', $this->episodeParent)
;
$podcast_episode->save(['noHooks' => true]);
}
$podcast_episode->of(false);
return $podcast_episode;
}
/**
* Parse time to seconds
* @param $duration
* @return float
*/
public function ___parseDuration($duration): float {
// HH:MM:SS, MM:SS, MMM:SS
if (preg_match('/\:/', $duration)) {
$parts = array_reverse(explode(':', $duration));
$seconds = (float) ($parts[0] ?? .0);
$minutes = (int) ($parts[1] ?? 0);
$hours = (int) ($parts[2] ?? 0);
return ($hours * 60 * 60) + ($minutes * 60) + $seconds;
}
// Seconds
else {
return floatval($duration);
}
}
/**
* Install
* Add field
*/
public function install() {
// Create fields
$fields = $this->getFieldData();
$field_names = '';
foreach ($fields as $field_name => $field_data) {
try {
$f = new Field();
$f->setImportData($field_data);
$f->save();
$field_names .= $field_name . " ";
} catch(\Exception $e) {
$this->warning($e->getMessage());
continue;
}
}
$this->message(sprintf($this->_('Created fields: %s'), $field_names));
// Create Templates
$templates = $this->getTemplateData();
$template_names = '';
foreach ($templates as $template_name => $template_data) {
try {
$fg = new Fieldgroup();
$fg->name = $template_name;
$template_names .= $template_name . " ";
foreach ($template_data['fieldgroupFields'] as $fieldname) {
$fg->add($fieldname);
}
$fg->save();
$t = new Template();
$t->setImportData($template_data) ;
$t->save();
} catch(\Exception $e) {
$this->warning($e->getMessage());
continue;
}
}
$this->message(sprintf($this->_('Created template: %s'), $template_names));
// copy template file in templates folder
$this->files->copy(
$this->config->paths->ProcessPodcastSubscriptionsEpisodes . 'templates/',
$this->config->paths->templates
);
$this->message(sprintf($this->_('Created template files: %s'), 'podcast-episode.php'));
}
/**
* @return void
*/
public function uninstall() {
$this->message(sprintf($this->_('Please delete the template "%1$s" and all field with the prefix "%2$s" by yourself.'), 'podcast-episode', 'episode_'));
}
/**
* Get field data
* @return mixed
*/
private function getFieldData() {
$fields_json = file_get_contents(__DIR__ . "/data/fields.json");
return json_decode($fields_json, true);
}
/**
* Get template data
* @return mixed
*/
private function getTemplateData() {
$templates_json = file_get_contents(__DIR__ . "/data/templates.json");
return json_decode($templates_json, true);
}
}