Skip to content

Commit 68490c2

Browse files
committed
Refactor some objects
Changes: - Code cleanup - Refactor some objects - Fix double cover fetch issue - Fix Textbox overflows Known issues: - There is a bug that crashes the entire Application. Looking for it. - If song has quote in its name it crashes whole database system (which also enables SQL Injection but since this is a local database application it doesnt matter that much). Rich Presence works but no data saved in database.
1 parent cee7003 commit 68490c2

11 files changed

Lines changed: 106 additions & 56 deletions

File tree

AMDiscordRPC/AMDiscordRPC.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,10 @@ static void Main(string[] args)
3535
}
3636
else
3737
{
38-
if (httpRes == Array.Empty<string>() || CoverThread != null)
38+
if (httpRes.Equals(new WebSongResponse()) || CoverThread != null)
3939
{
4040
httpRes = await GetCover(x.ArtistandAlbumName.Split('—')[1], HttpUtility.UrlEncode(ConvertToValidString(x.ArtistandAlbumName) + $" {ConvertToValidString(x.SongName)}"));
41-
log.Debug($"Set Cover: {((httpRes.Length > 0) ? httpRes[0] : null)}");
41+
log.Debug($"Set Cover: {((httpRes.artworkURL != null) ? httpRes.artworkURL : null)}");
4242
}
4343
SetPresence(x, httpRes);
4444
oldAlbumnArtist = x.ArtistandAlbumName;
@@ -127,7 +127,7 @@ static void AMEvent()
127127
string previousSong = string.Empty;
128128
string previousArtistAlbum = string.Empty;
129129
string lastFetchedArtistAlbum = string.Empty;
130-
int audioStatus = 3;
130+
AudioFormat format = AudioFormat.AAC;
131131
bool resetStatus = false;
132132
double oldValue = 0;
133133

@@ -185,7 +185,7 @@ static void AMEvent()
185185
Task t = new Task(async () =>
186186
{
187187
httpRes = await GetCover(idontknowwhatshouldinamethisbutitsaboutalbum.Split('—')[1], HttpUtility.UrlEncode(ConvertToValidString((isSingle) ? string.Join("-", dashSplit.Take(dashSplit.Length - 1).ToArray()) : string.Join("—", currentArtistAlbum.Split('—').Take(2).ToArray())) + $" {ConvertToValidString(currentSong)}"));
188-
log.Debug($"Set Cover: {((httpRes.Length > 0) ? httpRes[0] : null)}");
188+
log.Debug($"Set Cover: {((httpRes.artworkURL != null) ? httpRes.artworkURL : null)}");
189189
});
190190
CoverThread = t;
191191
t.Start();
@@ -202,21 +202,21 @@ static void AMEvent()
202202
switch (audioBadge?.Name)
203203
{
204204
case "Dolby Atmos":
205-
audioStatus = 1;
205+
format = AudioFormat.Dolby_Atmos;
206206
break;
207207
case "Dolby Audio":
208-
audioStatus = 2;
208+
format = AudioFormat.Dolby_Audio;
209209
break;
210210
default:
211-
audioStatus = 0;
211+
format = AudioFormat.Lossless;
212212
break;
213213
}
214214
}
215-
else audioStatus = 3;
215+
else format = AudioFormat.AAC;
216216
oldValue = 0;
217217
oldStartTime = startTime;
218218
oldEndTime = endTime;
219-
AMSongDataEvent.ChangeSong(new SongData(currentSong, (isSingle) ? string.Join("-", dashSplit.Take(dashSplit.Length - 1).ToArray()) : string.Join("—", currentArtistAlbum.Split('—').Take(2).ToArray()), currentArtistAlbum.Split('—').Length <= 1, startTime, endTime, audioStatus));
219+
AMSongDataEvent.ChangeSong(new SongData(currentSong, (isSingle) ? string.Join("-", dashSplit.Take(dashSplit.Length - 1).ToArray()) : string.Join("—", currentArtistAlbum.Split('—').Take(2).ToArray()), currentArtistAlbum.Split('—').Length <= 1, startTime, endTime, format));
220220
}
221221

222222
if (playButton?.Name != null && (localizedPlay != null && localizedPlay == playButton?.Name || localizedStop != null && localizedStop != playButton?.Name))

AMDiscordRPC/Covers.cs

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public class Covers
1212
{
1313
public static Task CoverThread;
1414

15-
public static async Task<String[]> AsyncFetchiTunes(string album, string searchStr)
15+
private static async Task<WebSongResponse> AsyncFetchiTunes(string album, string searchStr)
1616
{
1717
try
1818
{
@@ -24,30 +24,35 @@ public static async Task<String[]> AsyncFetchiTunes(string album, string searchS
2424
dynamic imageRes = JObject.Parse(await iTunesReq.Content.ReadAsStringAsync());
2525
if (imageRes["resultCount"] != 0)
2626
{
27-
string[] res = { imageRes["results"][0]["artworkUrl100"].ToString(), imageRes["results"][0]["trackViewUrl"].ToString(), imageRes["results"][0]["collectionName"].ToString() };
28-
Database.UpdateAlbum(new Database.SQLCoverResponse(album, res[0], res[1], null, null, null));
27+
WebSongResponse webRes = new WebSongResponse
28+
(
29+
imageRes["results"][0]["artworkUrl100"].ToString(),
30+
imageRes["results"][0]["trackViewUrl"].ToString(),
31+
imageRes["results"][0]["collectionName"].ToString()
32+
);
33+
Database.UpdateAlbum(new Database.SQLCoverResponse(album, webRes.artworkURL, webRes.trackURL));
2934
CoverThread = null;
30-
return res;
35+
return webRes;
3136
}
3237
else
3338
{
3439
log.Warn("iTunes no image found");
3540
CoverThread = null;
36-
return Array.Empty<string>();
41+
return new WebSongResponse();
3742
}
3843
}
3944
else
4045
{
4146
log.Warn("iTunes request failed");
4247
CoverThread = null;
43-
return Array.Empty<string>();
48+
return new WebSongResponse();
4449
}
4550
}
4651
catch (Exception e)
4752
{
4853
log.Error($"iTunes Exception {e.Message}");
4954
CoverThread = null;
50-
return Array.Empty<string>();
55+
return new WebSongResponse();
5156
}
5257
}
5358

@@ -72,24 +77,35 @@ public static async Task CheckAnimatedCover(string album, string url, Cancellati
7277
{
7378
log.Error($"Apple Music animatedCover exception: {e.Message}");
7479
Discord.animatedCoverCts = null;
75-
Database.UpdateAlbum(new Database.SQLCoverResponse(album, null, null, false, null, null));
80+
Database.UpdateAlbum(new Database.SQLCoverResponse(album, null, null, false));
7681
}
7782
}
7883

79-
public static async Task<string[]> GetCover(string album, string searchStr)
84+
public static async Task<WebSongResponse> GetCover(string album, string searchStr)
8085
{
8186
try
8287
{
8388
Database.SQLCoverResponse cover = Database.GetAlbumDataFromSQL(album);
8489
if (cover != null)
8590
{
86-
string[] res = { (cover.animated == true && cover.animatedURL != null) ? cover.animatedURL : (cover.source != null) ? cover.source : throw new Exception("Source not found."), cover.redirURL, album };
91+
WebSongResponse res = new WebSongResponse(
92+
(
93+
cover.animated == true && cover.animatedURL != null) ? cover.animatedURL : (cover.source != null) ? cover.source : throw new Exception("Source not found."),
94+
cover.redirURL,
95+
album
96+
);
97+
CoverThread = null;
8798
return res;
8899
}
89-
else return await AsyncFetchiTunes(album, searchStr);
100+
else
101+
{
102+
CoverThread = null;
103+
return await AsyncFetchiTunes(album, searchStr);
104+
}
90105
}
91106
catch (Exception ex)
92107
{
108+
CoverThread = null;
93109
return await AsyncFetchiTunes(album, searchStr);
94110
}
95111
}

AMDiscordRPC/Database.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ public class SQLCoverResponse
258258
public string streamURL { get; set; }
259259
public string animatedURL { get; set; }
260260

261-
public SQLCoverResponse(string album, string source, string redirURL, bool? animated, string streamURL, string animatedURL)
261+
public SQLCoverResponse(string album = null, string source = null, string redirURL = null, bool? animated = null, string streamURL = null, string animatedURL = null)
262262
{
263263
this.album = album;
264264
this.source = source;

AMDiscordRPC/Discord.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@ public static void SetPresence(SongData x)
5151

5252
private static async Task AsyncSetButton(SongData x)
5353
{
54-
string[] resp = await GetCover(x.ArtistandAlbumName.Split('—')[1], HttpUtility.UrlEncode(ConvertToValidString(x.ArtistandAlbumName) + $" {ConvertToValidString(x.SongName)}"));
54+
WebSongResponse resp = await GetCover(x.ArtistandAlbumName.Split('—')[1], HttpUtility.UrlEncode(ConvertToValidString(x.ArtistandAlbumName) + $" {ConvertToValidString(x.SongName)}"));
5555
oldData.Buttons = new Button[]
5656
{
57-
new Button() { Label = "Listen on Apple Music", Url = (resp.Length > 0) ? resp[1].Replace("https://", "music://") : "music://music.apple.com/home"}
57+
new Button() { Label = "Listen on Apple Music", Url = (resp.trackURL != null) ? resp.trackURL.Replace("https://", "music://") : "music://music.apple.com/home"}
5858
};
5959
client.SetPresence(oldData);
6060
thread = null;
@@ -67,7 +67,7 @@ public static async Task SetCover(string coverURL)
6767
animatedCoverCts = null;
6868
}
6969

70-
public static void SetPresence(SongData x, string[] resp)
70+
public static void SetPresence(SongData x, WebSongResponse resp)
7171
{
7272
log.Debug($"Timestamps {x.StartTime}/{x.EndTime}");
7373
if (thread != null) thread.Abort();
@@ -83,14 +83,14 @@ public static void SetPresence(SongData x, string[] resp)
8383
State = $"by {((x.IsMV) ? x.ArtistandAlbumName : ConvertToValidString(x.ArtistandAlbumName.Split('—')[0]))}",
8484
Assets = new Assets()
8585
{
86-
LargeImageKey = (resp.Length > 0) ? resp[0] : "",
87-
LargeImageText = (x.IsMV) ? resp[2] : ConvertToValidString(x.ArtistandAlbumName.Split('—')[1]),
88-
SmallImageKey = (x.AudioDetail == 0) ? "lossless" : (x.AudioDetail == 1 || x.AudioDetail == 2) ? "dolbysimplified" : null,
89-
SmallImageText = (x.AudioDetail == 0) ? "Lossless" : (x.AudioDetail == 1) ? "Dolby Atmos" : (x.AudioDetail == 2) ? "Dolby Audio" : null,
86+
LargeImageKey = (resp.artworkURL != null) ? resp.artworkURL : "",
87+
LargeImageText = (x.IsMV) ? resp.trackName : ConvertToValidString(x.ArtistandAlbumName.Split('—')[1]),
88+
SmallImageKey = (x.format == AudioFormat.Lossless) ? "lossless" : (x.format == AudioFormat.Dolby_Atmos || x.format == AudioFormat.Dolby_Audio) ? "dolbysimplified" : null,
89+
SmallImageText = (x.format == AudioFormat.Lossless) ? "Lossless" : (x.format == AudioFormat.Dolby_Atmos) ? "Dolby Atmos" : (x.format == AudioFormat.Dolby_Audio) ? "Dolby Audio" : null,
9090
},
9191
Buttons = new Button[]
9292
{
93-
new Button() { Label = "Listen on Apple Music", Url = (resp.Length > 0) ? resp[1].Replace("https://", "music://") : "music://music.apple.com/home"}
93+
new Button() { Label = "Listen on Apple Music", Url = (resp.trackURL != null) ? resp.trackURL.Replace("https://", "music://") : "music://music.apple.com/home"}
9494
},
9595
Timestamps = new Timestamps()
9696
{
@@ -99,10 +99,10 @@ public static void SetPresence(SongData x, string[] resp)
9999
}
100100
};
101101
client.SetPresence(oldData);
102-
if (resp?[0] is { Length: > 0 } && !resp[0].Contains((S3_Credentials != null) ? (S3_Credentials.GetNullKeys().Count == 0) ? S3_Credentials.bucketURL : "" : ""))
102+
if (resp.artworkURL != null && !resp.artworkURL.Contains((S3_Credentials != null) ? (S3_Credentials.GetNullKeys().Count == 0) ? S3_Credentials.bucketURL : "" : ""))
103103
{
104104
animatedCoverCts = new CancellationTokenSource();
105-
Task t = new Task(() => CheckAnimatedCover(ConvertToValidString(x.ArtistandAlbumName.Split('—')[1]), resp[1], animatedCoverCts.Token));
105+
Task t = new Task(() => CheckAnimatedCover(ConvertToValidString(x.ArtistandAlbumName.Split('—')[1]), resp.trackURL, animatedCoverCts.Token));
106106
t.Start();
107107
}
108108
}

AMDiscordRPC/Globals.cs

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
using System.Text;
1515
using System.Text.RegularExpressions;
1616
using System.Threading.Tasks;
17-
using static AMDiscordRPC.UI;
1817
using static AMDiscordRPC.Database;
18+
using static AMDiscordRPC.UI;
1919

2020
namespace AMDiscordRPC
2121
{
@@ -31,7 +31,7 @@ public static class Globals
3131
public static readonly Assembly assembly = Assembly.GetExecutingAssembly();
3232
public static HtmlParser parser = new HtmlParser();
3333
public static RichPresence oldData = new RichPresence();
34-
public static string[] httpRes = Array.Empty<string>();
34+
public static WebSongResponse httpRes = new WebSongResponse();
3535
public static string ffmpegPath;
3636
public static S3_Creds S3_Credentials;
3737
private static List<string> newMatchesArr;
@@ -41,6 +41,13 @@ public enum S3ConnectionStatus
4141
Disconnected,
4242
Error
4343
}
44+
public enum AudioFormat
45+
{
46+
Lossless,
47+
Dolby_Atmos,
48+
Dolby_Audio,
49+
AAC
50+
}
4451
public static S3ConnectionStatus S3Status = S3ConnectionStatus.Disconnected;
4552

4653
public static void ConfigureLogger()
@@ -121,7 +128,7 @@ private static void StartFFmpegProcess(string filename)
121128

122129
public static async void CheckFFmpeg()
123130
{
124-
List<string> paths = Environment.GetEnvironmentVariable("PATH").Split(';').Where(v => v.Contains("ffmpeg")).Select(s => $@"{s}\ffmpeg.exe").Prepend("ffmpeg").ToList() ;
131+
List<string> paths = Environment.GetEnvironmentVariable("PATH").Split(';').Where(v => v.Contains("ffmpeg")).Select(s => $@"{s}\ffmpeg.exe").Prepend("ffmpeg").ToList();
125132
object SQLQueryRes = ExecuteScalarCommand($"SELECT FFmpegPath from creds");
126133

127134
if (SQLQueryRes != null)
@@ -150,16 +157,16 @@ public class SongData : EventArgs
150157
public bool IsMV { get; set; }
151158
public DateTime StartTime { get; set; }
152159
public DateTime EndTime { get; set; }
153-
public int AudioDetail { get; set; }
160+
public AudioFormat format { get; set; }
154161

155-
public SongData(string SongName, string ArtistandAlbumName, bool IsMV, DateTime StartTime, DateTime EndTime, int AudioDetail)
162+
public SongData(string SongName, string ArtistandAlbumName, bool IsMV, DateTime StartTime, DateTime EndTime, AudioFormat format)
156163
{
157164
this.SongName = SongName;
158165
this.ArtistandAlbumName = ArtistandAlbumName;
159166
this.IsMV = IsMV;
160167
this.StartTime = StartTime;
161168
this.EndTime = EndTime;
162-
this.AudioDetail = AudioDetail;
169+
this.format = format;
163170
}
164171
}
165172

@@ -202,5 +209,27 @@ public List<object> GetNotNullValues()
202209
return GetType().GetProperties().Where(s => s.GetValue(this) != null).Select(p => (p.PropertyType == typeof(string)) ? $"'{p.GetValue(this)}'" : p.GetValue(this)).ToList();
203210
}
204211
}
212+
213+
public class WebSongResponse
214+
{
215+
public string artworkURL { get; set; }
216+
public string trackURL { get; set; }
217+
public string trackName { get; set; }
218+
219+
public WebSongResponse(string artworkURL = null, string trackURL = null, string trackName = null)
220+
{
221+
this.artworkURL = artworkURL;
222+
this.trackURL = trackURL;
223+
this.trackName = trackName;
224+
}
225+
226+
public override bool Equals(object obj)
227+
{
228+
return obj is WebSongResponse other &&
229+
artworkURL == other.artworkURL &&
230+
trackURL == other.trackURL &&
231+
trackName == other.trackName;
232+
}
233+
}
205234
}
206235
}

AMDiscordRPC/Helpers/TextBoxHelper.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,9 @@ private static bool GetOrCreateAdorner(TextBox textBoxControl, out PlaceholderAd
9696

9797
public class PlaceholderAdorner : Adorner
9898
{
99-
public PlaceholderAdorner(TextBox textBox) : base(textBox)
99+
public PlaceholderAdorner(TextBox textBox) : base(textBox)
100100
{
101-
IsHitTestVisible = false;
101+
IsHitTestVisible = false;
102102
}
103103

104104
protected override void OnRender(DrawingContext drawingContext)

AMDiscordRPC/Playlist.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ internal class Playlist
2424
public static async Task ConvertM3U8(string album, string playlistUrl, CancellationToken ct)
2525
{
2626
// ^I thought storing Master Playlist would be better for in case of bucket changes and Apple's codec changes on lowest quality.
27-
Database.UpdateAlbum(new Database.SQLCoverResponse(album, null, null, true, playlistUrl, null));
27+
Database.UpdateAlbum(new Database.SQLCoverResponse(album, null, null, true, playlistUrl));
2828
StreamInf playlist = await FetchResolution(playlistUrl);
2929
if (!ct.IsCancellationRequested && playlist != null)
3030
{

AMDiscordRPC/S3.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
using Amazon.Runtime;
22
using Amazon.S3;
33
using Amazon.S3.Model;
4+
using AMDiscordRPC.UIComponents;
45
using System;
56
using System.Collections.Generic;
67
using System.Linq;
78
using System.Net;
89
using System.Text;
910
using System.Threading.Tasks;
10-
using AMDiscordRPC.UIComponents;
1111
using static AMDiscordRPC.Globals;
1212

1313
namespace AMDiscordRPC
@@ -37,7 +37,8 @@ public static void InitS3()
3737
S3Status = S3ConnectionStatus.Disconnected;
3838
InputWindow.ChangeS3Status(S3ConnectionStatus.Disconnected);
3939
}
40-
} catch (Exception e)
40+
}
41+
catch (Exception e)
4142
{
4243
S3Status = S3ConnectionStatus.Error;
4344
InputWindow.ChangeS3Status(S3ConnectionStatus.Error);

AMDiscordRPC/UI.cs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
using AMDiscordRPC.UIComponents;
2+
using Microsoft.Win32;
23
using System;
34
using System.ComponentModel;
5+
using System.Diagnostics;
46
using System.Drawing;
7+
using System.IO;
58
using System.Threading;
69
using System.Windows;
710
using System.Windows.Forms;
8-
using Microsoft.Win32;
9-
using System.IO;
10-
using System.Diagnostics;
11-
using static AMDiscordRPC.Globals;
1211
using static AMDiscordRPC.Database;
12+
using static AMDiscordRPC.Globals;
1313
using Application = System.Windows.Application;
1414
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
1515

@@ -38,7 +38,8 @@ public static void CreateUI()
3838
public static void FFmpegDialog()
3939
{
4040
log.Warn("FFmpeg not found");
41-
Thread thread = new Thread(() => {
41+
Thread thread = new Thread(() =>
42+
{
4243
if (System.Windows.MessageBox.Show("FFmpeg not found. Do you want to specify the path?", "FFmpeg not found.", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)
4344
{
4445
log.Debug("Yes");

0 commit comments

Comments
 (0)