forked from WWBN/AVideo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EpgParser.php
391 lines (315 loc) · 11.3 KB
/
EpgParser.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
<?php
namespace buibr\xmlepg;
use XMLReader;
use SimpleXMLElement;
use RuntimeException;
use DateTimeZone;
class EpgParser {
// Source datas.
private $file;
private $url;
private $content;
// for temporary file if from content or from url.
private $isTemp;
public $temp_dir = '/tmp'; //unix, change this for windows.
// channel settings
private $channels;
private $channels_groupby = '@id';
// programmes settings.
private $epgdata;
private $epgdata_groupby = '@id';
// filter
private $channelfilter = [];
private $ignoreDescr = [];
// zone.
private $targetTimeZone;
// callbacks
public $onError;
public function __construct() {
$this->targetTimeZone = \date_default_timezone_get();
}
/**
* @param mixed $file`
*/
public function setFile($file): void {
$this->file = $file;
}
/**
* @param mixed $url - url
*/
public function setUrl($url): void {
$this->url = $url;
}
/**
* @param mixed $content = xml parsed string.
*/
public function setContent($content): void {
$this->content = $content;
}
/**
* @param mixed $channelfilter
*/
public function setChannelfilter($channelfilter): void {
$this->channelfilter[$channelfilter] = 1;
}
/**
* @param string $descr
*/
public function setIgnoreDescr(string $descr): void {
$this->ignoreDescr[$descr] = 1;
}
/**
* @param mixed $targetTimeZone
*/
public function setTargetTimeZone($targetTimeZone): void {
$this->targetTimeZone = $targetTimeZone;
}
/**
* Set group by for channels must be channels atribute.
* @param $group - channel will be grouped with. must be @id or pgram attribute.
*/
public function setChannelGroup($group) {
$this->channels_groupby = $group;
}
/**
* Set group by for channels must be channels atribute.
* @id = array index starting from 0
* @param $group - programes will be grouped with. must be @id or pgram attribute.
*/
public function setProgrammGroup($group) {
$this->epgdata_groupby = $group;
}
/**
* Parse the date from string in posible formats.
*/
public function getDate(string $date) {
try {
$dt = \DateTime::createFromFormat('YmdHis P', $date, new DateTimeZone('UTC'));
$dt->setTimezone(new DateTimeZone($this->targetTimeZone));
return $dt->format('Y-m-d H:i:s');
} catch (\Exception $e) {
} catch (\Error $e) {
}
try {
$dt = \DateTime::createFromFormat('YmdHis', $date, new DateTimeZone('UTC'));
$dt->setTimezone(new DateTimeZone($this->targetTimeZone));
return $dt->format('Y-m-d H:i:s');
} catch (\Exception $e) {
} catch (\Error $e) {
}
try {
$ex = explode(' ', $date);
$sd = $ex[0];
$ed = $ex[1];
if (strlen($sd) == 13) {
$sd = "{$sd}0";
}
$date = $sd . " " . $ed;
$dt = \DateTime::createFromFormat('YmdHis P', $date, new DateTimeZone('UTC'));
$dt->setTimezone(new DateTimeZone($this->targetTimeZone));
return $dt->format('Y-m-d H:i:s');
} catch (\Exception $e) {
} catch (\Error $e) {
}
return null;
}
/**
* @param $descr
*
* @return string
*/
private function filterDescr($descr): string {
if (array_key_exists($descr, $this->ignoreDescr)) {
return '';
}
return $descr;
}
/**
* @return mixed
*/
public function getChannels() {
return $this->channels;
}
/**
* @return array
*/
public function getEpgdata() {
return $this->epgdata;
}
/**
*
*/
public function resetChannelfilter(): void {
$this->channelfilter = [];
}
/**
*
*/
private function channelMatchFilter(string $channel): bool {
return array_key_exists($channel, $this->channelfilter);
}
/**
* @throws \RuntimeException
* @throws \Exception
*/
public function parseFile(): void {
if (!$this->file) {
throw new \RuntimeException('missing file: please use setFile before parse');
}
if (!file_exists($this->file)) {
throw new \RuntimeException('file does not exists: ' . $this->file);
}
//
$xml = new XMLReader();
// compress.zlib://'
$xml->open($this->file);
/** @noinspection PhpStatementHasEmptyBodyInspection */
/** @noinspection LoopWhichDoesNotLoopInspection */
/** @noinspection MissingOrEmptyGroupStatementInspection */
while ($xml->read() && $xml->name !== 'channel') {
}
$i = 0;
while ($xml->name === 'channel') {
$element = new SimpleXMLElement($xml->readOuterXML());
/** @noinspection PhpUndefinedFieldInspection */
$group_by = $this->channels_groupby === '@id' ? (@$i++) : (string) $element->attributes()->{$this->epgdata_groupby};
// se the id
$channel_id = $group_by ?: 1;
/** @noinspection PhpUndefinedFieldInspection */
$this->channels[$channel_id] = [
'id' => (string) $element->attributes()->id,
'display-name' => (string) $element->{'display-name'},
'url' => (string) $element->{'url'},
'email' => (string) $element->{'email'},
'icon' => null,
];
if (isset($element->{'icon'}) && $element->{'icon'} instanceof SimpleXMLElement) {
$attributes = $element->{'icon'}->attributes();
$pathinfo = pathinfo($attributes->src);
if (empty($attributes->src)) {
$this->channels[$channel_id]['icon'] = (string) $element->{'icon'};
$xml->next('channel');
unset($element);
} elseif (!filter_var($attributes->src, FILTER_VALIDATE_URL)) {
$this->channels[$channel_id]['icon'] = (string) $element->{'icon'};
$xml->next('channel');
unset($element);
} elseif (empty($pathinfo['extension'])) {
$this->channels[$channel_id]['icon'] = (string) $element->{'icon'};
$xml->next('channel');
unset($element);
continue;
} else {
$this->channels[$channel_id]['icon'] = (string) $attributes->src;
}
}
$xml->next('channel');
unset($element);
}
$xml->close();
$xml->open($this->file);
/** @noinspection PhpStatementHasEmptyBodyInspection */
/** @noinspection LoopWhichDoesNotLoopInspection */
/** @noinspection MissingOrEmptyGroupStatementInspection */
while ($xml->read() && $xml->name !== 'programme') {
}
while ($xml->name === 'programme') {
$element = new SimpleXMLElement($xml->readOuterXML());
/** @noinspection PhpUndefinedFieldInspection */
if (!\count($this->channelfilter) || (\count($this->channelfilter) && $this->channelMatchFilter((string) $element->attributes()->channel))) {
/** @noinspection PhpUndefinedFieldInspection */
$startString = $this->getDate((string) $element->attributes()->start);
/** @noinspection PhpUndefinedFieldInspection */
$stopString = $this->getDate((string) $element->attributes()->stop);
/** @noinspection PhpUndefinedFieldInspection */
$grouper = $this->epgdata_groupby === '@id' ? (@$i++) : (string) $element->attributes()->{$this->epgdata_groupby};
$icon = (string) $element->icon;
if (empty($icon) && !empty($element->icon->attributes()->src)) {
$icon = (string) $element->icon->attributes()->src;
}
/** @noinspection PhpUndefinedFieldInspection */
$this->epgdata[$grouper ?: 0] = [
'start' => $startString,
'start_raw' => (string) $element->attributes()->start,
'channel' => (string) $element->attributes()->channel,
'stop' => $stopString,
'title' => (string) $element->title,
'sub-title' => (string) $element->{'sub-title'},
'desc' => $this->filterDescr((string) $element->desc),
'date' => (int) (string) $element->date,
'category' => (string) $element->category,
'credits' => (string) $element->credits,
'country' => (string) $element->country,
'icon' => $icon,
'episode-num' => (string) $element->{'episode-num'},
];
}
$xml->next('programme');
unset($element);
}
$xml->close();
if ($this->isTemp) {
@unlink($this->file);
}
}
/**
* @throws \RuntimeException
* @throws \Exception
*/
public function parseUrl(): void {
if (!$this->url) {
throw new \RuntimeException('Url missing: please use setUrl before parseUrl');
}
if (!filter_var($this->url, FILTER_VALIDATE_URL)) {
throw new \RuntimeException('Url invalid: ' . $this->url);
}
$this->content = @\file_get_contents($this->url);
if (!strpos($http_response_header[0], "200")) {
throw new \RuntimeException("Invalid response headers: " . $http_response_header[0], 1);
}
$this->checkXml();
$this->saveTemp(); // will save the file.
$this->parseFile();
}
/**
* @throws \RuntimeException
* @throws \Exception
*/
public function parseContent(): void {
if (!$this->content) {
throw new \RuntimeException('Url missing: please use setUrl before parseUrl');
}
$this->checkXml();
$this->saveTemp(); // will save the file.
$this->parseFile();
}
/**
* Save content to temp file from ulr or from content.
*/
public function saveTemp(): void {
if (empty($this->temp_dir)) {
$this->temp_dir = '/tmp/';
}
$length = 15;
$filename = substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
$this->file = $this->temp_dir . '/' . $filename . '.xml';
if (!\file_put_contents($this->file, $this->content)) {
throw new \RuntimeException("Writing to {$this->file} is not possible.");
}
$this->isTemp = true;
$this->content = null;
}
/**
* Check content of response from xml f is xml
* @throws \RuntimeException
*/
public function checkXml() {
libxml_use_internal_errors(true);
$doc = simplexml_load_string($this->content);
if (!$doc) {
$errors = libxml_get_errors();
@$errors = $errors[0];
throw new \RuntimeException("Content of this request its not XML: $errors");
}
}
}