-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
4090 lines (4019 loc) · 160 KB
/
main.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
const axios = require('axios');
//const crypto = require('crypto');
const { channel } = require('diagnostics_channel');
const { version } = require('./package.json');
const fs = require('fs');
const { Console } = require('console');
const { waitForDebugger } = require('inspector');
var v5 = require('uuidv5');
const io = require("socket.io-client");
const { enabled } = require('debug/src/browser');
const { NostrWebLNProvider } = require("@getalby/sdk");
async function register({
registerHook,
registerSetting,
getRouter,
peertubeHelpers,
settingsManager,
storageManager,
registerVideoField,
registerExternalAuth,
registerClientRoute
}) {
const milliday = 24*60*60*1000;
registerSetting({
name: 'lightning-address',
label: 'Lightning address',
type: 'input',
descriptionHTML: 'This is a wallet for both the host split and host donations. Should be keysend compatible so getalby is a good choice',
private: false
})
registerSetting({
name: 'lightning-split',
label: 'Requires split for host',
default: '0',
type: 'input',
descriptionHTML: 'This will add a percentage split to any boostagrams or streams sent to videos hosted on this instance',
private: false
})
registerSetting({
name: 'lightning-tipVerb',
label: 'Verb to use for tipping',
type: 'input',
default: 'Boost',
descriptionHTML: 'Superchat, Zap, Boostagram, bits, spells, whatever your community would prefer.',
private: false
})
registerSetting({
name: 'alby-client-id',
label: 'Alby Api Client ID',
type: 'input',
descriptionHTML: 'This is the client ID obtained from Alby. Needed to allow users to authorize payments directly from PeerTube in any browser',
private: false
})
registerSetting({
name: 'alby-client-secret',
label: 'Alby API client secret',
type: 'input-password',
descriptionHTML: 'The client secret',
private: true
})
registerSetting({
name: 'boost-bot-account',
label: 'Boost bot account user name for posting cross app comments',
type: 'input',
descriptionHTML: '',
private: false
})
registerSetting({
name: 'boost-bot-password',
label: 'Password for boost bot',
type: 'input-password',
descriptionHTML: 'Needed to allow boost bot to post cross app comments',
private: true
})
registerSetting({
name: 'simpletip-token',
label: 'Simpletip token',
type: 'input-password',
descriptionHTML: 'used to authorize connections to the simpletip boost aggregator',
private: true
})
registerSetting({
name: 'legacy-enable',
default: true,
label: 'Enable legacy fiat tip services',
type: 'input-checkbox',
descriptionHTML: 'This will search support and description fields for various third party tip providers',
private: false
})
registerSetting({
name: 'keysend-enable',
default: true,
label: 'Enable Keysend lightning transactions',
type: 'input-checkbox',
descriptionHTML: 'This will enable keysend lightning tips, with boostagram meta data',
private: false
})
registerSetting({
name: 'lnurl-enable',
default: true,
label: 'Enable LNURL lightning wallet transactions',
type: 'input-checkbox',
descriptionHTML: 'This will enable LNURL lightning wallet transactions, lacks any metadata and is much more data intensive but supports less advanced lighting wallets',
private: false
})
registerSetting({
name: 'logon-enable',
default: false,
label: 'Enable logging in with alby wallet',
type: 'input-checkbox',
descriptionHTML: 'This will allow users to authenticate and create accounts using Alby Wallet credentials',
private: false
})
registerSetting({
name: 'debug-enable',
default: false,
label: 'Enable diagnostic log updates',
type: 'input-checkbox',
descriptionHTML: 'This will create more extensive logging of program state data both client and server side for finding and resolving errors ',
private: false
})
var timeCheck=new Date().getDay();
var checking=false;
//("⚡️⚡️⚡️⚡️ time stamp",timeCheck);
var base = await peertubeHelpers.config.getWebserverUrl();
var serverConfig = await peertubeHelpers.config.getServerConfig();
var hostName = serverConfig.instance.name;
var plugins = serverConfig.plugin.registered;
let lightningAddress = await settingsManager.getSetting("lightning-address");
let hostSplit = await settingsManager.getSetting("lightning-split");
if (!lightningAddress) {
console.log("⚡️⚡️No wallet configured for system");
}
if ((!hostSplit || !(hostSplit>0)) || !lightningAddress) {
hostSplit = 0;
} else {
hostSplit = parseInt(hostSplit);
if (!(hostSplit > 0 && hostSplit <= 100)) {
console.log("⚡️⚡️⚡️⚡️Invalid value for hostsplit", hostSplit);
hostSplit = 1;
}
}
let tipVerb = await settingsManager.getSetting('lightning-tipVerb');
let enableLegacy = await settingsManager.getSetting("legacy-enable");
let enableKeysend = await settingsManager.getSetting("keysend-enable");
let enableLnurl = await settingsManager.getSetting("lnurl-enable");
let enableDebug = await settingsManager.getSetting("debug-enable");
let enableAlbyAuth = await settingsManager.getSetting("logon-enable");
let client_id = await settingsManager.getSetting("alby-client-id");
let client_secret = await settingsManager.getSetting("alby-client-secret");
let botAccount = await settingsManager.getSetting("boost-bot-account");
let botPassword = await settingsManager.getSetting("boost-bot-password");
let simpletipToken = await settingsManager.getSetting("simpletip-token");
let botToken;
if (botAccount && botPassword) {
try {
botToken = await getPeerTubeToken(botAccount, botPassword);
} catch (err){
console.log("⚡️⚡️⚡️⚡️ error attempting to log bot on",err);
}
}
console.log("⚡️⚡️⚡️⚡️ Lightning plugin started", enableDebug,version);
let hostParts= base.split('//');
let hostDomain = hostParts.pop();
if (enableDebug) {
console.log("⚡️⚡️ server settings loaded", hostName, hostDomain, base, hostSplit, lightningAddress,serverConfig.plugin.registered);
}
let hostWalletData = {};
let dirtyHack;
if (enableKeysend || enableLnurl) {
if (lightningAddress) {
hostWalletData.address = lightningAddress;
hostWalletData.name = lightningAddress;
if (enableKeysend) {
let hostKeysendData = await getKeysendInfo(lightningAddress);
if (!hostKeysendData) {
console.log("⚡️⚡️⚡️⚡️failed to get system wallet data from provider", lightningAddress);
} else {
hostWalletData.keysend = hostKeysendData;
}
}
if (hostSplit >= 0 && hostSplit <= 100) {
hostWalletData.split = parseInt(hostSplit);
}
hostWalletData.fee = true;
hostWalletData.name = hostName;
}
}
let podcast2;
let hiveTube;
let podPing;
let liveChat;
for (var plugin of plugins){
switch (plugin.npmName){
case "peertube-plugin-podcast2" : podcast2=true;
break;
case "peertube-plugin-hive-tube" : hiveTube=true;
break;
case "peertube-plugin-podping" : podPing = true;
break;
case "peertube-plugin-livechat" : liveChat = true;
break;
}
}
let invoices = [];
registerHook({
target: 'filter:api.video-threads.list.result',
handler: async (result,params ) => {
//console.log("⚡️⚡️⚡️⚡️ threads", params,result);
return(result);
}
})
let hiveAuthorized, albyAuthorized;
registerHook({
target: 'action:activity-pub.remote-video.updated',
handler: async (video) => {
if (checking == true){
console.log("⚡️⚡️ already checking")
return video;
}
checking =true;
var check=new Date().getDay();
if (timeCheck != check) {
timeCheck = check;
await doSubscriptions();
} else {
}
checking=false;
return video
}
})
registerHook({
target: 'action:api.video-channel.created',
handler: async (videoChannel) => {
let crap = videoChannel;
console.log("⚡️⚡️ channel created", videoChannel.videoChannel.dataValues,"oahahaha", videoChannel.videoChannel.dataValues.id);
console.log("⚡️⚡️ channel created 2",videoChannel.videoChannel);
console.log("⚡️⚡️ channel created 3",videoChannel.videoChannel.Actor);
console.log("⚡️⚡️ channel created 4",videoChannel.videoChannel.Actor.preferredUsername);
console
let accountId = videoChannel.videoChannel.dataValues.accountId;
let channelId = videoChannel.videoChannel.dataValues.id;
let channelName = videoChannel.videoChannel.Actor.preferredUsername;
console.log("⚡️⚡️ game for it",accountId,channelId,channelName)
let accountApi =base + `/api/v1/users/${accountId}`;
let channelApi =base + `/api/v1/video-channels/${channelName}`;
console.log("⚡️⚡️ down for it",accountApi,channelApi);
let channelInfo;
try {
channelInfo = await axios.get(channelApi);
} catch (e) {
console.log("⚡️⚡️ had error getting channel info for new channel")
}
if (channelInfo && channelInfo.data){
console.log("⚡️⚡️ got channel info for new channel",channelInfo.data);
}
let userName;
if (channelInfo && channelInfo.data && channelInfo.data.ownerAccount){
userName = channelInfo.data.ownerAccount.name;
}
let v4vsettings,storedWallet;
if (userName){
v4vsettings= await storageManager.getData('v4vsettings-'+userName.replace(/\./g, "-"));
}
if (!v4vsettings && userName){
//if (userName){
console.log("⚡️⚡️⚡️⚡️ no saved v4v settings, checking for wallet info");
storedWallet = await storageManager.getData("lightning-" + userName.replace(/\./g, "-"));
}
console.log("⚡️⚡️⚡️⚡️v4v",v4vsettings,"wallet",storedWallet);
let lightningAddress;
if (v4vsettings && v4vsettings.boostBack){
lightningAddress = v4vsettings.boostBack;
}
if (!lightningAddress && storedWallet && storedWallet.address){
lightningAddress = storedWallet.address;
}
let createApi = base + `/plugins/lightning/router/createsplit?channel=` + channelName + `&splitaddress=` + lightningAddress + `&name=` + userName;
let createResult;
try{
createResult = await axios.get(createApi);
} catch (e){
console.log("failed to create split for new channel",createApi);
}
}
})
registerHook({
target: 'filter:feed.podcast.channel.create-custom-tags.result',
handler: async (result, params) => {
// { video: VideoChannelModel }
const { videoChannel } = params
if (params && params.videoChannel && params.videoChannel.dataValues && params.videoChannel.dataValues.Actor){
var channel = params.videoChannel.dataValues.Actor.dataValues.preferredUsername;
}
var storedSplitData = await getSavedSplit(channel);
var blocks = []
if (storedSplitData) {
for (var split of storedSplitData) {
let newBlock = {};
newBlock.name = split.name;
newBlock.type = "node";
newBlock.split = split.split;
if (split.address && split.address != "custom"){
newBlock.keysend = split.address;
}
if (split.fee) {
newBlock.fee = split.fee;
}
if (split.keysend){
newBlock.address = split.keysend.pubkey;
if (Array.isArray(split.keysend.customData) && split.keysend.customData[0] && split.keysend.customData[0].customKey) {
newBlock.customKey = split.keysend.customData[0].customKey;
newBlock.customValue = split.keysend.customData[0].customValue;
}
}
blockWrap = {};
blockWrap.name = "podcast:valueRecipient"
blockWrap.attributes = newBlock
blocks.push(blockWrap);
}
} else {
console.log("⚡️⚡️ no split info for channel", channel);
}
if (blocks.length > 0) {
let podreturn = [
{
name: "podcast:value",
attributes: {
"type": "lightning",
"method": "keysend",
"suggested": "0.00000005000"
},
value: blocks,
}
];
if (enableDebug) {
console.log("⚡️⚡️ channel level tags to add", podreturn);
}
return result.concat(podreturn)
}
}
})
registerHook({
target: 'action:live.video.state.updated',
handler: async (video) => {
if (enableDebug){
if (video && video.video){
console.log("⚡️⚡️ live video updated",video.video.uuid,video.video.state);
} else {
console.log("⚡️⚡️ video.video missing from action",video.dataValues,video.DataModel,video.video);
return;
}
}
if (video.video.state !=1){
console.log("⚡️⚡️ live stream ended");
return;
}
let liveValue;
try {
liveValue = await storageManager.getData("livevalue-" + video.video.uuid);
console.log("⚡️⚡️got live value", liveValue, "for",video.video.uuid);
} catch {
console.log("⚡️⚡️ hard failed getting lightning live value",video, video.video.uuid);
}
if (liveValue){
const socket = io(liveValue);
socket.on("connect", () => {
console.log("⚡️⚡️\n⚡️⚡️Connected to socket!\n⚡️⚡️");
});
socket.on('remoteValue', (data) => {
console.log(`⚡️⚡️\n⚡️⚡️message from socket to socket! \n⚡️⚡️`);
console.log(data.value);
storageManager.storeData("liveremotesplit-"+video.video.uuid,data);
});
}
return;
}
})
// For item level value tags
registerHook({
target: 'filter:feed.podcast.video.create-custom-tags.result',
handler: async (result, params) => {
// { video: VideoModel, liveItem: boolean }
const { video, liveItem } = params
//console.log("⚡️⚡️⚡️⚡️ initial video values ⚡️⚡️⚡️⚡️",result,params.video.VideoChannel,params.video.VideoChannel.Actor);
// console.log("⚡️⚡️⚡️⚡️ initial video values 2⚡️⚡️⚡️⚡️",params,params.video.VideoChannel.dataValues);
if (liveItem) {
}
var videoUuid = params.video.dataValues.uuid;
var storedSplitData = await getSavedSplit(videoUuid);
if (!storedSplitData){
storedSplitData = await getSavedSplit(params.video.VideoChannel.Actor.preferredUsername);
}
let remoteSplitData = await getRemoteSplit(videoUuid);
/*if (remoteSplitData && !storedSplitData){
console.log(console.log("⚡️⚡️⚡️⚡️ remote split without stored split, param data",params,params.video.videoChannel));
}
*/
if (remoteSplitData && !storedSplitData){
console.log("⚡️⚡️⚡️⚡️ need to get channel split because apps are whack",params.video.videoChannel);
}
var blocks = []
//var videoJSON = await peertubeHelpers.videos.loadByIdOrUUID(videoUuid);
//console.log("⚡️⚡️⚡️⚡️ video helper json",videoJSON)
if (storedSplitData) {
for (var split of storedSplitData) {
let newBlock = {};
newBlock.name = split.name;
newBlock.type = "node";
if (split.address && split.address !="custom"){
newBlock.keysend = split.address
}
newBlock.split = split.split;
if (split.fee) {
newBlock.fee = split.fee;
}
newBlock.address = split.keysend.pubkey;
if (split.keysend.customData[0] && split.keysend.customData[0].customKey) {
newBlock.customKey = split.keysend.customData[0].customKey;
newBlock.customValue = split.keysend.customData[0].customValue;
}
blockWrap = {};
blockWrap.name = "podcast:valueRecipient"
blockWrap.attributes = newBlock
blocks.push(blockWrap);
}
}
let remoteSplitBlock= [];
if (remoteSplitData){
//console.log("⚡️⚡️⚡️⚡️ remote split data",remoteSplitData);
for (var valueSplit of remoteSplitData.blocks){
if (!valueSplit){
continue;
}
//console.log("⚡️⚡️⚡️⚡️ remote split ",valueSplit.title,valueSplit.feedGuid,valueSplit.itemGuid,valueSplit.duration,valueSplit.startTime)
if (valueSplit.startTime && valueSplit.duration){
let remoteSplit ={};
remoteSplit.name = "podcast:valueTimeSplit"
remoteSplit.attributes={
"startTime": valueSplit.startTime,
"remotePercentage": valueSplit.settings.split,
"duration": valueSplit.duration,
}
if (valueSplit.feedGuid && valueSplit.itemGuid){
let remoteItem={};
remoteItem.name="podcast:remoteItem"
remoteItem.attributes={
"feedGuid": valueSplit.feedGuid,
"itemGuid": valueSplit.itemGuid
}
let hack = [];
hack.push(remoteItem);
//console.log("hack",hack);
remoteSplit.value = hack;
}
blocks.push(remoteSplit);
}
}
//console.log("⚡️⚡️⚡️⚡️ remote split",blocks);
}
let customObjects = [];
let valueBlock
if (blocks.length > 0) {
valueBlock = {
name: "podcast:value",
attributes: {
"type": "lightning",
"method": "keysend",
"suggested": "0.00000005000"
},
value: blocks,
}
//console.log("⚡️⚡️ value block",JSON.stringify(valueBlock, null, 4));
//console.log("⚡️⚡️ blocks",JSON.stringify(blocks, null, 4));
customObjects.push(valueBlock);
dirtyHack=valueBlock;
}
if (liveItem){
let liveValue;
try {
liveValue = await storageManager.getData("livevalue-" + videoUuid);
} catch {
console.log("⚡️⚡️ hard failed getting lightning live value");
}
if (liveValue){
let liveValueTag = {
name: "podcast:liveValue",
attributes: {
"uri": liveValue,
protocol: "socket.io",
}
}
customObjects.push(liveValueTag);
}
}
return result.concat(customObjects);
}
})
/*
registerHook({
target: 'action:api.video.updated',
handler: ({ video, body }) => {
if (enableDebug) {
console.log("⚡️⚡️updating video\n",body.pluginData);
}
//if (!body.pluginData) return
if (body.pluginData){
const seasonNode = body.pluginData['seasonnode'];
const seasonName = body.pluginData['seasonname'];
const episodeNode = body.pluginData['episodenode'];
const episodeName = body.pluginData['episodename'];
const chapters = body.pluginData['chapters'];
const itemTxt = body.pluginData['itemtxt'];
}
//if (!value) return
try {
if (seasonNode){
storageManager.storeData('seasonnode-' + video.id, seasonNode)
}
if (seasonName){
storageManager.storeData('seasonname-' + video.id, seasonName)
}
if (episodeNode){
storageManager.storeData('episodenode-' + video.id, episodeNode)
}
if (episodeName){
storageManager.storeData('episodename-' + video.id, episodeName)
}
if (chapters) {
storageManager.storeData('chapters-' + video.id, chapters)
}
if (itemTxt){
storageManager.storeData('itemtxt-' + video.id, itemTxt)
}
} catch (err) {
console.log("⚡️⚡️error updating video plugin data\n",err,body);
}
return;
}
})
*/
const router = getRouter();
//TODO normalize behavior for account and address
router.use('/walletinfo', async (req, res) => {
let now = Date.now();
if (enableDebug) {
console.log("⚡️⚡️Request for wallet info\n", req.query)
}
if (!enableLnurl && !enableKeysend) {
return res.status(503).send("No Lightning services enabled for plug-in");
}
let foundLightningAddress;
let account=req.query.account;
let address=req.query.address;
if (enableDebug) {
console.log("⚡️⚡️Request for wallet info", account,address,foundLightningAddress)
}
if (account) {
var storedWallet
storedWallet = await storageManager.getData("lightning-" + account.replace(/\./g, "-"));
if (enableDebug) {
console.log("⚡️⚡️stored walled returned", storedWallet)
}
if (storedWallet && storedWallet.retrieved && !req.query.refresh){
let timePassed = (now - storedWallet.retrieved)/milliday;
let cacheDate = new Date(storedWallet.retrieved);
if (enableDebug){
console.log(`⚡️⚡️ saved wallet ${timePassed} days ago on ${cacheDate.toLocaleDateString()}`);
}
if (timePassed < 1){
if (enableDebug){
console.log(`⚡️⚡️ returning cached wallet`,storedWallet);
}
return res.status(200).send(storedWallet);
} else {
if (enableDebug){
console.log(`⚡️⚡️ saved wallet data expired after ${timePassed} days`);
}
}
}
if (storedWallet && storedWallet.address) {
if (enableDebug) {
console.log("⚡️⚡️ stored wallet data expired, updating from existing lightning address", account, storedWallet);
}
let newWallet = await createWalletObject(storedWallet.address);
if (newWallet.keysend){
saveWellKnown(account, newWallet.keysend);
}
if (newWallet && newWallet.lnurl){
saveWellKnownLnurl(account, newWallet.lnurl);
}
if (enableDebug){
console.log(`⚡️⚡️ storing updatyed wallet`,account,newWallet);
}
newWallet.retrieved = Date.now();
await storageManager.storeData("lightning-" + account.replace(/\./g, "-"), newWallet);
return res.status(200).send(newWallet);
} else {
if (enableDebug) {
console.log("⚡️⚡️ unable to get wallet info for stored address", req.query,storedWallet);
}/*
if (storedWallet){
return res.status(404).send();
}
*/
}
let parts = account.split("@")
if (enableDebug) {
console.log("⚡️⚡️ account parts", parts)
}
if (parts.length >1){
let remoteWalletInfoApi = `https://${parts[1]}/plugins/lightning/router/walletinfo?account=${parts[0]}`;
if (enableDebug){
console.log("⚡️⚡️checking for remote instance wallet info via plugin",remoteWalletInfoApi);
}
let remoteWalletInfo;
try {
remoteWalletInfo = await axios.get(remoteWalletInfoApi);
} catch (e){
console.log("⚡️⚡️ error requesting remote wallet info",e);
}
if (remoteWalletInfo && remoteWalletInfo.data){
if (enableDebug) {
console.log("⚡️⚡️got remote wallet info via peertube api",remoteWalletInfoApi, remoteWalletInfo.data.length);
}
if (remoteWalletInfo.data.lnurl || remoteWalletInfo.data.keysend){
console.log("⚡️⚡️verified wallet config has some lightning data, saving");
remoteWalletInfo.data.retrieved = Date.now();
await storageManager.storeData("lightning-" + account.replace(/\./g, "-"), remoteWalletInfo.data);
return res.status(200).send(remoteWalletInfo.data);
} else {
console.log("⚡️⚡️peertube plugin response fails to pass validation");
}
}
}
if (parts.length > 1) {
apiCall = "https://" + parts[1] + "/api/v1/accounts/" + parts[0];
if (enableDebug) {
console.log("⚡️⚡️getting remote account info via API to search for address",apiCall);
}
} else {
apiCall = base + "/api/v1/accounts/" + account;
if (enableDebug) {
console.log("⚡️⚡️getting local account info via peertube api to search for address",apiCall);
}
}
let accountData;
try {
accountData = await axios.get(apiCall);
} catch (err) {
console.log("⚡️⚡️hard failure pulling acount information", apiCall, err);
}
if (!accountData) {
//hack for mastardon's lame api
apiCall = "https://" + parts[1] + "/api/v1/accounts/lookup?acct=" + parts[0]
try {
accountData = await axios.get(apiCall);
} catch (err) {
console.log("⚡️⚡️errored trying to pull information from mastodon", apiCall, err);
}
}
if (accountData) {
let remoteAccount = accountData.data
if (enableDebug) {
//console.log("⚡️⚡️account to search for address", account,account.description,account.fields,remoteAccount.note);///////////////
console.log(`⚡️⚡️ working on account ${account}\n⚡️⚡️ Description ${account.description} \n⚡️⚡️ fields ${account.fields}\n⚡️⚡️ note ${account.note}\n`)
}
//console.log("⚡️⚡️ description to search",remoteAccount.description);
if (remoteAccount.description) {
foundLightningAddress = await findLightningAddress(remoteAccount.description);
}
//console.log("⚡️⚡️ fields to search",remoteAccount.fields);
if (!foundLightningAddress && remoteAccount.fields) {
for (var field of remoteAccount.fields) {
//console.log("⚡️⚡️ checking",field.name.charCodeAt(0),'⚡️'.charCodeAt(0));
if (field.name.toLowerCase() === "lightning address" || field.name.toLowerCase() == "lud16" || field.name.charCodeAt(0) == 9889) {
foundLightningAddress = field.value;
} else {
//console.log("⚡️⚡️ no match",` >${field.name}< != >⚡️<`);
}
}
}
console.log("⚡️⚡️ notes to search",remoteAccount.note);
if (!foundLightningAddress && remoteAccount.note) {
foundLightningAddress = await findLightningAddress(remoteAccount.note);
}
if (!foundLightningAddress){
console.log("⚡️⚡️ no lightning address found");
//return res.status(420).send();
//foundLightningAddress = account
}
console.log("⚡️⚡️lightning address found", foundLightningAddress);
let newWallet = await createWalletObject(foundLightningAddress);
if (newWallet && (newWallet.lnurl || newWallet.keysend)){
if (newWallet.keysend){
saveWellKnown(account, newWallet.keysend);
}
if (newWallet.lnurl){
saveWellKnownLnurl(account, newWallet.lnurl);
}
console.log("⚡️⚡️wallet being saved and returned", newWallet);///////////////
newWallet.retrieved = Date.now();
await storageManager.storeData("lightning-" + account.replace(/\./g, "-"), newWallet);
return res.status(200).send(newWallet);
} else {
console.log("⚡️⚡️new wallet failed validation", newWallet);///////////////
}
}
if (enableDebug) {
console.log("⚡️⚡️failed to find address for account,", account,address);///////////////
}
if (!address){
//see if ap account is also a lightning address account/cache
address = account;
foundLightningAddress = null;
}
}
if (address) {
let storedWallet = await storageManager.getData("lightning-" + address.replace(/\./g, "-"));
if (storedWallet && !req.query.refresh){
let timePassed = (now - storedWallet.retrieved)/milliday;
if (enableDebug) {
console.log(`⚡️⚡️ found cached wallet data for ${address} from ${timePassed} days ago`,storedWallet)
}
if (timePassed < 1){
return res.status(200).send(storedWallet);
}
}
let newWallet = await createWalletObject(address);
if (enableDebug) {
console.log(`⚡️⚡️ created new wallet`,newWallet)
}
await storageManager.storeData("lightning-" + address.replace(/\./g, "-"), newWallet);
if (newWallet && (newWallet.lnurl || newWallet.keysend)){
return res.status(200).send(newWallet);
}
return res.status(420).send(`Error creating wallet info object for ${address}`);
}
})
router.use('/dirtyhack', async (req, res) => {
dirtyHack = `alby ${albyAuthorized} hive ${hiveAuthorized} hivetube ${hiveTube} podcast2 ${podcast2} podping ${podPing} livechat ${liveChat}`+dirtyHack;
console.log("⚡️⚡️⚡️⚡️ dirty hack",dirtyHack,req.query);
if (req.query.cp){
console.log("⚡️⚡️⚡️⚡️ clearing patronage paid days");
let subscriptions = await storageManager.getData('subscriptions');
let list = [];
if (subscriptions){
for (var sub of subscriptions){
sub.paiddays=0;
}
storageManager.storeData("subscriptions", subscriptions);
return res.status(200).send(subscriptions);
}
}
if (req.query.sub){
console.log("⚡️⚡️⚡️⚡️ patronage list");
let subscriptions = await storageManager.getData('subscriptions');
let list = [];
if (subscriptions){
for (var sub of subscriptions){
console.log(sub);
if (sub.public){
list.push(sub);
}
let startDate=new Date(sub.startdate);
let paidDate = sub.startdate+(sub.paiddays*milliday);
let today = Date.now();
let unPaidTime = today-paidDate;
let payDays = parseInt(Math.floor(unPaidTime / milliday));
let payStart = new Date(paidDate);
let payEnd = new Date(paidDate+(milliday*payDays));
console.log("⚡️payStart",payStart.toLocaleDateString(),"⚡️pay end",payEnd.toLocaleDateString(),"⚡️pay days",payDays);
console.log("⚡️paidDate",paidDate,"⚡️today",today,"⚡️unpaidTime",unPaidTime);
console.log("⚡️start date",startDate,"⚡️paid days",sub.paiddays,"⚡️confetti",sub.pendingconfetti);
}
//storageManager.storeData("subscriptions", subscriptions);
return res.status(200).send(list);
}
}
if (req.query.dosub){
doSubscriptions();
}
if (req.query.splitkit){
let remoteSplitData = await getRemoteSplit(req.query.splitkit);
let remoteSplitBlock= [];
if (remoteSplitData){
console.log("⚡️⚡️⚡️⚡️ remote split data",remoteSplitData);
for (var valueSplit of remoteSplitData.blocks){
console.log("⚡️⚡️⚡️⚡️ remote split ",valueSplit.title,valueSplit.feedGuid,valueSplit.itemGuid,valueSplit.duration,valueSplit.startTime)
if (valueSplit.startTime && valueSplit.duration){
let remoteSplit ={};
remoteSplit.name ="podcast:valueTimeSplit"
remoteSplit.startTime=valueSplit.startTime;
remoteSplit.remotePercentage= valueSplit.settings.split;
remoteSplit.duration=valueSplit.duration;
if (valueSplit.feedGuid && valueSplit.itemGuid){
let remoteItem={};
remoteItem.name = "podcast:remoteItem";
remoteItem.feedGuid = valueSplit.feedGuid;
remoteItem.itemGuid = valueSplit.itemGuid;
remoteSplit.remoteItem = remoteItem;
}
remoteSplitBlock.push(remoteSplit);
}
}
dirtyHack =remoteSplitData;
let split = dirtyHack.blocks[1];
console.log("remotesplit",remoteSplitData);
console.log("split",split);
console.log("⚡️⚡️⚡️⚡️ remote split",remoteSplitBlock);
}
}
if (req.query.status){
let wow = `Statuses:\nid:${client_id}\nlogon enabled:${enableAlbyAuth}\nkey length:${client_secret.length}`;
return res.status(200).send(wow);
}
if (req.query.nwc){
const authClient = new auth.OAuth2User({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
callback: "http://localhost:8080/callback",
scopes: [
"invoices:read",
"account:read",
"balance:read",
"invoices:create",
"invoices:read",
"payments:send",
],
token: {
access_token: undefined,
refresh_token: undefined,
expires_at: undefined,
}, // initialize with existing token
});
}
if (req.query.account){
let albyData = await storageManager.getData("alby-" + req.query.account.replace(/\./g, "-"));
let hiveData = await storageManager.getData("hive-" + req.query.account.replace(/\./g, "-"));
let walletData = await storageManager.getData("wallet-" + req.query.account.replace(/\./g, "-"));
let lightData = await storageManager.getData("lightning-" + req.query.account.replace(/\./g, "-"));
let v4vData = await storageManager.getData("v4vsettings-" + req.query.account.replace(/\./g, "-"));
console.log("⚡️⚡️alby",albyData, "hive", hiveData, "wallet",walletData,"light",lightData,"v4v", v4vData);
}
return res.status(200).send(dirtyHack);
});
router.use('/setWallet', async (req, res) => {
if (enableDebug) {
console.log("⚡️⚡️wallet setting request", req.query);
}
let user = await peertubeHelpers.user.getAuthUser(res);
if (user && user.dataValues && req.query.address) {
let userName = user.dataValues.username;
if (enableDebug) {
console.log("███ got authorized peertube user", user.dataValues.username);
}
if (enableDebug) {
console.log("⚡️⚡️⚡️⚡️ user", userName, "address:",req.query.address);
}
let newWallet = await createWalletObject(req.query.address);
if (newWallet.keysend){
saveWellKnown(userName, newWallet.keysend);
}
if (newWallet && newWallet.lnurl){
saveWellKnownLnurl(userName, newWallet.lnurl);
}
storageManager.storeData("lightning-" + userName.replace(/\./g, "-"), newWallet);
return res.status(200).send(newWallet);
}
return res.status(420).send();
/* disabling pubkey/custom value for now
if (!req.query.key) {
return res.status(400).send("missing key");
}
if (req.query.address) {
let walletInfo = getKeysendInfo(req.query.address);
if (walletInfo) {
let lightning = {};
lightning.address = req.query.address;
lightning.data = newData
console.log("⚡️⚡️saving wallet data", req.query.key, lightning);
//storageManager.storeData("lightning" + "-" + req.query.key, lightning);
return res.status(200).send(lightning);
} else {
console.log("failed to get wallet info for provided address", req.query.address);
return res.status(400).send();
}
}
if (!req.query.pubkey) {
return res.status(400).send("missing pubkey");
}
if (!req.query.tag) {
return res.status(400).send("missing tag");
}
let newData = {
status: "OK",
tag: req.query.tag,
pubkey: req.query.pubkey,
}
if (req.query.customvalue) {
if (!req.query.customkey) {
req.query.customkey = "696969";
}
let customData = {
customKey: req.query.customkey,
customValue: req.query.customvalue,
}
let customDataArray = [];
customDataArray.push(customData);
newData.customData = customDataArray;
}
let lightning = {};
lightning.data = newData
console.log("⚡️⚡️saving wallet data", req.query.key, lightning);
//storageManager.storeData("lightning" + "-" + req.query.key, lightning);
return res.status(200).send(lightning);
*/
})
router.use(`/podcast2`, async (req,res) => {
let original = `${req.protocol}://${req.get('host')}${req.originalUrl}`
let redirect = original.replace("lightning","podcast2");
res.set('location', redirect);
return res.status(301).send()
})
router.use(`/nwcallback`, async (req,res) => {
console.log("⚡️⚡️ callback from nwc", req.query);
return res.status(301).send()
})
router.use('/getinvoice', async (req, res) => {
// console.log(req);
if (enableDebug) {
console.log("⚡️⚡️ getting lnurl invoice", req.query,req.body);
}
if (!enableLnurl) {
return res.status(503).send();
}
let message = encodeURIComponent(req.query.message);
let invoiceRequest = req.query.callback + "?amount=" + req.query.amount + "&comment=" + message;
//console.log("⚡️⚡️invoice request url", invoiceRequest);
let result;
try {
result = await axios.get(invoiceRequest);
} catch (err) {
console.log("⚡️⚡️failed to get invoice", err);
return res.status(400).send(err);
}
//console.log("⚡️⚡️ Invoice data",result.data);
return res.status(200).send(result.data);
})
router.use('/getfeedid', async (req, res) => {
if (enableDebug) {
console.log("⚡️⚡️getting feed id", req.query);
}
let channel = req.query.channel;
if (!channel) {
return res.status(420).send("no channel in feed id request");
}
let feed;
let parts = channel.split('@');
if (parts.length > 1) {
return res.status(420).send("remote channel returned no feed id");
}
if (channel) {
try {
feed = await storageManager.getData("podcast" + "-" + channel)
} catch (err) {
console.log("⚡️⚡️error getting feedid", channel);
}
}
//console.log("⚡️⚡️ feed", feed);
if (feed) {
return res.status(200).send(feed.toString());
} else {
return res.status(400).send("no feed id found for requested channel");
}
})
router.use('/setfeedid', async (req, res) => {
if (enableDebug) {
console.log("⚡️⚡️setting feed id", req.query);
}
let channel = req.query.channel;
let feedID = req.query.feedid;
if (channel) {
try {
await storageManager.storeData("podcast" + "-" + channel, feedID);
return res.status(200).send();
} catch (err) {
console.log("⚡️⚡️ error storing feedid", channel, feedID);
return res.status(400).send();