podcasts work
[noxon-gateway.git] / src / podcasts.php
1 <?php
2 function sendPodcastList()
3 {
4     $files = glob(__DIR__ . '/../var/podcasts/*.url');
5     if (count($files) == 0) {
6         sendMessage('Keine Podcasts');
7         return;
8     }
9
10     $listItems = array();
11     foreach ($files as $file) {
12         $title = basename($file, '.url');
13         $listItems[] = '<Item>'
14             . '<ItemType>ShowOnDemand</ItemType>'
15             . '<ShowOnDemandName>' . htmlspecialchars($title) . '</ShowOnDemandName>'
16             . '<ShowOnDemandURL>http://radio567.vtuner.com/podcasts/' . urlencode(basename($file)) . '</ShowOnDemandURL>'
17             . '</Item>';
18     }
19     sendListItems($listItems);
20 }
21
22 function sendPodcast($file)
23 {
24     //strip /podcasts/
25     $file = substr(urldecode($file), 10);
26     if (strpos($file, '..') !== false) {
27         sendMessage('No');
28         return;
29     }
30
31     $path = __DIR__ . '/../var/podcasts/' . $file;
32     if (!file_exists($path)) {
33         return sendMessage('File does not exist: ' . $file);
34     }
35
36     $url = trim(file_get_contents($path));
37
38     $cacheFile = '/tmp/podcast-' . md5($file) . '.xml';
39     downloadIfNewer($url, $cacheFile);
40     
41     $sx = simplexml_load_file($cacheFile);
42     $listItems = array();
43     foreach ($sx->channel->item as $item) {
44         $title = (string) $item->title;
45         $desc = (string) $item->description;
46         $url = $item->enclosure['url'];
47
48         $listItems[] = '<Item>'
49             . '<ItemType>ShowEpisode</ItemType>'
50             . '<ShowEpisodeName>' . utf8_decode(htmlspecialchars($title)) . '</ShowEpisodeName>'
51             . '<ShowEpisodeURL>http://radio567.vtuner.com/play-url?url=' . urlencode($url) . '</ShowEpisodeURL>'
52             //. '<ShowEpisodeURL>' . htmlspecialchars($url) . '</ShowEpisodeURL>'
53             . '<ShowDesc>' . utf8_decode(htmlspecialchars($desc)) . '</ShowDesc>'
54             . '<ShowMime>MP3</ShowMime>' 
55             . '</Item>';
56     }
57     sendListItems($listItems);
58 }
59
60
61 function downloadIfNewer($url, $file)
62 {
63     $lastModified = 0;
64     if (file_exists($file)) {
65         $lastModified = filemtime($file);
66     }
67
68     $ctx = stream_context_create(
69         array(
70             'http' => array(
71                 'header' => 'If-Modified-Since: ' . date('r', $lastModified)
72             )
73         )
74     );
75     $content = file_get_contents($url, false, $ctx);
76     //unfortunately, redirects require manual parsing of this array
77     for ($n = count($http_response_header) - 1; $n >= 0; --$n) {
78         if (substr($http_response_header[$n], 0, 5) == 'HTTP/') {
79             list(, $code) = explode(' ', $http_response_header[$n]);
80             break;
81         }
82     }
83     if ($code == 200) {
84         file_put_contents($file, $content);
85     }
86 }
87
88 ?>