Add simple web interface to paste a page URL
[playVideoOnDreamboxProxy.git] / www / functions.php
1 <?php
2 function getPageUrl()
3 {
4     global $argv, $argc;
5     if (php_sapi_name() == 'cli') {
6         if ($argc < 2) {
7             errorInput('No URL given as command line parameter');
8         }
9         $pageUrl = $argv[1];
10     } else if (!isset($_SERVER['CONTENT_TYPE'])) {
11         errorInput('Content type header missing');
12     } else if ($_SERVER['CONTENT_TYPE'] == 'text/plain') {
13         //Android app
14         $pageUrl = file_get_contents('php://input');
15     } else if ($_SERVER['CONTENT_TYPE'] == 'application/x-www-form-urlencoded') {
16         //Web form
17         if (!isset($_POST['url'])) {
18             errorInput('"url" POST parameter missing');
19         }
20         $pageUrl = $_POST['url'];
21     } else {
22         errorInput('Content type is not text/plain but ' . $_SERVER['CONTENT_TYPE']);
23     }
24
25     $parts = parse_url($pageUrl);
26     if ($parts === false) {
27         errorInput('Invalid URL in POST data');
28     } else if (!isset($parts['scheme'])) {
29         errorInput('Invalid URL in POST data: No scheme');
30     } else if ($parts['scheme'] !== 'http' && $parts['scheme'] !== 'https') {
31         errorInput('Invalid URL in POST data: Non-HTTP scheme');
32     }
33     return $pageUrl;
34 }
35
36 function getYoutubeDlJson($pageUrl, $youtubedlPath)
37 {
38     $cmd = $youtubedlPath
39         . ' --no-playlist'//would otherwise cause multiple json blocks
40         . ' --quiet'
41         . ' --dump-json'
42         . ' ' . escapeshellarg($pageUrl);
43
44     $descriptors = [
45         1 => ['pipe', 'w'],//stdout
46         2 => ['pipe', 'w'],//stderr
47     ];
48     $proc = proc_open($cmd, $descriptors, $pipes);
49     if ($proc === false) {
50         errorOut('Error running youtube-dl');
51     }
52     $stdout = stream_get_contents($pipes[1]);
53     $stderr = stream_get_contents($pipes[2]);
54
55     $exitCode = proc_close($proc);
56
57     if ($exitCode === 0) {
58         //stdout contains the JSON data
59         return $stdout;
60     }
61
62     if (strlen($stderr)) {
63         $lines = explode("\n", trim($stderr));
64         $lastLine = end($lines);
65     } else {
66         $lines = explode("\n", trim($stdout));
67         $lastLine = end($lines);
68     }
69
70     if ($exitCode === 127) {
71         errorOut(
72             'youtube-dl not found at ' . $youtubedlPath,
73             '500 youtube-dl not found'
74         );
75     } else if (strpos($lastLine, 'Unsupported URL') !== false) {
76         errorOut(
77             'Unsupported URL  at ' . $pageUrl,
78             '406 Unsupported URL (No video found)'
79         );
80     }
81
82     errorOut('youtube-dl error: ' . $lastLine);
83 }
84
85 function extractVideoUrlFromJson($json)
86 {
87     $data = json_decode($json);
88     if ($data === null) {
89         errorOut('Cannot decode JSON: ' . json_last_error_msg());
90     }
91
92     $url = null;
93     foreach ($data->formats as $format) {
94         if (strpos($format->format, 'hls') !== false) {
95             //dreambox 7080hd does not play hls files
96             continue;
97         }
98         if ($format->protocol == 'http_dash_segments') {
99             //split up into multiple small files
100             continue;
101         }
102         $url = $format->url;
103     }
104
105     if ($url === null) {
106         //use URL chosen by youtube-dl
107         $url = $data->url;
108     }
109
110     if ($url == '') {
111         errorOut(
112             'No video URL found',
113             '406 No video URL found'
114         );
115     }
116     return $url;
117 }
118
119 function playVideoOnDreambox($videoUrl, $dreamboxUrl)
120 {
121     ini_set('track_errors', 1);
122     $xml = @file_get_contents($dreamboxUrl . '/web/session');
123     if ($xml === false) {
124         if (!isset($http_response_header)) {
125             errorOut(
126                 'Error fetching dreambox web interface token: '
127                 . $GLOBALS['lastError']
128             );
129         }
130
131         list($http, $code, $message) = explode(
132             ' ', $http_response_header[0], 3
133         );
134         if ($code == 401) {
135             //dreambox web interface authentication has been enabled
136             errorOut(
137                 'Error: Web interface authentication is required',
138                 '401 Dreambox web authentication required'
139             );
140         } else {
141             errorOut(
142                 'Failed to fetch dreambox session token: ' . $php_errormsg,
143                 $code . ' ' . $message
144             );
145         }
146     }
147     $sx = simplexml_load_string($xml);
148     $token = (string) $sx;
149
150     $playUrl = $dreamboxUrl
151         . '/web/mediaplayerplay'
152         . '?file=4097:0:1:0:0:0:0:0:0:0:'
153         . str_replace('%3A', '%253A', rawurlencode($videoUrl));
154
155     $ctx = stream_context_create(
156         array(
157             'http' => array(
158                 'method'  => 'POST',
159                 'header'  => 'Content-type: application/x-www-form-urlencoded',
160                 'content' => 'sessionid=' . $token,
161                 //'ignore_errors' => true
162             )
163         )
164     );
165     $ret = file_get_contents($playUrl, false, $ctx);
166     if ($ret !== false) {
167         if (php_sapi_name() != 'cli') {
168             header('HTTP/1.0 200 OK');
169         }
170         echo "Video play request sent to dreambox\n";
171         exit(0);
172     } else {
173         errorOut(
174             'Failed to send video play request to dreambox: ' . $php_errormsg
175         );
176     }
177 }
178
179 function errorHandlerStore($number, $message, $file, $line)
180 {
181     $GLOBALS['lastError'] = $message;
182     return false;
183 }
184 $GLOBALS['lastError'] = null;
185 ?>