Skip to content

Commit

Permalink
[YouTubeCommunityTabBridge] Improve building of content & title (#4089)
Browse files Browse the repository at this point in the history
* [YouTubeCommunityTabBridge] Improve building of content & title

Fixes truncated link hrefs in content and adds some general
improvements regarding the building of item content and item title

* [YouTubeCommunityTabBridge] Fix PHP deprecation warnings

Fixes the following deprecation warnings:

substr(): Passing null to parameter #1 ($string) of type string is
deprecated
  • Loading branch information
mightymt authored Apr 26, 2024
1 parent 154b8b9 commit d31f207
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions bridges/YouTubeCommunityTabBridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,15 @@ private function getText($runs)
$text = '';

foreach ($runs as $part) {
$text .= $this->formatUrls($part->text);
if (isset($part->navigationEndpoint->browseEndpoint->canonicalBaseUrl)) {
$text .= $this->formatUrls($part->text, $part->navigationEndpoint->browseEndpoint->canonicalBaseUrl);
} elseif (isset($part->navigationEndpoint->urlEndpoint->url)) {
$text .= $this->formatUrls($part->text, $part->navigationEndpoint->urlEndpoint->url);
} elseif (isset($part->navigationEndpoint->commandMetadata->webCommandMetadata->url)) {
$text .= $this->formatUrls($part->text, $part->navigationEndpoint->commandMetadata->webCommandMetadata->url);
} else {
$text .= $this->formatUrls($part->text, null);
}
}

return nl2br($text);
Expand Down Expand Up @@ -275,6 +283,7 @@ private function ellipsisTitle($text)
{
$length = 100;

$text = strip_tags($text);
if (strlen($text) > $length) {
$text = explode('<br>', wordwrap($text, $length, '<br>'));
return $text[0] . '...';
Expand All @@ -283,12 +292,26 @@ private function ellipsisTitle($text)
return $text;
}

private function formatUrls($content)
private function formatUrls($content, $url)
{
return preg_replace(
'/(http[s]{0,1}\:\/\/[a-zA-Z0-9.\/\?\&=\-_]{4,})/ims',
'<a target="_blank" href="$1" target="_blank">$1</a> ',
$content
);
if (substr(strval($url), 0, 1) == '/') {
// fix relative URL
$url = 'https://www.youtube.com' . $url;
} elseif (substr(strval($url), 0, 33) == 'https://www.youtube.com/redirect?') {
// extract actual URL from YouTube redirect
parse_str(substr($url, 33), $params);
if (strpos(($params['q'] ?? ''), rtrim($content, '.')) === 0) {
$url = $params['q'];
}
}

// ensure all URLs are made clickable
$url = $url ?? $content;

if (filter_var($url, FILTER_VALIDATE_URL)) {
return '<a href="' . $url . '" target="_blank">' . $content . '</a>';
}

return $content;
}
}

0 comments on commit d31f207

Please sign in to comment.