From 55eb1d14bd09d11ee1d2274ff85b816bdd06f487 Mon Sep 17 00:00:00 2001 From: yoqzii <109358690+ignYoqzii@users.noreply.github.com> Date: Mon, 9 Sep 2024 00:43:33 -0400 Subject: [PATCH] Added greetings with your username! --- .../StarZLauncher/Classes/Loader.cs | 95 +++ .../StarZLauncher/Classes/MusicPlayer.cs | 677 +++++++++--------- .../StarZLauncher/Classes/ThemesManager.cs | 2 - .../StarZLauncher/StarZLauncher.csproj | 5 +- .../StarZLauncher/Windows/MainWindow.xaml | 26 +- .../StarZLauncher/Windows/MainWindow.xaml.cs | 8 +- 6 files changed, 453 insertions(+), 360 deletions(-) diff --git a/StarZ Launcher/StarZLauncher/Classes/Loader.cs b/StarZ Launcher/StarZLauncher/Classes/Loader.cs index ac0b21d..dcc4b40 100644 --- a/StarZ Launcher/StarZLauncher/Classes/Loader.cs +++ b/StarZ Launcher/StarZLauncher/Classes/Loader.cs @@ -1,8 +1,12 @@ using System; using System.IO; +using System.Threading.Tasks; using System.Windows; +using System.DirectoryServices.AccountManagement; +using System.Windows.Media.Animation; using static StarZLauncher.Classes.MusicPlayer; using static StarZLauncher.Windows.MainWindow; +using System.Windows.Media; namespace StarZLauncher.Classes { @@ -86,6 +90,15 @@ public static void Load() { LogManager.Log($"Error retrieving local IP address: {ex.Message}", logFileName); } + try + { + Task.Run(() => LoadUserProfileInfo()); + LogManager.Log("Loaded Windows account username.", logFileName); + } + catch (Exception ex) + { + LogManager.Log($"Error retrieving Windows account username: {ex.Message}", logFileName); + } bool debug = ConfigManager.GetOfflineMode(); if (!debug) @@ -149,5 +162,87 @@ private static void CheckForItemsCount() MusicPlayerInformationTextBlock!.Visibility = Visibility.Collapsed; } } + + public static async Task LoadUserProfileInfo() + { + // Get the current greeting based on the time of day + string greeting = GetGreetingBasedOnTime(); + + // Set the initial text to "Greeting" and configure opacity + await Application.Current.Dispatcher.InvokeAsync(() => + { + WelcomeBack!.Text = greeting; + WelcomeBack.Opacity = 0; // Start with invisible text + + // Create a fade-in animation for the initial text + DoubleAnimation fadeInWelcomeAnimation = new() + { + From = 0, // Start from invisible + To = 1, // Fade in to fully visible + Duration = new Duration(TimeSpan.FromSeconds(0.5)) // Half a second fade-in + }; + + // Apply the animation to the Opacity property + WelcomeBack!.BeginAnimation(UIElement.OpacityProperty, fadeInWelcomeAnimation); + }); + + // Load the user display name asynchronously + string displayName = Environment.UserName; // Default to Environment.UserName + try + { + UserPrincipal userPrincipal = await Task.Run(() => UserPrincipal.Current); + displayName = userPrincipal.DisplayName; + } + catch + { + throw new Exception("No username found."); + } + + // Check if displayName is null or empty + if (string.IsNullOrWhiteSpace(displayName)) + { + // Stop execution and do not update the username textblock if displayName is empty or null + return; + } + + // Update the text and apply fade-in animation for the complete text + await Application.Current.Dispatcher.InvokeAsync(() => + { + // Update the text to include the username + WelcomeUsername!.Text = $", {displayName} !"; + + // Create a fade-in animation for the updated text + DoubleAnimation fadeInUsernameAnimation = new() + { + From = 0, // Start from invisible + To = 1, // Fade in to fully visible + Duration = new Duration(TimeSpan.FromSeconds(0.5)) // Half a second fade-in + }; + + // Apply the animation to the Opacity property + WelcomeUsername.BeginAnimation(UIElement.OpacityProperty, fadeInUsernameAnimation); + }); + } + + public static string GetGreetingBasedOnTime() + { + // Get the current hour + int currentHour = DateTime.Now.Hour; + + // Determine the greeting based on the time of day + if (currentHour >= 5 && currentHour < 12) + { + return "Good morning"; + } + else if (currentHour >= 12 && currentHour < 17) + { + return "Good afternoon"; + } + else + { + return "Good evening"; + } + } + } } diff --git a/StarZ Launcher/StarZLauncher/Classes/MusicPlayer.cs b/StarZ Launcher/StarZLauncher/Classes/MusicPlayer.cs index 3df9cb5..4a916aa 100644 --- a/StarZ Launcher/StarZLauncher/Classes/MusicPlayer.cs +++ b/StarZ Launcher/StarZLauncher/Classes/MusicPlayer.cs @@ -1,40 +1,40 @@ -using NReco.VideoConverter; -using StarZLauncher.Windows; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using YoutubeExplode; -using YoutubeExplode.Common; -using YoutubeExplode.Videos; -using static StarZLauncher.Windows.MainWindow; - -namespace StarZLauncher.Classes -{ - public static class MusicPlayer - { - public static string MusicDirectoryPath { get; private set; } - public static MediaPlayer MediaPlayer { get; private set; } - public static bool IsPaused { get; private set; } = false; - public static TimeSpan CurrentPosition { get; private set; } = TimeSpan.Zero; - public static bool IsStopped { get; private set; } = true; - private static readonly Random Random = new(); - - public static ObservableCollection MusicItems { get; set; } = new ObservableCollection(); - - static MusicPlayer() - { - MusicDirectoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "StarZ Launcher", "Musics"); - Directory.CreateDirectory(MusicDirectoryPath); - MediaPlayer = new MediaPlayer(); - MediaPlayer.MediaEnded += MediaPlayer_MediaEnded; +using NReco.VideoConverter; +using StarZLauncher.Windows; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using YoutubeExplode; +using YoutubeExplode.Common; +using YoutubeExplode.Videos; +using static StarZLauncher.Windows.MainWindow; + +namespace StarZLauncher.Classes +{ + public static class MusicPlayer + { + public static string MusicDirectoryPath { get; private set; } + public static MediaPlayer MediaPlayer { get; private set; } + public static bool IsPaused { get; private set; } = false; + public static TimeSpan CurrentPosition { get; private set; } = TimeSpan.Zero; + public static bool IsStopped { get; private set; } = true; + private static readonly Random Random = new(); + + public static ObservableCollection MusicItems { get; set; } = new ObservableCollection(); + + static MusicPlayer() + { + MusicDirectoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "StarZ Launcher", "Musics"); + Directory.CreateDirectory(MusicDirectoryPath); + MediaPlayer = new MediaPlayer(); + MediaPlayer.MediaEnded += MediaPlayer_MediaEnded; } private static async Task UpdateSongTime() @@ -72,126 +72,125 @@ private static async Task UpdateSongTime() { IsStopped = true; // Avoid crashing } - } - - - private static void MediaPlayer_MediaEnded(object sender, EventArgs e) - { - ShuffleAndPlayNext(); - } - - public static void AddMusic() - { - var openFileDialog = new Microsoft.Win32.OpenFileDialog - { - Multiselect = true, - Filter = "Audio Files|*.mp3" - }; - - if (openFileDialog.ShowDialog() == true) - { - foreach (var filePath in openFileDialog.FileNames) - { - var destinationPath = Path.Combine(MusicDirectoryPath, Path.GetFileName(filePath)); - System.IO.File.Copy(filePath, destinationPath, true); - } - - Loader.LoadMusicFiles(); - } - } - - public static string GetArtistFromSongFile(string filePath) - { - try - { - var file = TagLib.File.Create(filePath); - var artist = file.Tag.FirstPerformer; - return string.IsNullOrEmpty(artist) ? "Unknown" : artist; - } - catch (Exception) - { - return "Unknown"; - } - } - - public static ImageSource GetImageFromSongFile(string filePath) - { - var defaultImage = new BitmapImage(new Uri("/Resources/Unknow.png", UriKind.Relative)); - try - { - var file = TagLib.File.Create(filePath); - var picture = file.Tag.Pictures.FirstOrDefault(); - if (picture != null) - { - using var memoryStream = new MemoryStream(picture.Data.Data); - var bitmapImage = new BitmapImage(); - bitmapImage.BeginInit(); - bitmapImage.StreamSource = memoryStream; - bitmapImage.CacheOption = BitmapCacheOption.OnLoad; - bitmapImage.EndInit(); - return bitmapImage; - } - } - catch (Exception) - { - } - - return defaultImage; - } - - public static async void PlayMusic(string filepath) - { - if (IsPaused) - { - MediaPlayer.Position = CurrentPosition; - MediaPlayer.Play(); + } + + + private static void MediaPlayer_MediaEnded(object sender, EventArgs e) + { + ShuffleAndPlayNext(); + } + + public static void AddMusic() + { + var openFileDialog = new Microsoft.Win32.OpenFileDialog + { + Multiselect = true, + Filter = "Audio Files|*.mp3" + }; + + if (openFileDialog.ShowDialog() == true) + { + foreach (var filePath in openFileDialog.FileNames) + { + var destinationPath = Path.Combine(MusicDirectoryPath, Path.GetFileName(filePath)); + System.IO.File.Copy(filePath, destinationPath, true); + } + + Loader.LoadMusicFiles(); + } + } + + public static string GetArtistFromSongFile(string filePath) + { + try + { + var file = TagLib.File.Create(filePath); + var artist = file.Tag.FirstPerformer; + return string.IsNullOrEmpty(artist) ? "Unknown" : artist; + } + catch (Exception) + { + return "Unknown"; + } + } + + public static ImageSource GetImageFromSongFile(string filePath) + { + var defaultImage = new BitmapImage(new Uri("/Resources/Unknow.png", UriKind.Relative)); + try + { + var file = TagLib.File.Create(filePath); + var picture = file.Tag.Pictures.FirstOrDefault(); + if (picture != null) + { + using var memoryStream = new MemoryStream(picture.Data.Data); + var bitmapImage = new BitmapImage(); + bitmapImage.BeginInit(); + bitmapImage.StreamSource = memoryStream; + bitmapImage.CacheOption = BitmapCacheOption.OnLoad; + bitmapImage.EndInit(); + return bitmapImage; + } + } + catch (Exception) + { + } + + return defaultImage; + } + + public static async void PlayMusic(string filepath) + { + if (IsPaused) + { + MediaPlayer.Position = CurrentPosition; + MediaPlayer.Play(); IsPaused = false; - IsStopped = false; - await UpdateSongTime(); - bool DiscordRPCisEnabled = ConfigManager.GetDiscordRPC(); - bool OfflineModeisEnabled = ConfigManager.GetOfflineMode(); - if (DiscordRPCisEnabled == true & OfflineModeisEnabled == false) - { - string title = Path.GetFileNameWithoutExtension(filepath); - DiscordRichPresenceManager.DiscordClient.UpdateDetails($"Listening to {title}"); - DiscordRichPresenceManager.DiscordClient.UpdateState("Using the Music Player"); - } - } - else - { - MediaPlayer.Open(new Uri(filepath)); - MediaPlayer.Play(); - CurrentlyPlayingSongTitle!.Text = Path.GetFileNameWithoutExtension(filepath); - CurrentlyPlayingSongArtist!.Text = GetArtistFromSongFile(filepath); + IsStopped = false; + bool DiscordRPCisEnabled = ConfigManager.GetDiscordRPC(); + bool OfflineModeisEnabled = ConfigManager.GetOfflineMode(); + if (DiscordRPCisEnabled == true & OfflineModeisEnabled == false) + { + string title = Path.GetFileNameWithoutExtension(filepath); + DiscordRichPresenceManager.DiscordClient.UpdateDetails($"Listening to {title}"); + DiscordRichPresenceManager.DiscordClient.UpdateState("Using the Music Player"); + } + await UpdateSongTime(); + } + else + { + MediaPlayer.Open(new Uri(filepath)); + MediaPlayer.Play(); + CurrentlyPlayingSongTitle!.Text = Path.GetFileNameWithoutExtension(filepath); + CurrentlyPlayingSongArtist!.Text = GetArtistFromSongFile(filepath); CurrentlyPlayingSongImage!.Source = GetImageFromSongFile(filepath); - IsStopped = false; - await UpdateSongTime(); - - bool DiscordRPCisEnabled = ConfigManager.GetDiscordRPC(); - bool OfflineModeisEnabled = ConfigManager.GetOfflineMode(); - if (DiscordRPCisEnabled == true & OfflineModeisEnabled == false) - { - string title = Path.GetFileNameWithoutExtension(filepath); - DiscordRichPresenceManager.DiscordClient.UpdateDetails($"Listening to {title}"); - DiscordRichPresenceManager.DiscordClient.UpdateState("Using the Music Player"); - } - } - } - - public static void PauseMusic() - { - MediaPlayer.Pause(); - CurrentPosition = MediaPlayer.Position; - IsPaused = true; - IsStopped = true; - bool DiscordRPCisEnabled = ConfigManager.GetDiscordRPC(); - bool OfflineModeisEnabled = ConfigManager.GetOfflineMode(); - if (DiscordRPCisEnabled == true & OfflineModeisEnabled == false) - { - DiscordRichPresenceManager.IdlePresence(); - } - } - + IsStopped = false; + bool DiscordRPCisEnabled = ConfigManager.GetDiscordRPC(); + bool OfflineModeisEnabled = ConfigManager.GetOfflineMode(); + if (DiscordRPCisEnabled == true & OfflineModeisEnabled == false) + { + string title = Path.GetFileNameWithoutExtension(filepath); + DiscordRichPresenceManager.DiscordClient.UpdateDetails($"Listening to {title}"); + DiscordRichPresenceManager.DiscordClient.UpdateState("Using the Music Player"); + } + await UpdateSongTime(); + } + } + + public static void PauseMusic() + { + MediaPlayer.Pause(); + CurrentPosition = MediaPlayer.Position; + IsPaused = true; + IsStopped = true; + bool DiscordRPCisEnabled = ConfigManager.GetDiscordRPC(); + bool OfflineModeisEnabled = ConfigManager.GetOfflineMode(); + if (DiscordRPCisEnabled == true & OfflineModeisEnabled == false) + { + DiscordRichPresenceManager.IdlePresence(); + } + } + public static void StopMusic() { // Stop and close the MediaPlayer @@ -220,188 +219,188 @@ public static void StopMusic() { DiscordRichPresenceManager.IdlePresence(); } - } - - private static Queue shuffledIndices = new(); - - public static void ShuffleAndPlayNext() - { - // If the queue is empty, reshuffle - if (shuffledIndices.Count == 0) - { - // Create a new list of indices and shuffle them - var indices = Enumerable.Range(0, MusicItems.Count).OrderBy(x => Random.Next()).ToList(); - shuffledIndices = new Queue(indices); - } - - // If the queue is still empty, exit - if (shuffledIndices.Count == 0) - { - // Optionally, handle the case where there are no items to play - return; - } - - // Dequeue the next index - int nextIndex = shuffledIndices.Dequeue(); - - // Play the selected song - PlayMusic(MusicItems[nextIndex].FilePath); - } - - public static void DeleteMusic(MusicItem musicItem) - { - MusicItems.Remove(musicItem); - Loader.LoadMusicFiles(); - } - - public static event PropertyChangedEventHandler? PropertyChanged; - - private static void OnPropertyChanged(string propertyName) - { - PropertyChanged!.Invoke(null, new PropertyChangedEventArgs(propertyName)); - } - - public static async Task DownloadMusicAsync(string videoUrl) - { - try - { - var youtube = new YoutubeClient(); - var video = await youtube.Videos.GetAsync(videoUrl); - var streamManifest = await youtube.Videos.Streams.GetManifestAsync(video.Id); - var audioStreamInfo = streamManifest.GetAudioStreams().OrderByDescending(s => s.Bitrate).FirstOrDefault(); - - if (audioStreamInfo != null) - { - var sanitizedTitle = SanitizeFileName(video.Title); - var tempFilePath = Path.Combine(MusicDirectoryPath, $"{sanitizedTitle}.temp"); - var outputFilePath = Path.Combine(MusicDirectoryPath, $"{sanitizedTitle}.mp3"); - - // Download the audio stream to a temporary file - using (var httpClient = new HttpClient()) - using (var response = await httpClient.GetAsync(audioStreamInfo.Url, HttpCompletionOption.ResponseHeadersRead)) - using (var inputStream = await response.Content.ReadAsStreamAsync()) - using (var outputStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 8192, useAsync: true)) - { - await inputStream.CopyToAsync(outputStream); - } - - // Convert the temporary file to MP3 format - ConvertToMp3(tempFilePath, outputFilePath); - - // Delete the temporary file - File.Delete(tempFilePath); - - // Embed the thumbnail and Author into the MP3 file - await EmbedThumbnailandAuthorAsync(outputFilePath, video); - - Loader.LoadMusicFiles(); - } - else - { - StarZMessageBox.ShowDialog("No audio stream found for the provided video URL.", "Error", false); - } - } - catch (Exception ex) - { - StarZMessageBox.ShowDialog($"An error occurred: {ex.Message}", "Error!", false); - } - finally - { - // Force garbage collection - GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); - GC.WaitForPendingFinalizers(); - } - } - - private static void ConvertToMp3(string inputFilePath, string outputFilePath) - { - try - { - // Define the path to the FFMpeg executable - string ffmpegPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "StarZ Launcher", "Musics"); - - // Ensure the output directory exists - Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)); - - // Create the FFMpeg converter instance with the specified tool path - var converter = new FFMpegConverter { FFMpegToolPath = ffmpegPath }; - - // Configure conversion settings - var settings = new ConvertSettings - { - // Set audio bitrate - CustomOutputArgs = "-b:a 128k" - }; - - // Perform the conversion - converter.ConvertMedia(new[] { new FFMpegInput(inputFilePath) }, outputFilePath, "mp3", settings); - } - catch (Exception ex) - { - // Handle exceptions, log the error, or show a message to the user - StarZMessageBox.ShowDialog($"An error occurred during MP3 conversion: {ex.Message}", "Error", false); - } - } - - private static async Task EmbedThumbnailandAuthorAsync(string filePath, IVideo video) - { - try - { - // Get the highest resolution thumbnail - var thumbnailUrl = video.Thumbnails.OrderByDescending(t => t.Resolution.Width * t.Resolution.Height) - .Select(t => t.Url) - .FirstOrDefault() ?? $"https://i.ytimg.com/vi/{video.Id}/hqdefault.jpg"; - - using var httpClient = new HttpClient(); - byte[] imageData = await httpClient.GetByteArrayAsync(thumbnailUrl); - - // Use a new instance of the TagLib.File class - using (var file = TagLib.File.Create(filePath)) - { - // Create a new picture object with the image data - var picture = new TagLib.Picture(new TagLib.ByteVector(imageData)); - - // Assign the picture and author to the file's tag - file.Tag.Pictures = new TagLib.IPicture[] { picture }; - file.Tag.Performers = video.Author.ChannelTitle.Split(','); - - // Explicitly save changes - file.Tag.DateTagged = DateTime.Now; - file.Save(); - file.Dispose(); - } - } - catch (Exception ex) - { - StarZMessageBox.ShowDialog($"Failed to embed thumbnail: {ex.Message}", "Error", false); - } - } - - private static string SanitizeFileName(string fileName) - { - var invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); - foreach (var invalidChar in invalidChars) - { - fileName = fileName.Replace(invalidChar.ToString(), ""); - } - return fileName; - } - - } - - public class MusicItem - { - public string FilePath { get; } - public string Title { get; } - public string Artist { get; } - public ImageSource Image { get; } - - public MusicItem(string filePath) - { - FilePath = filePath; - Title = Path.GetFileNameWithoutExtension(filePath); - Artist = MusicPlayer.GetArtistFromSongFile(filePath); - Image = MusicPlayer.GetImageFromSongFile(filePath); - } - } + } + + private static Queue shuffledIndices = new(); + + public static void ShuffleAndPlayNext() + { + // If the queue is empty, reshuffle + if (shuffledIndices.Count == 0) + { + // Create a new list of indices and shuffle them + var indices = Enumerable.Range(0, MusicItems.Count).OrderBy(x => Random.Next()).ToList(); + shuffledIndices = new Queue(indices); + } + + // If the queue is still empty, exit + if (shuffledIndices.Count == 0) + { + // Optionally, handle the case where there are no items to play + return; + } + + // Dequeue the next index + int nextIndex = shuffledIndices.Dequeue(); + + // Play the selected song + PlayMusic(MusicItems[nextIndex].FilePath); + } + + public static void DeleteMusic(MusicItem musicItem) + { + MusicItems.Remove(musicItem); + Loader.LoadMusicFiles(); + } + + public static event PropertyChangedEventHandler? PropertyChanged; + + private static void OnPropertyChanged(string propertyName) + { + PropertyChanged!.Invoke(null, new PropertyChangedEventArgs(propertyName)); + } + + public static async Task DownloadMusicAsync(string videoUrl) + { + try + { + var youtube = new YoutubeClient(); + var video = await youtube.Videos.GetAsync(videoUrl); + var streamManifest = await youtube.Videos.Streams.GetManifestAsync(video.Id); + var audioStreamInfo = streamManifest.GetAudioStreams().OrderByDescending(s => s.Bitrate).FirstOrDefault(); + + if (audioStreamInfo != null) + { + var sanitizedTitle = SanitizeFileName(video.Title); + var tempFilePath = Path.Combine(MusicDirectoryPath, $"{sanitizedTitle}.temp"); + var outputFilePath = Path.Combine(MusicDirectoryPath, $"{sanitizedTitle}.mp3"); + + // Download the audio stream to a temporary file + using (var httpClient = new HttpClient()) + using (var response = await httpClient.GetAsync(audioStreamInfo.Url, HttpCompletionOption.ResponseHeadersRead)) + using (var inputStream = await response.Content.ReadAsStreamAsync()) + using (var outputStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 8192, useAsync: true)) + { + await inputStream.CopyToAsync(outputStream); + } + + // Convert the temporary file to MP3 format + ConvertToMp3(tempFilePath, outputFilePath); + + // Delete the temporary file + File.Delete(tempFilePath); + + // Embed the thumbnail and Author into the MP3 file + await EmbedThumbnailandAuthorAsync(outputFilePath, video); + + Loader.LoadMusicFiles(); + } + else + { + StarZMessageBox.ShowDialog("No audio stream found for the provided video URL.", "Error", false); + } + } + catch (Exception ex) + { + StarZMessageBox.ShowDialog($"An error occurred: {ex.Message}", "Error!", false); + } + finally + { + // Force garbage collection + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); + GC.WaitForPendingFinalizers(); + } + } + + private static void ConvertToMp3(string inputFilePath, string outputFilePath) + { + try + { + // Define the path to the FFMpeg executable + string ffmpegPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "StarZ Launcher", "Musics"); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath)); + + // Create the FFMpeg converter instance with the specified tool path + var converter = new FFMpegConverter { FFMpegToolPath = ffmpegPath }; + + // Configure conversion settings + var settings = new ConvertSettings + { + // Set audio bitrate + CustomOutputArgs = "-b:a 128k" + }; + + // Perform the conversion + converter.ConvertMedia(new[] { new FFMpegInput(inputFilePath) }, outputFilePath, "mp3", settings); + } + catch (Exception ex) + { + // Handle exceptions, log the error, or show a message to the user + StarZMessageBox.ShowDialog($"An error occurred during MP3 conversion: {ex.Message}", "Error", false); + } + } + + private static async Task EmbedThumbnailandAuthorAsync(string filePath, IVideo video) + { + try + { + // Get the highest resolution thumbnail + var thumbnailUrl = video.Thumbnails.OrderByDescending(t => t.Resolution.Width * t.Resolution.Height) + .Select(t => t.Url) + .FirstOrDefault() ?? $"https://i.ytimg.com/vi/{video.Id}/hqdefault.jpg"; + + using var httpClient = new HttpClient(); + byte[] imageData = await httpClient.GetByteArrayAsync(thumbnailUrl); + + // Use a new instance of the TagLib.File class + using (var file = TagLib.File.Create(filePath)) + { + // Create a new picture object with the image data + var picture = new TagLib.Picture(new TagLib.ByteVector(imageData)); + + // Assign the picture and author to the file's tag + file.Tag.Pictures = new TagLib.IPicture[] { picture }; + file.Tag.Performers = video.Author.ChannelTitle.Split(','); + + // Explicitly save changes + file.Tag.DateTagged = DateTime.Now; + file.Save(); + file.Dispose(); + } + } + catch (Exception ex) + { + StarZMessageBox.ShowDialog($"Failed to embed thumbnail: {ex.Message}", "Error", false); + } + } + + private static string SanitizeFileName(string fileName) + { + var invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); + foreach (var invalidChar in invalidChars) + { + fileName = fileName.Replace(invalidChar.ToString(), ""); + } + return fileName; + } + + } + + public class MusicItem + { + public string FilePath { get; } + public string Title { get; } + public string Artist { get; } + public ImageSource Image { get; } + + public MusicItem(string filePath) + { + FilePath = filePath; + Title = Path.GetFileNameWithoutExtension(filePath); + Artist = MusicPlayer.GetArtistFromSongFile(filePath); + Image = MusicPlayer.GetImageFromSongFile(filePath); + } + } } \ No newline at end of file diff --git a/StarZ Launcher/StarZLauncher/Classes/ThemesManager.cs b/StarZ Launcher/StarZLauncher/Classes/ThemesManager.cs index 4cd7b5d..9014706 100644 --- a/StarZ Launcher/StarZLauncher/Classes/ThemesManager.cs +++ b/StarZ Launcher/StarZLauncher/Classes/ThemesManager.cs @@ -67,8 +67,6 @@ public static void TabItemsSelectionChanged() ComputerTabImage!.Source = new BitmapImage(new Uri("/Resources/ComputerGray.png", UriKind.Relative)); SettingsTabImage!.Source = new BitmapImage(new Uri("/Resources/SettingsWhite.png", UriKind.Relative)); } - GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); - GC.WaitForPendingFinalizers(); } public static void LoadTheme(string theme) diff --git a/StarZ Launcher/StarZLauncher/StarZLauncher.csproj b/StarZ Launcher/StarZLauncher/StarZLauncher.csproj index a570e8f..8e0cbd0 100644 --- a/StarZ Launcher/StarZLauncher/StarZLauncher.csproj +++ b/StarZ Launcher/StarZLauncher/StarZLauncher.csproj @@ -13,8 +13,8 @@ StarZLauncher A Minecraft Bedrock Edition Launcher StarZ Team © - 5.1.5.0 - 5.1.5.0 + 5.1.6.0 + 5.1.6.0 x64 @@ -133,6 +133,7 @@ + diff --git a/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml b/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml index 6a5d89e..136455a 100644 --- a/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml +++ b/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml @@ -31,16 +31,13 @@ - + - + - - - - + @@ -511,8 +508,13 @@ + + + + + + - @@ -1433,16 +1435,13 @@ - - + - + - - - + @@ -2663,5 +2662,4 @@ - diff --git a/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml.cs b/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml.cs index e773473..d10bfb8 100644 --- a/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml.cs +++ b/StarZ Launcher/StarZLauncher/Windows/MainWindow.xaml.cs @@ -63,6 +63,8 @@ public partial class MainWindow : Window public static TextBlock? CurrentlyPlayingSongTitle; public static TextBlock? CurrentlyPlayingSongArtist; public static TextBlock? CurrentlyPlayingSongTime; + public static TextBlock? WelcomeUsername; + public static TextBlock? WelcomeBack; public static ProgressBar? CurrentlyPlayingSongProgress; @@ -79,7 +81,7 @@ public partial class MainWindow : Window public static StackPanel? FullVersionsListStackPanel; - private HardwareMonitor? hardwareMonitor; + private readonly HardwareMonitor? hardwareMonitor; public MainWindow() { @@ -128,6 +130,8 @@ public MainWindow() CurrentlyPlayingSongTitle = CurrentlyPlayingTitle; CurrentlyPlayingSongArtist = CurrentlyPlayingArtist; CurrentlyPlayingSongTime = CurrentlyPlayingTime; + WelcomeUsername = WelcomeUsernameTextBlock; + WelcomeBack = WelcomeBackTextBlock; // Progress Bar CurrentlyPlayingSongProgress = CurrentlyPlayingProgress; @@ -173,8 +177,6 @@ public MainWindow() AboutMenu.Visibility = Visibility.Collapsed; LogManager.Log("Hardware Monitoring is disabled. To re-enable it, change 'DebugHardwareMonitoring' value in Settings.txt to 'False'.", "HardwareMonitor.txt"); } - GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); - GC.WaitForPendingFinalizers(); } // Animation on program's launch