RSS-Bridge.rss-bridge/formats/M3uFormat.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

84 lines
2.2 KiB
PHP
Raw Normal View History

2024-03-04 15:30:22 +01:00
<?php
/**
* M3U
*
*/
class M3uFormat extends FormatAbstract
{
const MIME_TYPE = 'application/mpegurl';
public function stringify()
{
$contents = "#EXTM3U\n";
foreach ($this->getItems() as $item) {
$itemArray = $item->toArray();
2024-03-04 15:52:05 +01:00
$m3uitem = new M3uItem();
if (isset($itemArray['enclosure'])) {
$m3uitem->url = $itemArray['enclosure']['url'];
$m3uitem->bytes = $itemArray['enclosure']['length'];
}
if (isset($itemArray['itunes']) && isset($itemArray['itunes']['duration'])) {
$m3uitem->duration = self::parseDuration($itemArray['itunes']['duration']);
2024-03-04 15:52:05 +01:00
}
if (isset($itemArray['title'])) {
$m3uitem->title = $itemArray['title'];
2024-03-04 15:30:22 +01:00
}
2024-03-04 15:52:05 +01:00
$contents .= $m3uitem->render();
2024-03-04 15:30:22 +01:00
}
return mb_convert_encoding($contents, $this->getCharset(), 'UTF-8');
}
/*
* parseDuration converts a string like "00:4:20" to 260
* allowing to convert duration as used in the itunes:duration tag to the number of seconds
*/
private static function parseDuration(string $duration_string): int
{
$seconds = 0;
$parts = explode(':', $duration_string);
for ($i = 0; $i < count($parts); $i++) {
$seconds += intval($parts[count($parts) - $i - 1]) * pow(60, $i);
}
return $seconds;
2024-03-04 15:52:05 +01:00
}
}
2024-03-04 15:52:05 +01:00
class M3uItem
{
public $duration = null;
public $title = null;
public $url = null;
public $bytes = null;
2024-03-07 12:41:52 +01:00
public function isEmpty(): bool
{
return $this->url === null;
}
2024-03-05 19:54:37 +01:00
public function render(): string
2024-03-04 15:52:05 +01:00
{
2024-03-07 12:41:52 +01:00
if ($this->isEmpty()) {
2024-03-04 15:52:05 +01:00
return '';
}
2024-03-05 19:55:01 +01:00
$text = "\n";
2024-03-04 15:52:05 +01:00
$commentParts = [];
if ($this->duration !== null && $this->duration > 0) {
$commentParts[] = $this->duration;
}
if ($this->title !== null) {
$commentParts[] = $this->title;
}
if (count($commentParts) !== 0) {
$text .= '#EXTINF:' . implode(',', $commentParts) . "\n";
}
$text .= $this->url . "\n";
return $text;
}
}