-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviewserver.ts
More file actions
1312 lines (1185 loc) · 44.6 KB
/
viewserver.ts
File metadata and controls
1312 lines (1185 loc) · 44.6 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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ky from "npm:ky";
import { isGeneratorView } from "./indexserver/types/app/bsky/feed/defs.ts";
import * as ViewServerTypes from "./utils/viewservertypes.ts";
import * as ATPAPI from "npm:@atproto/api";
import {
searchParamsToJson,
resolveIdentity,
buildBlobUrl,
cachedFetch,
didWebToHttps,
getSlingshotRecord,
withCors,
} from "./utils/server.ts";
import QuickLRU from "npm:quick-lru";
import { validateRecord } from "./utils/records.ts";
import { indexHandlerContext } from "./index/types.ts";
import { Database } from "jsr:@db/sqlite@0.11";
import { JetstreamManager, SpacedustManager } from "./utils/sharders.ts";
import { SpacedustLinkMessage } from "./index/spacedust.ts";
import { setupUserDb } from "./utils/dbuser.ts";
import { config } from "./config.ts";
import { AtUri } from "npm:@atproto/api";
import { CID } from "../../Library/Caches/deno/npm/registry.npmjs.org/multiformats/9.9.0/cjs/src/cid.js";
import { uncid } from "./indexserver.ts";
import { getAuthenticatedDid } from "./utils/auth.ts";
const temporarydevelopmentblockednotiftypes: ATPAPI.AppBskyNotificationListNotifications.Notification["reason"][] = [
//'like',
//'repost',
//'follow',
//'mention',
//'reply',
//'quote',
//'starterpack-joined',
//'liked-via-repost',
//'repost-via-repost',
];
export interface ViewServerConfig {
baseDbPath: string;
systemDbPath: string;
}
interface BaseRow {
uri: string;
did: string;
cid: string | null;
rev: string | null;
createdat: number | null;
indexedAt: number;
json: string | null;
}
interface GeneratorRow extends BaseRow {
displayname: string | null;
description: string | null;
avatarcid: string | null;
}
interface LikeRow extends BaseRow {
subject: string;
}
interface RepostRow extends BaseRow {
subject: string;
}
interface BacklinkRow {
srcuri: string;
srcdid: string;
}
const FEED_LIMIT = 50;
export class ViewServer {
private config: ViewServerConfig;
public userManager: ViewServerUserManager;
public systemDB: Database;
constructor(config: ViewServerConfig) {
this.config = config;
// We will initialize the system DB and user manager here
this.systemDB = new Database(this.config.systemDbPath);
// TODO: We need to setup the system DB schema if it's new
this.userManager = new ViewServerUserManager(this); // Pass the server instance
}
public start() {
// This is where we'll kick things off, like the cold start
this.userManager.coldStart(this.systemDB);
console.log("viewServer started.");
}
async unspeccedGetRegisteredUsers(): Promise<{
did: string;
role: string;
registrationdate: string;
onboardingstatus: string;
pfp?: string;
displayname: string;
handle: string;
}[]|undefined> {
const stmt = this.systemDB.prepare(`
SELECT *
FROM users;
`);
const result = stmt.all() as
{
did: string;
role: string;
registrationdate: string;
onboardingstatus: string;
}[];
const hydrated = await Promise.all( result.map(async (user)=>{
const identity = await resolveIdentity(user.did);
const profile = (await getSlingshotRecord(identity.did,"app.bsky.actor.profile","self")).value as ATPAPI.AppBskyActorProfile.Record;
const avatarcid = uncid(profile.avatar?.ref);
const avatar = avatarcid
? buildBlobUrl(identity.pds, identity.did, avatarcid)
: undefined;
return {...user,handle: identity.handle,pfp: avatar, displayname:profile.displayName ?? identity.handle }
}))
//const exists = result !== undefined;
return hydrated;
}
async viewServerHandler(req: Request): Promise<Response> {
const url = new URL(req.url);
const pathname = url.pathname;
const bskyUrl = `https://api.bsky.app${pathname}${url.search}`;
const hasAuth = req.headers.has("authorization");
const xrpcMethod = pathname.startsWith("/xrpc/")
? pathname.slice("/xrpc/".length)
: null;
const searchParams = searchParamsToJson(url.searchParams);
const jsonUntyped = searchParams;
let tempauthdid: string | undefined = undefined;
try {
tempauthdid = (await getAuthenticatedDid(req)) ?? undefined;
} catch (_e) {
// nothing lol
}
const authdid = tempauthdid
? this.handlesDid(tempauthdid)
? tempauthdid
: undefined
: undefined;
console.log("authed:", authdid);
if (xrpcMethod === "app.bsky.unspecced.getTrendingTopics") {
// const jsonTyped =
// jsonUntyped as ViewServerTypes.AppBskyUnspeccedGetTrendingTopics.QueryParams;
const faketopics: ATPAPI.AppBskyUnspeccedDefs.TrendingTopic[] = [
{
$type: "app.bsky.unspecced.defs#trendingTopic",
topic: "Git Repo",
displayName: "Git Repo",
description: "Git Repo",
link: "https://tangled.sh/@whey.party/skylite",
},
{
$type: "app.bsky.unspecced.defs#trendingTopic",
topic: "this View Server url",
displayName: "this View Server url",
description: "this View Server url",
link: config.viewServer.host,
},
{
$type: "app.bsky.unspecced.defs#trendingTopic",
topic: "this social-app fork url",
displayName: "this social-app fork url",
description: "this social-app fork url",
link: "https://github.com/rimar1337/social-app/tree/publicappview-colorable",
},
{
$type: "app.bsky.unspecced.defs#trendingTopic",
topic: "whey dot party",
displayName: "whey dot party",
description: "whey dot party",
link: "https://whey.party/",
},
];
const response: ViewServerTypes.AppBskyUnspeccedGetTrendingTopics.OutputSchema =
{
topics: faketopics,
suggested: faketopics,
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
//if (xrpcMethod !== 'app.bsky.actor.getPreferences' && xrpcMethod !== 'app.bsky.notification.listNotifications') {
if (
!hasAuth
// (!hasAuth ||
// xrpcMethod === "app.bsky.labeler.getServices" ||
// xrpcMethod === "app.bsky.unspecced.getConfig") &&
// xrpcMethod !== "app.bsky.notification.putPreferences"
) {
return new Response(
JSON.stringify({
error: "XRPCNotSupported",
message:
"(no auth) HEY hello there my name is whey dot party and you have used my custom appview that is very cool but have you considered that XRPC Not Supported",
}),
{
status: 404,
headers: withCors({ "Content-Type": "application/json" }),
}
);
//return await sendItToApiBskyApp(req);
}
if (
// !hasAuth ||
xrpcMethod === "app.bsky.labeler.getServices" ||
xrpcMethod === "app.bsky.unspecced.getConfig" //&&
//xrpcMethod !== "app.bsky.notification.putPreferences"
) {
return new Response(
JSON.stringify({
error: "XRPCNotSupported",
message:
"(getservices / getconfig) HEY hello there my name is whey dot party and you have used my custom appview that is very cool but have you considered that XRPC Not Supported",
}),
{
status: 404,
headers: withCors({ "Content-Type": "application/json" }),
}
);
//return await sendItToApiBskyApp(req);
}
const authDID = "did:plc:mn45tewwnse5btfftvd3powc"; //getAuthenticatedDid(req);
switch (xrpcMethod) {
case "app.bsky.feed.getFeedGenerators": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyFeedGetFeedGenerators.QueryParams;
const feeds: ATPAPI.AppBskyFeedDefs.GeneratorView[] = (
await Promise.all(
jsonTyped.feeds.map(async (feed) => {
try {
const did = new ATPAPI.AtUri(feed).hostname;
const rkey = new ATPAPI.AtUri(feed).rkey;
const identity = await resolveIdentity(did);
const feedgetRecord = await getSlingshotRecord(
identity.did,
"app.bsky.feed.generator",
rkey
);
const profile = (
await getSlingshotRecord(
identity.did,
"app.bsky.actor.profile",
"self"
)
).value as ATPAPI.AppBskyActorProfile.Record;
const anyprofile = profile as any;
const value =
feedgetRecord.value as ATPAPI.AppBskyFeedGenerator.Record;
return {
$type: "app.bsky.feed.defs#generatorView",
uri: feed,
cid: feedgetRecord.cid,
did: identity.did,
creator: /*AppBskyActorDefs.ProfileView*/ {
$type: "app.bsky.actor.defs#profileView",
did: identity.did,
handle: identity.handle,
displayName: profile.displayName,
description: profile.description,
avatar: buildBlobUrl(
identity.pds,
identity.did,
anyprofile.avatar.ref["$link"]
),
//associated?: ProfileAssociated
//indexedAt?: string
//createdAt?: string
//viewer?: ViewerState
//labels?: ComAtprotoLabelDefs.Label[]
//verification?: VerificationState
//status?: StatusView
},
displayName: value.displayName,
description: value.description,
//descriptionFacets?: AppBskyRichtextFacet.Main[]
avatar: buildBlobUrl(
identity.pds,
identity.did,
(value as any).avatar.ref["$link"]
),
//likeCount?: number
//acceptsInteractions?: boolean
//labels?: ComAtprotoLabelDefs.Label[]
//viewer?: GeneratorViewerState
contentMode: value.contentMode,
indexedAt: new Date().toISOString(),
};
} catch (err) {
return undefined;
}
})
)
).filter(isGeneratorView);
const response: ViewServerTypes.AppBskyFeedGetFeedGenerators.OutputSchema =
{
feeds: feeds ? feeds : [],
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.feed.getFeed": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyFeedGetFeed.QueryParams;
const cursor = jsonTyped.cursor;
const feed = jsonTyped.feed;
const limit = jsonTyped.limit;
const proxyauth = req.headers.get("authorization") || "";
const did = new ATPAPI.AtUri(feed).hostname;
const rkey = new ATPAPI.AtUri(feed).rkey;
const identity = await resolveIdentity(did);
const feedgetRecord = (
await getSlingshotRecord(
identity.did,
"app.bsky.feed.generator",
rkey
)
).value as ATPAPI.AppBskyFeedGenerator.Record;
const skeleton = (await cachedFetch(
`${didWebToHttps(
feedgetRecord.did
)}/xrpc/app.bsky.feed.getFeedSkeleton?feed=${jsonTyped.feed}${
cursor ? `&cursor=${cursor}` : ""
}${limit ? `&limit=${limit}` : ""}`,
proxyauth
)) as ATPAPI.AppBskyFeedGetFeedSkeleton.OutputSchema;
const nextcursor = skeleton.cursor;
const dbgrqstid = skeleton.reqId;
const uriarray = skeleton.feed;
// Step 1: Chunk into 25 max
const chunks = [];
for (let i = 0; i < uriarray.length; i += 25) {
chunks.push(uriarray.slice(i, i + 25));
}
// Step 2: Hydrate via getPosts
const hydratedPosts: ATPAPI.AppBskyFeedDefs.FeedViewPost[] = [];
for (const chunk of chunks) {
const searchParams = new URLSearchParams();
for (const uri of chunk.map((item) => item.post)) {
searchParams.append("uris", uri);
}
const postResp = await ky
// TODO aaaaaa dont do this please use the new getServiceEndpointFromIdentity()
.get(`https://api.bsky.app/xrpc/app.bsky.feed.getPosts`, {
// headers: {
// Authorization: proxyauth,
// },
searchParams,
})
.json<ATPAPI.AppBskyFeedGetPosts.OutputSchema>();
for (const post of postResp.posts) {
const matchingSkeleton = uriarray.find(
(item) => item.post === post.uri
);
if (matchingSkeleton) {
//post.author.handle = post.author.handle + ".percent40.api.bsky.app"; // or any logic to modify it
hydratedPosts.push({
post,
reason: matchingSkeleton.reason,
//reply: matchingSkeleton,
});
}
}
}
// Step 3: Compose final response
const response: ViewServerTypes.AppBskyFeedGetFeed.OutputSchema = {
feed: hydratedPosts,
cursor: nextcursor,
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.actor.getProfile": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyActorGetProfile.QueryParams;
const response: ViewServerTypes.AppBskyActorGetProfile.OutputSchema =
((await this.resolveGetProfiles([jsonTyped.actor])) ?? [])[0];
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.actor.getProfiles": {
const jsonhalfTyped =
jsonUntyped as ViewServerTypes.AppBskyActorGetProfiles.QueryParams;
const actors = jsonhalfTyped.actors as string[] | string
const queryactors = Array.isArray(actors)
? actors
: [actors];
//console.log("queryactors:",jsonTyped.actors)
const response: ViewServerTypes.AppBskyActorGetProfiles.OutputSchema = {
profiles: (await this.resolveGetProfiles(queryactors)) ?? [],
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.feed.getAuthorFeed": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyFeedGetAuthorFeed.QueryParams;
const userindexservice = "";
const isbskyfallback = true;
if (isbskyfallback) {
return this.sendItToApiBskyApp(req);
}
const response: ViewServerTypes.AppBskyFeedGetAuthorFeed.OutputSchema =
{};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.feed.getPostThread": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyFeedGetPostThread.QueryParams;
const userindexservice = "";
const isbskyfallback = true;
if (isbskyfallback) {
return this.sendItToApiBskyApp(req);
}
const response: ViewServerTypes.AppBskyFeedGetPostThread.OutputSchema =
{};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.unspecced.getPostThreadV2": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyUnspeccedGetPostThreadV2.QueryParams;
const userindexservice = "";
const isbskyfallback = true;
if (isbskyfallback) {
return this.sendItToApiBskyApp(req);
}
const response: ViewServerTypes.AppBskyUnspeccedGetPostThreadV2.OutputSchema =
{};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
// case "app.bsky.actor.getProfile": {
// const jsonTyped =
// jsonUntyped as ViewServerTypes.AppBskyActorGetProfile.QueryParams;
// const response: ViewServerTypes.AppBskyActorGetProfile.OutputSchema= {};
// return new Response(JSON.stringify(response), {
// headers: withCors({ "Content-Type": "application/json" }),
// });
// }
// case "app.bsky.actor.getProfiles": {
// const jsonTyped = jsonUntyped as ViewServerTypes.AppBskyActorGetProfiles.QueryParams;
// const response: ViewServerTypes.AppBskyActorGetProfiles.OutputSchema = {};
// return new Response(JSON.stringify(response), {
// headers: withCors({ "Content-Type": "application/json" }),
// });
// }
// case "whatever": {
// const jsonTyped = jsonUntyped as ViewServerTypes.AppBskyFeedGetAuthorFeed.QueryParams;
// const response: ViewServerTypes.AppBskyFeedGetAuthorFeed.OutputSchema = {}
// return new Response(JSON.stringify(response), {
// headers: withCors({ "Content-Type": "application/json" }),
// });
// }
case "app.bsky.notification.listNotifications": {
if (!authdid) return new Response("Not Found", { status: 404 });
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyNotificationListNotifications.QueryParams;
const response: ViewServerTypes.AppBskyNotificationListNotifications.OutputSchema =
await this.queryNotificationsList(authdid, jsonTyped.cursor, jsonTyped.limit);
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.feed.getPosts": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyFeedGetPosts.QueryParams;
const inputUris = Array.isArray(jsonTyped.uris)
? jsonTyped.uris
: [jsonTyped.uris];
const response: ViewServerTypes.AppBskyFeedGetPosts.OutputSchema = {
posts: await this.resolveGetPosts(inputUris),
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.unspecced.getConfig": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyUnspeccedGetConfig.QueryParams;
const response: ViewServerTypes.AppBskyUnspeccedGetConfig.OutputSchema =
{
checkEmailConfirmed: true,
liveNow: [
{
$type: "app.bsky.unspecced.getConfig#liveNowConfig",
did: "did:plc:mn45tewwnse5btfftvd3powc",
domains: ["local3768forumtest.whey.party"],
},
],
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
case "app.bsky.graph.getLists": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyGraphGetLists.QueryParams;
const response: ViewServerTypes.AppBskyGraphGetLists.OutputSchema = {
lists: [],
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
//https://shimeji.us-east.host.bsky.network/xrpc/app.bsky.unspecced.getTrendingTopics?limit=14
case "app.bsky.unspecced.getTrendingTopics": {
const jsonTyped =
jsonUntyped as ViewServerTypes.AppBskyUnspeccedGetTrendingTopics.QueryParams;
const faketopics: ATPAPI.AppBskyUnspeccedDefs.TrendingTopic[] = [
{
$type: "app.bsky.unspecced.defs#trendingTopic",
topic: "Git Repo",
displayName: "Git Repo",
description: "Git Repo",
link: "https://tangled.sh/@whey.party/skylite",
},
{
$type: "app.bsky.unspecced.defs#trendingTopic",
topic: "Red Dwarf Lite",
displayName: "Red Dwarf Lite",
description: "Red Dwarf Lite",
link: "https://reddwarf.whey.party/",
},
{
$type: "app.bsky.unspecced.defs#trendingTopic",
topic: "whey dot party",
displayName: "whey dot party",
description: "whey dot party",
link: "https://whey.party/",
},
];
const response: ViewServerTypes.AppBskyUnspeccedGetTrendingTopics.OutputSchema =
{
topics: faketopics,
suggested: faketopics,
};
return new Response(JSON.stringify(response), {
headers: withCors({ "Content-Type": "application/json" }),
});
}
default: {
return new Response(
JSON.stringify({
error: "XRPCNotSupported",
message:
"(default) HEY hello there my name is whey dot party and you have used my custom appview that is very cool but have you considered that XRPC Not Supported",
}),
{
status: 404,
headers: withCors({ "Content-Type": "application/json" }),
}
);
}
}
// return new Response("Not Found", { status: 404 });
}
async sendItToApiBskyApp(req: Request): Promise<Response> {
const url = new URL(req.url);
const pathname = url.pathname;
const searchParams = searchParamsToJson(url.searchParams);
let reqBody: undefined | string;
let jsonbody: undefined | Record<string, unknown>;
if (req.body) {
const body = await req.json();
jsonbody = body;
// console.log(
// `called at euh reqreqreqreq: ${pathname}\n\n${JSON.stringify(body)}`
// );
reqBody = JSON.stringify(body, null, 2);
}
const bskyUrl = `https://public.api.bsky.app${pathname}${url.search}`;
console.log("request", searchParams);
const proxyHeaders = new Headers(req.headers);
// Remove Authorization and set browser-like User-Agent
proxyHeaders.delete("authorization");
proxyHeaders.delete("Access-Control-Allow-Origin"),
proxyHeaders.set(
"user-agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
);
proxyHeaders.set("Access-Control-Allow-Origin", "*");
const proxyRes = await fetch(bskyUrl, {
method: req.method,
headers: proxyHeaders,
body: ["GET", "HEAD"].includes(req.method.toUpperCase())
? undefined
: reqBody,
});
const resBody = await proxyRes.text();
// console.log(
// "← Response:",
// JSON.stringify(await JSON.parse(resBody), null, 2)
// );
return new Response(resBody, {
status: proxyRes.status,
headers: proxyRes.headers,
});
}
viewServerIndexer(ctx: indexHandlerContext) {
const record = validateRecord(ctx.value);
switch (record?.$type) {
case "app.bsky.feed.like": {
return;
}
default: {
// what the hell
return;
}
}
}
/**
* please do not use this, use openDbForDid() instead
* @param did
* @returns
*/
internalCreateDbForDid(did: string): Database {
const path = `${this.config.baseDbPath}/${did}.sqlite`;
const db = new Database(path);
// TODO maybe split the user db schema between view server and index server
setupUserDb(db);
//await db.exec(/* CREATE IF NOT EXISTS statements */);
return db;
}
public handlesDid(did: string): boolean {
return this.userManager.handlesDid(did);
}
async resolveGetPosts(
uris: string[]
): Promise<ATPAPI.AppBskyFeedDefs.PostView[]> {
const grouped: Record<string, string[]> = {};
// Group URIs by resolved endpoint
for (const uri of uris) {
const did = new AtUri(uri).host;
const endpoint = await getSkyliteEndpoint(did);
if (!endpoint) continue;
if (!grouped[endpoint]) {
grouped[endpoint] = [];
}
grouped[endpoint].push(uri);
}
const postviews: ATPAPI.AppBskyFeedDefs.PostView[] = [];
// Fetch posts per endpoint
for (const [endpoint, urisForEndpoint] of Object.entries(grouped)) {
const query = urisForEndpoint
.map((u) => `uris=${encodeURIComponent(u)}`)
.join("&");
const url = `${endpoint}/xrpc/app.bsky.feed.getPosts?${query}`;
const resp = await fetch(url);
if (!resp.ok) {
throw new Error(
`Failed to fetch posts from ${endpoint} for uris=${urisForEndpoint.join(
","
)}`
);
}
const raw =
(await resp.json()) as ATPAPI.AppBskyFeedGetPosts.OutputSchema;
postviews.push(...raw.posts);
}
return postviews;
}
async resolveGetProfiles(
dids: string[]
): Promise<ATPAPI.AppBskyActorDefs.ProfileViewDetailed[] | undefined> {
const profiles: ATPAPI.AppBskyActorDefs.ProfileViewDetailed[] = [];
for (const did of dids) {
const endpoint = await getSkyliteEndpoint(did);
const url = `${endpoint}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(
did
)}`;
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to fetch profile for ${did} via ${url}`);
const raw =
(await resp.json()) as ATPAPI.AppBskyActorGetProfile.OutputSchema;
profiles.push(raw);
}
return profiles;
}
async queryNotificationsList(
did: string,
cursor?: string,
limit?: number
): Promise<ATPAPI.AppBskyNotificationListNotifications.OutputSchema> {
if (!this.handlesDid(did)) {
return { notifications: [] };
}
const db = this.userManager.getDbForDid(did);
if (!db) {
return { notifications: [] };
}
const NOTIFS_LIMIT = limit ?? 30;
const offset = cursor ? parseInt(cursor, 10) : 0;
const mapReason = (
field: string
):
| ATPAPI.AppBskyNotificationListNotifications.Notification["reason"]
| undefined => {
switch (field) {
//'like' | 'repost' | 'follow' | 'mention' | 'reply' | 'quote' | 'starterpack-joined' | 'verified' | 'unverified' | 'like-via-repost' | 'repost-via-repost' |
case "app.bsky.feed.like:subject.uri":
return "like";
case "app.bsky.feed.like:via.uri":
return "liked-via-repost";
case "app.bsky.feed.repost:subject.uri":
return "repost";
case "app.bsky.feed.repost:via.uri":
return "repost-via-repost";
case "app.bsky.feed.post:reply.root.uri":
return "reply";
case "app.bsky.feed.post:reply.parent.uri":
return "reply";
case "app.bsky.feed.post:embed.media.record.record.uri":
return "quote";
case "app.bsky.feed.post:embed.record.uri":
return "quote";
//case"app.bsky.feed.threadgate:post": return "threadgate subject
//case"app.bsky.feed.threadgate:hiddenReplies": return "threadgate items (array)
case "app.bsky.feed.post:facets.features.did":
return "mention";
//case"app.bsky.graph.block:subject": return "blocks
case "app.bsky.graph.follow:subject":
return "follow";
//case"app.bsky.graph.listblock:subject": return "list item (blocks)
//case"app.bsky.graph.listblock:list": return "blocklist mention (might not exist)
//case"app.bsky.graph.listitem:subject": return "list item (blocks)
//"app.bsky.graph.listitem:list": return "list mention
// case "like": return "like";
// case "repost": return "repost";
// case "follow": return "follow";
// case "replyparent": return "reply";
// case "replyroot": return "reply";
// case "mention": return "mention";
default:
return undefined;
}
};
// --- Build Query ---
let query = `
SELECT srcuri, suburi, srcfield, indexedAt
FROM backlink_skeleton
WHERE
-- Find actions targeting the user's content or profile
(suburi LIKE ? OR suburi = ?)
-- Exclude notifications from the user themselves
AND srcuri NOT LIKE ?
ORDER BY indexedAt DESC, srcuri DESC
LIMIT ? OFFSET ?
`;
const params: (string | number)[] = [
`at://${did}/%`,
did,
`at://${did}/%`,
NOTIFS_LIMIT,
offset
];
// if (cursor) {
// const [indexedAt, srcuri] = cursor.split("::");
// if (indexedAt && srcuri && !Number.isNaN(+indexedAt)) {
// query += ` AND (indexedAt < ? OR (indexedAt = ? AND srcuri < ?))`;
// params.push(+indexedAt, +indexedAt, srcuri);
// }
// }
// query += ` ORDER BY indexedAt DESC, srcuri DESC LIMIT ${NOTIFS_LIMIT}`;
// --- Fetch and Process ---
const stmt = db.prepare(query);
const rows = stmt.all(...params) as {
srcuri: string;
suburi: string; // might be uri, might be just a did
srcfield: string;
indexedAt: number;
}[];
const notificationPromises = rows.map(async (row) => {
try {
const reason = mapReason(row.srcfield);
// i have a hunch that follow notifs are crashing the client
if (!reason || temporarydevelopmentblockednotiftypes.includes(reason)) {
return null;
}
// Skip if it's a backlink type we don't have a notification for
if (!reason) return null;
const srcURI = new AtUri(row.srcuri);
const [authorRes, recordRes] = await Promise.allSettled([
this.resolveProfileView(srcURI.host, ""),
getSlingshotRecord(srcURI.host, srcURI.collection, srcURI.rkey),
]);
const author = authorRes.status === "fulfilled" ? authorRes.value : null;
const getrecord = recordRes.status === "fulfilled" ? recordRes.value : null;
const reasonsubject =
row.suburi.startsWith("at://") ? row.suburi : `at://${row.suburi}`;
// If we can't resolve the author or the record, we can't form a valid notification
if (!author || !getrecord || !reason || !reasonsubject) return null;
author.viewer = {
"muted": false,
"blockedBy": false,
//"following":
} // TODO: proper mutes and blocks here
if (!getrecord?.value?.$type) getrecord.value.$type = srcURI.collection
return {
uri: row.srcuri,
cid: getrecord.cid,
author: author,
reason: reason,
// The reasonSubject is the URI of the post that was liked, reposted, or replied to
reasonSubject: reasonsubject,
record: getrecord.value,
isRead: false, // Placeholder for read-state logic
indexedAt: new Date(row.indexedAt).toISOString(),
labels: [], // Placeholder for label logic
} as ATPAPI.AppBskyNotificationListNotifications.Notification;
} catch (e) {console.log("error:",e)}
});
const seen = new Set<string>();
const notifications = (await Promise.all(notificationPromises))
.filter((n): n is ATPAPI.AppBskyNotificationListNotifications.Notification => {
if (!n) return false;
const key = `${n.uri}:${n.reason}:${n.reasonSubject}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
// --- Create next cursor ---
const nextCursor:number = Number(offset) + Number(limit ?? 0)
// const lastItem = rows[rows.length - 1];
// const nextCursor = lastItem
// ? `${lastItem.indexedAt}::${lastItem.srcuri}`
// : undefined;
return {
cursor: `${nextCursor}`,//nextCursor,
notifications: notifications,
priority:false,
seenAt: new Date().toISOString()
};
}
async resolveProfileView(
did: string,
type: ""
): Promise<ATPAPI.AppBskyActorDefs.ProfileView | undefined>;
async resolveProfileView(
did: string,
type: "Basic"
): Promise<ATPAPI.AppBskyActorDefs.ProfileViewBasic | undefined>;
async resolveProfileView(
did: string,
type: "Detailed"
): Promise<ATPAPI.AppBskyActorDefs.ProfileViewDetailed | undefined>;
async resolveProfileView(
did: string,
type: "" | "Basic" | "Detailed"
): Promise<
| ATPAPI.AppBskyActorDefs.ProfileView
| ATPAPI.AppBskyActorDefs.ProfileViewBasic
| ATPAPI.AppBskyActorDefs.ProfileViewDetailed
| undefined
> {
const record = (
await getSlingshotRecord(did, "app.bsky.actor.profile", "self")
).value as ATPAPI.AppBskyActorProfile.Record;
const identity = await resolveIdentity(did);
const avatarcid = uncid(record.avatar?.ref);
const avatar = avatarcid
? buildBlobUrl(identity.pds, identity.did, avatarcid)
: undefined;
const bannercid = uncid(record.banner?.ref);
const banner = bannercid
? buildBlobUrl(identity.pds, identity.did, bannercid)
: undefined;
// simulate different types returned
switch (type) {
case "": {
const result: ATPAPI.AppBskyActorDefs.ProfileView = {
$type: "app.bsky.actor.defs#profileView",
did: did,
handle: identity.handle,
displayName: record.displayName ?? identity.handle,
description: record.description ?? undefined,
avatar: avatar, // create profile URL from resolved identity
//associated?: ProfileAssociated,
indexedAt: record.createdAt
? new Date(record.createdAt).toISOString()
: undefined,
createdAt: record.createdAt
? new Date(record.createdAt).toISOString()
: undefined,
//viewer?: ViewerState,
//labels?: ComAtprotoLabelDefs.Label[],
//verification?: VerificationState,
//status?: StatusView,
};
return result;
}
case "Basic": {
const result: ATPAPI.AppBskyActorDefs.ProfileViewBasic = {
$type: "app.bsky.actor.defs#profileViewBasic",
did: did,