-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatreonScript.js
More file actions
901 lines (774 loc) · 30.2 KB
/
PatreonScript.js
File metadata and controls
901 lines (774 loc) · 30.2 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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
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 URL_LAUNCHER_CARDS = BASE_URL_API + "/launcher/cards";
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_PROFILE_CREATORS_URL = /https:\/\/(?:www\.)?patreon.com\/profile\/creators\?u=(\d+)/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
// Common request modifier for all Patreon requests
let PATREON_REQUEST_MODIFIER = {
headers: {
"Referer": "https://www.patreon.com/",
"Origin": "https://www.patreon.com"
}
};
var config = {};
var _settings = {};
let _channelCache = {};
//Source Methods
source.enable = function (conf, settings, savedState) {
config = conf ?? {};
_settings = settings ?? {};
PATREON_REQUEST_MODIFIER.headers["User-Agent"] = config.authentication.userAgent;
}
source.getHome = function () {
if (!bridge.isLoggedIn()) {
return new ContentPager([], false);
}
const baseResp = http.GET(BASE_URL, PATREON_REQUEST_MODIFIER.headers, false);
if (!baseResp.isOk)
{
throwIfCaptcha(baseResp);
throw new ScriptException("Failed to get channel");
}
return new HomePager();
};
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.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;
}
}
//Home Pager
class HomePager extends ContentPager {
constructor() {
const initialData = getHomeContent();
super(initialData.results, initialData.hasMore);
this.nextPageUrl = initialData.nextPageUrl;
}
nextPage() {
if (!this.nextPageUrl) {
this.hasMore = false;
return this;
}
const newData = getHomeContent(this.nextPageUrl);
this.results = newData.results;
this.hasMore = newData.hasMore;
this.nextPageUrl = newData.nextPageUrl;
return this;
}
}
//Channel
source.isChannelUrl = function (url) {
return REGEX_CHANNEL_URL.test(url);
};
// Function to get channel information from vanity URL
function getChannelFromVanityUrl(url, htmlContent) {
// First, try to extract campaign ID from HTML content
let campaignId = null;
if (htmlContent) {
// Look for campaign ID in various places in the HTML
const campaignIdPatterns = [
/campaign\/(\d+)/g,
/p\/campaign\/(\d+)/g,
/campaign_id['":\s]*(\d+)/g,
/"id":\s*"?(\d+)"?[,}]/g
];
for (const pattern of campaignIdPatterns) {
let match;
while ((match = pattern.exec(htmlContent)) !== null) {
// Look for IDs that are likely campaign IDs (8+ digits)
if (match[1] && match[1].length >= 7) {
campaignId = match[1];
break;
}
}
if (campaignId) break;
}
}
if (campaignId) {
// Try to get campaign data via campaigns API
const apiUrl = BASE_URL_API + "/campaigns/" + campaignId + "?include=creator";
const apiResp = http.GET(apiUrl, PATREON_REQUEST_MODIFIER.headers, true);
if (apiResp.isOk) {
const apiData = JSON.parse(apiResp.body);
if (apiData.data && apiData.data.attributes) {
// Convert API response to expected format
const channel = {
campaign: {
data: {
id: apiData.data.id,
attributes: {
name: apiData.data.attributes.name,
description: apiData.data.attributes.description || apiData.data.attributes.summary,
url: apiData.data.attributes.url,
patron_count: apiData.data.attributes.patron_count,
avatar_photo_url: apiData.data.attributes.avatar_photo_url,
image_url: apiData.data.attributes.image_url || apiData.data.attributes.cover_photo_url
}
}
}
};
const platformChannel = campaignToPlatformChannel(channel);
_channelCache[url] = platformChannel;
return platformChannel;
}
}
}
throw new ScriptException("Failed to get channel from HTML content. Campaign ID not found or API call failed.");
}
// Function to get channel information from user ID (for profile/creators URLs)
function getChannelFromUserId(userId, originalUrl) {
// First, try to get user information from the API
const userApiUrl = BASE_URL_API + "/user/" + userId + "?include=campaign";
const userResp = http.GET(userApiUrl, {}, true);
if (userResp.isOk) {
const userData = JSON.parse(userResp.body);
// Check if user has a campaign (is a creator) via relationships
if (userData.data && userData.data.relationships && userData.data.relationships.campaign) {
const campaignId = userData.data.relationships.campaign.data.id;
const campaign = userData.included?.find(item => item.type === 'campaign' && item.id === campaignId);
if (campaign) {
const channel = campaignToPlatformChannel({ campaign: { data: campaign }});
_channelCache[originalUrl] = channel;
return channel;
}
}
// If we have user data, create a basic channel from the user information
if (userData.data && userData.data.attributes) {
const userAttrs = userData.data.attributes;
// Create a minimal channel object from user data
const basicChannel = {
campaign: {
data: {
id: userId, // Use user ID as campaign ID
attributes: {
name: userAttrs.full_name || userAttrs.vanity || "Unknown Creator",
description: userAttrs.about || "",
url: userAttrs.url || (BASE_URL + "/" + userAttrs.vanity),
patron_count: 0, // We don't have this info
avatar_photo_url: userAttrs.image_url || userAttrs.thumb_url,
image_url: userAttrs.image_url || userAttrs.thumb_url
}
}
}
};
const channel = campaignToPlatformChannel(basicChannel);
_channelCache[originalUrl] = channel;
return channel;
}
}
throw new ScriptException("Failed to get channel from user ID: " + userId);
}
source.getChannel = function (url) {
// Check if this is a profile/creators URL and handle it specially
const profileMatch = REGEX_PROFILE_CREATORS_URL.exec(url);
if (profileMatch && profileMatch.length === 2) {
const userId = profileMatch[1];
return getChannelFromUserId(userId, url);
}
const channelResp = http.GET(url, PATREON_REQUEST_MODIFIER.headers, false);
if (!channelResp.isOk)
{
throwIfCaptcha(channelResp);
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 {
// Try API approach
return getChannelFromVanityUrl(url, channelResp.body);
}
}
}
else
channel = JSON.parse(channelJson[1]);
_channelCache[url] = campaignToPlatformChannel(channel);
return _channelCache[url];
};
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: BASE_URL + "/{{CLAIMVALUE}}"
}
};
};
//Video
source.isContentDetailsUrl = function (url) {
return REGEX_URL_ID.test(url);
};
source.getContentDetails = function (url) {
const postId = getPostIdFromUrl(url);
const postRes = http.GET(`https://www.patreon.com/api/posts/${postId}`, PATREON_REQUEST_MODIFIER.headers, true);
if (postRes.isOk) {
const postBody = JSON.parse(postRes.body);
const campaign = postBody.included.find(a => a.type == 'campaign');
const channel = campaignToPlatformChannel({ campaign: { data : campaign }});
return parseSinglePost(postBody.data, postBody, channel, true);
}
throw new ScriptException("Failed to get post details");
};
//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)
log("CommentPager resp:", resp);
const nextUrl = resp?.links?.next;
super([], !!nextUrl);
this.contextUrl = url;
this.results = this.parseResponse(resp);
this.nextPageUrl = nextUrl;
this.hasMore = !!nextUrl;
}
nextPage() {
const resp = http.GET(this.nextPageUrl, {}, true);
if (!resp.isOk)
throw new ScriptException("Failed to get next comment page [" + resp.code + "]")
const responseBody = JSON.parse(resp.body);
this.results = this.parseResponse(responseBody);
this.nextPageUrl = responseBody?.links?.next;
this.hasMore = !!this.nextPageUrl;
return this;
}
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.name, 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, PATREON_REQUEST_MODIFIER.headers, true);
if (!dataResp.isOk)
{
log("Failed to get posts [" + dataResp.code + "]");
throwIfCaptcha(dataResp);
return {
results: [],
nextPage: null,
hasMore: false
}
}
const data = JSON.parse(dataResp.body);
if (IS_TESTING)
console.log("getPosts data:", data);
// Map all posts to Platform content using the reusable mapping functions
const contents = data?.data
?.map(post => mapPostToPlatformContent(post, context, data))
?.filter(content => content != null) ?? [];
return {
results: contents,
nextPage: data?.links?.next
};
}
function campaignToPlatformChannel(channel) {
return 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 ?? channel?.campaign?.data?.attributes?.summary,
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 ?? channel?.campaign?.data?.attributes?.cwh_cover_image_urls?.large,
thumbnail: channel?.campaign?.data?.attributes?.avatar_photo_url ?? channel?.campaign?.data?.attributes?.avatar_photo_image_urls?.thumbnail
})
}
function parseSinglePost(item, data, context, isDetails=false) {
if (!item) return null;
if (isDetails) {
// Throw unsupported error for PlatformNestedMediaContent or PlatformPostDetails
if (item?.attributes?.embed ||
item?.attributes?.post_type == 'text_only' ||
item?.attributes?.post_type == 'image_file') {
throw new UnavailableException("Unsupported content type while deep linking. Consider opening it from inside the channel.");
}
}
return mapPostToPlatformContent(item, context, data);
}
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);
}
function getPostIdFromUrl(url) {
const match = url.match(/\/posts\/(?:[\w-]+-)?(\d+)/);
return match ? match[1] : null;
}
// Function to get home content from launcher/cards API
function getHomeContent(url) {
const requestUrl = url || (URL_LAUNCHER_CARDS +
"?include=campaign.creator.null,campaign.null,campaign.rewards.null,campaign.current_user_pledge.null," +
"latest_posts,latest_posts.audio.null,latest_posts.recent_comments.parent,latest_posts.recent_comments.on_behalf_of_campaign.null," +
"latest_posts.recent_comments.commenter.campaign.null,latest_posts.recent_comments.commenter_identity," +
"latest_posts.recent_comments.commenter_identity.primary_avatar,latest_posts.recent_comments.first_reply.commenter_identity," +
"latest_posts.recent_comments.first_reply.commenter_identity.primary_avatar,latest_posts.recent_comments.first_reply.commenter.campaign.null," +
"latest_posts.recent_comments.first_reply.parent,latest_posts.recent_comments.first_reply.post," +
"latest_posts.recent_comments.first_reply.on_behalf_of_campaign.null,latest_posts.images.null,latest_posts.poll.null," +
"latest_posts.poll.choices,latest_posts.poll.current_user_responses.user.null,latest_posts.poll.current_user_responses.choice," +
"latest_posts.access_rules,latest_posts.access_rules.tier,latest_posts.drop,latest_posts.livestream,latest_posts.shows," +
"latest_posts.content_unlock_options,latest_posts.content_unlock_options.product_variant.null," +
"latest_posts.content_unlock_options.product_variant.collection.null,latest_posts.content_unlock_options.reward.null," +
"latest_highlights,latest_product_variant,latest_product_variant.content_media,latest_product_variant.preview_media," +
"upcoming_drops.null,upcoming_drops.post.null,upcoming_drops.post.drop.null,upcoming_drops.post.livestream,upcoming_drops.post.audio.null%5E" +
"&fields%5Bcampaign%5D=id,avatar_photo_image_urls,name,url,vanity,cover_photo_url_sizes,creation_count,currency," +
"current_user_is_free_member,main_video_embed,main_video_url,offers_paid_membership,one_liner,pay_per_name,post_count," +
"pledge_url,primary_theme_color,summary,is_monthly%5E" +
"&fields%5Bcomment%5D=body,created,deleted_at,is_by_patron,is_by_creator,is_liked_by_creator,vote_sum,current_user_vote,reply_count,visibility_state" +
"&fields%5Bcontent-unlock-option%5D=content_unlock_type,reward_benefit_categories" +
"&fields%5Bdisplay-identity%5D=name,link_url" +
"&fields%5Bpost%5D=id,attachments_media,change_visibility_at,comment_count,content,content_teaser_text,current_user_can_comment," +
"current_user_can_report,current_user_can_view,current_user_has_liked,created_at,current_user_comment_disallowed_reason," +
"embed,is_new_to_current_user,image,images,is_paid,like_count,likes,patreon_url,pledge_url,post_file,post_type," +
"post_metadata,preview_asset_type,published_at,teaser_text,thumbnail,title,upgrade_url,url,was_posted_by_campaign_owner,video_preview" +
"&fields%5Bproduct-variant%5D=name,id,price_cents,published_at_datetime,url,access_metadata,content_type,checkout_url" +
"&fields%5Bdrop%5D=created_at,expires_at,scheduled_for,cover_image,cover_image.url,is_droppable,comments_cid,presence_cid,presence_count" +
"&fields%5Bmedia%5D=id,image_urls,display,download_url,metadata,file_name,state" +
"&fields%5Blivestream%5D=state,display" +
"&filter%5Bshow_shop_posts%5D=false" +
"&json-api-version=1.0" +
"&json-api-use-default-includes=false" +
"&page%5Bcount%5D=10");
const response = http.GET(requestUrl, {}, true);
if (!response.isOk) {
console.log("Failed to get home content: " + response.code);
return { results: [], hasMore: false, nextPageUrl: null };
}
const data = JSON.parse(response.body);
const contents = [];
// Build lookup maps for efficient access
const includedMap = createIncludedLookupMap(data.included);
// Extract campaigns and their posts
if (data.data) {
for (const card of data.data) {
if (card.type === "launcher-card" && card.attributes?.card_type === "campaign") {
// Get campaign from included data
const campaignId = card.relationships?.campaign?.data?.id;
const campaign = includedMap.get(`campaign:${campaignId}`);
if (campaign) {
// Create campaign context for posts
const campaignContext = {
name: campaign.attributes?.name,
url: campaign.attributes?.url,
thumbnail: campaign.attributes?.avatar_photo_image_urls?.thumbnail,
subscribers: campaign.attributes?.patron_count || 0
};
// Get latest posts for this campaign
const postIds = card.relationships?.latest_posts?.data || [];
for (const postRef of postIds) {
const post = includedMap.get(`post:${postRef.id}`);
if (post && post.attributes?.current_user_can_view) {
// Process post based on type
const content = processPost(post, includedMap, campaignContext);
if (content) {
contents.push(content);
}
}
}
}
}
}
}
return {
results: contents,
hasMore: !!data.links?.next,
nextPageUrl: data.links?.next || null
};
}
// Unified post processing function
function processPost(post, includedMap, context) {
return mapPostToPlatformContent(post, context, includedMap);
}
// Helper to create author from post and context
function createAuthor(post, context) {
return new PlatformAuthorLink(
new PlatformID(config.name, post.relationships?.campaign?.data?.id, config.id, PLATFORM_CLAIMTYPE),
context.name,
context.url,
context.thumbnail,
context.subscribers || 0
);
}
// ===== REUSABLE MAPPING FUNCTIONS =====
// Maps a Patreon post to the appropriate Platform content class
function mapPostToPlatformContent(post, context, includedLookup) {
const attrs = post?.attributes;
if (!attrs) return null;
// Handle locked content
if (!attrs.current_user_can_view) {
return mapToLockedContent(post, context);
}
// Handle embedded content first
if (attrs.embed?.url) {
return mapToNestedMediaContent(post, context);
}
// Handle different post types
switch (attrs.post_type) {
case "video_external_file":
case "podcast":
return mapToVideoContent(post, context);
case "audio_file":
return mapToAudioContent(post, context);
case "text_only":
return mapToTextContent(post, context);
case "image_file":
return mapToImageContent(post, context, includedLookup);
default:
return null;
}
}
// Maps post to PlatformVideoDetails for video content
function mapToVideoContent(post, context) {
const attrs = post?.attributes;
if (!attrs?.post_file?.url) return null;
return new PlatformVideoDetails({
id: new PlatformID(config.name, post.id, config.id),
name: attrs.title,
author: createAuthor(post, context),
datetime: attrs.published_at ? (Date.parse(attrs.published_at) / 1000) : 0,
url: attrs.url || (BASE_URL + "/posts/" + post.id),
duration: attrs.post_file.duration || 0,
description: attrs.content || attrs.teaser_text || "",
rating: new RatingLikes(attrs.like_count || 0),
thumbnails: new Thumbnails([
new Thumbnail(attrs.thumbnail?.url || attrs.image?.thumb_url, 1)
].filter(t => t.url)),
video: createVideoDescriptor(attrs.post_file)
});
}
// Maps post to PlatformVideoDetails for audio content
function mapToAudioContent(post, context) {
const attrs = post?.attributes;
if (!attrs?.post_file?.url) return null;
return new PlatformVideoDetails({
id: new PlatformID(config.name, post.id, config.id),
name: attrs.title,
author: createAuthor(post, context),
datetime: attrs.published_at ? (Date.parse(attrs.published_at) / 1000) : 0,
url: attrs.url || (BASE_URL + "/posts/" + post.id),
duration: attrs.post_file.duration || 0,
description: attrs.content || attrs.teaser_text || "",
rating: new RatingLikes(attrs.like_count || 0),
thumbnails: new Thumbnails([
new Thumbnail(attrs.thumbnail?.url, 1)
].filter(t => t.url)),
video: new UnMuxVideoSourceDescriptor([], [
new AudioUrlSource({
name: "Audio",
url: attrs.post_file.url,
duration: attrs.post_file.duration,
requestModifier: PATREON_REQUEST_MODIFIER
})
])
});
}
// Maps post to PlatformPostDetails for text content
function mapToTextContent(post, context) {
const attrs = post?.attributes;
if (!attrs?.title && !attrs?.content) return null;
const maxDescriptionLength = 500;
let description = attrs.teaser_text || "";
if (attrs.content) {
const text = domParser.parseFromString(attrs.content).text;
description = text.length > maxDescriptionLength
? text.substring(0, maxDescriptionLength) + "..."
: text;
}
return new PlatformPostDetails({
id: new PlatformID(config.name, post.id, config.id),
name: attrs.title || "Text Post",
author: createAuthor(post, context),
datetime: attrs.published_at ? (Date.parse(attrs.published_at) / 1000) : 0,
url: attrs.url || (BASE_URL + "/posts/" + post.id),
rating: new RatingLikes(attrs.like_count || 0),
description: description,
textType: Type.Text.HTML,
content: attrs.content || attrs.teaser_text || "",
images: [],
thumbnails: []
});
}
// Maps post to PlatformPostDetails for image content
function mapToImageContent(post, context, includedLookup) {
const attrs = post?.attributes;
if (!attrs?.post_metadata?.image_order) return null;
// Use provided lookup or search in included data
const images = attrs.post_metadata.image_order
.map(id => {
if (includedLookup instanceof Map) {
return includedLookup.get(`media:${id}`);
} else if (includedLookup?.included) {
return includedLookup.included.find(item => item.id === id);
}
return null;
})
.filter(item => item && item.attributes?.image_urls);
if (images.length === 0) return null;
const maxDescriptionLength = 500;
let description = attrs.teaser_text || "";
if (attrs.content) {
const text = domParser.parseFromString(attrs.content).text;
description = text.length > maxDescriptionLength
? text.substring(0, maxDescriptionLength) + "..."
: text;
}
return new PlatformPostDetails({
id: new PlatformID(config.name, post.id, config.id),
name: attrs.title || "Image Post",
author: createAuthor(post, context),
datetime: attrs.published_at ? (Date.parse(attrs.published_at) / 1000) : 0,
url: attrs.url || (BASE_URL + "/posts/" + post.id),
rating: new RatingLikes(attrs.like_count || 0),
description: description,
textType: Type.Text.HTML,
content: attrs.content || "",
images: images.map(img => img.attributes.image_urls.original),
thumbnails: images.map(img => img.attributes.image_urls.thumbnail
? new Thumbnails([new Thumbnail(img.attributes.image_urls.thumbnail, 1)])
: null)
});
}
// Maps post to PlatformNestedMediaContent for embedded content
function mapToNestedMediaContent(post, context) {
const attrs = post?.attributes;
if (!attrs?.embed?.url) return null;
return new PlatformNestedMediaContent({
id: new PlatformID(config.name, post.id, config.id),
name: attrs.title,
author: createAuthor(post, context),
datetime: attrs.published_at ? (Date.parse(attrs.published_at) / 1000) : 0,
url: attrs.url || (BASE_URL + "/posts/" + post.id),
contentUrl: attrs.embed.url,
contentName: attrs.embed.subject,
contentDescription: attrs.embed.description,
contentProvider: attrs.embed.provider,
contentThumbnails: new Thumbnails([
new Thumbnail(attrs.thumbnail?.large, 1)
].filter(x => x.url))
});
}
// Maps post to PlatformLockedContent for locked content
function mapToLockedContent(post, context) {
const attrs = post?.attributes;
if (_settings?.hideUnpaidContent) return null;
return new PlatformLockedContent({
id: new PlatformID(config.name, post.id, config.id),
name: attrs.title,
author: createAuthor(post, context),
datetime: attrs.published_at ? (Date.parse(attrs.published_at) / 1000) : 0,
url: attrs.url || (BASE_URL + "/posts/" + post.id),
contentName: attrs.embed?.subject,
contentThumbnails: new Thumbnails([
new Thumbnail(attrs.thumbnail?.large || attrs.image?.thumb_url, 1)
].filter(x => x.url)),
lockDescription: "Exclusive for members",
unlockUrl: attrs.url || (BASE_URL + "/posts/" + post.id),
});
}
// Creates appropriate video descriptor based on file type
function createVideoDescriptor(postFile) {
if (!postFile?.url) return null;
if (postFile.url.includes('.m3u8')) {
return new VideoSourceDescriptor([
new HLSSource({
name: "Original",
duration: postFile.duration,
url: postFile.url,
requestModifier: PATREON_REQUEST_MODIFIER
})
]);
} else {
return new VideoSourceDescriptor([
new VideoUrlSource({
name: "Original",
url: postFile.url,
duration: postFile.duration,
requestModifier: PATREON_REQUEST_MODIFIER
})
]);
}
}
// Creates a Map for efficient lookup of included data
function createIncludedLookupMap(includedData) {
const map = new Map();
if (includedData) {
for (const item of includedData) {
const key = `${item.type}:${item.id}`;
map.set(key, item);
}
}
return map;
}
function throwIfCaptcha(resp) {
if (resp != null && resp.body != null && resp.code == 403) {
const body = resp.body.toLowerCase();
// Check for Cloudflare captcha
if (body.includes('/cdn-cgi/challenge-platform')) {
throw new CaptchaRequiredException(resp.url, resp.body);
}
}
return true;
}
log("LOADED");