Skip to content

Commit

Permalink
Merge pull request #371 from Fooxboy/290-save-last-opened-playlist
Browse files Browse the repository at this point in the history
#290 сохранение текущего трека между рестартами
  • Loading branch information
Fooxboy authored Apr 26, 2024
2 parents 6985b5f + 9f1ab0c commit 4872e2c
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 46 deletions.
5 changes: 5 additions & 0 deletions MusicX/Models/ConfigModel.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using MusicX.Services.Player;

namespace MusicX.Models
{
Expand Down Expand Up @@ -53,5 +54,9 @@ public class ConfigModel
public string? DeviceId { get; set; }

public string? ExchangeToken { get; set; }

public bool? SavePlayerState { get; set; }

public PlayerState? LastPlayerState { get; set; }
}
}
60 changes: 33 additions & 27 deletions MusicX/RootWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ public RootWindow(NavigationService navigationService, VkService vkService, Logg

playerSerivce.TrackChangedEvent += PlayerSerivce_TrackChangedEvent;

Closing += RootWindow_Closing;

SingleAppService.Instance.RunWitchArgs += Instance_RunWitchArgs;

togetherService.ConnectedToSession += TogetherServiceOnConnectedToSession;
Expand Down Expand Up @@ -125,29 +123,6 @@ await Task.Factory.StartNew(async() =>

}

private async void RootWindow_Closing(object? sender, CancelEventArgs e)
{
try
{
var listenTogetherService = StaticService.Container.GetRequiredService<ListenTogetherService>();

if (listenTogetherService.IsConnectedToServer && listenTogetherService.PlayerMode != PlayerMode.None)
{
if (listenTogetherService.PlayerMode == PlayerMode.Owner)
{
await listenTogetherService.StopPlaySessionAsync();
}
else
{
await listenTogetherService.LeavePlaySessionAsync();
}
}
}catch(Exception ex)
{
//nothing
}

}
private void PlayerSerivce_TrackChangedEvent(object? sender, EventArgs e)
{
if (PlayerShowed) return;
Expand Down Expand Up @@ -316,6 +291,13 @@ private async void Window_Loaded(object sender, RoutedEventArgs e)
if (config.NotifyMessages is null)
config.NotifyMessages = new() { ShowListenTogetherModal = true, LastShowedTelegramBlock = null };

if (config.LastPlayerState is not null)
{
await playerControl.PlayerService.RestoreFromStateAsync(config.LastPlayerState);

config.LastPlayerState = null;
}

await configService.SetConfig(config);

if(config.NotifyMessages.ShowListenTogetherModal)
Expand Down Expand Up @@ -575,11 +557,35 @@ private void NotifyIcon_LeftClick(NotifyIcon sender, RoutedEventArgs e)
}*/

private void RootWindow_OnClosing(object? sender, CancelEventArgs e)
private async void RootWindow_OnClosing(object? sender, CancelEventArgs e)
{
configService.Config.Width = Width;
configService.Config.Height = Height;
configService.SetConfig(configService.Config).SafeFireAndForget(continueOnCapturedContext: true);

if (configService.Config.SavePlayerState is true)
configService.Config.LastPlayerState = PlayerState.CreateOrNull(playerControl.PlayerService);

await configService.SetConfig(configService.Config);

try
{
var listenTogetherService = StaticService.Container.GetRequiredService<ListenTogetherService>();

if (listenTogetherService.IsConnectedToServer && listenTogetherService.PlayerMode != PlayerMode.None)
{
if (listenTogetherService.PlayerMode == PlayerMode.Owner)
{
await listenTogetherService.StopPlaySessionAsync();
}
else
{
await listenTogetherService.LeavePlaySessionAsync();
}
}
}catch(Exception ex)
{
//nothing
}
}

private void RootFrame_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
Expand Down
16 changes: 9 additions & 7 deletions MusicX/Services/Player/PlayerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ public PlayerService(Logger logger, ISnackbarService snackbarService,

public async Task RestoreFromStateAsync(PlayerState state)
{
await PlayAsync(state.Playlist, state.Track);
Seek(state.Position);
await PlayAsync(state.Playlist, state.Track, state.Position);
}

public async void Play()
Expand Down Expand Up @@ -118,12 +117,13 @@ await Task.WhenAll(
_statsListeners.Select(b => b.TrackChangedAsync(previousTrack, CurrentTrack!, ChangeReason.TrackChange)));
}

private async Task PlayTrackAsync(PlaylistTrack track)
private async Task PlayTrackAsync(PlaylistTrack track, TimeSpan? position = null)
{
try
{
if (CurrentTrack == track)
{
if (position is not null) Seek(position.Value);
player.Play();
return;
}
Expand Down Expand Up @@ -172,6 +172,8 @@ private async Task PlayTrackAsync(PlaylistTrack track)
await NextTrack();
return;
}

if (position is not null) Seek(position.Value);

player.Play();
UpdateWindowsData().SafeFireAndForget();
Expand All @@ -195,12 +197,12 @@ private async Task PlayTrackAsync(PlaylistTrack track)

}

public async Task PlayAsync(IPlaylist playlist, PlaylistTrack? firstTrack = null)
public async Task PlayAsync(IPlaylist playlist, PlaylistTrack? firstTrack = null, TimeSpan? startPosition = null)
{
if(_listenTogetherService.PlayerMode == PlayerMode.Listener)
{
await _listenTogetherService.LeavePlaySessionAsync();
await Application.Current.Dispatcher.InvokeAsync(() => PlayAsync(playlist).SafeFireAndForget());
await Application.Current.Dispatcher.InvokeAsync(() => PlayAsync(playlist, firstTrack, startPosition).SafeFireAndForget());
return;
}

Expand Down Expand Up @@ -237,7 +239,7 @@ await Application.Current.Dispatcher.InvokeAsync(() =>
});
}

firstTrackTask = PlayTrackAsync(firstTrack);
firstTrackTask = PlayTrackAsync(firstTrack, startPosition);

await Task.WhenAll(
_statsListeners.Select(b => b.TrackChangedAsync(CurrentTrack, firstTrack, ChangeReason.PlaylistChange)));
Expand All @@ -260,7 +262,7 @@ await Task.WhenAll(
if (firstTrack is null)
{
var previousTrack = CurrentTrack;
await PlayTrackAsync(Tracks[0]);
await PlayTrackAsync(Tracks[0], startPosition);

await Task.WhenAll(
_statsListeners.Select(b => b.TrackChangedAsync(previousTrack, CurrentTrack!, ChangeReason.PlaylistChange)));
Expand Down
9 changes: 4 additions & 5 deletions MusicX/ViewModels/Modals/AvailableNewUpdateModalViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,11 @@ private async Task Execute()
await _updateManager.DownloadUpdatesAsync(UpdateInfo, ProgressHandler);

var playerState = PlayerState.CreateOrNull(StaticService.Container.GetRequiredService<PlayerService>());
var configService = StaticService.Container.GetRequiredService<ConfigService>();

_updateManager.WaitExitThenApplyUpdates(UpdateInfo, restartArgs: new []
{
"--play",
playerState is null ? "null" : JsonSerializer.Serialize(playerState)
});
configService.Config.LastPlayerState = playerState;

_updateManager.WaitExitThenApplyUpdates(UpdateInfo);

Application.Current.Shutdown();
}
Expand Down
13 changes: 13 additions & 0 deletions MusicX/Views/SettingsView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,19 @@
FontSize="18"
Unchecked="MinimizeToTray_Unchecked" />
</StackPanel>

<TextBlock
FontFamily="{StaticResource VKSansMedium}"
FontSize="24"
Text="Воспроизведение" />
<StackPanel Margin="15,10">
<wpfui:ToggleSwitch
x:Name="SavePlayerState"
Checked="SavePlayerState_OnCheckChanged"
Content="Сохранять текущий трек между перезапусками приложения"
FontSize="18"
Unchecked="SavePlayerState_OnCheckChanged" />
</StackPanel>
</StackPanel>
</wpfui:CardExpander>

Expand Down
8 changes: 8 additions & 0 deletions MusicX/Views/SettingsView.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ private async void SettingsView_Loaded(object sender, RoutedEventArgs e)
WinterTheme.IsChecked = config.WinterTheme.Value;
MinimizeToTray.IsChecked = config.MinimizeToTray.Value;
GetBetaUpdates.IsChecked = config.GetBetaUpdates.Value;
SavePlayerState.IsChecked = config.SavePlayerState.GetValueOrDefault();

UserName.Text = config.UserName;

Expand Down Expand Up @@ -586,5 +587,12 @@ private void CatalogsCard_Click(object sender, RoutedEventArgs e)
{
StaticService.Container.GetRequiredService<NavigationService>().OpenSection("profiles");
}

private async void SavePlayerState_OnCheckChanged(object sender, RoutedEventArgs e)
{
config.SavePlayerState = SavePlayerState.IsChecked;

await configService.SetConfig(config);
}
}
}
7 changes: 0 additions & 7 deletions MusicX/Views/StartingWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,6 @@ await container.GetRequiredService<IVkApiAuthAsync>()
{
await rootWindow.StartListenTogether(arg[1]);
}

var playArgIndex = Array.BinarySearch(_args, "--play",
StringComparer.OrdinalIgnoreCase);
if (playArgIndex >= 0 && playArgIndex + 1 < _args.Length &&
JsonSerializer.Deserialize<PlayerState>(string.Join(string.Empty, _args[(playArgIndex + 1)..])) is { } state)
await container.GetRequiredService<PlayerService>()
.RestoreFromStateAsync(state);
}

this.Close();
Expand Down

0 comments on commit 4872e2c

Please sign in to comment.