?AlkantarClanX12
| Current Path : /home/rankinh/reunionmag/ |
| Current File : /home/rankinh/reunionmag/import-youtube-video.php |
<?php
// Configuration
define('YOUTUBE_API_KEY_0', 'AIzaSyByQuFbnntDt9isx0X7_Zud_zLJfDXsPuw');
define('YOUTUBE_API_KEY_1', 'AIzaSyB-gRM-54jw6Zkmgx4ZGbHLgr483G5IL1Y');
define('YOUTUBE_API_KEY_2', 'AIzaSyB7KMRiDTKZxLakGpNGOJD6cCkWk7KzTD4');
define('WP_SITE_URL_DOMAIN', 'https://reunionmag.re');
define('WP_SITE_URL', WP_SITE_URL_DOMAIN . '/wp-json/wp/v2/posts');
define('WP_MEDIA_URL', WP_SITE_URL_DOMAIN . '/wp-json/wp/v2/media');
define('WP_SITE_POST_CATEGORIES_URL', WP_SITE_URL_DOMAIN . '/wp-json/wp/v2/categories');
define('WP_USERNAME', 'Dev974');
define('WP_PASSWORD', '$hS69J0)K@sNeV^Ovv');
define('MAX_VIDEOS_PER_CATEGORY', 1);
define('HISTORY_FILE', 'published_videos.json');
define('CACHE_FILE', 'cache_videos.json');
define('CACHE_EXPIRATION', 86400); // 24 heures
$api_keys = [YOUTUBE_API_KEY_1, YOUTUBE_API_KEY_2];
define('YOUTUBE_API_KEY', $api_keys[array_rand($api_keys)]);
function dump($a){
echo "<pre>";
var_dump($a);
echo "</pre>";
}
// dump('YOUTUBE_API_KEY');
// dump(YOUTUBE_API_KEY);
$categories = [
"https://www.youtube.com/@ZapReunion" => ["Tendances & Actus"],
"https://www.youtube.com/@NotreHistoiredoc" => ["Culture & Patrimoine"],
"https://www.youtube.com/@reportagekulture3014" => ["Culture & Patrimoine"],
"https://www.youtube.com/@KanalAustral-TV" => ["Entreprises & Innovations"],
"https://www.youtube.com/@Food_Story" => ["Gastronomie & Saveurs"],
"https://www.youtube.com/@SLICE_Voyage" => ["Gastronomie & Saveurs"],
"https://www.youtube.com/@KDMFAMILYTV" => ["Musique & Spectacles"],
"https://www.youtube.com/@974Muzik" => ["Musique & Spectacles"],
"https://www.youtube.com/@ReunionTourisme" => ["Nature & Paysages", "Sports & Aventures"],
"https://www.youtube.com/@reunionla1ere" => ["Entreprises & Innovations", "News & Actualités", "Sports & Aventures", "Tendances & Actus"],
"https://www.youtube.com/@antennereunion1394" => ["News & Actualités"],
"https://www.youtube.com/@SecretsdeLaTerre" => ["Reportages & Immersion"],
"https://www.youtube.com/c/Echapp%C3%A9esbellesofficiel" => ["Reportages & Immersion"],
];
// $categories = [
// "Culture & Patrimoine" => ["https://www.youtube.com/@NotreHistoiredoc", "https://www.youtube.com/@reportagekulture3014"],
// "Entreprises & Innovations" => ["https://www.youtube.com/@KanalAustral-TV"],
// "Gastronomie & Saveurs" => ["https://www.youtube.com/@Food_Story", "https://www.youtube.com/@SLICE_Voyage"],
// "Musique & Spectacles" => ["https://www.youtube.com/@KDMFAMILYTV", "https://www.youtube.com/@974Muzik"],
// "Nature & Paysages" => ["https://www.youtube.com/@ReunionTourisme"],
// "News & Actualités" => ["https://www.youtube.com/@reunionla1ere", "https://www.youtube.com/@antennereunion1394"],
// "Reportages & Immersion" => ["https://www.youtube.com/c/Echapp%C3%A9esbellesofficiel", "https://www.youtube.com/@SecretsdeLaTerre"],
// "Sports & Aventures" => [ "https://www.youtube.com/@ReunionTourisme"],
// "Tendances & Actus" => ["https://www.youtube.com/@ZapReunion"]
// ];
// CATEGORIES = {
// "Culture & Patrimoine": ["https://www.youtube.com/@NotreHistoiredoc", "https://www.youtube.com/@reportagekulture3014"],
// "Entreprises & Innovations": ["https://www.youtube.com/@reunionla1ere", "https://www.youtube.com/@KanalAustral-TV"],
// "Gastronomie & Saveurs": ["https://www.youtube.com/@Food_Story", "https://www.youtube.com/@SLICE_Voyage"],
// "Musique & Spectacles": ["https://www.youtube.com/@KDMFAMILYTV", "https://www.youtube.com/@974Muzik"],
// "Nature & Paysages": ["https://www.youtube.com/@ReunionTourisme"],
// "News & Actualités": ["https://www.youtube.com/@reunionla1ere", "https://www.youtube.com/@antennereunion1394"],
// "Reportages & Immersion": ["https://www.youtube.com/c/Echapp%C3%A9esbellesofficiel", "https://www.youtube.com/@SecretsdeLaTerre"],
// "Sports & Aventures": ["https://www.youtube.com/@reunionla1ere", "https://www.youtube.com/@ReunionTourisme"],
// "Tendances & Actus": ["https://www.youtube.com/@reunionla1ere", "https://www.youtube.com/@ZapReunion"]
// }
function get_jwt_token($username, $password) {
$url = WP_SITE_URL_DOMAIN . "/wp-json/jwt-auth/v1/token";
$post_data = json_encode([
"username" => $username,
"password" => $password
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
// dump($response);
curl_close($ch);
$data = json_decode($response, true);
var_dump($data);
return $data['token'] ?? null; // Retourne le token JWT
}
// Utilisation
define('JWT_TOKEN', get_jwt_token(WP_USERNAME, WP_PASSWORD));
if (JWT_TOKEN) {
echo "Token JWT : " . JWT_TOKEN;
} else {
echo "Échec de l'authentification.";
die;
}
function load_published_videos() {
return file_exists(HISTORY_FILE) ? json_decode(file_get_contents(HISTORY_FILE), true) : [];
}
function save_published_video($video_id) {
$history = load_published_videos();
$history[] = $video_id;
file_put_contents(HISTORY_FILE, json_encode($history));
}
function get_youtube_channel_ID($url){
$html = file_get_contents($url);
// preg_match("'<link rel=\"canonical\" href=\"https://www.youtube.com/channel/(.*?)\"'si", $html, $match);
preg_match('/<link rel="canonical" href="https:\/\/www\.youtube\.com\/channel\/(.*?)"/i', $html, $match);
if($match && $match[1]) {
echo $match[1] . '\n';
return $match[1];
}
}
function get_latest_videos($channel_url, $max_results = MAX_VIDEOS_PER_CATEGORY) {
// $username = explode('@', $channel_url);
// $username = end($username);
$username = str_replace('https://www.youtube.com/', '', $channel_url);
$username = str_replace('c/', '', $username);
// $username = str_replace('@', '', $username);
$channel_id = get_youtube_channel_ID($channel_url);
// dump($channel_id);
$search_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&relevanceLanguage=fr&order=date&maxResults=$max_results&channelId=$channel_id&key=" . YOUTUBE_API_KEY;
// $search_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&order=date&maxResults=$max_results&q=$username&key=" . YOUTUBE_API_KEY;
$response = json_decode(file_get_contents($search_url), true);
dump('search_url');
dump($search_url);
// dump('get_latest_videos');
// dump($response);
$videos = [];
if (!empty($response['items'])) {
foreach ($response['items'] as $item) {
if (!empty($item['id']['videoId'])) {
$video_id = $item['id']['videoId'];
$videos[] = [
'video_id' => $video_id,
'title' => $item['snippet']['title'],
'description' => $item['snippet']['description'],
'video_url' => "https://www.youtube.com/watch?v=$video_id",
'thumbnail_url' => $item['snippet']['thumbnails']['high']['url']
];
}
}
}
dump('videos');
dump($videos);
return $videos;
}
function get_category_id($category_name) {
$url = WP_SITE_POST_CATEGORIES_URL . "?search=" . str_replace(" ", "%20", $category_name);
dump(__LINE__ .' - '. $url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . JWT_TOKEN
// 'Authorization: Basic ' . base64_encode(WP_USERNAME . ':' . WP_PASSWORD)
]);
$response = curl_exec($ch);
curl_close($ch);
// dump($response);
$categories = json_decode($response, true);
if (!empty($categories) && isset($categories[0]['id'])) {
return $categories[0]['id']; // Retourne l'ID si la catégorie existe
}
// Si la catégorie n'existe pas, la créer
// return create_category($category_name);
}
// function create_category($category_name) {
// $post_data = json_encode(["name" => $category_name]);
// $ch = curl_init(WP_SITE_POST_CATEGORIES_URL);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_HTTPHEADER, [
// 'Content-Type: application/json',
// 'Authorization: Basic ' . base64_encode(WP_USERNAME . ':' . WP_PASSWORD)
// ]);
// curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// $response = curl_exec($ch);
// dump($response);
// curl_close($ch);
// $category = json_decode($response, true);
// return $category['id'] ?? null; // Retourne l'ID de la nouvelle catégorie
// }
function create_thumbnail($video_id, $thumbnail_url){
// Télécharger l'image dans un fichier temporaire
$tmp_file = tempnam(sys_get_temp_dir(), 'thumb_');
file_put_contents($tmp_file, file_get_contents($thumbnail_url));
$original_filename = basename(parse_url($thumbnail_url, PHP_URL_PATH)); // ex: hqdefault.jpg
$extension = pathinfo($original_filename, PATHINFO_EXTENSION);
// Nouveau nom de fichier : hqdefault-wKklnWgP3TI.jpg
$filename = "{$video_id}-{$original_filename}";
// Déterminer le Content-Type selon l'extension
$mime_types = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp'
];
$content_type = $mime_types[$extension] ?? 'application/octet-stream';
// Lire le contenu de l'image
$image_data = file_get_contents($tmp_file);
unlink($tmp_file); // Nettoyage
$ch_media = curl_init(WP_MEDIA_URL);
curl_setopt($ch_media, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_media, CURLOPT_POST, true);
curl_setopt($ch_media, CURLOPT_POSTFIELDS, $image_data);
curl_setopt($ch_media, CURLOPT_HTTPHEADER, [
'Content-Disposition: attachment; filename="' . $filename . '"',
'Content-Type: ' . $content_type, // à adapter si nécessaire
'Authorization: Bearer ' . JWT_TOKEN
]);
$media_response = curl_exec($ch_media);
dump($media_response);
curl_close($ch_media);
$media_data = json_decode($media_response, true);
$media_id = $media_data['id'] ?? null;
if (!$media_id) {
echo "Impossible d'uploader l'image en tant que media.";
return null;
}
return $media_id;
}
function create_wordpress_post($video_id, $title, $content, $categories, $video_url, $thumbnail_url) {
$categories_ids = [];
foreach ($categories as $category) {
$categories_ids[] = get_category_id($category);
}
if (!$categories_ids) {
$categories_str = implode(" et ", $categories);
echo "Impossible de récupérer les IDs des catégories : $categories_str";
return null;
}
$media_id = create_thumbnail($video_id, $thumbnail_url);
$post_data = json_encode([
"title" => $title,
"content" => $content . "<br><br><a href='$video_url'>Voir la vidéo</a>",
"status" => "publish",
"categories" => $categories_ids,
"format" => "video",
"featured_media" => $media_id,
"meta" => [
"bk_feat_img_status" => 'from-themeoptions',
"bk_final_score" => 0,
"bk_heading_related_posts" => 'enable',
"bk_media_embed_code_post" => $video_url,
"bk_popup_frame" => 0,
"bk_post_layout" => 'single_template_11',
"bk_post_nav_style" => 'from-themeoptions',
"bk_post_sb_select" => 'global',
"bk_review_box_position" => 'left',
"bk_review_checkbox" => 0,
"bk_sidebar_position" => 'right',
"bk_user_rating" => 0,
"post_views_count" => 0,
]
]);
$ch = curl_init(WP_SITE_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . JWT_TOKEN
]);
// curl_setopt($ch, CURLOPT_HTTPHEADER, [
// 'Content-Type: application/json',
// 'Authorization: Basic ' . base64_encode(WP_USERNAME . ':' . WP_PASSWORD)
// ]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
dump($response);
curl_close($ch);
return json_decode($response, true);
}
function get_cached_videos() {
return (file_exists(CACHE_FILE) && (time() - filemtime(CACHE_FILE) < CACHE_EXPIRATION)) ? json_decode(file_get_contents(CACHE_FILE), true) : null;
}
function cache_videos($data) {
file_put_contents(CACHE_FILE, json_encode($data));
}
// TEST MEDIA
// create_thumbnail("wKklnWgP3TI","https://i.ytimg.com/vi/wKklnWgP3TI/hqdefault.jpg");
// die;
// Exécution
$cached_videos = get_cached_videos();
if (!$cached_videos) {
$cached_videos = [];
foreach ($categories as $channel_url => $categories) {
$videos = get_latest_videos($channel_url);
if(count($videos) > 0){
$cached_videos[$channel_url] = [
"videos" => $videos,
"categories" => $categories
];
}
}
// foreach ($categories as $category => $channels) {
// foreach ($channels as $channel_url) {
// $videos = get_latest_videos($channel_url);
// if(count($videos) > 0){
// $cached_videos[$category] = $videos;
// }
// }
// }
if(count($cached_videos) > 0){
cache_videos($cached_videos);
}
}
$published_videos = load_published_videos();
foreach ($cached_videos as $datas) {
$videos = $datas["videos"];
$categories = $datas["categories"];
// dump(__LINE__);
// // dump($datas);
// dump($videos);
// dump($categories);
// dump(__LINE__);
foreach ($videos as $video) {
if (!in_array($video['video_id'], $published_videos)) {
// echo "Ajout de l'article : " . $video['title'] . "<br>";
echo "Ajout de l'article : " . $video['title'] . ". Catégorie : ".$categories.". Description : ". $video['description'] ."<br>";
echo 'Url de la vidéo <a href="'. $video['video_url'] .'">' . $video['video_url'] . '</a><br><br>';
create_wordpress_post($video['video_id'], $video['title'], $video['description'], $categories, $video['video_url'], $video['thumbnail_url']);
save_published_video($video['video_id']);
}
}
}
// foreach ($cached_videos as $category => $videos) {
// foreach ($videos as $video) {
// if (!in_array($video['video_id'], $published_videos)) {
// echo "Ajout de l'article : " . $video['title'] . "<br>";
// echo "Ajout de l'article : " . $video['title'] . ". Catégorie : ".$category.". Description : ". $video['description'] ."<br>";
// echo 'Url de la vidéo <a href="'. $video['video_url'] .'">' . $video['video_url'] . '</a><br><br>';
// // create_wordpress_post($video['video_id'], $video['title'], $video['description'], $category, $video['video_url'], $video['thumbnail_url']);
// // save_published_video($video['video_id']);
// }
// }
// }