-
Notifications
You must be signed in to change notification settings - Fork 2
/
PartyMonitor.cs
470 lines (432 loc) · 18.3 KB
/
PartyMonitor.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net;
using System.Drawing;
using Advanced_Combat_Tracker;
using AngleSharp.Parser.Html;
using AngleSharp.Dom.Html;
using Tulpep.NotificationWindow;
namespace FFLogsEasyCheck
{
public enum Servers
{
Adamantoise = 000,
Balmung = 001,
Behemoth = 002,
Brynhildr = 003,
Cactuar = 004,
Coeurl = 005,
Diabolos = 006,
Excalibur = 007,
Exodus = 008,
Faerie = 009,
Famfrit = 010,
Gilgamesh = 011,
Goblin = 012,
Hyperion = 013,
Jenova = 014,
Lamia = 015,
Leviathan = 016,
Malboro = 017,
Mateus = 018,
Midgardsormr = 019,
Sargatanas = 020,
Siren = 021,
Ultros = 022,
Zalera = 023,
//EU
Cerberus = 100,
Lich = 101,
Louisoix = 102,
Moogle = 103,
Odin = 104,
Omega = 105,
Phoenix = 106,
Ragnarok = 107,
Shiva = 108,
Spriggan = 109,
Twintania = 110,
Zodiark = 111,
//JP
Aegis = 200,
Alexander = 201,
Anima = 202,
Asura = 203,
Atomos = 204,
Bahamut = 205,
Belias = 206,
Carbuncle = 207,
Chocobo = 208,
Durandal = 209,
Fenrir = 210,
Garuda = 211,
Gungnir = 212,
Hades = 213,
Ifrit = 214,
Ixion = 215,
Kujata = 216,
Mandragora = 217,
Masamune = 218,
Pandaemonium = 219,
Ramuh = 220,
Ridill = 221,
Shinryu = 222,
Tiamat = 223,
Titan = 224,
Tonberry = 225,
Typhon = 226,
Ultima = 227,
Unicorn = 228,
Valefor = 229,
Yojimbo = 230,
Zeromus = 231
}
public enum Regions
{
NA = 000,
EU = 100,
JP = 200
}
public partial class PartyMonitor : UserControl, IActPluginV1
{
private const string PartyJoinMessageFooter = "joins the party.";
private readonly string settingsFile = Path.Combine(ActGlobals.oFormActMain.AppDataFolder.FullName,
"Config\\FFlLogsEasyCheck.config.xml");
private Label lblStatus;
private SettingsSerializer xmlSettings;
private List<string> logs = new List<string>();
internal class RankData
{
public string profilePicUrl;
public string job;
public int rank;
public int allStarPoints;
public RankData(string profilePicUrl, string job, int rank, int allStarPoints)
{
this.profilePicUrl = profilePicUrl;
this.job = job;
this.rank = rank;
this.allStarPoints = allStarPoints;
}
private RankData() { }
}
public PartyMonitor ()
{
InitializeComponent();
}
object[] servers;
public void InitPlugin (TabPage pluginScreenSpace, Label pluginStatusText)
{
lblStatus = pluginStatusText; // Hand the status label's reference to our local var
pluginScreenSpace?.Controls.Add(this); // Add this UserControl to the tab ACT provides
pluginScreenSpace.GotFocus += PluginScreenSpace_GotFocus;
Dock = DockStyle.Fill; // Expand the UserControl to fill the tab's client space
xmlSettings = new SettingsSerializer(this); // Create a new settings serializer and pass it this instance
servers = Enum.GetValues(typeof(Servers)).Cast<object>().ToArray();
RegionDropdown.Items.AddRange(Enum.GetValues(typeof(Regions)).Cast<object>().ToArray());
LoadSettings();
ActGlobals.oFormActMain.OnLogLineRead += OnLogLineReadAsync;
lblStatus.Text = "Plugin Started";
}
private void PluginScreenSpace_GotFocus (object sender, EventArgs e)
{
RegionDropdown_SelectedIndexChanged(null, null);
}
public void DeInitPlugin ()
{
ActGlobals.oFormActMain.OnLogLineRead -= OnLogLineReadAsync;
SaveSettings();
lblStatus.Text = "Plugin Exited";
}
private void OnLogLineReadAsync (bool isImport, LogLineEventArgs logInfo)
{
if(ActGlobals.oFormActMain.InvokeRequired)
{
ActGlobals.oFormActMain.Invoke(new Action(() => Task.Run(() => ParseLogForPartyInfo(logInfo))));
}
else
{
// Faster if invoke is not needed
Task.Run(() => ParseLogForPartyInfo(logInfo));
}
}
private async Task ParseLogForPartyInfo (LogLineEventArgs logInfo)
{
var log = logInfo.logLine;
//2 for the pos after the ] then the space
log = log.Substring(log.IndexOf(']') + 2);
// `/echo DEBUG FFLEC`
var debugFlag = log.Contains("DEBUG FFLEC");
if (log.StartsWith("00:1039:") || log.StartsWith("00:2239:") || debugFlag)
{
if (log.EndsWith(PartyJoinMessageFooter) || debugFlag)
{
string serverName = "", characterName = "", regionName = "";
Servers server = Servers.Adamantoise;
if (!debugFlag)
{
foreach (var ser in servers)
{
string s = Enum.GetName(typeof(Servers), ser);
if (log.Contains(s))
{
serverName = s;
server = (Servers)ser;
log = log.Replace(s, "");
break;
}
}
if (serverName == "")
{
if (ServerDropdown.SelectedIndex > 0)
{
serverName = Enum.GetName(typeof(Servers), ServerDropdown.SelectedItem);
server = (Servers)ServerDropdown.SelectedItem;
}
else
{
//TODO we dont have any server information at this point so we cant look them up, tell the user something went wrong and to check their server settings in the plugin ui
ShowPopup("Error", "Could not find the server that the new party member belongs to. Check the plugin settings in ACT to make sure your server is set to your logged-in character's home world.");
return;
}
}
//Message type header is 8 chars long so we start at 9
characterName = log.Substring(8, log.IndexOf(PartyJoinMessageFooter) - 8).Trim();
}
else
{
server = Servers.Chocobo;
serverName = Enum.GetName(typeof(Servers), server);
characterName = "Yoshi'p Sampo";
}
regionName = Enum.GetName(typeof(Regions), GetRegionFromServer(server));
var encodedRegion = Uri.EscapeUriString(regionName);
var encodedName = Uri.EscapeUriString(characterName);
var encodedServer = Uri.EscapeUriString(serverName);
var url = $"https://www.fflogs.com/character/{encodedRegion}/{encodedServer}/{encodedName}";
string title = $"{characterName} ({serverName} {regionName}) joins the party!";
//Add to the ACT window text log
AddLineToLog(title + $" ({url})");
//Show Notification
if (showNotificationBox.Checked)
{
var rankData = await ScrapeProfileData(url);
Image profilePic = null;
if(rankData != null)
profilePic = DownloadProfilePic(rankData.profilePicUrl);
var rankDataCorrupt = rankData == null || string.IsNullOrEmpty(rankData.job) || rankData.rank == -1 || rankData.allStarPoints == -1;
var body = rankDataCorrupt ? "Could not retrieve rank data." : $"{rankData.job} - Rank {rankData.rank} ({rankData.allStarPoints})\n\nClick Here for Full Logs!";
ShowPopup(title, body, profilePic, OnClick: () => Process.Start(url));
}
//Auto Open
if (autoOpenLogsBox.Checked)
{
Process.Start(url);
}
}
}
}
public void AddLineToLog(string line)
{
ActGlobals.oFormActMain.Invoke(new Action(() =>
{
logs.Add(line);
if (logs.Count > 1000) logs.RemoveAt(0);
logTextBox.Lines = logs.ToArray();
logTextBox.SelectionStart = logTextBox.Text.Length;
logTextBox.ScrollToCaret();
}));
}
public static void ShowPopup(string title, string body, Image picture = null, Action OnClick = null, Action OnDisposed = null)
{
ActGlobals.oFormActMain.Invoke(new Action(() =>
{
var popup = new PopupNotifier();
popup.TitleText = title;
popup.Delay = 5000;
popup.ContentText = body;
popup.BodyColor = Color.DarkBlue;
popup.ContentColor = Color.White;
popup.HeaderColor = Color.DarkGray;
popup.TitleColor = Color.White;
popup.TitleFont = new Font("Power Green", 10, FontStyle.Bold);
popup.ContentFont = new Font("Arial", 8, FontStyle.Regular);
popup.UseDarkBodyGradient = true;
popup.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
popup.GradientPower = 75;
//p is the popup sending itself back with empty args
if(OnClick != null)
popup.Click += (p, emptyArgs) => { OnClick(); };
if (OnDisposed != null)
popup.Disposed += (p, emptyArgs) => { OnDisposed(); };
popup.IsRightToLeft = false;
popup.ShowCloseButton = true;
if (picture != null)
{
popup.Image = picture;
popup.ImagePadding = new Padding(1, 0, 0, 1);
popup.ImageSize = new Size(90, 90);
}
popup.Popup();
}));
}
private void LoadSettings ()
{
// Add any controls you want to save the state of
//xmlSettings.AddControlSetting(textBox1.Name, textBox1);
xmlSettings.AddLongSetting("LastSavedContentId");
xmlSettings.AddControlSetting(RegionDropdown.Name, RegionDropdown);
xmlSettings.AddControlSetting(ServerDropdown.Name, ServerDropdown);
xmlSettings.AddControlSetting(showNotificationBox.Name, showNotificationBox);
xmlSettings.AddControlSetting(autoOpenLogsBox.Name, autoOpenLogsBox);
if (File.Exists(settingsFile))
{
var fs = new FileStream(settingsFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var xReader = new XmlTextReader(fs);
try
{
while (xReader.Read())
if (xReader.NodeType == XmlNodeType.Element)
if (xReader.LocalName == "SettingsSerializer")
xmlSettings.ImportFromXml(xReader);
}
catch (Exception ex)
{
lblStatus.Text = "Error loading settings: " + ex.Message;
}
xReader.Close();
}
}
private void SaveSettings ()
{
var fs = new FileStream(settingsFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
var xWriter = new XmlTextWriter(fs, Encoding.UTF8);
xWriter.Formatting = Formatting.Indented;
xWriter.Indentation = 1;
xWriter.IndentChar = '\t';
xWriter.WriteStartDocument(true);
xWriter.WriteStartElement("Config"); // <Config>
xWriter.WriteStartElement("SettingsSerializer"); // <Config><SettingsSerializer>
xmlSettings.ExportToXml(xWriter); // Fill the SettingsSerializer XML
xWriter.WriteEndElement(); // </SettingsSerializer>
xWriter.WriteEndElement(); // </Config>
xWriter.WriteEndDocument(); // Tie up loose ends (shouldn't be any)
xWriter.Flush(); // Flush the file buffer to disk
xWriter.Close();
}
internal async Task<RankData> ScrapeProfileData(string siteUrl)
{
try
{
var response = await GetDataFromUrl(siteUrl);
HtmlParser parser = new HtmlParser();
IHtmlDocument document = parser.Parse(response);
int rank = -1;
int asp = -1;
var pic = document.GetElementById("character-portrait-image")?.Attributes?.FirstOrDefault(a => a.Name == "src")?.Value;
var job = AddSpacesAfterCapitals(document.GetElementsByClassName("allstar-header-icon")?.FirstOrDefault()?.ClassList?.FirstOrDefault(s => s.Contains("actor-sprite-"))?.Substring(13));
int.TryParse(document.GetElementsByClassName("header-zone-positions")?.FirstOrDefault()?.GetElementsByClassName("header-rank")?.FirstOrDefault()?.TextContent, out rank);
int.TryParse(document.GetElementsByClassName("header-zone-points")?.FirstOrDefault()?.GetElementsByClassName("header-rank")?.FirstOrDefault()?.TextContent, out asp);
var rankData = new RankData(pic, job, rank, asp);
return rankData;
}
catch(OperationCanceledException e)
{
//Network related error
return null;
}
}
internal async Task<Stream> GetDataFromUrl(string url)
{
using (HttpClient httpClient = new HttpClient())
{
CancellationTokenSource cancellationToken = new CancellationTokenSource();
HttpResponseMessage request = await httpClient.GetAsync(url);
cancellationToken.Token.ThrowIfCancellationRequested();
Stream response = await request.Content.ReadAsStreamAsync();
cancellationToken.Token.ThrowIfCancellationRequested();
return response;
}
}
string AddSpacesAfterCapitals(string text)
{
if (string.IsNullOrWhiteSpace(text))
return "";
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]) && text[i - 1] != ' ')
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
private Image DownloadProfilePic(string picUrl)
{
using (var wc = new WebClient())
{
using (var imgStream = new MemoryStream(wc.DownloadData(picUrl)))
{
var profilePic = Image.FromStream(imgStream);
return profilePic;
}
}
}
private Regions GetRegionFromServer (Servers server)
{
var i = (int)server;
if (i >= (int)Regions.NA && i < (int)Regions.EU) return Regions.NA;
else if (i >= (int)Regions.EU && i < (int)Regions.JP) return Regions.EU;
return Regions.JP;
}
private void RegionDropdown_SelectedIndexChanged (object sender, EventArgs e)
{
ServerDropdown.Items.Clear();
ServerDropdown.ResetText();
var selection = (Regions)RegionDropdown.SelectedItem;
switch (selection)
{
default:
ServerDropdown.SelectedIndex = -1;
ServerDropdown.Enabled = false;
break;
case Regions.NA:
ServerDropdown.Enabled = true;
ServerDropdown.Items.AddRange(servers.Where(s => (int)s >= (int)Regions.NA && (int)s < (int)Regions.EU).ToArray());
break;
case Regions.EU:
ServerDropdown.Enabled = true;
ServerDropdown.Items.AddRange(servers.Where(s => (int)s >= (int)Regions.EU && (int)s < (int)Regions.JP).ToArray());
break;
case Regions.JP:
ServerDropdown.Enabled = true;
ServerDropdown.Items.AddRange(servers.Where(s => (int)s >= (int)Regions.JP).ToArray());
break;
}
}
private void ServerDropdown_SelectedIndexChanged (object sender, EventArgs e)
{
}
private void logTextBox_LinkClicked (object sender, LinkClickedEventArgs e)
{
Process.Start(e.LinkText);
}
private void showNotificationBox_CheckedChanged(object sender, EventArgs e)
{
}
private void autoOpenLogsBox_CheckedChanged(object sender, EventArgs e)
{
}
}
}