forked from dadur604/RocksmithScrobbler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
432 lines (355 loc) · 15.7 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
using RocksmithScrobbler.Addons;
using RocksmithScrobbler.Configuration;
using RockSnifferLib.Cache;
using RockSnifferLib.Events;
using RockSnifferLib.Logging;
using RockSnifferLib.RSHelpers;
using RockSnifferLib.Sniffing;
using RockSnifferLib.SysHelpers;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Lpfm.LastFmScrobbler.Api;
using Lpfm.LastFmScrobbler;
using Microsoft.Win32;
namespace RocksmithScrobbler
{
class Program
{
internal const string version = "0.1.3";
internal static Program p;
internal static ICache cache;
internal static Config config;
internal static Process rsProcess;
public static Random random = new Random();
internal static string cachedir = AppDomain.CurrentDomain.BaseDirectory + "cache";
private static AddonService addonService;
private Image defaultAlbumCover = new Bitmap(256, 256);
private RSMemoryReadout memReadout = new RSMemoryReadout();
private SongDetails details = new SongDetails();
private QueuingScrobbler scrobbler;
private const string apiKey = "9a781b5c563ddf03d4b3a358a3851e72";
private const string apiSecret = "072678231c0eb4d61228b50b50293079";
public string LpfmRegistryNameSpace = "HKEY_CURRENT_USER\\Software\\RocksmithScrobbler";
private Track lastscrobbled;
static void Main(string[] args)
{
p = new Program();
p.Initialize();
string sessionKey = p.GetSessionKey();
p.scrobbler = new QueuingScrobbler(apiKey, apiSecret, sessionKey);
//Keep running even when rocksmith disappears
while (true)
{
try
{
p.Run();
}
catch (Exception e)
{
//Catch all exceptions that are not handled and log
Logger.LogError("Encountered unhandled exception: {0}\r\n{1}", e.Message, e.StackTrace);
p.scrobbler.Process(true);
throw e;
}
}
}
private string GetSessionKey() {
const string sessionKeyRegistryKeyName = "LastFmSessionKey";
// try get the session key from the registry
string sessionKey = GetRegistrySetting(sessionKeyRegistryKeyName, null);
if (string.IsNullOrEmpty(sessionKey)) {
// instantiate a new scrobbler
var scrobbler = new Scrobbler(apiKey, apiSecret);
//NOTE: This is demo code. You would not normally do this in a production application
while (string.IsNullOrEmpty(sessionKey)) {
// Try get session key from Last.fm
try {
sessionKey = scrobbler.GetSession();
// successfully got a key. Save it to the registry for next time
SetRegistrySetting(sessionKeyRegistryKeyName, sessionKey);
} catch (LastFmApiException exception) {
// get a url to authenticate this application
string url = scrobbler.GetAuthorisationUri();
// open the URL in the default browser
Process.Start(url);
//Console.ReadKey();
}
}
}
return sessionKey;
}
public string GetRegistrySetting(string valueName, string defaultValue) {
if (string.IsNullOrEmpty(valueName)) throw new ArgumentException("valueName cannot be empty or null", "valueName");
valueName = valueName.Trim();
object regValue = Registry.GetValue(LpfmRegistryNameSpace, valueName, defaultValue);
if (regValue == null) {
// Key does not exist
return defaultValue;
} else {
return regValue.ToString();
}
}
public void SetRegistrySetting(string valueName, string value) {
if (string.IsNullOrEmpty(valueName)) throw new ArgumentException("valueName cannot be empty or null", "valueName");
valueName = valueName.Trim();
Registry.SetValue(LpfmRegistryNameSpace, valueName, value);
}
public void Initialize()
{
//Set title and print version
//Console.Title = string.Format("RockSniffer {0}", version);
Logger.Log("RockSniffer {0} ({1}bits)", version, CustomAPI.Is64Bits() ? "64" : "32");
//Initialize and load configuration
config = new Config();
try
{
config.Load();
}
catch (Exception e)
{
Logger.LogError("Could not load configuration: {0}\r\n{1}", e.Message, e.StackTrace);
throw e;
}
//Transfer logging options
Logger.logStateMachine = config.debugSettings.debugStateMachine;
Logger.logCache = config.debugSettings.debugCache;
Logger.logFileDetailQuery = config.debugSettings.debugFileDetailQuery;
Logger.logMemoryReadout = config.debugSettings.debugMemoryReadout;
Logger.logSongDetails = config.debugSettings.debugSongDetails;
Logger.logSystemHandleQuery = config.debugSettings.debugSystemHandleQuery;
//Initialize cache
cache = new FileCache(cachedir);
//Create directories
Directory.CreateDirectory("output");
//Enable addon service if configured
if (config.addonSettings.enableAddons)
{
try
{
addonService = new AddonService(config.addonSettings.ipAddress, config.addonSettings.port);
}
catch (SocketException e)
{
Logger.LogError("Please verify that the IP address is valid and the port is not already in use");
Logger.LogError("Could not start addon service: {0}\r\n{1}", e.Message, e.StackTrace);
}
catch (Exception e)
{
Logger.LogError("Could not start addon service: {0}\r\n{1}", e.Message, e.StackTrace);
}
}
}
public void Run()
{
//Clear output / create output files
ClearOutput();
Logger.Log("Waiting for rocksmith");
//Loop infinitely trying to find rocksmith process
while (true)
{
var processes = Process.GetProcessesByName("Rocksmith2014");
//Sleep for 1 second if no processes found
if (processes.Length == 0)
{
Thread.Sleep(1000);
continue;
}
//Select the first rocksmith process and open a handle
rsProcess = processes[0];
if (rsProcess.HasExited || !rsProcess.Responding)
{
Thread.Sleep(1000);
continue;
}
break;
}
Logger.Log("Rocksmith found! Sniffing...");
//Initialize file handle reader and memory reader
Sniffer sniffer = new Sniffer(rsProcess, cache);
//Listen for events
sniffer.OnSongChanged += Sniffer_OnCurrentSongChanged;
sniffer.OnMemoryReadout += Sniffer_OnMemoryReadout;
//Inform AddonService
if (config.addonSettings.enableAddons && addonService != null)
{
addonService.SetSniffer(sniffer);
}
while (true)
{
if (rsProcess == null || rsProcess.HasExited)
{
break;
}
OutputDetails();
//GOTTA GO FAST
Thread.Sleep(1000);
if (random.Next(0, 100) > 99)
{
Console.WriteLine("*sniff sniff*");
}
}
sniffer.Stop();
scrobbler.Process(true);
//Clean up as best as we can
rsProcess.Dispose();
rsProcess = null;
Logger.Log("This is rather unfortunate, the Rocksmith2014 process has vanished :/");
}
private void Sniffer_OnMemoryReadout(object sender, OnMemoryReadoutArgs args)
{
memReadout = args.memoryReadout;
if (string.IsNullOrEmpty(details.artistName) ||
string.IsNullOrEmpty(details.songName)){
return;
}
var currentTrack = new Track();
currentTrack.ArtistName = details.artistName;
currentTrack.TrackName = details.songName;
currentTrack.Duration = TimeSpan.FromSeconds(details.songLength);
if (!string.IsNullOrEmpty(details.albumName)) {
currentTrack.AlbumName = details.albumName;
}
currentTrack.WhenStartedPlaying = DateTime.Now.AddSeconds(-details.songLength);
if (lastscrobbled == null || (lastscrobbled.ArtistName != currentTrack.ArtistName && lastscrobbled.TrackName != lastscrobbled.TrackName)) {
//Halfway through a song
if (memReadout.songTimer >= (details.songLength / 2)) {
scrobbler.Scrobble(currentTrack);
Logger.Log($"Scrobbled: {currentTrack.ToString()}");
lastscrobbled = currentTrack;
}
}
}
private void Sniffer_OnCurrentSongChanged(object sender, OnSongChangedArgs args)
{
details = args.songDetails;
lastscrobbled = null;
//Write album art
if (details.albumArt != null)
{
WriteImageToFileLocking("output/album_cover.jpeg", details.albumArt);
}
else
{
WriteImageToFileLocking("output/album_cover.jpeg", defaultAlbumCover);
}
}
public static string FormatTime(float lengthTime)
{
TimeSpan t = TimeSpan.FromSeconds(Math.Ceiling(lengthTime));
return t.ToString(config.formatSettings.timeFormat);
}
public static string FormatPercentage(double frac)
{
return string.Format(config.formatSettings.percentageFormat, frac * 100d);
}
private void OutputDetails()
{
//TODO: remember state of each file and only update the ones that have changed!
foreach (OutputFile of in config.outputSettings.output)
{
//Clone the output text format so we can replace strings in it without changing the original
string outputtext = (string)of.format.Clone();
//Replace strings from song details
outputtext = outputtext.Replace("%SONG_ID%", details.songID);
outputtext = outputtext.Replace("%SONG_ARTIST%", details.artistName);
outputtext = outputtext.Replace("%SONG_NAME%", details.songName);
outputtext = outputtext.Replace("%SONG_ALBUM%", details.albumName);
outputtext = outputtext.Replace("%ALBUM_YEAR%", details.albumYear.ToString());
outputtext = outputtext.Replace("%SONG_LENGTH%", FormatTime(details.songLength));
//Toolkit details
if (details.toolkit != null)
{
outputtext = outputtext.Replace("%TOOLKIT_VERSION%", details.toolkit.version);
outputtext = outputtext.Replace("%TOOLKIT_AUTHOR%", details.toolkit.author);
outputtext = outputtext.Replace("%TOOLKIT_PACKAGE_VERSION%", details.toolkit.package_version);
outputtext = outputtext.Replace("%TOOLKIT_COMMENT%", details.toolkit.comment);
}
//If this output contained song detail information
if (outputtext != of.format)
{
//And our current song details are not valid
if (!details.IsValid())
{
//Output nothing
outputtext = "";
}
}
//Replace strings from memory readout
outputtext = outputtext.Replace("%SONG_TIMER%", FormatTime(memReadout.songTimer));
outputtext = outputtext.Replace("%NOTES_HIT%", memReadout.totalNotesHit.ToString());
outputtext = outputtext.Replace("%CURRENT_STREAK%", (memReadout.currentHitStreak - memReadout.currentMissStreak).ToString());
outputtext = outputtext.Replace("%HIGHEST_STREAK%", memReadout.highestHitStreak.ToString());
outputtext = outputtext.Replace("%NOTES_MISSED%", memReadout.totalNotesMissed.ToString());
outputtext = outputtext.Replace("%TOTAL_NOTES%", memReadout.TotalNotes.ToString());
outputtext = outputtext.Replace("%CURRENT_ACCURACY%", FormatPercentage((memReadout.totalNotesHit > 0 && memReadout.TotalNotes > 0) ? ((double)memReadout.totalNotesHit / (double)memReadout.TotalNotes) : 0));
//Write to output
WriteTextToFileLocking("output/" + of.filename, outputtext);
}
}
private void ClearOutput()
{
//Clear all output files
foreach (OutputFile of in config.outputSettings.output)
{
//Write to output
WriteTextToFileLocking("output/" + of.filename, "");
}
//Clear album art
WriteImageToFileLocking("output/album_cover.jpeg", defaultAlbumCover);
}
private void WriteImageToFileLocking(string file, Image image)
{
//If the file doesn't exist, create it by writing an empty string into it
if (!File.Exists(file))
{
File.WriteAllText(file, "");
}
try
{
//Open a file stream, write access, no sharing
using (FileStream fstream = new FileStream(file, FileMode.Truncate, FileAccess.Write, FileShare.None))
{
image.Save(fstream, ImageFormat.Jpeg);
}
}
catch (Exception e)
{
Logger.LogError("Unable to write to file {0}: {1}\r\n{2}", file, e.Message, e.StackTrace);
}
}
private void WriteTextToFileLocking(string file, string contents)
{
//If the file doesn't exist, create it by writing an empty string into it
if (!File.Exists(file))
{
File.WriteAllText(file, "");
}
//Encode with UTF-8
byte[] data = Encoding.UTF8.GetBytes(contents);
//Write to file
WriteToFileLocking(file, data);
}
private void WriteToFileLocking(string file, byte[] contents)
{
try
{
//Open a file stream, write access, read only sharing
using (FileStream fstream = new FileStream(file, FileMode.Truncate, FileAccess.Write, FileShare.Read))
{
//Write to file
fstream.Write(contents, 0, contents.Length);
}
}
catch (Exception e)
{
Logger.LogError("Unable to write to file {0}: {1}\r\n{2}", file, e.Message, e.StackTrace);
}
}
}
}