-
Notifications
You must be signed in to change notification settings - Fork 2
/
FourChan.cs
285 lines (267 loc) · 11.2 KB
/
FourChan.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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Canaan
{
public class FourChan : Api
{
#region Constructors
public FourChan(CancellationToken ct) : base(ct) { Initialized = true; }
public FourChan() : base() { Initialized = true; }
#endregion
#region Properties
static Regex repliesRegex = new Regex(">>\\d+", RegexOptions.Compiled);
#endregion
#region Methods
public async Task<IEnumerable<NewsThread>> GetThreads(string board)
{
using (var op = Begin("Get threads for board {0}", board))
{
var r = await HttpClient.GetAsync($"http://a.4cdn.org/{board}/threads.json", CancellationToken);
r.EnsureSuccessStatusCode();
var json = await r.Content.ReadAsStringAsync();
var pages = JArray.Parse(json);
var threads = new List<NewsThread>();
foreach (dynamic page in pages)
{
int p = 1;
foreach (dynamic thread in page.threads)
{
var t = new NewsThread()
{
Source = "4ch.pol",
No = thread.no,
Id = ((string)thread.no) + "-" + YY,
Position = p++,
LastModified = DateTimeOffset.FromUnixTimeSeconds((long)thread.last_modified).UtcDateTime,
ReplyCount = thread.replies
};
threads.Add(t);
}
}
op.Complete();
return threads;
}
}
public async Task<IDictionary<NewsThread, List<Post>>> GetPosts(string board, IEnumerable<NewsThread> threads, int delay = 500)
{
using (var op = Begin("Get posts for {0} threads for board {1}", threads.Count(), board))
{
Task<HttpResponseMessage>[] threadTasks =
threads.Select(t => HttpClient.GetAsync($"http://a.4cdn.org/{board}/thread/{t.No}.json", CancellationToken)).ToArray();
try
{
foreach (var task in threadTasks)
{
await task;
await Task.Delay(delay);
}
}
catch { }
foreach (var task in threadTasks.Where(t => t.IsFaulted || t.IsCanceled))
{
if (task.Exception != null)
{
Error(task.Exception, "Could not fetch thread.");
}
else
{
Error("Could not fetch thread. Thread task did not complete.");
}
}
var threadsResponseTask = threadTasks
.Where(t => t.IsCompleted)
.Select(t => t.Result)
.Where(r => r.StatusCode == HttpStatusCode.OK)
.Select(r => r.Content.ReadAsStringAsync());
await Task.WhenAll(threadsResponseTask);
var threadsJson = threadsResponseTask.Select(r => r.Result);
var posts = new ConcurrentDictionary<NewsThread, List<Post>>();
Parallel.ForEach(threadsJson, (j) =>
{
dynamic o = JObject.Parse(j);
JArray threadPosts = o.posts;
dynamic subjectPost = threadPosts[0];
NewsThread thread = threads.Single(t => t.No == (long)subjectPost.no);
thread.Subject = subjectPost.sub;
thread.Text = WebScraper.ExtractTextFromHtmlFrag((string)subjectPost.com);
thread.User = subjectPost.name;
thread.ReplyCount = subjectPost.replies;
if (!posts.TryAdd(thread, new List<Post>()))
{
Error("Could not add thread {0} to posts collection.", thread.Id);
}
int pos = 1;
foreach (dynamic post in threadPosts)
{
posts[thread].Add(
new Post()
{
Source = $"4ch.{board}",
ThreadId = thread.Id,
No = post.no,
Id = post.no.ToString() + "-" + YY,
Position = pos++,
User = post.name,
DatePublished = DateTimeOffset.FromUnixTimeSeconds((long)post.time).UtcDateTime,
Text = WebScraper.ExtractTextFromHtmlFrag((string)post.com),
Links = WebScraper.ExtractLinksFromHtmlFrag((string)post.com),
Additional = GetAdditionalPropsForPost((JObject)post)
});
}
});
foreach (var tp in posts)
{
foreach (var p in tp.Value)
{
var rnos = ExtractPostRepliesFromText(p);
foreach (var no in rnos)
{
p.ReplyTo.Add(no.ToString() + "-" + YY);
var replyto = tp.Value.SingleOrDefault(v => v.No == no);
if (replyto != null)
{
replyto.Replies.Add(p.Id);
}
}
p.Text = repliesRegex.Replace(p.Text, string.Empty).Replace(">", string.Empty);
p.Text = WebScraper.RemoveUrlsFromText(p.Text);
}
}
foreach(var p in posts.Values.SelectMany(x => x))
{
p.HasIdentityHate = HateWords.IdentityHateWords.Any(w => p.Text.Contains(w));
}
op.Complete();
return posts;
}
}
public async Task<ValueTuple<NewsThread, List<Post>>> GetThread(string board, string threadno)
{
var r = await HttpClient.GetAsync($"http://a.4cdn.org/{board}/thread/{threadno}.json", CancellationToken);
r.EnsureSuccessStatusCode();
var json = await r.Content.ReadAsStringAsync();
dynamic o = JObject.Parse(json);
JArray threadPosts = o.posts;
dynamic subjectPost = threadPosts[0];
NewsThread thread = new NewsThread()
{
Source = $"4ch.{board}",
No = subjectPost.no,
Id = subjectPost.no.ToString() + "-" + YY,
DatePublished = DateTimeOffset.FromUnixTimeSeconds((long)subjectPost.time).UtcDateTime,
Subject = subjectPost.sub,
Text = WebScraper.ExtractTextFromHtmlFrag((string)subjectPost.com),
User = subjectPost.name,
ReplyCount = subjectPost.replies
};
var posts = ParsePostsFromThreadJson(board, json);
foreach (var p in posts)
{
p.ThreadId = thread.Id;
}
foreach (var p in posts)
{
var rnos = ExtractPostRepliesFromText(p);
foreach (var no in rnos)
{
p.ReplyTo.Add(no.ToString() + "-" + YY);
var replyto = posts.SingleOrDefault(v => v.No == no);
if (replyto != null)
{
replyto.Replies.Add(p.Id);
}
}
p.Text = repliesRegex.Replace(p.Text, string.Empty).Replace(">", string.Empty);
p.Text = WebScraper.RemoveUrlsFromText(p.Text);
p.HasIdentityHate = HateWords.IdentityHateWords.Any(w => p.Text.Contains(w));
}
return (thread, posts);
}
protected List<Post> ParsePostsFromThreadJson(string board, string json)
{
dynamic o = JObject.Parse(json);
JArray threadPosts = o.posts;
dynamic subjectPost = threadPosts[0];
int pos = 1;
List<Post> posts = new List<Post>();
foreach (dynamic post in threadPosts)
{
posts.Add(
new Post()
{
Source = $"4ch.{board}",
No = post.no,
Id = post.no.ToString() + "-" + YY,
Position = pos++,
User = post.name,
DatePublished = DateTimeOffset.FromUnixTimeSeconds((long)post.time).UtcDateTime,
Text = WebScraper.ExtractTextFromHtmlFrag((string)post.com),
Links = WebScraper.ExtractLinksFromHtmlFrag((string)post.com),
Additional = GetAdditionalPropsForPost(post)
});
}
return posts;
}
protected Dictionary<string, object> GetAdditionalPropsForPost(JObject post)
{
Dictionary<string, object> props = new Dictionary<string, object>();
if (post.TryGetValue("filename", out JToken filename))
{
props.Add("filename", (string) filename);
}
if (post.TryGetValue("ext", out JToken ext))
{
props.Add("ext", (string) ext);
}
if (post.TryGetValue("w", out JToken w))
{
props.Add("w", (int) w);
}
if (post.TryGetValue("h", out JToken h))
{
props.Add("h", (int) h);
}
if (post.TryGetValue("fsize", out JToken fsize))
{
props.Add("fsize", (int) fsize);
}
if (post.TryGetValue("country_name", out JToken country_name))
{
props.Add("country_name", (string) country_name);
}
return props;
}
private IEnumerable<long> ExtractPostRepliesFromText(Post post)
{
var match = repliesRegex.Match(post.Text);
if (!match.Success)
{
return Array.Empty<long>();
}
else
{
List<long> rnos = new List<long>();
while (match.Success)
{
string no = match.Value.Replace(">>", string.Empty);
if (Int64.TryParse(no, out long _no))
{
rnos.Add(_no);
}
match = match.NextMatch();
}
return rnos;
}
}
#endregion
}
}