forked from OrbisWeb3/orbis-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1486 lines (1274 loc) · 42.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
/** Ceramic */
import { CeramicClient } from '@ceramicnetwork/http-client';
import { TileDocument } from '@ceramicnetwork/stream-tile';
import { DIDSession } from 'did-session'
import { EthereumWebAuth, getAccountId } from '@didtools/pkh-ethereum'
import axios from 'axios';
/** To generate dids from a Seed */
import { DID } from 'dids'
import { Ed25519Provider } from 'key-did-provider-ed25519'
import { getResolver } from 'key-did-resolver'
/** Lit Protocol */
import {
connectLitClient,
generateLitSignature,
generateLitSignatureV2,
generateAccessControlConditionsForDMs,
encryptDM,
encryptPost,
decryptString
} from "./utils/lit-helpers.js";
/** Internal helpers */
import { indexer } from './lib/indexer-db.js';
import {
forceIndex,
forceIndexDid,
sleep,
randomSeed,
sortByKey,
getAuthMethod,
getAddressFromDid,
resizeFile
} from "./utils/index.js";
import { authenticatePkp } from "./utils/ceramic-helpers.js"
/** Initiate the node URLs for the two networks */
const MAINNET_NODE_URL = "https://node1.orbis.club/";
const TESTNET_NODE_URL = "https://ceramic-clay.3boxlabs.com";
let PINATA_GATEWAY = "https://orbis.mypinata.cloud/ipfs/";
let PINATA_API_KEY = null;
let PINATA_SECRET_API_KEY = null;
/** Set schemas Commit IDs */
const postSchemaStream = "kjzl6cwe1jw1498inegtpji0iqf0htspb0qqswlofjy0hak1s3u2pf19qql7oak";
const postSchemaCommit = "k1dpgaqe3i64kjuyet4w0zyaqwamf9wrp1jim19y27veqkppo34yghivt2pag4wxp0fv2yl4hedynpfuynp2wvd8s7ctabea6lx732xrr8b0cgqauwlh0vwg6";
const groupSchemaStream = "kjzl6cwe1jw1487a0xluwl3ip6lcdcfn8ahgomsbf8x5rf65mktdjuouz8xopbf";
const groupSchemaCommit = "k3y52l7qbv1fry2bramzfrq10z2vrywf96yk6n61d8ffsyzvs0k0wd68sanjjo16o";
const channelSchemaStream = "kjzl6cwe1jw148ehiqrzh9npfr4kk4kyqd4as259yqzcr3i1dnrnm30ck5q0t6f";
const channelSchemaCommit = "k3y52l7qbv1fry3r0laf0asokw0wi74l2zhaknj9iv3veoow9t50nx1ehbcp1rhmo";
const profileSchemaStream = "kjzl6cwe1jw145ak5a52cln1i6ztmece01w5qd03dib4lg8i3tt57sjauu14be8";
const profileSchemaCommit = "k3y52l7qbv1frxhn39k40plvupdqqna03kdgorggo0274ojggr7z93ex979jyp14w";
const reactionSchemaStream = "kjzl6cwe1jw146a2jirsoiku1eqsckmk8o7egba22jufwenwbb9fs096s340efk";
const reactionSchemaCommit = "k3y52l7qbv1frxonm2thnyc45m0uhleofxo4ms07iq54h2g9xsg3475tc7q4iumm8";
const followSchemaStream = "kjzl6cwe1jw14av566q7ja9a2jy78uv5ih7pa683ozdulkpsc46qwsxfqzz3po5";
const followSchemaCommit = "k3y52l7qbv1fryl9grzudl4xzm5v7izhj7eersc9m9nmhlfbdi5rzd9przztmejnk";
const groupMemberSchemaStream = "kjzl6cwe1jw146jk7s8ls9bjql42yqn1j5d3z0meue1zkgxeq2drqr0nl43soi8";
const groupMemberSchemaCommit = "k3y52l7qbv1frxqj3rct6wya4d25131fuw65890fdk3y4xkdkpcxxa84nq56zy9kw";
const conversationSchemaStream = "kjzl6cwe1jw149ibyxllm19uiqvaj4gj2f84lq3y3xzs0nqpo2ufw63ut3xwn7i";
const conversationSchemaCommit = "k3y52l7qbv1frybmd4exlop211b2ivzpjl89sqho2k1qf8otyj88h0rff301451c0";
const messageSchemaStream = "kjzl6cwe1jw14bcux0xa3ba15686iwkw78y4xda0djl58ufyq219e116ihujfh8";
const messageSchemaCommit = "k1dpgaqe3i64kk0894kb0j6w3oznbcz99blyot3fjkpl3t12zuj0a05yx15yodie1fnsskh5fmcas76fqqjx98lio3yqhce4za88vpbr7f0eda2oebxsga7hx";
const notificationsReadSchemaStream = "kjzl6cwe1jw14a4hg7d96srbp4tm2lox68ry6uv4m0m3pfsjztxx4pe6rliqquu"
const notificationsReadSchemaCommit = "k3y52l7qbv1fryfzw38e9ccib6qakyi97weer4rhcskd6cwb26sx7lgkw491a6z9c"
/** Definition of the Orbis class powering the Orbis SDK */
export class Orbis {
/** Initiate some values for the class */
ceramic;
session;
api;
chain = "ethereum";
/**
* Initialize the SDK by connecting to a Ceramic node, developers can pass their own Ceramic object if the user is
* already connected within their application
*/
constructor(options) {
if(options && options.ceramic) {
/** Initialize the Orbis object using the Ceramic object passed in the option */
this.ceramic = options.ceramic;
} else {
/** Either connect to mainnet or testnet */
if(options && options.node) {
this.ceramic = new CeramicClient(options.node);
console.log("Ceramic: Connected to node: " + options.node);
} else {
try {
this.ceramic = new CeramicClient(MAINNET_NODE_URL);
console.log("Ceramic: Connected to node: " + MAINNET_NODE_URL);
} catch(e) {
console.log("Error creating Ceramic object: ", e);
}
}
}
/** Assign Pinata API keys */
if(options) {
if(options.PINATA_GATEWAY) {
PINATA_GATEWAY = options.PINATA_GATEWAY;
}
if(options.PINATA_API_KEY) {
PINATA_API_KEY = options.PINATA_API_KEY;
}
if(options.PINATA_SECRET_API_KEY) {
PINATA_SECRET_API_KEY = options.PINATA_SECRET_API_KEY;
}
}
/** Create API object that developers can use to query content from Orbis */
this.api = indexer;
/** Connect to Lit */
connectLitClient();
}
/** The connect function will connect to an EVM wallet and create or connect to a Ceramic did */
async connect(provider, lit = true) {
/** If provider isn't passed we use window.ethereum */
if(!provider) {
if(window.ethereum) {
console.log("Orbis SDK: You need to pass the provider as an argument in the `connect()` function. We will be using window.ethereum by default.");
provider = window.ethereum;
} else {
alert("An ethereum provider is required to proceed with the connection to Ceramic.");
return false;
}
}
/** Step 1: Enable Ethereum provider (can be browser wallets or WalletConnect for now) */
let addresses;
try {
addresses = await provider.enable();
} catch(e) {
return {
status: 300,
error: e,
result: "Error enabling Ethereum provider."
}
}
/** Step 2: Check if user already has an active account on Orbis */
let authMethod;
let defaultChain = "1";
let address = addresses[0].toLowerCase();
let accountId = await getAccountId(provider, address)
/** Check if the user trying to connect already has an existing did on Orbis */
let {data: existingDids, error: errorDids} = await this.getDids(address);
if(existingDids && existingDids.length > 0) {
let sortedDids = sortByKey(existingDids, "count_followers");
let _didArr = sortedDids[0].did.split(":");
let defaultNetwork = _didArr[2];
if(defaultNetwork == "eip155") {
defaultChain = _didArr[3];
}
}
/** Update the default accountId used to connect */
console.log("Default chain to use: ", defaultChain);
accountId.chainId.reference = defaultChain.toString();
/** Step 2: Create an authMethod object using the address connected */
try {
authMethod = await EthereumWebAuth.getAuthMethod(provider, accountId)
} catch(e) {
return {
status: 300,
error: e,
result: "Error creating Ethereum provider object for Ceramic."
}
}
/** Step 3: Create a new session for this did */
let did;
try {
/** Expire session in 90 days by default */
const threeMonths = 60 * 60 * 24 * 90;
this.session = await DIDSession.authorize(
authMethod,
{
resources: [`ceramic://*`],
expiresInSecs: threeMonths
}
);
did = this.session.did;
} catch(e) {
return {
status: 300,
error: e,
result: "Error creating a session for the DiD."
}
}
/** Step 3 bis: Store session in localStorage to re-use */
try {
const sessionString = this.session.serialize()
localStorage.setItem("ceramic-session", sessionString);
} catch(e) {
console.log("Error creating sessionString: " + e);
}
/** Step 4: Assign did to Ceramic object */
this.ceramic.did = did;
/** Step 5 (optional): Initialize the connection to Lit */
if(lit == true) {
let _userAuthSig = localStorage.getItem("lit-auth-signature-" + address);
if(!_userAuthSig || _userAuthSig == "" || _userAuthSig == undefined) {
try {
/** Generate the signature for Lit */
let resLitSig = await generateLitSignature(provider, address);
} catch(e) {
console.log("Error connecting to Lit network: " + e);
}
} else {
/** User is already connected, save current accoutn signature in lit-auth-signature object for easy retrieval */
localStorage.setItem("lit-auth-signature", _userAuthSig);
}
}
/** Step 6: Force index did to retrieve blockchain details automatically */
let _resDid = await forceIndexDid(this.session.id);
/** Step 7: Get user profile details */
let { data, error, status } = await this.getProfile(this.session.id);
/** Check if user has configured Lit */
let hasLit = false;
let hasLitSig = localStorage.getItem("lit-auth-signature");
if(hasLitSig) {
hasLit = true;
}
let details;
if(data) {
details = data.details;
details.hasLit = hasLit;
} else {
details = {
did: this.session.id,
hasLit: hasLit,
profile: null
}
}
/** Return result */
return {
status: 200,
did: this.session.id,
details: details,
result: "Success connecting to the DiD."
}
}
/** The connect function will connect to an EVM wallet and create or connect to a Ceramic did */
async connect_v2({provider, chain = "ethereum", lit = false, oauth = null}) {
/** Save chain we are using in global state */
this.chain = chain;
/** If provider isn't passed we use window.ethereum */
if(!provider) {
if(window.ethereum) {
console.log("Orbis SDK: You need to pass the provider as an argument in the `connect()` function. We will be using window.ethereum by default.");
provider = window.ethereum;
} else {
alert("An ethereum provider is required to proceed with the connection to Ceramic.");
return false;
}
}
/** Variables */
const threeMonths = 60 * 60 * 24 * 90;
let did;
/** User is connecting with a web2 provider */
if(provider == 'oauth') {
/** Generate request variables for API call */
let oauthData = await fetch("http://localhost:3004/assign-pkp", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
accessToken: oauth.accessToken,
userId: oauth.userId,
authType: oauth.type,
hostname: window.location.hostname
})
});
let oauthResult = await oauthData.json();
/** Request was successful, proceed */
if(oauthResult.status == 200) {
/** API generated a new PKP and a session-string, proceed to login the user */
if(oauthResult.sessionString) {
console.log("API generated a new PKP and a session-string, proceed to login the user: ", oauthResult);
await this.isConnected(oauthResult.sessionString);
}
/** User already has a PKP, get it to sign a SIWE message */
else {
console.log("User is connecting to an existing pkp: ", oauthResult);
let pkpAuthenticated = await authenticatePkp({
ipfs: oauthResult.result.authMethod.ipfs,
address: oauthResult.result.pkp.address,
publicKey: oauthResult.result.pkp.publicKey,
accessToken: oauth.accessToken,
userId: oauth.userId,
authMethodType: 3
});
if(pkpAuthenticated.status == 200) {
this.session = pkpAuthenticated.session;
console.log("this.session", this.session);
did = this.session.did;
} else {
return {
status: 300,
result: "Couldn't authenticate PKP."
}
}
}
} else {
return {
status: 300,
error: oauthResult,
result: "Failed to generate PKP for Oauth method."
}
}
}
/** User is connecting with a web3 provider */
else {
/** Initialize some value */
let { authMethod, address } = await getAuthMethod(provider, chain);
/** Step 3: Create a new session for this did */
try {
/** Expire session in 90 days by default */
this.session = await DIDSession.authorize(
authMethod,
{
resources: [`ceramic://*`],
expiresInSecs: threeMonths
}
);
console.log("this.session", this.session);
did = this.session.did;
} catch(e) {
return {
status: 300,
error: e,
result: "Error creating a session for the DiD."
}
}
}
/** Step 3 bis: Store session in localStorage to re-use */
try {
const sessionString = this.session.serialize()
localStorage.setItem("ceramic-session", sessionString);
} catch(e) {
console.log("Error creating sessionString: " + e);
}
/** Step 4: Assign did to Ceramic object */
this.ceramic.did = did;
/** Step 5 (optional): Initialize the connection to Lit */
if(lit == true) {
let _userAuthSig = localStorage.getItem("lit-auth-signature-" + address);
if(!_userAuthSig || _userAuthSig == "" || _userAuthSig == undefined) {
try {
/** Generate the signature for Lit */
let resLitSig = await generateLitSignatureV2(provider, address, chain);
} catch(e) {
console.log("Error connecting to Lit network: " + e);
}
} else {
/** User is already connected, save current accoutn signature in lit-auth-signature object for easy retrieval */
localStorage.setItem("lit-auth-signature", _userAuthSig);
}
}
/** Step 6: Force index did to retrieve blockchain details automatically */
let _resDid = await forceIndexDid(this.session.id);
/** Step 7: Get user profile details */
let { data, error, status } = await this.getProfile(this.session.id);
/** Check if user has configured Lit */
let hasLit = false;
let hasLitSig = localStorage.getItem("lit-auth-signature");
if(hasLitSig) {
hasLit = true;
}
let details;
if(data) {
details = data.details;
details.hasLit = hasLit;
} else {
details = {
did: this.session.id,
hasLit: hasLit,
profile: null
}
}
/** Return result */
return {
status: 200,
did: this.session.id,
details: details,
result: "Success connecting to the DiD."
}
}
/** Automatically reconnects to a session stored in localStorage, returns false if there isn't any session in localStorage */
async isConnected(sessionString) {
await this.ceramic;
/** Check if an existing session is stored in localStorage */
if(!sessionString) {
sessionString = localStorage.getItem("ceramic-session");
if(!sessionString) {
return false;
}
}
/** Connect to Ceramic using the session previously stored */
try {
this.session = await DIDSession.fromSession(sessionString, null);
console.log("Reconnected to Ceramic automatically.");
} catch(e) {
console.log("Error reconnecting to Ceramic automatically: " + e);
return false;
}
/** Check if session is expired */
if(this.session.hasSession && this.session.isExpired) {
return false;
}
/** Session is still valid, connect */
try {
this.ceramic.did = this.session.did;
} catch(e) {
console.log("Error assigning did to Ceramic object: " + e);
return false;
}
/** Check with which network was this did create with */
let { address, chain, network } = getAddressFromDid(this.session.id);
switch (network) {
case "eip155":
this.chain = "ethereum";
break;
case "solana":
this.chain = "solana";
break;
}
/** Step 6: Force index did to retrieve blockchain details automatically */
let _resDid = await forceIndexDid(this.session.id);
/** Step 7: Get user profile details */
let { data, error, status } = await this.getProfile(this.session.id);
/** Check if user has configured Lit */
let hasLit = false;
if(typeof Storage !== "undefined") {
let hasLitSig = localStorage.getItem("lit-auth-signature");
if(hasLitSig) {
hasLit = true;
}
}
let details;
if(data) {
details = data.details;
details.hasLit = hasLit;
} else {
details = {
did: this.session.id,
hasLit: hasLit,
profile: null
}
}
/** Return result */
return {
status: 200,
did: this.session.id,
details: details,
result: "Success re-connecting to the DiD."
}
}
/** Connect to Lit only (usually in the case the lit signature wasn't generated in the first place) */
async connectLit(provider) {
console.log("Enter connectLit()");
let { address, chain, network } = getAddressFromDid(this.session.id);
console.log("Retrieved address from Did: ", address);
switch (network) {
case "eip155":
this.chain = "ethereum";
break;
case "solana":
this.chain = "solana";
break;
}
/** Require address */
if(!address) {
return {
status: 300,
result: "You must pass the address as a parameter in the connectLit function."
}
}
/** If provider isn't passed we use window.ethereum */
if(!provider) {
if(window.ethereum) {
console.log("Orbis SDK: You need to pass the provider as an argument in the `connectLit()` function. We will be using window.ethereum by default.");
provider = window.ethereum;
} else {
alert("An ethereum provider is required to proceed with the connection to Lit Protocol.");
return {
status: 300,
error: e,
result: "An ethereum provider is required to proceed with the connection to Lit Protocol."
}
}
}
/** Initialize the connection to Lit */
try {
/** Generate the signature for Lit */
let resLitSig = await generateLitSignatureV2(provider, address, this.chain);
/** Return success state */
return {
status: 200,
result: "Generated Lit signature for address: " + address
}
} catch(e) {
console.log("Error connecting to Lit network: " + e);
/** Return result */
return {
status: 300,
error: e,
result: "Error generating Lit signature."
}
}
}
/** Destroys the Ceramic session string stored in localStorage */
logout() {
try {
localStorage.removeItem("ceramic-session");
localStorage.removeItem("lit-auth-signature");
localStorage.removeItem("lit-auth-sol-signature");
return {
status: 200,
result: "Logged out from Orbis and Ceramic."
}
} catch(e) {
return {
status: 300,
error: e,
result: "Error logging out."
}
}
}
/** Authenticate a did with a seed */
async connectWithSeed(seed) {
/** Create the provider and resolve it */
const provider = new Ed25519Provider(seed)
const did = new DID({ provider, resolver: getResolver() })
/** Authenticate the Did */
await did.authenticate()
/** Assign did to Ceramic object */
this.ceramic.did = did;
this.session = {
did: did,
id: did.id
};
/** Return result */
return {
status: 200,
did: did.id,
details: null,
result: "Success connecting to the did:key."
}
}
/** Update user profile */
async updateProfile(content) {
/** Create a new stream with those details */
let result = await this.createTileDocument(content, ["orbis", "profile"], profileSchemaCommit);
return result;
}
/** Save the last read time for notifications for the connected user */
async setNotificationsReadTime(type, timestamp, context = null) {
let result;
if(context) {
/** Create tile with the settings details, including context */
result = await this.createTileDocument({
last_notifications_read_time: timestamp,
context: context
}, ["orbis", "settings", "notifications", type], notificationsReadSchemaCommit);
} else {
/** Create tile with the settings details */
result = await this.createTileDocument({last_notifications_read_time: timestamp}, ["orbis", "settings", "notifications", type], notificationsReadSchemaCommit);
}
/** Return confirmation results */
return result;
}
/** Connected users can share a new post following our schemas */
async createPost(content, encryptionRules = null) {
/** Make sure post isn't empty */
if(!content || !content.body || content.body == "" || content.body == undefined) {
return {
status: 300,
result: "You can't share an empty post."
}
}
/** Check if posts should be encrypted */
let _encryptedContent;
if(encryptionRules && encryptionRules.type) {
try {
/** Encrypt the content */
_encryptedContent = await encryptPost(content.body, encryptionRules);
/** Save encrypted content in `content` object to be stored in Ceramic */
content.encryptedBody = _encryptedContent;
content.body = "";
} catch(e) {
console.log("There was an error encrypting this post: ", e);
return {
status: 300,
error: e,
result: "There was an error encrypting this post."
}
}
}
/** Create tile with post schema */
let result = await this.createTileDocument(content, ["orbis", "post"], postSchemaCommit);
/** Return confirmation results */
return result;
}
/** Connected users can edit their post */
async editPost(stream_id, content, encryptionRules = null) {
/** Make sure post isn't empty */
if(!content || !content.body || content.body == "" || content.body == undefined) {
return {
status: 300,
result: "You can't share an empty post."
}
}
/** Check if posts should be encrypted */
let _encryptedContent;
if(encryptionRules) {
try {
/** Encrypt the content */
_encryptedContent = await encryptPost(content.body, encryptionRules);
/** Save encrypted content in `content` object to be stored in Ceramic */
content.encryptedBody = _encryptedContent;
content.body = "";
} catch(e) {
console.log("There was an error encrypting this post: ", e);
return {
status: 300,
error: e,
result: "There was an error encrypting this post."
}
}
}
/** Update tile with post schema */
let result = await this.updateTileDocument(stream_id, content, ["orbis", "post"], postSchemaCommit);
/** Return confirmation results */
return result;
}
/** Users can delete one of their post */
async deletePost(stream_id) {
/** Update tile with post schema */
let result = await this.updateTileDocument(stream_id, {is_deleted: true, body: ""}, ["orbis", "post"]);
/** Return confirmation results */
return result;
}
/** Connected users can react to an existing post */
async react(post_id, type) {
/** Require post_id */
if(!post_id || post_id == undefined) {
return {
status: 300,
result: "`post_id` is required when reacting to a post."
}
}
/** Require post_id */
if(!type || type == undefined) {
return {
status: 300,
result: "`type` is required when reacting to a post."
}
}
/** Create the content object */
let content = {
type: type,
post_id: post_id
}
/** Try to create the stream and return the result */
let result = await this.createTileDocument(content, ["orbis", "reaction"], reactionSchemaCommit);
return result;
}
/** Users can create or update a new group which can be used as a context when sharing posts */
async createGroup(content) {
/** Try to create a new Orbis group stream */
let result = await this.createTileDocument(content, ["orbis", "group"], groupSchemaCommit);
/** If group creation was successful we also create the first channel */
if(result.doc) {
/** Automatically join group created */
let joinRes = await this.setGroupMember(result.doc, true);
/**let channel_content = {
group_id: result.doc,
name: "general",
type: "feed"
};
/** Create a new stream for the channel
let channel_result = await this.createChannel(result.doc, channel_content);*/
/** Return result */
return result;
} else {
console.log("Error creating the initial channel.");
return {
status: 200,
group_id: result.doc,
result: "Group created without first channel."
}
}
}
/** Users can create a channel in a group */
async createChannel(group_id, content) {
if(!group_id || group_id == undefined) {
return {
status: 300,
result: "`group_id` is required when creating a channel."
}
}
/** Create channel object */
let result = await this.createTileDocument(content, ["orbis", "channel"], channelSchemaCommit);
return result;
}
/** User can update a channel */
async updateChannel(channel_id, content) {
if(!channel_id) {
console.log("`channel_id` is required to update a channel.");
return {
status: 300,
result: "`channel_id` is required to update a channel."
}
}
/** Update TileDocument with new content */
let result = await this.updateTileDocument(channel_id, content, ["orbis", "channel"], channelSchemaCommit);
return result;
}
/** Users can join or leave groups using this function */
async setGroupMember(group_id, active = true) {
/** Make sure group_id is available */
if(!group_id) {
console.log("`group_id` is required to join/leave a group.");
return {
status: 300,
result: "`group_id` is required to join/leave a group."
}
}
/** Create stream content */
let content = {
active: active,
group_id: group_id
}
/** Try to create the stream */
let result = await this.createTileDocument(content, ["orbis", "group_member"], groupMemberSchemaCommit);
return result;
}
/** Users can follow other users */
async setFollow(did, active = true) {
/** Make sure group_id is available */
if(!did) {
console.log("`did` is required to follow a user.");
return {
status: 300,
result: "`did` is required to follow a user."
}
}
/** Create stream content */
let content = {
active: active,
did: did
}
/** Try to create the stream */
let result = await this.createTileDocument(content, ["orbis", "follow"], followSchemaCommit);
return result;
}
/** User can update a group */
async updateGroup(stream_id, content) {
if(!stream_id) {
console.log("`stream_id` is required to update a group.");
return {
status: 300,
result: "`stream_id` is required to update a group."
}
}
/** Update TileDocument with new content */
let result = await this.updateTileDocument(stream_id, content, ["orbis", "group"], groupSchemaCommit);
return result;
}
/** Update a post */
async updatePost(stream_id, body) {
}
/** Create a new conversation */
async createConversation(content) {
/** Make sure recipients field isn't empty */
if(!content || !content.recipients || content.recipients.length == 0) {
return {
status: 300,
error: e,
result: "You can't create a conversations without recipients."
}
}
/** Add sender to the list of recipients to make sure it can decrypt the messages as well */
let _content = {...content};
let recipients = _content.recipients;
recipients.push(this.session.id);
/** Create tile */
let result = await this.createTileDocument(_content, ["orbis", "conversation"], conversationSchemaCommit);
/** Return confirmation results */
return result;
}
/** Send a direct message in a conversation */
async sendMessage(content) {
/** Require `message` */
if(!content || !content.body || content.body == undefined || content.body == "") {
return {
status: 300,
result: "`body` is required when sending a new message."
}
}
/** Require `conversation_id` */
if(!content || !content.conversation_id || content.conversation_id == undefined || content.conversation_id == "") {
return {
status: 300,
result: "`conversation_id` is required when sending a new message."
}
}
/** Retrieve list of recipients from conversation_id */
let conversation;
try {
conversation = await this.ceramic.loadStream(content.conversation_id);
} catch(e) {
return {
status: 300,
error: e,
result: "Couldn't load recipients from this `content.conversation_id`"
}
}
/** Make sure recipients array is valid */
if(!conversation.content?.recipients || conversation.content?.recipients.length <= 0) {
return {
status: 300,
error: "Recipients array is empty or doesn't exist. Please retry or create a new conversation.",
result: "Couldn't load recipients from this conversation id"
}
}
/** Try to encrypt content */
try {
let { encryptedMessage, encryptedMessageSolana } = await encryptDM(conversation.content.recipients, content.body);
/** Create content object */
let _content = {
conversation_id: content.conversation_id,
encryptedMessage: encryptedMessage,
encryptedMessageSolana: encryptedMessageSolana
}
/** Create tile for this message */
let result = await this.createTileDocument(_content, ["orbis", "message"], messageSchemaCommit);
return result;
} catch(e) {
return {
status: 300,
error: e,
result: "Couldn't encrypt DM."
}
}
}
/** Function to upload a media to Orbis */
async uploadMedia(file) {
console.log("Enter uploadMedia with: ", file);
if(!PINATA_API_KEY) {
console.log("You haven't setup your PINATA_API_KEY yet.");
return {
status: 300,
error: e,
result: "You haven't setup your PINATA_API_KEY yet."
}
}
if(!PINATA_SECRET_API_KEY) {
console.log("You haven't setup your PINATA_SECRET_API_KEY yet.");
return {
status: 300,
error: e,
result: "You haven't setup your PINATA_SECRET_API_KEY yet."
}
}
/** Try to resize media
try {
switch(file.type) {
case "image/gif":
console.log("This is a GIF, we can't resize it.");
break;
case "image/png":
mediaToUpload = await resizeFile(file, 1024, "PNG", "file");
break;
case "image/jepg":
mediaToUpload = await resizeFile(file, 1024, "JPEG", "file");
break;
default:
mediaToUpload = await resizeFile(file, 1024, "PNG", "file");
break;
}
} catch(e) {
return {