-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathTools.cs
More file actions
417 lines (398 loc) · 14.4 KB
/
Tools.cs
File metadata and controls
417 lines (398 loc) · 14.4 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SitePlugin;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Common;
using System.Windows.Media;
using System.Net;
using System.Reflection;
using System.Collections;
using TwicasSitePlugin.LowObject;
namespace TwicasSitePlugin
{
class MessageLink : IMessageLink
{
public string Text { get; set; }
public string Url { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj is MessageLink text)
{
return this.Text.Equals(text.Text) && this.Url.Equals(text.Url);
}
return false;
}
public override int GetHashCode()
{
return Text.GetHashCode() ^ Url.GetHashCode();
}
}
//class MessageText : IMessageText
//{
// public string Text { get; }
// public MessageText(string text)
// {
// Text = text;
// }
// public override bool Equals(object obj)
// {
// if (obj == null)
// {
// return false;
// }
// if (obj is MessageText text)
// {
// return this.Text.Equals(text.Text);
// }
// return false;
// }
// public override int GetHashCode()
// {
// return Text.GetHashCode();
// }
//}
//public class MessageImage : IMessageImage
//{
// public int? Width { get; set; }
// public int? Height { get; set; }
// public string Url { get; set; }
// public string Alt { get; set; }
// public override bool Equals(object obj)
// {
// if (obj == null)
// {
// return false;
// }
// if (obj is MessageImage image)
// {
// return this.Url.Equals(image.Url) && this.Alt.Equals(image.Alt);
// }
// return false;
// }
// public override int GetHashCode()
// {
// return Url.GetHashCode() ^ Alt.GetHashCode();
// }
//}
static class Tools
{
public static bool IsKiitos(Item item)
{
return item.ItemImage.Contains("item_funding_stamp");
}
public static string DecodeBase64(string encoded)
{
if (string.IsNullOrEmpty(encoded)) return encoded;
var bytes = Convert.FromBase64String(encoded);
var s = Encoding.UTF8.GetString(bytes);
return s;
}
public static List<Cookie> ExtractCookies(CookieContainer container)
{
var cookies = new List<Cookie>();
var table = (Hashtable)container.GetType().InvokeMember("m_domainTable",
BindingFlags.NonPublic |
BindingFlags.GetField |
BindingFlags.Instance,
null,
container,
new object[] { });
foreach (var key in table.Keys)
{
var domain = key as string;
if (domain == null)
continue;
if (domain.StartsWith("."))
domain = domain.Substring(1);
var address = string.Format("http://{0}/", domain);
if (Uri.TryCreate(address, UriKind.RelativeOrAbsolute, out Uri uri) == false)
continue;
foreach (Cookie cookie in container.GetCookies(uri))
{
cookies.Add(cookie);
}
}
return cookies;
}
public static Color ColorFromArgb(string argb)
{
if (argb == null)
throw new ArgumentNullException("argb");
var pattern = "#(?<a>[0-9a-fA-F]{2})(?<r>[0-9a-fA-F]{2})(?<g>[0-9a-fA-F]{2})(?<b>[0-9a-fA-F]{2})";
var match = System.Text.RegularExpressions.Regex.Match(argb, pattern, System.Text.RegularExpressions.RegexOptions.Compiled);
if (!match.Success)
{
throw new ArgumentException("形式が不正");
}
else
{
var a = byte.Parse(match.Groups["a"].Value, System.Globalization.NumberStyles.HexNumber);
var r = byte.Parse(match.Groups["r"].Value, System.Globalization.NumberStyles.HexNumber);
var g = byte.Parse(match.Groups["g"].Value, System.Globalization.NumberStyles.HexNumber);
var b = byte.Parse(match.Groups["b"].Value, System.Globalization.NumberStyles.HexNumber);
return Color.FromArgb(a, r, g, b);
}
}
public static string ToText(this IEnumerable<IMessagePart> messageParts)
{
var s = "";
foreach (var part in messageParts)
{
if (part is IMessageText text)
{
s += text.Text;
}
else if (part is IMessageLink link)
{
s += link.Url;
}
}
return s;
}
public static T Deserialize<T>(string json)
{
T low;
try
{
low = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
throw new ParseException(json, ex);
}
return low;
}
public static string ReplaceLink(string str)
{
return Regex.Replace(str, "<a href=\"(?<url>[^\"]+)\" .+?>.+?</a>", m =>
{
return "<a href=\"" + m.Groups["url"].Value + "\" />";
});
}
public static string ReplaceHtmlEntities(string html)
{
var sb = new StringBuilder(html);
sb.Replace("'", "'");
sb.Replace("'", "'");
sb.Replace(""", "\"");
sb.Replace(" ", " ");
sb.Replace("<wbr>", "");
sb.Replace("<", "<");
sb.Replace(">", ">");
sb.Replace("&", "&");
#if DEBUG
var matches = Regex.Matches(sb.ToString(), "(?<entity>&[^;]+;)");
foreach (Match match in matches)
{
using (var sw = new System.IO.StreamWriter("entity.txt", true))
{
sw.WriteLine(match.Groups["entity"].Value);
}
}
#endif
return sb.ToString();
}
public static List<IMessagePart> ParseMessage(string message)
{
var b = ReplaceLink(message);
var arr = Regex.Split(b, "(\\<[^\\>]+?\\>)");
var list = new List<IMessagePart>();
foreach (var s in arr)
{
if (!s.StartsWith("<"))
{
var decoded = ReplaceHtmlEntities(s);
list.Add(MessagePartFactory.CreateMessageText(decoded));
}
else if (s.StartsWith("<a href"))
{
var match = Regex.Match(s, "^<a href=\"(?<url>[^\"]+)\"");
if (match.Success)
{
var url = match.Groups["url"].Value;
list.Add(new MessageLink { Text = url, Url = url });
}
}
else if (s.StartsWith("<br"))
{
list.Add(MessagePartFactory.CreateMessageText(Environment.NewLine));
}
else if (s == "<wbr>")
{
//do nothing
}
else if (s.StartsWith("<img"))
{
var match = Regex.Match(s, "(\\<img class=\"emoji\" src=\"(?<url>[^\"]+)\" width=\"(?<width>\\d+)\" height=\"(?<height>\\d+)\" /\\>)");
if (match.Success)
{
var url = "https://twitcasting.tv" + match.Groups["url"].Value;//domainを追加しないと
var width = int.Parse(match.Groups["width"].Value);
var height = int.Parse(match.Groups["height"].Value);
list.Add(new MessageImage { Url = url, Alt = "", Height = height, Width = width });
}
}
else
{
#if DEBUG
using (var sw = new System.IO.StreamWriter("tag.txt", true))
{
sw.WriteLine(s);
}
#endif
}
}
return list;
}
public static bool IsValidUserId(string input)
{
return Regex.IsMatch(input, "^[a-zA-Z0-9:_]+$");
}
internal static string ExtractBroadcasterId(string input)
{
if (string.IsNullOrEmpty(input))
throw new ArgumentNullException(nameof(input));
if (IsValidUserId(input))
{
return input;
}
var match0 = Regex.Match(input, "twitcasting\\.tv/([a-zA-Z0-9:_]+)");
if (match0.Success)
{
return match0.Groups[1].Value;
}
throw new ArgumentException("invalid input");
}
public static bool IsValidUrl(string input)
{
return Regex.IsMatch(input, "twitcasting\\.tv/([a-zA-Z0-9:_]+)");
}
internal static InternalComment Parse(Low.ListAll.Comment low)
{
return new InternalComment
{
CreatedAt = Common.UnixTimeConverter.FromUnixTime(low.CreatedAt.Value / 1000).ToLocalTime(),
Grade = low.Author.Grade,
Id = low.Id,
ProfileImageUrl = low.Author.ProfileImage,
Message = low.Message,
ScreenName = low.Author.ScreenName,
UserId = low.Author.Id,
UserName = low.Author.Name,
};
}
internal static InternalComment Parse(Comment low)
{
var (name, preThumbnailUrl, message) = SplitHtml(low.html);
string thumbnailUrl;
if (preThumbnailUrl.StartsWith("https://"))
{
thumbnailUrl = preThumbnailUrl;
}
else if (preThumbnailUrl.StartsWith("//"))
{
thumbnailUrl = "https:" + preThumbnailUrl;
}
else
{
throw new ParseException(low.html);
}
//var inter = new InternalComment
//{
// Id = comment.Id,
// Message = comment.Message,
// RawMessage = comment.RawMessage,
// HasMention = comment.HasMention,
// CreatedAt = UnixTime2DateTime(comment.CreatedAt / 1000),
// SpecialImage = comment.SpecialImage,
// UserId = comment.Author.Id,
// UserName = comment.Author.ScreenName,//2020/01/04 Twicasのバグだろうか。NameとScreenNameが逆な気がする
// ScreenName = comment.Author.Name,
// ProfileImageUrl = profileImageUrl,
// Grade = comment.Author.Grade,
// Raw = raw,
//};
//var data = new CommentData
//{
// Id = low.id,
// UserId = low.uid,
// Name = ReplaceHtmlEntities(name),
// Message = ParseMessage(message),
// ThumbnailUrl = thumbnailUrl,
// ThumbnailHeight = 50,
// ThumbnailWidth = 50,
// Date = DateTime.Parse(low.date),//"Sat, 28 Apr 2018 02:21:28 +0900"
//};
//return data;
DateTime createdAt;
try
{
createdAt = DateTime.Parse(low.date);
}
catch (Exception ex)
{
throw new ParseException(low.date);
}
return new InternalComment
{
Message = message,
ScreenName = name,
UserName = low.screen,
UserId = low.uid,
CreatedAt = createdAt,
Id = low.id,
ProfileImageUrl = thumbnailUrl,
};
}
/// <summary>
///
/// </summary>
/// <param name="html"></param>
/// <exception cref="SpecChangedException"></exception>
/// <returns></returns>
public static (string name, string thumbnailUrl, string message) SplitHtml(string html)
{
string thumbnailUrl;
string name;
string message;
var match = Regex.Match(html, "<img src=\"(?<thumbnail>[^\"]+)\" width=\"\\d+\" height=\"\\d+\"");
if (match.Success)
{
thumbnailUrl = match.Groups["thumbnail"].Value;
}
else
{
throw new SpecChangedException("仕様変更があったかも", html);
}
//名前に"<"とか">"が含まれることがある。
//2018/05/11 名前に改行が含まれている場合があったためRegexOptions.Singlelineを追加
var match1 = Regex.Match(html, "<span class=\"user\"><a .+?>(?<name>.*?)</a>", RegexOptions.Singleline);
if (match1.Success)
{
name = match1.Groups["name"].Value;
}
else
{
throw new SpecChangedException("仕様変更があったかも", html);
}
var match2 = Regex.Match(html, "<span class=\"comment-text\">(?<message>.+?)</span>");
if (match2.Success)
{
message = match2.Groups["message"].Value;
}
else
{
throw new SpecChangedException("仕様変更があったかも", html);
}
return (name, thumbnailUrl, message);
}
}
}