summaryrefslogtreecommitdiff
path: root/init.php
blob: 6d713b7091a37ae572d8e969249d3b28519e13aa (plain)
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
<?php
class Af_Z_Video_Fill_Poster extends Plugin {

	/* @var PluginHost $host */
	private $host;

	/* @var DiskCache $cache */
	private $cache;

	function about() {
		return array(1.0,
			"Fills missing poster attributes of HTML5 video elements (uses ffmpeg)",
			"fox");
	}

	function init($host) {
		$this->host = $host;
		$this->cache = new DiskCache("images");

		$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
	}

	private function ffmpeg_thumbnail($input_filename, $output_filename) {
		$cmdline_tpl = "ffmpeg -ss 00:00:01 -i %s -frames:v 1 ".
			"-f singlejpeg %s 2>/dev/null";

		$rc = -1;
		$cmdline = sprintf($cmdline_tpl, escapeshellarg($input_filename), escapeshellarg($output_filename));

		exec($cmdline, $output, $rc);;

		return $rc === 0;
	}

	function hook_article_filter($article) {
		$need_saving = false;
		$doc = new DOMDocument();

		if (@$doc->loadHTML('<?xml encoding="UTF-8">' . $article["content"])) {
			$xpath = new DOMXPath($doc);
			$videos = $xpath->query('(//video)');

			foreach ($videos as $video) {
				if (!$video->hasAttribute("poster")) {
					$source = $xpath->query("//source[@src]", $video)->item(0);

					if ($source) {
						$video_url = $source->getAttribute("src");
						$local_filename = sha1($video_url);
						$thumb_filename = $local_filename . "-POSTER";

						if ($this->cache->exists($thumb_filename)) {
							$video->setAttribute("poster", $this->cache->getUrl($thumb_filename));
							$need_saving = true;

						} else {
							if ($this->cache->exists($local_filename)) {
								if ($this->ffmpeg_thumbnail(
									$this->cache->getFullPath($local_filename),
									$this->cache->getFullPath($thumb_filename))) {

									$video->setAttribute("poster", $this->cache->getUrl($thumb_filename));
									$need_saving = true;
								}
							} else {
								$data = fetch_file_contents(["url" => $video_url, "max_size" => MAX_CACHE_FILE_SIZE]);

								if ($data) {
									if ($this->cache->put($local_filename, $data)) {
										if ($this->ffmpeg_thumbnail(
											$this->cache->getFullPath($local_filename),
											$this->cache->getFullPath($thumb_filename))) {

											$video->setAttribute("poster", $this->cache->getUrl($thumb_filename));
											$need_saving = true;
										}
									}
								}
							}
						}
					}
				}
			}

			if ($need_saving)
				$article["content"] = $doc->saveHTML();
		}

		return $article;
	}

	function api_version() {
		return 2;
	}
}