1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-06 03:50:04 +02:00
This commit is contained in:
daniel 2020-03-20 11:06:03 -03:00
parent b84c226445
commit 968ba051b6

View file

@ -64,12 +64,12 @@ class YouTubeAPI extends PluginAbstract {
public function listVideos() { public function listVideos() {
global $global; global $global;
$youTubeObj = $this->getDataObject(); $youTubeObj = $this->getDataObject();
if(empty($_GET['page'])){ if (empty($_GET['page'])) {
$page = 1; $page = 1;
}else{ } else {
$page = intval($_GET['page']); $page = intval($_GET['page']);
} }
$name = "YouTubeAPI-ListVideos-{$page}"; $name = "YouTubeAPI-ListVideos-{$page}-" . md5(@$_GET['search']);
$cache = ObjectYPT::getSessionCache($name, $youTubeObj->cacheTimeout); $cache = ObjectYPT::getSessionCache($name, $youTubeObj->cacheTimeout);
if (empty($cache)) { if (empty($cache)) {
@ -109,14 +109,14 @@ class YouTubeAPI extends PluginAbstract {
//'regionCode' => $youTubeObj->regionCode, //'regionCode' => $youTubeObj->regionCode,
); );
if(!empty($youTubeObj->keyword)){ if (!empty($youTubeObj->keyword)) {
$options['q'] = $youTubeObj->keyword; $options['q'] = $youTubeObj->keyword;
}else if(!empty($_GET['search'])){ } else if (!empty($_GET['search'])) {
$options['q'] = $_GET['search']; $options['q'] = $_GET['search'];
} }
if(!empty($_GET['pageToken'])){ if (!empty($_GET['pageToken'])) {
$options['pageToken'] = $_GET['pageToken']; $options['pageToken'] = $_GET['pageToken'];
} }
$searchResponse = $youtube->search->listSearch('snippet,contentDetails,statistics', $options); $searchResponse = $youtube->search->listSearch('snippet,contentDetails,statistics', $options);
@ -130,13 +130,13 @@ class YouTubeAPI extends PluginAbstract {
$searchResult["id"]["videoId"], $searchResult['snippet']["title"], $searchResult['snippet']["description"], $searchResult['snippet']["thumbnails"]["high"]["url"], $searchResult['snippet']["channelTitle"], "https://www.youtube.com/embed/{$searchResult["id"]["videoId"]}"); $searchResult["id"]["videoId"], $searchResult['snippet']["title"], $searchResult['snippet']["description"], $searchResult['snippet']["thumbnails"]["high"]["url"], $searchResult['snippet']["channelTitle"], "https://www.youtube.com/embed/{$searchResult["id"]["videoId"]}");
$object->videos[] = $vid; $object->videos[] = $vid;
} }
if(!empty($object->videos)){ if (!empty($object->videos)) {
$object->error = false; $object->error = false;
ObjectYPT::setSessionCache($name, $object); ObjectYPT::setSessionCache($name, $object);
ObjectYPT::setCache($name, $object); ObjectYPT::setCache($name, $object);
}else{ } else {
$oldCache = ObjectYPT::getCache($name, 0); $oldCache = ObjectYPT::getCache($name, 0);
if(!empty($oldCache->videos)){ if (!empty($oldCache->videos)) {
$cache = $oldCache; $cache = $oldCache;
} }
} }
@ -151,221 +151,221 @@ class YouTubeAPI extends PluginAbstract {
return $cache; return $cache;
} }
} }
/* Not ready yet
public function upload($videos_id) {
global $global;
require_once $global['systemRootPath'] . 'plugin/YouTubeAPI/youtube-api/autoload.php';
$object = new stdClass();
$object->error = true;
$object->msg = "";
$object->url = self::getUploadedURL($videos_id);
$object->databaseSaved = false;
_error_log('YouTube::upload start ' . $videos_id); /* Not ready yet
if (!empty($object->url)) { public function upload($videos_id) {
$object->msg = __("Video already uploaded") . " " . $object->url; global $global;
$object->databaseSaved = true; require_once $global['systemRootPath'] . 'plugin/YouTubeAPI/youtube-api/autoload.php';
_error_log('YouTube::upload ' . $object->msg); $object = new stdClass();
return $object; $object->error = true;
} $object->msg = "";
$object->url = self::getUploadedURL($videos_id);
$object->databaseSaved = false;
$v = new Video("", "", $videos_id); _error_log('YouTube::upload start ' . $videos_id);
if (!empty($object->url)) {
$object->msg = __("Video already uploaded") . " " . $object->url;
$object->databaseSaved = true;
_error_log('YouTube::upload ' . $object->msg);
return $object;
}
if (empty($v->getFilename())) { $v = new Video("", "", $videos_id);
$object->msg = __("Video Filename not found");
_error_log('YouTube::upload ' . $object->msg);
return $object;
}
$source = Video::getHigestResolutionVideoMP4Source($v->getFilename()); if (empty($v->getFilename())) {
$file_name = $source['path']; $object->msg = __("Video Filename not found");
_error_log('YouTube::upload ' . $object->msg);
return $object;
}
if (!file_exists($file_name)) { $source = Video::getHigestResolutionVideoMP4Source($v->getFilename());
$object->msg = __("Video MP4 File was not found"); $file_name = $source['path'];
_error_log('YouTube::upload ' . $object->msg . " $file_name");
return $object;
}
$youTubeObj = $this->getDataObject(); if (!file_exists($file_name)) {
$object->msg = __("Video MP4 File was not found");
_error_log('YouTube::upload ' . $object->msg . " $file_name");
return $object;
}
$client = new Google_Client(); $youTubeObj = $this->getDataObject();
$client->setClientId($youTubeObj->client_id);
$client->setClientSecret($youTubeObj->client_secret); $client = new Google_Client();
$client->setScopes('https://www.googleapis.com/auth/youtube'); $client->setClientId($youTubeObj->client_id);
//$redirectUri = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],FILTER_SANITIZE_URL); $client->setClientSecret($youTubeObj->client_secret);
$redirectUri = "{$global['webSiteRootURL']}plugin/YouTubeAPI/redirect.json.php"; $client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setRedirectUri($redirectUri); //$redirectUri = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],FILTER_SANITIZE_URL);
// Define an object that will be used to make all API requests. $redirectUri = "{$global['webSiteRootURL']}plugin/YouTubeAPI/redirect.json.php";
$youtube = new Google_Service_YouTube($client); $client->setRedirectUri($redirectUri);
// Check if an auth token exists for the required scopes // Define an object that will be used to make all API requests.
$tokenSessionKey = 'token-' . $client->prepareScopes(); $youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_SESSION[$tokenSessionKey])) { if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]); $client->setAccessToken($_SESSION[$tokenSessionKey]);
} }
// Check to ensure that the access token was successfully acquired. // Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) { if ($client->getAccessToken()) {
try { try {
$time_start = microtime(true); $time_start = microtime(true);
// REPLACE this value with the path to the file you are uploading. // REPLACE this value with the path to the file you are uploading.
$videoPath = $v->getExistingVideoFile(); $videoPath = $v->getExistingVideoFile();
// Create a snippet with title, description, tags and category ID // Create a snippet with title, description, tags and category ID
// Create an asset resource and set its snippet metadata and type. // Create an asset resource and set its snippet metadata and type.
// This example sets the video's title, description, keyword tags, and // This example sets the video's title, description, keyword tags, and
// video category. // video category.
$snippet = new Google_Service_YouTube_VideoSnippet(); $snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($v->getTitle()); $snippet->setTitle($v->getTitle());
$snippet->setDescription($v->getDescription()); $snippet->setDescription($v->getDescription());
$snippet->setTags(array("AVideo", $config->getWebSiteTitle())); $snippet->setTags(array("AVideo", $config->getWebSiteTitle()));
// Numeric video category. See // Numeric video category. See
// https://developers.google.com/youtube/v3/docs/videoCategories/list // https://developers.google.com/youtube/v3/docs/videoCategories/list
// $snippet->setCategoryId("22"); // $snippet->setCategoryId("22");
// Set the video's status to "public". Valid statuses are "public", // Set the video's status to "public". Valid statuses are "public",
// "private" and "unlisted". // "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus(); $status = new Google_Service_YouTube_VideoStatus();
$privacy_view = "public"; $privacy_view = "public";
if (!empty($video->getVideo_password())) { if (!empty($video->getVideo_password())) {
$privacy_view = "private"; $privacy_view = "private";
} else if ($video->getType() == 'u') { } else if ($video->getType() == 'u') {
$privacy_view = "unlisted"; $privacy_view = "unlisted";
} else if (!Video::isPublic($videos_id)) { } else if (!Video::isPublic($videos_id)) {
$privacy_view = "private"; $privacy_view = "private";
} }
$status->privacyStatus = $privacy_view; $status->privacyStatus = $privacy_view;
// Associate the snippet and status objects with a new video resource. // Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video(); $video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet); $video->setSnippet($snippet);
$video->setStatus($status); $video->setStatus($status);
// Specify the size of each chunk of data, in bytes. Set a higher value for // Specify the size of each chunk of data, in bytes. Set a higher value for
// reliable connection as fewer chunks lead to faster uploads. Set a lower // reliable connection as fewer chunks lead to faster uploads. Set a lower
// value for better recovery on less reliable connections. // value for better recovery on less reliable connections.
$chunkSizeBytes = 1 * 1024 * 1024; $chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called // Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately. // with ->execute(); instead of making the API call immediately.
$client->setDefer(true); $client->setDefer(true);
// Create a request for the API's videos.insert method to create and upload the video. // Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video); $insertRequest = $youtube->videos->insert("status,snippet", $video);
// Create a MediaFileUpload object for resumable uploads. // Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload( $media = new Google_Http_MediaFileUpload(
$client, $insertRequest, 'video/*', null, true, $chunkSizeBytes $client, $insertRequest, 'video/*', null, true, $chunkSizeBytes
); );
$media->setFileSize(filesize($videoPath)); $media->setFileSize(filesize($videoPath));
// Read the media file and upload it chunk by chunk. // Read the media file and upload it chunk by chunk.
$status = false; $status = false;
$handle = fopen($videoPath, "rb"); $handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) { while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes); $chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk); $status = $media->nextChunk($chunk);
} }
fclose($handle); fclose($handle);
// If you want to make other calls after the file upload, set setDefer back to false // If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(false); $client->setDefer(false);
$time_end = microtime(true); $time_end = microtime(true);
$time = $time_end - $time_start; //Time it took $time = $time_end - $time_start; //Time it took
$bytes_per_sec = $bytes / $time; $bytes_per_sec = $bytes / $time;
$KB_per_sec = $bytes_per_sec / 1024; $KB_per_sec = $bytes_per_sec / 1024;
$MB_per_sec = intval($KB_per_sec / 1024); $MB_per_sec = intval($KB_per_sec / 1024);
$object->error = false; $object->error = false;
$object->url = 'https://youtu.be/' . $status['id']; $object->url = 'https://youtu.be/' . $status['id'];
$object->msg = $file_name . ' has been uploaded to ' . $object->url . " took " . secondsToHumanTiming($time) . " to complete"; $object->msg = $file_name . ' has been uploaded to ' . $object->url . " took " . secondsToHumanTiming($time) . " to complete";
_error_log('YouTube::upload ' . $object->msg . " {$MB_per_sec} Mbps"); _error_log('YouTube::upload ' . $object->msg . " {$MB_per_sec} Mbps");
$saveUpload = new YouTubeUploads(0); $saveUpload = new YouTubeUploads(0);
$saveUpload->setVideos_id($videos_id); $saveUpload->setVideos_id($videos_id);
$saveUpload->setUrl($object->url); $saveUpload->setUrl($object->url);
$object->databaseSaved = $saveUpload->save(); $object->databaseSaved = $saveUpload->save();
$v->setYoutubeId($status['id']); $v->setYoutubeId($status['id']);
$v->save(); $v->save();
} catch (Google_Service_Exception $e) { } catch (Google_Service_Exception $e) {
$object->msg = sprintf(__("A service error occurred: %s"), $e->getMessage()); $object->msg = sprintf(__("A service error occurred: %s"), $e->getMessage());
} catch (Google_Exception $e) { } catch (Google_Exception $e) {
$object->msg = sprintf(__("An client error occurred: %s"), $e->getMessage()); $object->msg = sprintf(__("An client error occurred: %s"), $e->getMessage());
} }
$_SESSION[$tokenSessionKey] = $client->getAccessToken(); $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif (empty($youTubeObj->client_id) || empty($youTubeObj->client_secret)) { } elseif (empty($youTubeObj->client_id) || empty($youTubeObj->client_secret)) {
$object->msg = "<h3>Client Credentials Required</h3> $object->msg = "<h3>Client Credentials Required</h3>
<p> <p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding. <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>"; <p>";
} else { } else {
// If the user hasn't authorized the app, initiate the OAuth flow // If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand(); $state = mt_rand();
$client->setState($state); $client->setState($state);
$_SESSION['state'] = $state; $_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl(); $authUrl = $client->createAuthUrl();
$object->msg = "<h3>Authorization Required</h3><p>You need to <a href=\"{$authUrl}\" class='btn btn-danger'><span class='fab fa-youtube-square'></span> authorize access</a> before proceeding.<p>"; $object->msg = "<h3>Authorization Required</h3><p>You need to <a href=\"{$authUrl}\" class='btn btn-danger'><span class='fab fa-youtube-square'></span> authorize access</a> before proceeding.<p>";
} }
return $object; return $object;
} }
public function getHeadCode() { public function getHeadCode() {
global $global; global $global;
$baseName = basename($_SERVER['REQUEST_URI']); $baseName = basename($_SERVER['REQUEST_URI']);
$js = ""; $js = "";
if ($baseName === 'mvideos') { if ($baseName === 'mvideos') {
$js .= "<script>function youTubeUpload(video_id){ $js .= "<script>function youTubeUpload(video_id){
modal.showPleaseWait(); modal.showPleaseWait();
\$.ajax({ \$.ajax({
url: '{$global['webSiteRootURL']}plugin/YouTubeAPI/upload.json.php', url: '{$global['webSiteRootURL']}plugin/YouTubeAPI/upload.json.php',
data: {\"video_id\": video_id}, data: {\"video_id\": video_id},
type: 'post', type: 'post',
success: function (response) { success: function (response) {
if(response.error){ if(response.error){
swal('" . __("Sorry!") . "', response.msg, 'error'); swal('" . __("Sorry!") . "', response.msg, 'error');
}else{ }else{
swal('" . __("Congratulations!") . "', response.msg, 'success'); swal('" . __("Congratulations!") . "', response.msg, 'success');
} }
console.log(response); console.log(response);
modal.hidePleaseWait(); modal.hidePleaseWait();
} }
});}</script>"; });}</script>";
} else } else
if ($baseName === 'plugins') { if ($baseName === 'plugins') {
$js .= "<script>function youTubeUploadAll(){ $js .= "<script>function youTubeUploadAll(){
\$.ajax({ \$.ajax({
url: '{$global['webSiteRootURL']}plugin/YouTubeAPI/uploadAll.json.php', url: '{$global['webSiteRootURL']}plugin/YouTubeAPI/uploadAll.json.php',
success: function (response) { success: function (response) {
if(response.error){ if(response.error){
swal('" . __("Sorry!") . "', response.msg, 'error'); swal('" . __("Sorry!") . "', response.msg, 'error');
}else{ }else{
swal('" . __("Congratulations!") . "', response.msg, 'success'); swal('" . __("Congratulations!") . "', response.msg, 'success');
} }
console.log(response); console.log(response);
} }
}); });
swal('" . __("Process Start") . "', 'It may take a while', 'warning'); swal('" . __("Process Start") . "', 'It may take a while', 'warning');
}</script>"; }</script>";
} }
return $js; return $js;
} }
public function getVideosManagerListButton() { public function getVideosManagerListButton() {
$btn = '<button type="button" class="btn btn-danger btn-sm btn-xs btn-block " onclick="youTubeUpload(\' + row.id + \');" data-row-id="right" data-toggle="tooltip" data-placement="left" title="Upload to YouTube"><i class="fab fa-youtube"></i> Upload</button>'; $btn = '<button type="button" class="btn btn-danger btn-sm btn-xs btn-block " onclick="youTubeUpload(\' + row.id + \');" data-row-id="right" data-toggle="tooltip" data-placement="left" title="Upload to YouTube"><i class="fab fa-youtube"></i> Upload</button>';
return $btn; return $btn;
} }
public static function getUploadedURL($videos_id) { public static function getUploadedURL($videos_id) {
$youTubeUpload = new YouTubeUploads(0); $youTubeUpload = new YouTubeUploads(0);
$youTubeUpload->loadFromVideosID($videos_id); $youTubeUpload->loadFromVideosID($videos_id);
if (empty($youTubeUpload->getUrl())) { if (empty($youTubeUpload->getUrl())) {
return false; return false;
} }
return $youTubeUpload->getUrl(); return $youTubeUpload->getUrl();
} }
public function getPluginMenu() {
global $global;
$link = "<button class='btn btn-primary btn-xs btn-block' title='Upload All Videos to YouTube' onclick='youTubeUploadAll()'><i class='fab fa-youTube-v'></i> Upload All Videos</button>";
return $link;
}
*
*/
public function getPluginMenu() {
global $global;
$link = "<button class='btn btn-primary btn-xs btn-block' title='Upload All Videos to YouTube' onclick='youTubeUploadAll()'><i class='fab fa-youTube-v'></i> Upload All Videos</button>";
return $link;
}
*
*/
} }