-
Notifications
You must be signed in to change notification settings - Fork 0
/
PatreonScript.js
468 lines (423 loc) · 15.7 KB
/
PatreonScript.js
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
const PLATFORM = "Patreon";
const PLATFORM_CLAIMTYPE = 12;
const BASE_URL = "https://www.patreon.com";
const BASE_URL_API = "https://www.patreon.com/api";
const URL_HOME = BASE_URL + "/home";
const URL_POSTS = BASE_URL_API + "/posts";
const URL_SEARCH_CREATORS = BASE_URL_API + "/search";
const URL_USER = BASE_URL_API + "/current_user";
const REGEX_CHANNEL_DETAILS = /Object\.assign\(window\.patreon\.bootstrap, ({.*?})\);/s
const REGEX_CHANNEL_DETAILS2 = /window\.patreon = ({.*?});/s
const REGEX_CHANNEL_DETAILS3 = /id="__NEXT_DATA__" type="application\/json">(.*?)<\/script>/s
const REGEX_CHANNEL_URL = /https:\/\/(?:www\.)?patreon.com\/(.+)/s
const REGEX_MEMBERSHIPS = /<ul aria-label="Memberships".*?>(.*?)<\/ul>/s
const REGEX_MEMBERSHIPS_URLS = /<a href="(.*?)"/g
const REGEX_URL_ID = /https:\/\/(?:www\.)?patreon.com\/posts\/.*-(.*)\/?/s
var config = {};
var _settings = {};
let _channelCache = {};
//Source Methods
source.enable = function (conf, settings, savedState) {
config = conf ?? {};
_settings = settings ?? {};
}
source.getHome = function () {
return new ContentPager([], false);
};
source.searchSuggestions = function (query) {
return [];
};
source.getSearchCapabilities = () => {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: []
};
};
source.search = function (query, type, order, filters) {
return new ContentPager([].false);
};
source.getSearchChannelContentsCapabilities = function () {
return {
types: [Type.Feed.Mixed],
sorts: [Type.Order.Chronological],
filters: []
};
};
source.searchChannelContents = function (channelUrl, query, type, order, filters) {
throw new ScriptException("This is a sample");
};
source.searchChannels = function (query) {
return new SearchChannelPager(query);
};
class SearchChannelPager extends ChannelPager {
constructor(query) {
super(searchChannels(query, 1))
this.query = query;
this.page = 1;
}
nextPage() {
this.page = this.page + 1;
this.results = searchChannels(query, this.page + 1);
this.hasMore = this.results.length > 0;
return this;
}
}
//Channel
source.isChannelUrl = function (url) {
return REGEX_CHANNEL_URL.test(url);
};
source.getChannel = function (url) {
const channelResp = http.GET(url, {}, false);
if (!channelResp.isOk)
throw new ScriptException("Failed to get channel");
let channelJson = REGEX_CHANNEL_DETAILS.exec(channelResp.body);
let channel = null;
if (!channelJson || channelJson.length != 2) {
channelJson = REGEX_CHANNEL_DETAILS2.exec(channelResp.body);
if (channelJson && channelJson.length == 2) {
channel = JSON.parse(channelJson[1]);
if (channel && channel.bootstrap)
channel = channel.bootstrap;
else
throw new ScriptException("Failed to parse channel");
}
else {
channelJson = REGEX_CHANNEL_DETAILS3.exec(channelResp.body);
if (channelJson && channelJson.length == 2) {
const channelWrapperObj = JSON.parse(channelJson[1]);
channel = channelWrapperObj?.props?.pageProps?.bootstrapEnvelope?.bootstrap
?? channelWrapperObj?.props?.pageProps?.bootstrapEnvelope?.pageBootstrap;
if (!channel)
throw new ScriptException("Failed to parse channel");
}
else
throw new ScriptException("Failed to extract channel");
}
}
else
channel = JSON.parse(channelJson[1]);
const result = new PlatformChannel({
id: new PlatformID(config.name, channel?.campaign?.data?.id, config.id, PLATFORM_CLAIMTYPE),
name: channel?.campaign?.data?.attributes?.name,
description: channel?.campaign?.data?.attributes?.description,
url: channel?.campaign?.data?.attributes?.url,
subscribers: channel?.campaign?.data?.attributes?.patron_count,
banner: channel?.campaign?.data?.attributes?.image_url ?? channel?.campaign?.data?.attributes?.cover_photo_url,
thumbnail: channel?.campaign?.data?.attributes?.avatar_photo_url
});
_channelCache[url] = result;
return result;
};
source.getChannelContents = function (url) {
const channel = (_channelCache[url]) ? _channelCache[url] : source.getChannel(url);
_channelCache[url] = channel;
return new ChannelContentPager(channel.id.value, channel);
};
class ChannelContentPager extends ContentPager {
constructor(campaignId, channel) {
const initialResults = getPosts(campaignId, channel);
super(initialResults.results, true);
this.nextPageUrl = initialResults.nextPage;
this.hasMore = !!this.nextPageUrl;
this.campaignId = campaignId;
this.channel = channel;
}
nextPage() {
if (!this.nextPage)
throw new ScriptException("No next page");
const newResults = getPosts(this.campaignId, this.channel, this.nextPageUrl) ?? [];
this.results = newResults.results;
this.nextPageUrl = newResults.nextPage;
this.hasMore = !!newResults.nextPage;
return this;
}
}
source.getChannelTemplateByClaimMap = () => {
return {
//Patreon
12: {
0: URL_BASE + "/{{CLAIMVALUE}}"
}
};
};
//Video
source.isContentDetailsUrl = function (url) {
return REGEX_URL_ID.test(url);
};
source.getContentDetails = function (url) {
throw new ScriptException("This is a sample");
};
//Comments
source.getComments = function (url, page = 0) {
const idMatch = REGEX_URL_ID.exec(url) ?? [];
if (idMatch.length != 2)
return new CommentPager([], false);
const id = idMatch[1];
const commentsResp = http.GET("https://www.patreon.com/api/posts/" + id + "/comments" +
"?include=include_replies%2Ccommenter%2Creplies%2Creplies.commenter" +
"&fields[comment]=body%2Ccreated%2Cvote_sum%2Creply_count" +
"&fields[post]=comment_count" +
"&fields[user]=image_url%2Cfull_name%2Curl" +
"&fields[flair]=image_tiny_url%2Cname" +
"&page[count]=10" +
"&sort=-created" +
"&json-api-use-default-includes=false" +
"&json-api-version=1.0", {}, true);
if (!commentsResp.isOk)
throw new ScriptException("Failed to get comments [" + commentsResp.code + "]");
return new PatreonCommentPager(url, JSON.parse(commentsResp.body));
}
source.getSubComments = function (comment) {
return new CommentPager([], false);
}
class PatreonCommentPager extends CommentPager {
constructor(url, resp) {
if (IS_TESTING)
console.log("CommentPager resp:", resp);
const nextUrl = resp?.links?.next;
super([], !!nextUrl);
this.contextUrl = url;
this.results = this.parseResponse(resp);
this.nextPageUrl = nextUrl;
}
nextPage() {
const resp = http.GET(this.nextPageUrl, {}, true);
if (!resp.isOk)
throw new ScriptException("Failed to get next comment page [" + resp.code + "]")
this.results = this.parseResponse(JSON.parse(resp.body));
this.nextPageUrl = resp?.links?.next;
this.hasMore = !!this.nextPageUrl;
}
parseResponse(resp) {
return resp.data.map(x => this.parseComment(x, resp)).filter(x => x != null)
}
parseComment(comment, resp) {
const commenterId = comment?.relationships?.commenter?.data?.id;
if (!commenterId)
return null;
const commenter = resp.included?.find(y => y.id == commenterId);
if (!commenter)
return null;
return new PatreonComment({
contextUrl: this.contextUrl,
author: new PlatformAuthorLink(new PlatformID(config.platform, comment.id, PLATFORM_CLAIMTYPE), commenter.attributes.full_name, commenter.attributes.url, commenter.attributes.image_url),
message: comment.attributes.body,
rating: new RatingLikes(comment.attributes.vote_sum),
date: parseInt(Date.parse(comment.attributes.created) / 1000),
replyCount: comment.attributes.reply_count ?? 0,
subComments: comment.relationships.replies?.data
?.map(y => resp.included?.find(z => z.id == y.id))
?.map(y => this.parseComment(y, resp))
?.filter(z => z != null) ?? []
});
}
}
class PatreonComment extends Comment {
constructor(obj) {
super(obj);
if (obj.subComments)
this.subComments = obj.subComments;
else
this.subComments = [];
}
getReplies() {
return new CommentPager(this.subComments, false);
}
}
source.getUserSubscriptions = function () {
const homePageResp = http.GET(URL_USER + "?include=active_memberships.campaign", {}, true);
if (!homePageResp.isOk)
throw new ScriptException("Failed to get subscriptions");
const response = JSON.parse(homePageResp.body)
return response.data.relationships.active_memberships.data.map((membership) => {
const channel_id = response.included.find((extra) => extra.id === membership.id).relationships.campaign.data.id
const channel_url = response.included.find((extra) => extra.id === channel_id).attributes.url
return channel_url
})
}
function getPosts(campaign, context, nextPage) {
const dataResp = http.GET((!nextPage) ? BASE_URL_API + "/posts" +
"?filter[campaign_id]=" + campaign +
"&include=images" +
"&filter[contains_exclusive_posts]=true" +
"&sort=-published_at" : nextPage, {}, true);
if (!dataResp.isOk)
throw new ScriptException("Failed to get posts");
const data = JSON.parse(dataResp.body);
if (IS_TESTING)
console.log("getPosts data:", data);
const maxDescriptionLength = 500;
const contents = [];
for (let item of data.data) {
if (item?.attributes?.embed)
contents.push(new PlatformNestedMediaContent({
id: new PlatformID(config.name, item?.id, config.id),
name: item?.attributes?.title,
author: getPlatformAuthorLink(item, context),
datetime: (Date.parse(item?.attributes?.published_at) / 1000),
url: item?.attributes?.url,
contentUrl: item?.attributes?.embed?.url,
contentName: item?.attributes?.embed?.subject,
contentDescription: item?.attributes?.embed?.description,
contentProvider: item?.attributes?.embed?.provider,
contentThumbnails: new Thumbnails([
new Thumbnail(item?.attributes?.thumbnail?.large, 1)
].filter(x => x.url))
}));
else if (item?.attributes?.current_user_can_view) {
switch (item?.attributes?.post_type) {
case "text_only":
if (item?.attributes?.content) {
let description = item?.attributes?.teaser_text ?? "";
if (item.attributes.content) {
const text = domParser.parseFromString(item.attributes.content).text;
if (text.length > maxDescriptionLength)
description = text.substring(0, maxDescriptionLength) + "...";
else
description = text;
}
contents.push(new PlatformPostDetails({
id: new PlatformID(config.name, item?.id, config.id),
name: item?.attributes?.title,
author: getPlatformAuthorLink(item, context),
datetime: (Date.parse(item?.attributes?.published_at) / 1000),
url: item?.attributes?.url,
rating: new RatingLikes(item?.attributes?.like_count ?? 0),
description: description,
textType: Type.Text.HTML,
content: item.attributes.content,
images: [],
thumbnails: [],
}));
}
break;
case "image_file":
if (item?.attributes?.post_metadata && item.attributes.post_metadata.image_order) {
const images = item.attributes.post_metadata.image_order
.map(x => data.included?.find(y => y.id == x))
.filter(x => x && x.attributes.image_urls);
let description = item?.attributes?.teaser_text ?? "";
if (item.attributes.content) {
const text = domParser.parseFromString(item.attributes.content).text;
if (text.length > maxDescriptionLength)
description = text.substring(0, maxDescriptionLength) + "...";
else
description = text;
}
contents.push(new PlatformPostDetails({
id: new PlatformID(config.name, item?.id, config.id),
name: item?.attributes?.title,
author: getPlatformAuthorLink(item, context),
datetime: (Date.parse(item?.attributes?.published_at) / 1000),
url: item?.attributes?.url,
rating: new RatingLikes(item?.attributes?.like_count),
description: description,
textType: Type.Text.HTML,
content: item.attributes.content,
images: images.map(x => x.attributes.image_urls.original),
thumbnails: images.map(x => (x.attributes.image_urls.thumbnail) ? new Thumbnails([
new Thumbnail(x.attributes.image_urls.thumbnail, 1)
]) : null)
}));
}
break;
case "video_external_file":
if (item?.attributes?.post_file)
contents.push(new PlatformVideoDetails({
id: new PlatformID(config.name, item?.id, config.id),
name: item?.attributes?.title,
author: getPlatformAuthorLink(item, context),
datetime: (Date.parse(item?.attributes?.published_at) / 1000),
url: item?.attributes?.url,
duration: item?.attributes?.post_file?.duration,
description: item?.attributes?.teaser_text,
rating: new RatingLikes(item?.attributes?.like_count),
thumbnails: new Thumbnails([
new Thumbnail(item?.attributes?.thumbnail?.url, 1)
]),
video: new VideoSourceDescriptor([
new HLSSource({
name: "Original",
duration: item?.attributes?.post_file?.duration,
url: item?.attributes?.post_file?.url
})
])
}));
break;
case "audio_file":
if (item?.attributes?.post_file)
contents.push(new PlatformVideoDetails({
id: new PlatformID(config.name, item?.id, config.id),
name: item?.attributes?.title,
author: getPlatformAuthorLink(item, context),
datetime: (Date.parse(item?.attributes?.published_at) / 1000),
url: item?.attributes?.url,
duration: item?.attributes?.post_file?.duration,
description: item?.attributes?.teaser_text,
rating: new RatingLikes(item?.attributes?.like_count),
thumbnails: new Thumbnails([
new Thumbnail(item?.attributes?.thumbnail?.url, 1)
]),
video: new UnMuxVideoSourceDescriptor([], [
new AudioUrlSource({
name: "Audio",
url: item?.attributes?.post_file?.url,
duration: item?.attributes?.post_file?.duration
})
])
}));
break;
}
}
else {
if (!_settings?.hideUnpaidContent) {
contents.push(new PlatformLockedContent({
id: new PlatformID(config.name, item?.id, config.id),
name: item?.attributes?.title,
author: getPlatformAuthorLink(item, context),
datetime: (Date.parse(item?.attributes?.published_at) / 1000),
url: item?.attributes?.url,
contentName: item?.attributes?.embed?.subject,
contentThumbnails: new Thumbnails([
new Thumbnail(item?.attributes?.thumbnail?.large ?? item?.attributes?.image?.thumb_url, 1)
].filter(x => x.url)),
lockDescription: "Exclusive for members",
unlockUrl: item?.attributes?.url,
}));
}
}
}
return {
results: contents.filter(x => x != null),
nextPage: data?.links?.next
};
}
function getPlatformAuthorLink(item, context) {
return new PlatformAuthorLink(new PlatformID(config.name, item?.relationships?.campaign?.data?.id, config.id, PLATFORM_CLAIMTYPE),
context?.name,
context?.url,
context?.thumbnail,
context?.subscribers ?? 0)
}
function searchChannels(query, page) {
const dataResp = http.GET(URL_SEARCH_CREATORS +
"?q=" + query +
"&page[number]=" + page +
"&json-api-version=1.0&includes=[]", {}, false);
if (!dataResp.isOk)
throw new ScriptException("Failed to search creators");
const data = JSON.parse(dataResp.body);
const channels = [];
for (let item of data.data) {
const id = item.id;
if (id.startsWith("campaign_"))
channels.push(new PlatformAuthorLink(new PlatformID(config.name, id.substring("campaign_".length), config.id, PLATFORM_CLAIMTYPE),
item.attributes.name,
item.attributes.url,
item.attributes.avatar_photo_url,
item.attributes.patron_count));
}
return channels.filter(x => x != null);
}
console.log("LOADED");