Better error reporting for youtube-dl errors
authorChristian Weiske <cweiske@cweiske.de>
Wed, 6 Mar 2019 20:19:35 +0000 (21:19 +0100)
committerChristian Weiske <cweiske@cweiske.de>
Wed, 6 Mar 2019 20:19:35 +0000 (21:19 +0100)
www/functions.php

index b015953624d56f0f3c7884d22441544097a22919..ffd6667c685d520d0b9d110e055d54134e40b5ba 100644 (file)
@@ -32,28 +32,47 @@ function getYoutubeDlJson($pageUrl, $youtubedlPath)
         . ' --no-playlist'//would otherwise cause multiple json blocks
         . ' --quiet'
         . ' --dump-json'
-        . ' ' . escapeshellarg($pageUrl)
-        . ' 2> /dev/null';
+        . ' ' . escapeshellarg($pageUrl);
 
-    $lastLine = exec($cmd, $output, $exitCode);
-    if ($exitCode !== 0) {
-        if ($exitCode === 127) {
-            errorOut(
-                'youtube-dl not found at ' . $youtubedlPath,
-                '500 youtube-dl not found'
-            );
-        } else if (strpos($lastLine, 'Unsupported URL') !== false) {
-            errorOut(
-                'Unsupported URL  at ' . $pageUrl,
-                '406 Unsupported URL (No video found)'
-            );
-        } else {
-            errorOut('youtube-dl error: ' . $lastLine);
-        }
+    $descriptors = [
+        1 => ['pipe', 'w'],//stdout
+        2 => ['pipe', 'w'],//stderr
+    ];
+    $proc = proc_open($cmd, $descriptors, $pipes);
+    if ($proc === false) {
+        errorOut('Error running youtube-dl');
+    }
+    $stdout = stream_get_contents($pipes[1]);
+    $stderr = stream_get_contents($pipes[2]);
+
+    $exitCode = proc_close($proc);
+
+    if ($exitCode === 0) {
+        //stdout contains the JSON data
+        return $stdout;
+    }
+
+    if (strlen($stderr)) {
+        $lines = explode("\n", trim($stderr));
+        $lastLine = end($lines);
+    } else {
+        $lines = explode("\n", trim($stdout));
+        $lastLine = end($lines);
+    }
+
+    if ($exitCode === 127) {
+        errorOut(
+            'youtube-dl not found at ' . $youtubedlPath,
+            '500 youtube-dl not found'
+        );
+    } else if (strpos($lastLine, 'Unsupported URL') !== false) {
+        errorOut(
+            'Unsupported URL  at ' . $pageUrl,
+            '406 Unsupported URL (No video found)'
+        );
     }
 
-    $json = implode("\n", $output);
-    return $json;
+    errorOut('youtube-dl error: ' . $lastLine);
 }
 
 function extractVideoUrlFromJson($json)