Files
manifest.json
options.html
options.js
popup.css
popup.html
popup.js
Code
6 770
popup.js
const API_KEY_STORAGE = 'youtube_api_key';
const CACHE_KEY = 'speedtelly_cache';
const CACHE_DURATION = 30 * 60 * 1000; // 30 minutes
document.getElementById('searchBtn').addEventListener('click', searchVideos);
document.getElementById('settingsBtn').addEventListener('click', () => {
chrome.runtime.openOptionsPage();
});
document.getElementById('openSettings')?.addEventListener('click', (e) => {
e.preventDefault();
chrome.runtime.openOptionsPage();
});
async function searchVideos() {
const apiKey = await getApiKey();
if (!apiKey) {
showNoKeyWarning();
return;
}
hideAllMessages();
showLoading(true);
const sortBy = document.getElementById('sortBy').value;
const minViews = parseInt(document.getElementById('minViews').value) || 0;
try {
const videos = await fetchSpeedTellyVideos(apiKey, sortBy);
const filtered = videos.filter(v => v.viewCount >= minViews);
displayVideos(filtered);
if (filtered.length === 0) {
showNoResults();
}
} catch (error) {
console.error('Erreur lors de la recherche:', error);
showError('Erreur: ' + error.message);
} finally {
showLoading(false);
}
}
async function fetchSpeedTellyVideos(apiKey, sortBy) {
const cache = await getCache();
if (cache && cache.timestamp > Date.now() - CACHE_DURATION) {
return sortVideos(cache.videos, sortBy);
}
const searchQuery = 'minecraft speedtelly OR #speedtelly';
const url = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(searchQuery)}&type=video&maxResults=50&key=${apiKey}&relevanceLanguage=fr&videoCategoryId=20`;
const response = await fetch(url);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || 'Erreur API YouTube');
}
const data = await response.json();
const videoIds = data.items.map(item => item.id.videoId).join(',');
const statsUrl = `https://www.googleapis.com/youtube/v3/videos?part=statistics,snippet&id=${videoIds}&key=${apiKey}`;
const statsResponse = await fetch(statsUrl);
const statsData = await statsResponse.json();
const videos = statsData.items.map(item => ({
id: item.id,
title: item.snippet.title,
channel: item.snippet.channelTitle,
thumbnail: item.snippet.thumbnails.medium.url,
publishedAt: item.snippet.publishedAt,
viewCount: parseInt(item.statistics.viewCount) || 0,
likeCount: parseInt(item.statistics.likeCount) || 0,
commentCount: parseInt(item.statistics.commentCount) || 0,
description: item.snippet.description,
hashtags: extractHashtags(item.snippet.title + ' ' + item.snippet.description)
}));
await setCache({ videos, timestamp: Date.now() });
return sortVideos(videos, sortBy);
}
function sortVideos(videos, sortBy) {
const sorted = [...videos];
switch (sortBy) {
case 'viewCount':
sorted.sort((a, b) => b.viewCount - a.viewCount);
break;
case 'likeCount':
sorted.sort((a, b) => b.likeCount - a.likeCount);
break;
case 'date':
sorted.sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
break;
}
return sorted;
}
function extractHashtags(text) {
const hashtagRegex = /#[a-zA-Z0-9_]+/g;
const matches = text.match(hashtagRegex);
return matches ? [...new Set(matches.map(h => h.toLowerCase()))] : [];
}
function displayVideos(videos) {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = '';
videos.forEach(video => {
const card = document.createElement('div');
card.className = 'video-card';
const timeAgo = getTimeAgo(video.publishedAt);
card.innerHTML = `
<div class="video-title">${escapeHtml(video.title)}</div>
<div class="video-channel">${escapeHtml(video.channel)}</div>
<div class="video-stats">
<span>👁️ ${formatNumber(video.viewCount)}</span>
<span>👍 ${formatNumber(video.likeCount)}</span>
<span>💬 ${formatNumber(video.commentCount)}</span>
<span>📅 ${timeAgo}</span>
</div>
<div class="video-hashtags">
${video.hashtags.slice(0, 5).map(tag => `<span class="hashtag">${escapeHtml(tag)}</span>`).join('')}
</div>
<div class="video-actions">
<button class="btn-watch" data-video-id="${video.id}">▶️ Regarder</button>
<button class="btn-copy" data-hashtags='${JSON.stringify(video.hashtags)}'>📋 Copier #</button>
</div>
`;
resultsDiv.appendChild(card);
});
document.querySelectorAll('.btn-watch').forEach(btn => {
btn.addEventListener('click', () => {
const videoId = btn.getAttribute('data-video-id');
chrome.tabs.create({ url: `https://www.youtube.com/watch?v=${videoId}` });
});
});
document.querySelectorAll('.btn-copy').forEach(btn => {
btn.addEventListener('click', async () => {
const hashtags = JSON.parse(btn.getAttribute('data-hashtags'));
const text = hashtags.join(' ');
try {
await navigator.clipboard.writeText(text);
btn.textContent = '✅ Copié!';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = '📋 Copier #';
btn.classList.remove('copied');
}, 2000);
} catch (error) {
console.error('Erreur copie:', error);
btn.textContent = '❌ Erreur';
}
});
});
}
function formatNumber(num) {
if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
return num.toString();
}
function getTimeAgo(dateString) {
const now = new Date();
const date = new Date(dateString);
const seconds = Math.floor((now - date) / 1000);
if (seconds < 3600) return Math.floor(seconds / 60) + ' min';
if (seconds < 86400) return Math.floor(seconds / 3600) + 'h';
if (seconds < 2592000) return Math.floor(seconds / 86400) + 'j';
return Math.floor(seconds / 2592000) + ' mois';
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
async function getApiKey() {
const result = await chrome.storage.local.get(API_KEY_STORAGE);
return result[API_KEY_STORAGE] || '';
}
async function getCache() {
const result = await chrome.storage.local.get(CACHE_KEY);
return result[CACHE_KEY] || null;
}
async function setCache(data) {
await chrome.storage.local.set({ [CACHE_KEY]: data });