diff --git a/src/Juka/GUI/Clicked.cs b/src/Juka/GUI/Clicked.cs index 8ee2d2e..e985707 100644 --- a/src/Juka/GUI/Clicked.cs +++ b/src/Juka/GUI/Clicked.cs @@ -66,7 +66,7 @@ public static void ResumeVideo() } } - public static void itemclicked() + public static async void itemclicked() { if (keyboardOn == true) @@ -92,8 +92,8 @@ public static void itemclicked() if (Menus.MediaPlayer == currentscreen) { var apikey = "AIzaSyBzpZzE4nQVxr_EQLgWqTfREpvWON - gWu8"; - var youtube = new YouTubeApiService(apikey); - var videos = youtube.GetTopVideosSync(); + youtube = new YouTubeApiService(apikey); + var videos = await youtube.GetTopVideosAsync(); videoInfos = videos.Select(v => new VideoInfo { @@ -133,7 +133,7 @@ public static void itemclicked() } else if (menuOptions[Menus.MenuMain][i] == "Media Downloader") { - Helper.GenerateMedia(); + await Helper.GenerateMedia(); currentscreen = Menus.MediaPlayer; } else @@ -176,7 +176,7 @@ public static void itemclicked() { if (menuOptions[Menus.MediaPlayer][i] == "Back") { - YouTubeApiService.DeleteThumbnails(videoInfos); + youtube.DeleteThumbnails(videoInfos); currentscreen = Menus.MenuMain; } else if(menuOptions[Menus.MediaPlayer][i] == "Search") diff --git a/src/Juka/GUI/Globals.cs b/src/Juka/GUI/Globals.cs index 3d2ce95..a67b16c 100644 --- a/src/Juka/GUI/Globals.cs +++ b/src/Juka/GUI/Globals.cs @@ -92,6 +92,8 @@ public enum Menus public static Process ffplayProcess; public static StreamWriter ffplayInput; + public static YouTubeApiService youtube; + } public class Descript diff --git a/src/Juka/GUI/Helper.cs b/src/Juka/GUI/Helper.cs index 0fc58c0..dccfd25 100644 --- a/src/Juka/GUI/Helper.cs +++ b/src/Juka/GUI/Helper.cs @@ -76,11 +76,11 @@ public static async Task GeneratePackages() //packages } - public static void GenerateMedia() + public static async Task GenerateMedia() { var apikey = "AIzaSyBzpZzE4nQVxr_EQLgWqTfREpvWON - gWu8"; var youtube = new YouTubeApiService(apikey); - var videos = youtube.GetTopVideosSync(); + var videos = await youtube.GetTopVideosAsync(); videoInfos = videos.Select(v => new VideoInfo { diff --git a/src/Juka/GUI/YouTube.cs b/src/Juka/GUI/YouTube.cs index db8adf0..6839ab3 100644 --- a/src/Juka/GUI/YouTube.cs +++ b/src/Juka/GUI/YouTube.cs @@ -1,229 +1,198 @@ -using System.Net; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; using System.Text.Json; +using System.Threading.Tasks; using static Juka.GUI.Globals; -namespace Juka.GUI; - -public class YouTubeApiService +namespace Juka.GUI { - private string _apiKey; - - public YouTubeApiService(string apiKey) - { - _apiKey = apiKey; - } - - public List GetTopVideosSync(string regionCode = "US") + public class YouTubeApiService { - var chart = "mostPopular"; - var url = $"https://www.googleapis.com/youtube/v3/videos?part=snippet&chart={chart}®ionCode={Uri.EscapeDataString(regionCode)}&maxResults=4&key={Uri.EscapeDataString(_apiKey)}"; + private readonly string _apiKey; + private readonly HttpClient _httpClient; + private readonly string _tempDirectory; - if (keyboardbuffer.Length > 0) + public YouTubeApiService(string apiKey) { - var encodedSearchTerm = Uri.EscapeDataString(keyboardbuffer); - url = $"https://www.googleapis.com/youtube/v3/search?part=snippet&q={encodedSearchTerm}®ionCode={Uri.EscapeDataString(regionCode)}&maxResults=4&key={Uri.EscapeDataString(_apiKey)}"; - + _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey)); + _httpClient = new HttpClient(); + _tempDirectory = Path.Combine(Directory.GetCurrentDirectory(), "temp"); + InitializeTempDirectory(); } - - ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; - - try + private void InitializeTempDirectory() { - var request = (HttpWebRequest)WebRequest.Create(url); - request.Method = "GET"; + if (Directory.Exists(_tempDirectory)) + { + Directory.Delete(_tempDirectory, true); + } + Directory.CreateDirectory(_tempDirectory); + } - using (var response = (HttpWebResponse)request.GetResponse()) + public async Task> GetTopVideosAsync(string regionCode = "US") + { + var chart = "mostPopular"; + var url = $"https://www.googleapis.com/youtube/v3/videos?part=snippet&chart={chart}®ionCode={Uri.EscapeDataString(regionCode)}&maxResults=4&key={Uri.EscapeDataString(_apiKey)}"; + if (!string.IsNullOrEmpty(keyboardbuffer)) { - if (response.StatusCode == HttpStatusCode.OK) - { - using (Stream stream = response.GetResponseStream()) + var encodedSearchTerm = Uri.EscapeDataString(keyboardbuffer); + url = $"https://www.googleapis.com/youtube/v3/search?part=snippet&q={encodedSearchTerm}®ionCode={Uri.EscapeDataString(regionCode)}&maxResults=4&key={Uri.EscapeDataString(_apiKey)}"; + } - using (StreamReader reader = new StreamReader(stream)) - { - string jsonResponse - = reader.ReadToEnd(); + try + { + var response = await _httpClient.GetAsync(url); - YouTubeResponse youtubeResponse = DeserializeYouTubeResponse(jsonResponse); // Needs implementation + if (response.IsSuccessStatusCode) + { + var jsonResponse = await response.Content.ReadAsStringAsync(); + var youtubeResponse = DeserializeYouTubeResponse(jsonResponse); - DownloadThumbnails(youtubeResponse.Items); - return youtubeResponse.Items; - } + await DownloadThumbnailsAsync(youtubeResponse.Items); + return youtubeResponse.Items; } else { - Console.WriteLine($"Error: {response.StatusCode} - {response.StatusDescription}"); - return null; // Handle error or return a defaultvalue + Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}"); + return null; } } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - return null; - } - } - private void DownloadThumbnails(List videos) - { - foreach (var video in videos) - { - if (!File.Exists(video.VideoId + ".jpg")) + catch (Exception ex) { - DownloadImage("https://img.youtube.com/vi/" + video.VideoId + "/0.jpg", video.VideoId + ".jpg"); + Console.WriteLine($"Error: {ex.Message}"); + return null; } } - } - public static void DeleteThumbnails(List videos) - { - foreach (var video in videos) + private async Task DownloadThumbnailsAsync(List videos) { - if (File.Exists(video.VideoId + ".jpg")) + var tasks = new List(); + + foreach (var video in videos) { - DeleteImage(video.VideoId + ".jpg"); + var filePath = Path.Combine(_tempDirectory, $"{video.VideoId}.jpg"); + if (!File.Exists(filePath)) + { + tasks.Add(DownloadImageAsync($"https://img.youtube.com/vi/{video.VideoId}/0.jpg", filePath)); + } } + + await Task.WhenAll(tasks); } - } - public static bool DeleteImage(string filePath) - { - try + public void DeleteThumbnails(List videos) { - if (File.Exists(filePath)) + foreach (var video in videos) { - File.Delete(filePath); + var filePath = Path.Combine(_tempDirectory, $"{video.VideoId}.jpg"); + if (File.Exists(filePath)) + { + DeleteImage(filePath); + } } - return true; } - catch (Exception ex) - { - Console.WriteLine($"Error deleting image: {ex.Message}"); - return false; - } - } - private bool DownloadImage(string url, string filePath) - { - try + public bool DeleteImage(string filePath) { - using (var client = new WebClient()) + try { - client.DownloadFile(url, filePath); + if (File.Exists(filePath)) + { + File.Delete(filePath); + } return true; } + catch (Exception ex) + { + Console.WriteLine($"Error deleting image: {ex.Message}"); + return false; + } } - catch (Exception ex) - { - Console.WriteLine($"Error downloading thumbnail for {url}: {ex.Message}"); - return false; - } - } - private YouTubeResponse DeserializeYouTubeResponse(string json) - { - if(keyboardbuffer.Length > 0) + private async Task DownloadImageAsync(string url, string filePath) { - return DeserializeSearchResponse(json); + try + { + var imageBytes = await _httpClient.GetByteArrayAsync(url); + await File.WriteAllBytesAsync(filePath, imageBytes); + return true; + } + catch (Exception ex) + { + Console.WriteLine($"Error downloading thumbnail for {url}: {ex.Message}"); + return false; + } } - else + + private YouTubeResponse DeserializeYouTubeResponse(string json) { - return DeserializeVideoResponse(json); + return !string.IsNullOrEmpty(keyboardbuffer) ? DeserializeSearchResponse(json) : DeserializeVideoResponse(json); } - } - - private YouTubeResponse DeserializeVideoResponse(string json) - { - // Your existing deserialization logic for videos - var youtubeResponse = new YouTubeResponse { Items = new List() }; - using (JsonDocument doc = JsonDocument.Parse(json)) + private YouTubeResponse DeserializeVideoResponse(string json) { - if (doc.RootElement.TryGetProperty("items", out JsonElement items)) + var youtubeResponse = new YouTubeResponse { Items = new List() }; + + using (var doc = JsonDocument.Parse(json)) { - foreach (JsonElement item in items.EnumerateArray()) + if (doc.RootElement.TryGetProperty("items", out var items)) { - var videoInfo = new VideoInfo(); - - if (item.TryGetProperty("id", out JsonElement id)) - { - videoInfo.VideoId = id.GetString(); - } - - if (item.TryGetProperty("snippet", out JsonElement snippet)) + foreach (var item in items.EnumerateArray()) { - if (snippet.TryGetProperty("title", out JsonElement title)) + var videoInfo = new VideoInfo { - videoInfo.Title = title.GetString(); - } + VideoId = item.GetProperty("id").GetString() + }; - if (snippet.TryGetProperty("description", out JsonElement description)) + if (item.TryGetProperty("snippet", out var snippet)) { - videoInfo.Description = description.GetString(); + videoInfo.Title = snippet.GetProperty("title").GetString(); + videoInfo.Description = snippet.GetProperty("description").GetString(); } - } - youtubeResponse.Items.Add(videoInfo); + youtubeResponse.Items.Add(videoInfo); + } } } + return youtubeResponse; } - return youtubeResponse; - } - private YouTubeResponse DeserializeSearchResponse(string json) - { - var youtubeResponse = new YouTubeResponse { Items = new List() }; - - try + private YouTubeResponse DeserializeSearchResponse(string json) { - using (var document = JsonDocument.Parse(json)) + var youtubeResponse = new YouTubeResponse { Items = new List() }; + + using (var doc = JsonDocument.Parse(json)) { - if (document.RootElement.TryGetProperty("items", out JsonElement items)) + if (doc.RootElement.TryGetProperty("items", out var items)) { foreach (var item in items.EnumerateArray()) { var videoInfo = new VideoInfo(); - if (item.TryGetProperty("id", out JsonElement idElement)) + if (item.TryGetProperty("id", out var idElement) && idElement.TryGetProperty("videoId", out var videoIdElement)) { - if (idElement.TryGetProperty("videoId", out JsonElement videoIdElement)) - { - videoInfo.VideoId = videoIdElement.GetString(); - } + videoInfo.VideoId = videoIdElement.GetString(); } - if (item.TryGetProperty("snippet", out JsonElement snippet)) + if (item.TryGetProperty("snippet", out var snippet)) { - if (snippet.TryGetProperty("title", out JsonElement title)) - { - videoInfo.Title = title.GetString(); - } - - if (snippet.TryGetProperty("description", out JsonElement description)) - { - videoInfo.Description = description.GetString(); - } - - + videoInfo.Title = snippet.GetProperty("title").GetString(); + videoInfo.Description = snippet.GetProperty("description").GetString(); } youtubeResponse.Items.Add(videoInfo); } } } + return youtubeResponse; } - catch (JsonException ex) + + public class YouTubeResponse { - Console.WriteLine($"Error deserializing YouTube search response: {ex.Message}"); - // Handle the error appropriately + public List Items { get; set; } } - - return youtubeResponse; - } - - - public class YouTubeResponse - { - public List Items { get; set; } } -} +} \ No newline at end of file