Skip to content

Commit

Permalink
Merge pull request #340 from jwallet/popup-spotify-api
Browse files Browse the repository at this point in the history
One popup spotify api; catching process fail; spotify api same instance
  • Loading branch information
jwallet authored Jan 28, 2021
2 parents 3205d41 + 6e54bcb commit 1826847
Show file tree
Hide file tree
Showing 8 changed files with 102 additions and 45 deletions.
1 change: 1 addition & 0 deletions EspionSpotify/API/IExternalAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public interface IExternalAPI
ExternalAPIType GetTypeAPI { get; }
bool IsAuthenticated { get; }
Task Authenticate();
void Reset();

Task UpdateTrack(Track track);
Task<(string, bool)> GetCurrentPlayback();
Expand Down
5 changes: 5 additions & 0 deletions EspionSpotify/API/LastFMAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,11 @@ public void MapLastFMTrackToTrack(Track track, LastFMTrack trackExtra)
track.ArtSmallUrl = trackExtra.Album?.SmallCoverUrl;
}

public void Reset()
{
_loggedSilentExceptionOnce = false;
}

#region NotImplementedExternalAPI
public bool IsAuthenticated { get => true; }
public async Task Authenticate() => await Task.CompletedTask;
Expand Down
38 changes: 20 additions & 18 deletions EspionSpotify/API/SpotifyAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,16 @@ public SpotifyAPI(string clientId, string secretId, string redirectUrl = SPOTIFY
}
}

public async Task Authenticate() => await GetSpotifyWebAPI();

public async Task<(string, bool)> GetCurrentPlayback()
{
var playing = false;
string title = null;

var api = await GetSpotifyWebAPI();
await GetSpotifyWebAPI();

if (api != null)
if (_api != null)
{
var playback = await api.GetPlaybackAsync();

var playback = await _api.GetPlaybackAsync();
if (playback != null && !playback.HasError())
{
playing = playback.IsPlaying;
Expand Down Expand Up @@ -128,10 +125,11 @@ public void MapSpotifyAlbumToTrack(Track track, FullAlbum spotifyAlbum)
#region Spotify Track updater
private async Task UpdateTrack(Track track, bool retry = false)
{
var api = await GetSpotifyWebAPI();
if (api == null) return;
await GetSpotifyWebAPI();

if (_api == null) return;

var playback = await api.GetPlaybackAsync();
var playback = await _api.GetPlaybackAsync();
var hasNoPlayback = playback == null || playback.Item == null;

if (!retry && hasNoPlayback)
Expand All @@ -143,14 +141,11 @@ private async Task UpdateTrack(Track track, bool retry = false)

if (hasNoPlayback || playback.HasError())
{
api.Dispose();
_api.Dispose();

// open spotify authentication page if user is disconnected
// user might be connected with a different account that the one that granted rights
if (!_connectionDialogOpened)
{
OpenAuthenticationDialog();
}
OpenAuthenticationDialog();

// fallback in case getting the playback did not work
ExternalAPI.Instance = _lastFmApi;
Expand All @@ -172,7 +167,7 @@ private async Task UpdateTrack(Track track, bool retry = false)

if (playback.Item.Album?.Id == null) return;

var album = await api.GetAlbumAsync(playback.Item.Album.Id);
var album = await _api.GetAlbumAsync(playback.Item.Album.Id);

if (album.HasError()) return;

Expand Down Expand Up @@ -200,17 +195,18 @@ private async void AuthOnAuthReceived(object sender, AuthorizationCode payload)

private void OpenAuthenticationDialog()
{
if (_connectionDialogOpened) return;
_auth.ShowDialog = true;
_auth.OpenBrowser();
_connectionDialogOpened = true;
}

private async Task<SpotifyWebAPI> GetSpotifyWebAPI()
private async Task GetSpotifyWebAPI()
{
if (_token == null)
{
OpenAuthenticationDialog();
return null;
return;
}

if (_token.IsExpired())
Expand Down Expand Up @@ -240,10 +236,16 @@ private async Task<SpotifyWebAPI> GetSpotifyWebAPI()
_authorizationCodeAuth.Stop();
}
}
}

public async Task Authenticate() => await GetSpotifyWebAPI();

return _api;
public void Reset()
{
_connectionDialogOpened = false;
}


public void Dispose()
{
Dispose(true);
Expand Down
2 changes: 1 addition & 1 deletion EspionSpotify/AudioSessions/MainAudioSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public MainAudioSession(string audioEndPointDeviceID, IProcessManager processMan
{
_processManager = processManager;

_spytifyProcessId = _processManager.GetCurrentProcess().Id;
_spytifyProcessId = (int)_processManager.GetCurrentProcess()?.Id;

AudioMMDevices = new MMDeviceEnumerator();
AudioMMDevicesManager = new AudioMMDevicesManager(AudioMMDevices, audioEndPointDeviceID);
Expand Down
65 changes: 58 additions & 7 deletions EspionSpotify/Native/ProcessManager.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
using EspionSpotify.Native.Models;
using System.Linq;
using System.Linq;
using EspionSpotify.Native.Models;
using NativeProcess = System.Diagnostics.Process;

namespace EspionSpotify.Native
{
public class ProcessManager : IProcessManager
{
public IProcess GetCurrentProcess()
{
var process = System.Diagnostics.Process.GetCurrentProcess();
NativeProcess process;

try
{
process = NativeProcess.GetCurrentProcess();
}
catch
{
return null;
}

return new Process
{
Id = process.Id,
Expand All @@ -18,7 +29,17 @@ public IProcess GetCurrentProcess()

public IProcess[] GetProcesses()
{
var processes = System.Diagnostics.Process.GetProcesses();
NativeProcess[] processes;

try
{
processes = NativeProcess.GetProcesses();
}
catch
{
return new Process[] { };
}

return processes.Select(x => new Process
{
Id = x.Id,
Expand All @@ -29,7 +50,17 @@ public IProcess[] GetProcesses()

public IProcess[] GetProcessesByName(string processName)
{
var processes = System.Diagnostics.Process.GetProcessesByName(processName);
NativeProcess[] processes;

try
{
processes = NativeProcess.GetProcessesByName(processName);
}
catch
{
return new Process[] { };
}

return processes.Select(x => new Process
{
Id = x.Id,
Expand All @@ -40,7 +71,17 @@ public IProcess[] GetProcessesByName(string processName)

public IProcess GetProcessById(int processId)
{
var process = System.Diagnostics.Process.GetProcessById(processId);
NativeProcess process;

try
{
process = NativeProcess.GetProcessById(processId);
}
catch
{
return null;
}

return new Process
{
Id = process.Id,
Expand All @@ -51,7 +92,17 @@ public IProcess GetProcessById(int processId)

public IProcess Start(string fileName)
{
var process = System.Diagnostics.Process.Start(fileName);
NativeProcess process;

try
{
process = NativeProcess.Start(fileName);
}
catch
{
return null;
}

return new Process
{
Id = process.Id,
Expand Down
2 changes: 1 addition & 1 deletion EspionSpotify/Spotify/SpotifyProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public async Task<ISpotifyStatus> GetSpotifyStatus()
{
isSpotifyAudioPlaying = await _audioSession.IsSpotifyCurrentlyPlaying();
var process = _processManager.GetProcessById(_spotifyProcessId.Value);
mainWindowTitle = process.MainWindowTitle;
mainWindowTitle = process?.MainWindowTitle ?? "";
}
}
catch (Exception ex)
Expand Down
33 changes: 15 additions & 18 deletions EspionSpotify/Watcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public class Watcher : IWatcher, IDisposable
private bool _disposed = false;
private const int NEXT_SONG_EVENT_MAX_ESTIMATED_DELAY_SECS = 5;
private const int WATCHER_DELAY_MS = 500;
private const int PREVENT_SLEEP_EVENT_DELAY_MS = (WATCHER_DELAY_MS * 2) * 5 * 60;

public static bool Running { get; internal set; }
public static bool Ready { get; private set; } = true;
Expand Down Expand Up @@ -302,17 +301,18 @@ private async Task EnableRecordingTimer()
_recordingTimer.Enabled = true;
}

private void EndRecordingSession()
private void ResetAudioSession()
{
Ready = true;

if (_audioSession != null)
{
MutesSpotifyAds(false);
_audioSession.SetSpotifyVolumeToHighAndOthersToMute(false);
_audioSession.ClearSpotifyAudioSessionControls();
}
}

private void ResetSpotifyHandler()
{
if (Spotify != null)
{
Spotify.ListenForEvents = false;
Expand All @@ -321,7 +321,15 @@ private void EndRecordingSession()
Spotify.OnTrackTimeChange -= OnTrackTimeChanged;
Spotify.Dispose();
}

}

private void EndRecordingSession()
{
Ready = true;

ResetAudioSession();
ResetSpotifyHandler();

_form.UpdateStartButton();
_form.UpdatePlayingTitle(Constants.SPOTIFY);
_form.UpdateIconSpotify(false);
Expand Down Expand Up @@ -385,19 +393,8 @@ protected virtual void Dispose(bool disposing)
DoIKeepLastSong();
NativeMethods.AllowSleep();

if (_audioSession != null)
{
MutesSpotifyAds(false);
_audioSession.SetSpotifyVolumeToHighAndOthersToMute(false);
_audioSession.ClearSpotifyAudioSessionControls();

Spotify.ListenForEvents = false;
Spotify.OnPlayStateChange -= OnPlayStateChanged;
Spotify.OnTrackChange -= OnTrackChanged;
Spotify.OnTrackTimeChange -= OnTrackTimeChanged;
Spotify.Dispose();
Spotify = null;
}
ResetAudioSession();
ResetSpotifyHandler();

_recorderTasks.ForEach(x =>
{
Expand Down
1 change: 1 addition & 0 deletions EspionSpotify/frmEspionSpotify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,7 @@ public void StopRecording()
}

Watcher.Running = false;
ExternalAPI.Instance.Reset();
_toggleStopRecordingDelayed = false;
timer1.Stop();

Expand Down

0 comments on commit 1826847

Please sign in to comment.