forked from TimAstier/react-roguelike
-
Notifications
You must be signed in to change notification settings - Fork 2
/
roguelike.tsx
1427 lines (1236 loc) · 48.3 KB
/
roguelike.tsx
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
/* export APIs to the Bodhi ecology, including the follow APIs:
- read bodhi text assets
- read bodhi pic assets
- read bodhi assets sliced
- read bodhi spaces
- using bodhi as a auth? That may be c00l.
*/
// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";
// for ether
import { ethers } from "https://cdn.skypack.dev/[email protected]";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { render } from "@deno/gfm";
import { gql } from "https://deno.land/x/[email protected]/mod.ts";
import { print } from "https://deno.land/x/[email protected]/mod.ts";
console.log("Hello from Functions!");
const router = new Router();
// Configuration for your smart contract
const contractABI = [
// Include only the necessary ABI details for balanceOf
"function balanceOf(address owner, uint256 asset_id) view returns (uint256)",
];
const contractAddress = "0x2ad82a4e39bac43a54ddfe6f94980aaf0d1409ef";
// Provider URL, you should replace it with your actual Optimism provider
const provider = new ethers.providers.JsonRpcProvider(
"https://mainnet.optimism.io"
);
const contract = new ethers.Contract(contractAddress, contractABI, provider);
// img checker.
function containsImage(markdownString) {
const regex = /!\[.*?\]\((.*?)\)/;
return regex.test(markdownString);
}
function extractImageLink(markdownImageString: string): string | null {
// Regular expression to match the format ![some_text](url)
const regex = /!\[.*?\]\((.*?)\)/;
// Use the regex to find matches
const match = markdownImageString.match(regex);
// If a match is found and it has a group capture, return the URL
if (match && match[1]) {
return match[1];
}
// If no match is found, return null
return null;
}
// balance checker.
async function checkTokenHold(addr, assetId, minHold) {
try {
// Call the balanceOf function
const balance = await contract.balanceOf(addr, assetId);
// Convert balance from BigInt to a number in ethers and adjust for token decimals (18 decimals)
const balanceInEth = parseFloat(ethers.utils.formatUnits(balance, 18));
// Compare the balance against the minimum hold requirement
return balanceInEth >= minHold;
} catch (error) {
console.error("Error accessing the contract or parsing balance:", error);
return false;
}
}
// Helper function to escape XML special characters
function escapeXml(unsafe: string | null | undefined): string {
if (unsafe == null) return "";
return unsafe.replace(/[<>&'"]/g, (c) => {
switch (c) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "'":
return "'";
case '"':
return """;
}
return c;
});
}
async function getAssetsByAuthor(supabase, author, onlyTitle, cursor, limit) {
let query = supabase
.from("bodhi_text_assets")
.select("*")
.eq("author_true", author.toLowerCase())
.order("id", { ascending: false })
.limit(limit);
if (cursor) {
query = query.lt("id", cursor + 1);
}
const { data, error } = await query;
if (error) {
throw error;
}
const processedData = data.map((item) => {
if (onlyTitle) {
const { content, ...rest } = item;
const lines = content?.split("\n") || [];
const firstLine = lines.find((line) => line.trim() !== "") || ""; // Find the first non-empty line
const abstract = firstLine.trim().startsWith("#")
? firstLine.trim().replace(/^#+\s*/, "") // Remove leading '#' and spaces
: firstLine.trim();
const fiveLine = lines.slice(1, 5).join("\n") || "";
return { ...rest, abstract, fiveLine };
} else {
const { embedding, ...rest } = item;
const lines = item.content?.split("\n") || [];
const firstLine = lines.find((line) => line.trim() !== "") || ""; // Find the first non-empty line
const abstract = firstLine.trim().startsWith("#")
? firstLine.trim().replace(/^#+\s*/, "") // Remove leading '#' and spaces
: firstLine.trim();
const fiveLine = lines.slice(1, 5).join("\n") || "";
return { ...rest, abstract, fiveLine };
}
});
const nextCursor = data.length === limit ? data[data.length - 1].id : null;
return { assets: processedData, nextCursor };
}
async function getAssetsBySpace(
supabase,
spaceContractAddr,
onlyTitle,
cursor,
limit
) {
let query = supabase
.from("bodhi_text_assets")
.select()
.eq("creator", spaceContractAddr.toLowerCase())
.order("id", { ascending: false })
.limit(limit);
if (cursor) {
query = query.lt("id", cursor + 1);
}
const { data, error } = await query;
if (error) {
throw error;
}
const processedData = data.map((item) => {
if (onlyTitle) {
const { content, ...rest } = item;
const lines = content?.split("\n") || [];
const firstLine = lines.find((line) => line.trim() !== "") || ""; // Find the first non-empty line
const abstract = firstLine.trim().startsWith("#")
? firstLine.trim().replace(/^#+\s*/, "") // Remove leading '#' and spaces
: firstLine.trim();
const fiveLine = lines.slice(1, 5).join("\n") || "";
return { ...rest, abstract, fiveLine };
} else {
const { embedding, ...rest } = item;
const lines = item.content?.split("\n") || [];
const firstLine = lines.find((line) => line.trim() !== "") || ""; // Find the first non-empty line
const abstract = firstLine.trim().startsWith("#")
? firstLine.trim().replace(/^#+\s*/, "") // Remove leading '#' and spaces
: firstLine.trim();
const fiveLine = lines.slice(1, 5).join("\n") || "";
return { ...rest, abstract, fiveLine };
}
});
const nextCursor = data.length === limit ? data[data.length - 1].id : null;
return { assets: processedData, nextCursor };
}
router
.get("/spaces", async (context) => {
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
try {
// Assuming 'name' is a non-null field you want to check
const { data, error } = await supabase
.from("bodhi_spaces")
.select("*")
.not("name", "is", "NULL");
if (error) {
throw error;
}
context.response.status = 200;
context.response.body = data; // Send the retrieved data as the response
} catch (err) {
console.error("Error fetching spaces:", err);
context.response.status = 500;
context.response.body = { error: "Failed to fetch spaces" };
}
})
.get("/set_img", async (context) => {
const queryParams = context.request.url.searchParams;
let asset_id = parseInt(queryParams.get("asset_id"), 10);
const category = queryParams.get("category");
const adminKey = queryParams.get("admin_key");
// Example: Basic admin key verification
if (adminKey !== Deno.env.get("ADMIN_KEY")) {
context.response.status = 403;
context.response.body = "Unauthorized";
return;
}
if (!asset_id || !category) {
context.response.status = 400;
context.response.body = "Missing required parameters";
return;
}
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
const { data, error } = await supabase
.from("bodhi_img_assets_k_v")
.update({ category })
.eq("id_on_chain", asset_id);
if (error) {
console.error("Error updating asset category:", error);
context.response.status = 500;
context.response.body = { error: "Failed to update category" };
return;
}
context.response.body = { message: "Category updated successfully", data };
})
.get("/", async (context) => {
context.response.body = { result: "Hello World!" };
})
.get("/imgs_latest_id", async (context) => {
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
// Query to get the row with the maximum ID
const { data, error } = await supabase
.from("bodhi_img_assets_k_v")
.select("id") // Assuming 'id' is the primary key or a unique identifier
.order("id", { ascending: false }) // Order by id descending
.limit(1); // Only fetch one record
if (error) {
console.error("Error fetching the latest ID:", error);
context.response.status = 500;
context.response.body = { error: "Failed to fetch the latest ID" };
return;
}
// Assuming 'data' contains the fetched row, and you're extracting 'id'
const latestId = data && data.length > 0 ? data[0].id : null;
// Return the latest ID
context.response.body = { latestId: latestId };
})
.get("/text_search", async (context) => {
const queryParams = context.request.url.searchParams;
const key = queryParams.get("keyword");
const tableName = queryParams.get("table_name");
const column = queryParams.get("column");
const limit = parseInt(queryParams.get("limit"), 10); // Get limit from query and convert to integer
const onlyTitle = queryParams.has("only_title"); // Check if only_title param exists
// List of searchable tables
const searchableTables = ["bodhi_text_assets", "bodhi_text_assets_k_v"];
// Check if the table is allowed to be searched
if (!searchableTables.includes(tableName)) {
context.response.status = 403; // Forbidden status code
context.response.body = {
error: "The specified table is not searchable.",
};
return;
}
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
try {
let query = supabase
.from(tableName)
.select("*") // Select all columns initially
.textSearch(column, key)
.order("id_on_chain", { ascending: false }); // Order results by id_on_chain in descending order
if (!isNaN(limit) && limit > 0) {
query = query.limit(limit); // Apply limit to the query if valid
}
const { data, error } = await query;
if (error) {
throw error;
}
// Modify data based on only_title parameter
const processedData = data.map((item) => {
if (onlyTitle) {
const { content, ...rest } = item; // Exclude content from the result
const lines = content?.split("\n") || [];
const firstLine = lines.find((line) => line.trim() !== "") || ""; // Find the first non-empty line
const abstract = firstLine.trim().startsWith("#")
? firstLine.trim().replace(/^#+\s*/, "") // Remove leading '#' and spaces
: firstLine.trim();
return { ...rest, abstract }; // Return other data with abstract
} else {
const { embedding, ...rest } = item; // Exclude embedding from the result if it exists
return rest;
}
});
context.response.status = 200;
context.response.body = processedData;
} catch (error) {
console.error("Error fetching data:", error);
context.response.status = 500;
context.response.body = { error: "Failed to fetch data" };
}
})
.get("/constant", async (context) => {
// * get value by the key and app name.
// TODO: impl the param parser of get/post in the scaffold-aptos.
// 1. parse params in get req.
const queryParams = context.request.url.searchParams;
const key = queryParams.get("key");
// 2. parse params in post req.
// let content = await context.request.body.text();
// content = JSON.parse(content);
// const uuid = content.uuid;
const supabase = createClient(
// Supabase API URL - env var exported by default.
Deno.env.get("SUPABASE_URL") ?? "",
// Supabase API ANON KEY - env var exported by default.
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
// Create client with Auth context of the user that called the function.
// This way your row-level-security (RLS) policies are applied.
// { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
);
// Querying data from Supabase
const { data, error } = await supabase
.from("bodhi_constants")
.select("*")
.eq("key", key)
.single();
if (error) {
console.error("Error fetching data:", error);
context.response.status = 500;
context.response.body = "Failed to fetch data";
return;
}
context.response.body = data;
})
.get("/imgs_page", async (context) => {
const queryParams = context.request.url.searchParams;
const page = parseInt(queryParams.get("page"), 10) || 1;
const limit = parseInt(queryParams.get("limit"), 10) || 10; // Default to 10 items per page if not specified
const category = queryParams.get("category");
const offset = (page - 1) * limit; // Calculate offset
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
let query = supabase
.from("bodhi_img_assets_k_v")
.select() // Select fields as needed, could specify like "id, link, metadata"
.order("id", { ascending: false }) // Or order by any other relevant field
// .limit(limit)
.range(offset, offset + limit - 1);
if (category) {
query = query.eq("category", category); // Filter by category if it is provided
}
const { data, error } = await query;
if (error) {
console.error("Error fetching images:", error);
context.response.status = 500;
context.response.body = { error: "Failed to fetch images" };
return;
}
// Assuming 'data' contains the fetched images
context.response.body = { images: data, page, limit };
})
.get("/imgs", async (context) => {
let cursor = context.request.url.searchParams.get("cursor");
let limit = context.request.url.searchParams.get("limit");
let category = context.request.url.searchParams.get("category");
cursor = parseInt(cursor, 10);
limit = limit ? parseInt(limit, 10) : 10;
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
const query = supabase
.from("bodhi_img_assets_k_v")
.select() // Select fields you need
.order("created_at", { ascending: false }) // Sorting by 'created_at' in descending order
.limit(limit);
if (cursor) {
query.lt("id", cursor + 1); // Fetch records newer than the cursor
}
// Apply the category filter condition
if (category) {
query.eq("category", category); // Filter by category
}
const { data, error } = await query;
if (error) {
console.error("Error fetching images:", error);
context.response.status = 500;
context.response.body = { error: "Failed to fetch images" };
return;
}
// Assuming 'data' contains the fetched images
context.response.body = { images: data };
})
.get("/batch_to_img", async (context) => {
const supabase = createClient(
// Supabase API URL - env var exported by default.
Deno.env.get("SUPABASE_URL") ?? "",
// Supabase API ANON KEY - env var exported by default.
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
// Create client with Auth context of the user that called the function.
// This way your row-level-security (RLS) policies are applied.
// { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
);
const { data, error } = await supabase
.from("bodhi_text_assets_k_v")
.select()
.eq("if_to_img_assets", 0);
// .eq('id', 9324);
console.log("error:", error);
// for all the data
for (const item of data) {
console.log("handle item:", item.id);
const hasImage = containsImage(item.data); // Assuming 'content' contains the markdown text
console.log("hasImage:", hasImage);
const newValue = hasImage ? 2 : 1; // If it has image, set to 2, otherwise set to 1
if (newValue == 2) {
console.log("detect img item:", item.id);
// Insert into bodhi_img_assets_k_v, omitting the embedding field
// Function to extract image link from Markdown content
const imgLink = extractImageLink(item.data);
// Prepare the item for insertion by omitting certain fields
const itemToInsert = {
id_on_chain: item.id_on_chain,
creator: item.creator,
created_at: item.created_at,
metadata: item.metadata,
link: imgLink, // Set the extracted image link
};
const insertResponse = await supabase
.from("bodhi_img_assets_k_v")
.insert([itemToInsert]);
if (insertResponse.error) {
console.log(
`Failed to insert item ${item.id} into bodhi_img_assets_k_v:`,
insertResponse.error
);
} else {
console.log(
`Item ${item.id} inserted into bodhi_img_assets_k_v successfully.`
);
}
}
// update the bodhi_text_assets_k_v table.
const updateResponse = await supabase
.from("bodhi_text_assets_k_v")
.update({ if_to_img_assets: newValue })
.match({ id: item.id }); // Assuming 'id' is the primary key of the table
if (updateResponse.error) {
console.log(`Failed to update item ${item.id}:`, updateResponse.error);
} else {
console.log(`Item ${item.id} updated successfully.`);
}
}
context.response.body = { result: "batch to img done" };
})
.get("/bodhi_auth", async (context) => {
// 1. verify that addr, msg and signature is valid(验证签名).
// 2. check the token hodl(检查持仓).
// Assuming the URL might be "/bodhi_auth?addr=0x00&msg=abcdefg&signature=0x01&asset_id=1&hold=0.001"
const queryParams = context.request.url.searchParams;
const addr = queryParams.get("addr");
const msg = queryParams.get("msg");
const signature = queryParams.get("signature");
// const assetId = queryParams.get('asset_id'); // Example usage
const hold = queryParams.get("hold"); // Example usage
let if_pass = false;
// Example usage
const assetId = 14020; // Example usage
const minHold = 0.001; // Minimum required balance
// if_pass = await checkTokenHold(addr, assetId, minHold);
try {
// 1. Verify the signature
// const messageHash = ethers.utils.hashMessage(msg);
const recoveredAddr = ethers.utils.verifyMessage(msg, signature);
if (recoveredAddr.toLowerCase() === addr.toLowerCase()) {
// 2. Check token hold (This part would need actual logic to check token holdings)
// Assuming the logic to check token holdings is implemented elsewhere
// if (checkTokenHold(addr, asset_id, hold)) {
// if_pass = true;
// }
// Simulate token hold check for demonstration purposes
if_pass = await checkTokenHold(addr, assetId, minHold);
}
} catch (error) {
console.error("Error verifying signature or checking token hold:", error);
}
if (if_pass) {
context.response.body = {
result: "Auth Pass, You could see the secrect things now!",
};
} else {
context.response.body = { result: "Auth unPass" };
}
})
.get("/assets_index_latest", async (context) => {
const supabase = createClient(
// Supabase API URL - env var exported by default.
Deno.env.get("SUPABASE_URL") ?? "",
// Supabase API ANON KEY - env var exported by default.
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
// Create client with Auth context of the user that called the function.
// This way your row-level-security (RLS) policies are applied.
// { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
);
const { data, error } = await supabase
.from("bodhi_indexer")
.select("index")
.eq("name", "bodhi")
.single();
context.response.body = data;
})
.get("/assets", async (context) => {
// Create a Supabase client with the Auth context of the logged in user.
const supabase = createClient(
// Supabase API URL - env var exported by default.
Deno.env.get("SUPABASE_URL") ?? "",
// Supabase API ANON KEY - env var exported by default.
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
// Create client with Auth context of the user that called the function.
// This way your row-level-security (RLS) policies are applied.
// { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
);
// Assuming the URL might be "/assets?asset_begin=0&asset_end=10&space_id=456"
const queryParams = context.request.url.searchParams;
const onlyTitle = queryParams.has("only_title"); // Check if only_title param exists
if (queryParams.has("asset_begin")) {
// Done: get data from asset begin to asset to, return the arrary of assets in bodhi_text_assets which id_on_chain = asset_num
const assetBegin = parseInt(queryParams.get("asset_begin"), 10);
const assetEnd = parseInt(queryParams.get("asset_end"), 10);
if (isNaN(assetBegin) || isNaN(assetEnd)) {
context.response.status = 400;
context.response.body = "Invalid asset range provided";
return;
}
// Fetch assets within the range from the database
const { data, error } = await supabase
.from("bodhi_text_assets")
.select()
.gte("id_on_chain", assetBegin)
.lte("id_on_chain", assetEnd)
.order("id_on_chain", { ascending: true });
if (error) {
console.error("Error fetching assets:", error);
context.response.status = 500;
context.response.body = { error: "Failed to fetch assets" };
return;
}
const processedData = data.map((item) => {
if (onlyTitle) {
const { content, ...rest } = item; // Exclude content from the result
const lines = content?.split("\n") || [];
const firstLine = lines.find((line) => line.trim() !== "") || ""; // Find the first non-empty line
const abstract = firstLine.trim().startsWith("#")
? firstLine.trim().replace(/^#+\s*/, "") // Remove leading '#' and spaces
: firstLine.trim();
return { ...rest, abstract }; // Return other data with abstract
} else {
const { embedding, ...rest } = item; // Exclude embedding from the result if it exists
return rest;
}
});
context.response.body = { assets: processedData };
return;
}
if (queryParams.has("space_addr")) {
console.log("B"); // If space_id is in params, print "B"
context.response.body = "Assets Endpoint Hit";
}
})
// TODO: more abstract the APIs.
.get("/assets_by_table_name", async (context) => {
// Create a Supabase client with the Auth context of the logged in user.
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
// To implement row-level security (RLS), uncomment and adjust the following lines:
// , {
// global: {
// headers: { Authorization: `Bearer ${context.request.headers.get('Authorization')}` }
// }
// }
);
const queryParams = context.request.url.searchParams;
const tableName = queryParams.get("table_name");
try {
// Define a basic select query for fetching all data from the first table
let query = supabase.from(tableName).select("*");
// Execute the first query
const { data: initialData, error: initialError } = await query;
if (initialError) {
throw initialError;
}
// Extract the id_on_chain values from the initial query result
const idOnChains = initialData.map((item) => item.id_on_chain);
// Execute the second query using the id_on_chain values to fetch from bodhi_text_assets
const { data: secondaryData, error: secondaryError } = await supabase
.from("bodhi_text_assets")
.select("*")
.in("id_on_chain", idOnChains);
if (secondaryError) {
throw secondaryError;
}
// Create a map from id_on_chain to category and type from initialData
const categoryTypeMap = initialData.reduce((acc, item) => {
acc[item.id_on_chain] = { category: item.category, type: item.type };
return acc;
}, {});
// Append category and type to each item in secondaryData
const enrichedSecondaryData = secondaryData.map((item) => {
return {
...item,
...categoryTypeMap[item.id_on_chain], // Merge category and type based on id_on_chain
};
});
// Return the enriched secondaryData as a JSON response.
context.response.body = enrichedSecondaryData;
context.response.status = 200;
} catch (err) {
console.error("Failed to fetch data:", err);
context.response.status = 500;
context.response.body = { error: "Failed to fetch data" };
}
})
.get("/assets_by_space_v2", async (context) => {
// Create a Supabase client with the Auth context of the logged in user.
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
// To implement row-level security (RLS), uncomment and adjust the following lines:
// , {
// global: {
// headers: { Authorization: `Bearer ${context.request.headers.get('Authorization')}` }
// }
// }
);
const queryParams = context.request.url.searchParams;
const spaceContractAddr = queryParams.get("space_addr") + "_indexer";
// Check if 'type' parameter exists and set the variable accordingly
let typeFilter = queryParams.has("type") ? queryParams.get("type") : null;
let categoryFilter = queryParams.has("category")
? queryParams.get("category")
: null;
try {
// Define a basic select query for fetching all data from the first table
let query = supabase.from(spaceContractAddr).select("*");
// If typeFilter is set, modify the query to filter by 'type' column
if (typeFilter) {
query = query.eq("type", typeFilter);
}
if (categoryFilter) {
query = query.eq("category", categoryFilter);
}
// Execute the first query
const { data: initialData, error: initialError } = await query;
if (initialError) {
throw initialError;
}
// Extract the id_on_chain values from the initial query result
const idOnChains = initialData.map((item) => item.id_on_chain);
// Execute the second query using the id_on_chain values to fetch from bodhi_text_assets
const { data: secondaryData, error: secondaryError } = await supabase
.from("bodhi_text_assets")
.select("*")
.in("id_on_chain", idOnChains);
if (secondaryError) {
throw secondaryError;
}
// Create a map from id_on_chain to category and type from initialData
const categoryTypeMap = initialData.reduce((acc, item) => {
acc[item.id_on_chain] = { category: item.category, type: item.type };
return acc;
}, {});
// Append category and type to each item in secondaryData
const enrichedSecondaryData = secondaryData.map((item) => {
return {
...item,
...categoryTypeMap[item.id_on_chain], // Merge category and type based on id_on_chain
};
});
// Return the enriched secondaryData as a JSON response.
context.response.body = enrichedSecondaryData;
context.response.status = 200;
} catch (err) {
console.error("Failed to fetch data:", err);
context.response.status = 500;
context.response.body = { error: "Failed to fetch data" };
}
})
.get("/assets_by_space", async (context) => {
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
const queryParams = context.request.url.searchParams;
const onlyTitle = queryParams.has("only_title");
const spaceContractAddr = queryParams.get("space_addr");
let cursor = queryParams.get("cursor");
const limit = parseInt(queryParams.get("limit") || "10", 10);
if (!spaceContractAddr) {
context.response.status = 400;
context.response.body = { error: "space_addr parameter is required" };
return;
}
try {
const result = await getAssetsBySpace(
supabase,
spaceContractAddr,
onlyTitle,
cursor,
limit
);
context.response.body = result;
} catch (err) {
console.error("Error fetching assets by space:", err);
context.response.status = 500;
context.response.body = { error: "Failed to fetch assets by space" };
}
})
.get("/collections", async (context) => {
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
try {
const { data, error } = await supabase
.from("bodhi_collections")
.select("*");
if (error) {
throw error;
}
context.response.status = 200;
context.response.body = data; // Send the retrieved data as the response
} catch (err) {
console.error("Error fetching collections:", err);
context.response.status = 500;
context.response.body = { error: "Failed to fetch collections" };
}
})
.get("/gen_rss", async (context) => {
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
const queryParams = context.request.url.searchParams;
let author = queryParams.get("author");
const title = queryParams.get("title") || "RSS Feed";
const description = queryParams.get("description") || "Generated RSS feed";
const cursor = queryParams.get("cursor") || null;
const limit = queryParams.get("limit") || 100;
if (!author) {
context.response.status = 400;
context.response.body = { error: "Author parameter is required" };
return;
}
try {
// Query the bodhi_rss_feeds table
const { data: rssData, error: rssError } = await supabase
.from("bodhi_rss_feeds")
.select("feed_id, user_id")
.eq("unique_id", author.toLowerCase())
.single();
if (rssError) {
console.error("The feed is not verified yet:", rssError);
}
const result = await getAssetsByAuthor(
supabase,
author,
false,
cursor,
limit
);
// Generate RSS XML
context.response.headers.set(
"Content-Type",
"application/rss+xml; charset=utf-8"
);
const rssItems = result.assets
.map(
(asset) => `
<item>
<title>${escapeXml(asset.abstract)}</title>
<link>https://bodhi.wtf/${asset.id_on_chain}</link>
<guid>https://bodhi.wtf/${asset.id_on_chain}</guid>
<pubDate>${new Date(asset.created_at).toUTCString()}</pubDate>
<description><![CDATA[${render(asset.fiveLine)}]]></description>
<content:encoded><![CDATA[
${render(asset.content)}
<div style="display: flex; justify-content: center; align-items: center; margin: 0 auto;">
<a href="https://bodhi.wtf/${asset.id_on_chain}">
<button style="background-color: rgb(0, 95, 189) !important; color: white !important; border: none; border-radius: 4px; font-size: 18px; cursor: pointer; font-weight: 400; padding: 10px 16px; line-height: 1.3333333;">
Comment 留言
</button>
</a>
<a href="https://bodhi.wtf/${asset.id_on_chain}?action=buy">
<button style="background-color: rgb(0, 95, 189) !important; color: white !important; border: none; border-radius: 4px; font-size: 18px; cursor: pointer; font-weight: 400; padding: 10px 16px; line-height: 1.3333333;">
Buy Shares 购买份额
</button>
</a>
</div>
]]></content:encoded>
<author>${escapeXml(author)}</author>
</item>
`
)
.join("");
let feedIdUserIdString = "";
if (rssData) {
feedIdUserIdString = ` feedId:${rssData.feed_id}+userId:${rssData.user_id}`;
}
const rss = `<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title>${escapeXml(title)}</title>
<link>https://bodhi.wtf/address/${author}</link>
<description>${escapeXml(
description
)}${feedIdUserIdString}</description>
<language>zh-cn</language>
${rssItems}
</channel>
</rss>`;
context.response.body = rss;
} catch (err) {
console.error("Error generating RSS:", err);
context.response.status = 500;
context.response.body = { error: "Failed to generate RSS feed" };
}
})
.get("/gen_rss_by_space", async (context) => {
const supabase = createClient(
Deno.env.get("SUPABASE_URL") ?? "",
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
);
const queryParams = context.request.url.searchParams;
const spaceContractAddr = queryParams.get("space_addr");
const cursor = queryParams.get("cursor") || null;
const limit = parseInt(queryParams.get("limit") || "100", 10);
if (!spaceContractAddr) {
context.response.status = 400;
context.response.body = { error: "space_addr parameter is required" };
return;
}
try {
// Query the bodhi_spaces table to get the id_on_chain
const { data: spaceData, error: spaceError } = await supabase
.from("bodhi_spaces")
.select()
.eq("contract_addr", spaceContractAddr)
.single();
if (spaceError || !spaceData) {
throw new Error("Space not found");
}
const spaceIdOnChain = spaceData.id_on_chain;
// Query the bodhi_rss_feeds table
const { data: rssData, error: rssError } = await supabase
.from("bodhi_rss_feeds")
.select("feed_id, user_id")
.eq("unique_id", spaceContractAddr.toLowerCase())