af_redditimgur: cleanup, rework to embed stuff from reddit-provided JSON first

This commit is contained in:
Andrew Dolgov 2021-01-19 22:21:57 +03:00
parent 2933483393
commit 1ded706f8f
1 changed files with 312 additions and 272 deletions

View File

@ -96,67 +96,165 @@ class Af_RedditImgur extends Plugin {
echo __("Configuration saved");
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
private function inline_stuff($article, &$doc, $xpath) {
private function process_post_media($data, $doc, $xpath, $anchor) {
$found = 0;
$entries = $xpath->query('(//a[@href]|//img[@src])');
$img_entries = $xpath->query("(//img[@src])");
if (is_array($data["media_metadata"])) {
foreach ($data["media_metadata"] as $media) {
$media_url = htmlspecialchars_decode($media["s"]["u"]);
Debug::log("found media_metadata (gallery): $media_url", Debug::$LOG_VERBOSE);
if ($media_url) {
$this->handle_as_image($doc, $anchor, $media_url);
$found = 1;
}
}
}
// v.redd.it - see below
/* if (is_array($data["media"])) {
foreach ($data["media"] as $media) {
if (isset($media["fallback_url"])) {
$stream_url = $media["fallback_url"];
if (isset($data["preview"]["images"][0]["source"]))
$poster_url = $data["preview"]["images"][0]["source"]["url"];
else
$poster_url = "";
Debug::log("found stream fallback_url: $stream_url / poster $poster_url", Debug::$LOG_VERBOSE);
$this->handle_as_video($doc, $anchor, $stream_url, $poster_url);
}
$found = 1;
}
} */
if ($data["post_hint"] == "hosted:video") {
$media_url = $data["url"];
if (isset($data["preview"]["images"][0]["source"]))
$poster_url = htmlspecialchars_decode($data["preview"]["images"][0]["source"]["url"]);
else
$poster_url = "";
Debug::log("found hosted video url: $media_url / poster $poster_url, looking up fallback url...", Debug::$LOG_VERBOSE);
$fallback_url = $data["media"]["reddit_video"]["fallback_url"];
if ($fallback_url) {
Debug::log("found video fallback_url: $fallback_url", Debug::$LOG_VERBOSE);
$this->handle_as_video($doc, $anchor, $fallback_url, $poster_url);
$found = 1;
}
}
if ($data["post_hint"] == "video") {
$media_url = $data["url"];
if (isset($data["preview"]["images"][0]["source"]))
$poster_url = htmlspecialchars_decode($data["preview"]["images"][0]["source"]["url"]);
else
$poster_url = "";
Debug::log("found video url: $media_url / poster $poster_url", Debug::$LOG_VERBOSE);
$this->handle_as_video($doc, $anchor, $media_url, $poster_url);
$found = 1;
}
if ($data["post_hint"] == "image") {
$media_url = $data["url"];
Debug::log("found image url: $media_url", Debug::$LOG_VERBOSE);
$this->handle_as_image($doc, $anchor, $media_url);
$found = 1;
}
return $found;
}
private function inline_stuff($article, &$doc, $xpath) {
$found = false;
foreach ($entries as $entry) {
if ($entry->hasAttribute("href")) {
$entry_href = $entry->getAttribute("href");
// deal with json-provided media content first
if ($article["link"]) {
Debug::log("JSON: requesting from URL: " . $article["link"] . "/.json", Debug::$LOG_VERBOSE);
Debug::log("processing href: " . $entry_href, Debug::$LOG_VERBOSE);
$tmp = UrlHelper::fetch($article["link"] . "/.json");
// embed before reddit <table> post layout
$anchor = $xpath->query('//body/*')->item(0);
if ($tmp && $anchor) {
$json = json_decode($tmp, true);
Debug::log("JSON: processing media elements...", Debug::$LOG_EXTENDED);
if ($json) {
foreach ($json as $listing) {
foreach ($listing["data"]["children"] as $child) {
$data = $child["data"];
if (is_array($data["crosspost_parent_list"])) {
Debug::log("JSON: processing child crosspost_parent_list", Debug::$LOG_EXTENDED);
foreach ($data["crosspost_parent_list"] as $parent) {
if ($this->process_post_media($parent, $doc, $xpath, $anchor)) {
$found = 1;
continue;
}
}
}
Debug::log("JSON: processing child data element...", Debug::$LOG_EXTENDED);
if (!$found && $this->process_post_media($data, $doc, $xpath, $anchor)) {
$found = 1;
continue;
}
}
}
}
} else {
if (!$tmp) {
global $fetch_last_error;
Debug::log("JSON: failed to fetch post:" . $fetch_last_error, Debug::$LOG_EXTENDED);
}
if (!$anchor) {
Debug::log("JSON: anchor element not found, unable to embed", Debug::$LOG_EXTENDED);
}
}
}
if ($found) {
Debug::log("JSON: found media data, skipping further processing of content", Debug::$LOG_VERBOSE);
$this->remove_post_thumbnail($doc, $xpath);
return true;
}
$entries = $xpath->query('//a[@href]');
foreach ($entries as $entry) {
$entry_href = $entry->getAttribute("href");
$matches = [];
if (!$found && preg_match("/^https?:\/\/www\.reddit\.com\/gallery\/(.*)/", $entry_href, $matches)) {
Debug::log("handling as a reddit gallery: " . $matches[1], Debug::$LOG_VERBOSE);
$tmp = UrlHelper::fetch($entry_href);
if ($tmp) {
$tmpdoc = new DOMDocument();
if (@$tmpdoc->loadHTML($tmp)) {
$tmpxpath = new DOMXPath($tmpdoc);
$links = $tmpxpath->query("//figure/a[@href]");
foreach ($links as $link) {
$link_href = $link->getAttribute("href");
if (strpos($link_href, "preview.redd.it") !== false) {
Debug::log("found URL: $link_href", Debug::$LOG_EXTENDED);
// TODO: could there be other media types? videos?
if (strpos($link_href, ".jpg") !== false) {
$img = $doc->createElement("img");
$img->setAttribute("src", $link_href);
$p = $doc->createElement("p");
$p->appendChild($img);
$entry->parentNode->insertBefore($p, $entry);
$found = true;
}
}
}
}
}
}
/* skip other links going to reddit other than galleries (and any other blacklisted stuff) */
/* skip links going back to reddit (and any other blacklisted stuff) */
if (!$found && $this->is_blacklisted($entry_href, ["reddit.com"])) {
Debug::log("domain is blacklisted, skipping", Debug::$LOG_VERBOSE);
Debug::log("BODY: domain of $entry_href is blacklisted, skipping", Debug::$LOG_EXTENDED);
continue;
}
Debug::log("BODY: processing URL: " . $entry_href, Debug::$LOG_VERBOSE);
if (!$found && preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry_href, $matches)) {
Debug::log("handling as twitter: " . $matches[1] . " " . $matches[2], Debug::$LOG_VERBOSE);
@ -203,77 +301,6 @@ class Af_RedditImgur extends Plugin {
}
}
if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry_href, $matches)) {
Debug::log("Handling as reddit inline video", Debug::$LOG_VERBOSE);
$img = $img_entries->item(0);
if ($img) {
$poster_url = $img->getAttribute("src");
} else {
$poster_url = false;
}
// Get original article URL from v.redd.it redirects
$source_article_url = $this->get_location($matches[0]);
Debug::log("Resolved ".$matches[0]." to ".$source_article_url, Debug::$LOG_VERBOSE);
$source_stream = false;
if ($source_article_url) {
$j = json_decode(UrlHelper::fetch($source_article_url.".json"), true);
if ($j) {
foreach ($j as $listing) {
foreach ($listing["data"]["children"] as $child) {
if ($child["data"]["url"] == $matches[0]) {
try {
$source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
}
catch (Exception $e) {
}
break 2;
}
}
}
}
}
if (!$source_stream) {
$source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
}
$this->handle_as_video($doc, $entry, $source_stream, $poster_url);
$found = 1;
}
if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry_href)) {
Debug::log("Handling as Streamable", Debug::$LOG_VERBOSE);
$tmp = UrlHelper::fetch($entry_href);
if ($tmp) {
$tmpdoc = new DOMDocument();
if (@$tmpdoc->loadHTML($tmp)) {
$tmpxpath = new DOMXPath($tmpdoc);
$source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
$poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
if ($source_node && $poster_node) {
$source_stream = $source_node->getAttribute("src");
$poster_url = $poster_node->getAttribute("poster");
$this->handle_as_video($doc, $entry, $source_stream, $poster_url);
$found = 1;
}
}
}
}
// imgur .gif -> .gifv
if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry_href)) {
Debug::log("Handling as imgur gif (->gifv)", Debug::$LOG_VERBOSE);
@ -322,7 +349,7 @@ class Af_RedditImgur extends Plugin {
}
if (!$found && (preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?[$\?]/i", $entry_href) ||
mb_strpos($entry_href, "i.reddituploads.com") !== false ||
/* mb_strpos($entry_href, "i.reddituploads.com") !== false || */
mb_strpos($this->get_content_type($entry_href), "image/") !== false)) {
Debug::log("Handling as a picture", Debug::$LOG_VERBOSE);
@ -435,14 +462,8 @@ class Af_RedditImgur extends Plugin {
}
}
}
// remove tiny thumbnails
if ($entry->hasAttribute("src")) {
if ($entry->parentNode && $entry->parentNode->parentNode) {
$entry->parentNode->parentNode->removeChild($entry->parentNode);
}
}
if ($found)
$this->remove_post_thumbnail($doc, $xpath);
}
return $found;
@ -510,6 +531,23 @@ class Af_RedditImgur extends Plugin {
return 2;
}
private function remove_post_thumbnail($doc, $xpath) {
$thumb = $xpath->query("//td/a/img[@src]")->item(0);
if ($thumb)
$thumb->parentNode->parentNode->removeChild($thumb->parentNode);
}
private function handle_as_image($doc, $entry, $image_url) {
$img = $doc->createElement("img");
$img->setAttribute("src", $image_url);
$p = $doc->createElement("p");
$p->appendChild($img);
$entry->parentNode->insertBefore($p, $entry);
}
private function handle_as_video($doc, $entry, $source_stream, $poster_url = false) {
Debug::log("handle_as_video: $source_stream", Debug::$LOG_VERBOSE);
@ -538,32 +576,34 @@ class Af_RedditImgur extends Plugin {
$entry->parentNode->insertBefore($img, $entry);*/
}
// TODO: draw a form or something if url/article_url are not given
function testurl() {
header("Content-type: text/plain");
Debug::set_enabled(true);
Debug::set_loglevel(Debug::$LOG_VERBOSE);
Debug::set_loglevel(Debug::$LOG_EXTENDED);
$url = htmlspecialchars($_REQUEST["url"]);
$url = clean($_REQUEST["url"]);
$article_url = clean($_REQUEST["article_url"]);
Debug::log("URL: $url", Debug::$LOG_VERBOSE);
$doc = new DOMDocument();
@$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
@$doc->loadHTML("<html><body><table><tr><td><a href=\"$url\">[link]</a></td></tr></table></body>");
$xpath = new DOMXPath($doc);
$found = $this->inline_stuff([], $doc, $xpath);
$found = $this->inline_stuff(["link" => $article_url], $doc, $xpath);
Debug::log("Inline result: $found");
Debug::log("Inline result: $found", Debug::$LOG_VERBOSE);
if (!$found) {
Debug::log("Readability result:");
Debug::log("Readability result:", Debug::$LOG_VERBOSE);
$article = $this->readability([], $url, $doc, $xpath);
print_r($article);
} else {
Debug::log("Resulting HTML:");
Debug::log("Resulting HTML:", Debug::$LOG_VERBOSE);
print $doc->saveHTML();
}