Skip to content

Commit

Permalink
Swallow UpdateUpNext errors + call it more often and faster + better …
Browse files Browse the repository at this point in the history
…crash reporting
  • Loading branch information
Difegue committed Sep 16, 2022
1 parent ab01453 commit 140b799
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 22 deletions.
43 changes: 33 additions & 10 deletions Sources/Stylophone.Common/Services/MPDConnectionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
using Stylophone.Common.Interfaces;
using MpcNET.Commands.Reflection;
using Stylophone.Localization.Strings;
using CommunityToolkit.Mvvm.DependencyInjection;
using Stylophone.Common.ViewModels;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter;
using System.Drawing;

namespace Stylophone.Common.Services
{
Expand Down Expand Up @@ -180,7 +185,7 @@ public async Task<PooledObjectWrapper<MpcConnection>> GetConnectionAsync(Cancell
/// <typeparam name="T">Return type of the command</typeparam>
/// <param name="command">IMpcCommand to send</param>
/// <returns>The command results, or default value.</returns>
public async Task<T> SafelySendCommandAsync<T>(IMpcCommand<T> command)
public async Task<T> SafelySendCommandAsync<T>(IMpcCommand<T> command, bool showError = true)
{
if (!IsConnected)
return default(T);
Expand All @@ -205,8 +210,23 @@ public async Task<T> SafelySendCommandAsync<T>(IMpcCommand<T> command)
}
catch (Exception e)
{
_notificationService.ShowInAppNotification(string.Format(Resources.ErrorSendingMPDCommand, command.GetType().Name),
e.Message, NotificationType.Error);
System.Diagnostics.Debug.WriteLine($"MPD Error: {e.Message}");

if (showError)
_notificationService.ShowInAppNotification(string.Format(Resources.ErrorSendingMPDCommand, command.GetType().Name),
e.Message, NotificationType.Error);

#if DEBUG
#else
var enableAnalytics = Ioc.Default.GetRequiredService<IApplicationStorageService>().GetValue<bool>(nameof(SettingsViewModel.EnableAnalytics), true);
if (enableAnalytics)
{
var dict = new Dictionary<string, string>();
dict.Add("command", command.Serialize());
dict.Add("exception", e.ToString());
Analytics.TrackEvent("MPDError", dict);
}
#endif
}

return default(T);
Expand All @@ -233,18 +253,21 @@ private async Task<MpcConnection> GetConnectionInternalAsync(CancellationToken t

private void InitializeStatusUpdater(CancellationToken token = default)
{
// Update status every second
_statusUpdater?.Stop();
_statusUpdater?.Dispose();
_statusUpdater = new System.Timers.Timer(1000);
_statusUpdater.Elapsed += async (s, e) => await UpdateStatusAsync(_statusConnection);
_statusUpdater.Start();

// Run an idle loop in a spare thread to fire events when needed
Task.Run(async () =>
{
while (true)
{
if (_statusUpdater?.Enabled != true && _statusConnection.IsConnected)
{
// Update status every second
_statusUpdater?.Stop();
_statusUpdater?.Dispose();
_statusUpdater = new System.Timers.Timer(1000);
_statusUpdater.Elapsed += async (s, e) => await UpdateStatusAsync(_statusConnection);
_statusUpdater.Start();
}
try
{
if (token.IsCancellationRequested || _idleConnection == null || !_idleConnection.IsConnected)
Expand Down
4 changes: 4 additions & 0 deletions Sources/Stylophone.Common/Stylophone.Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@
<PackageReference Include="RangedObservableCollection" Version="1.0.1" />
<PackageReference Include="SkiaSharp" Version="2.88.1" />
<PackageReference Include="SkiaSharp.Views.Desktop.Common" Version="2.88.1" />
<PackageReference Include="Microsoft.AppCenter.Analytics" Version="4.5.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Stylophone.Localization\Stylophone.Localization.csproj" />
</ItemGroup>

<ItemGroup>
<None Remove="Microsoft.AppCenter.Analytics" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -192,7 +193,7 @@ public double MediaVolume
volumeTasks.Add(Task.Run(async () =>
{
await _mpdService.SafelySendCommandAsync(new SetVolumeCommand((byte)value));
Thread.Sleep(1000); // Wait for MPD to acknowledge the new volume in its status...
Thread.Sleep(500); // Wait for MPD to acknowledge the new volume in its status...
if (volumeTasks.Count == 1)
MediaVolume = _mpdService.CurrentStatus.Volume; // Update the value to the current server volume
Expand Down Expand Up @@ -355,7 +356,8 @@ public void ToggleRepeat()
{
await _mpdService.SafelySendCommandAsync(new RepeatCommand(IsRepeatEnabled));
await _mpdService.SafelySendCommandAsync(new SingleCommand(IsSingleEnabled));
Thread.Sleep(1000); // Wait for MPD to acknowledge the new status...
Thread.Sleep(500); // Wait for MPD to acknowledge the new status...
await UpdateUpNextAsync(_mpdService.CurrentStatus);
}, cts.Token));

}
Expand All @@ -375,7 +377,7 @@ public void ToggleShuffle()
stateTasks.Add(Task.Run(async () =>
{
await _mpdService.SafelySendCommandAsync(new RandomCommand(IsShuffleEnabled));
Thread.Sleep(1000); // Wait for MPD to acknowledge the new status...
Thread.Sleep(500); // Wait for MPD to acknowledge the new status...
await UpdateUpNextAsync(_mpdService.CurrentStatus);
}, cts.Token));
}
Expand All @@ -395,7 +397,7 @@ public void ToggleConsume()
stateTasks.Add(Task.Run(async () =>
{
await _mpdService.SafelySendCommandAsync(new ConsumeCommand(IsConsumeEnabled));
Thread.Sleep(1000); // Wait for MPD to acknowledge the new status...
Thread.Sleep(500); // Wait for MPD to acknowledge the new status...
}, cts.Token));
}

Expand Down Expand Up @@ -495,7 +497,8 @@ private async Task UpdateUpNextAsync(MpdStatus status)
var nextSongId = status.NextSongId;
if (nextSongId != -1)
{
var response = await _mpdService.SafelySendCommandAsync(new PlaylistIdCommand(nextSongId));
// Don't show errors if we can't get the next track due to an old status or something, it's fairly minor
var response = await _mpdService.SafelySendCommandAsync(new PlaylistIdCommand(nextSongId), false);

if (response != null)
{
Expand Down Expand Up @@ -581,6 +584,10 @@ private void OnStateChange(object sender, EventArgs eventArgs)
// Ditto for shuffle/repeat/single
if (stateTasks.Count == 0)
{
if (status.Random != IsShuffleEnabled || IsRepeatEnabled != status.Repeat || IsSingleEnabled != status.Single)
{
UpdateUpNextAsync(status);
}
IsShuffleEnabled = status.Random;
IsRepeatEnabled = status.Repeat;
IsSingleEnabled = status.Single;
Expand Down
7 changes: 7 additions & 0 deletions Sources/Stylophone.iOS/AppDelegate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using Microsoft.AppCenter.Crashes;
using System.Threading;
using AVFoundation;
using System.Collections.Generic;

namespace Stylophone.iOS
{
Expand Down Expand Up @@ -127,6 +128,12 @@ await Ioc.Default.GetRequiredService<IDispatcherService>().ExecuteOnUIThreadAsyn
// Initialize AppCenter
AppCenter.Start("90b62f5a-2448-4ef1-81ca-3fb807a5b126",
typeof(Analytics), typeof(Crashes));

AppDomain.CurrentDomain.UnhandledException += (sender, args) => {
var dict = new Dictionary<string, string>();
dict.Add("exception", args.ExceptionObject.ToString());
Analytics.TrackEvent("UnhandledCrash", dict);
};
}
#endif
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Stylophone.iOS/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
<string>zh</string>
</array>
<key>CFBundleShortVersionString</key>
<string>2.5.3</string>
<string>2.5.4</string>
<key>CFBundleVersion</key>
<string>2.5.3</string>
<string>2.5.4</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>MinimumOSVersion</key>
Expand Down
16 changes: 11 additions & 5 deletions Sources/Stylophone.iOS/ViewControllers/QueueViewController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,17 @@ private void ScrollToPlayingSong(object sender = null, SongChangedEventArgs e =
if (playing != null)
UIApplication.SharedApplication.BeginInvokeOnMainThread(() =>
{
var indexPath = NSIndexPath.FromRowSection(ViewModel.Source.IndexOf(playing), 0);
var tableViewRows = TableView.NumberOfRowsInSection(0);
if (tableViewRows >= indexPath.Row)
TableView.ScrollToRow(indexPath, UITableViewScrollPosition.Middle, true);
try
{
var indexPath = NSIndexPath.FromRowSection(ViewModel.Source.IndexOf(playing), 0);
var tableViewRows = TableView.NumberOfRowsInSection(0);
if (tableViewRows >= indexPath.Row)
TableView.ScrollToRow(indexPath, UITableViewScrollPosition.Middle, true);
} catch (Exception e)
{
System.Diagnostics.Debug.WriteLine($"Error while scrolling to row: {e}");
}
});
}

Expand Down

0 comments on commit 140b799

Please sign in to comment.