-
-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathinternalApi.js
1203 lines (847 loc) · 30.7 KB
/
internalApi.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
/** UNFINISHED **/
/* eslint-disable no-unused-vars */
const bluebird = require('bluebird');
const Promise = require('bluebird');
const request = bluebird.promisifyAll(require('request'), { multiArgs: true });
const graph = require('fbgraph');
const Twit = require('twit');
const formidable = require('formidable');
const path = require('path');
const multer = require('multer');
const fs = require('fs-extra');
const multiparty = require('multiparty');
var B2 = require('easy-backblaze');
const _ = require('lodash');
var randomstring = require('randomstring');
var ffmpeg = require('fluent-ffmpeg');
var mongoose = require('mongoose');
var concat = require('concat-files');
var Busboy = require('busboy');
const mkdirp = Promise.promisifyAll(require('mkdirp'));
const mv = require('mv');
const FileType = require('file-type');
const srt2vtt = Promise.promisifyAll(require('srt2vtt'));
const backblaze = require('../../lib/uploading/backblaze');
const domainNameAndTLD = process.env.DOMAIN_NAME_AND_TLD;
const createAdminAction = require('../../lib/administration/createAdminAction');
const { saveAndServeFilesDirectory } = require('../../lib/helpers/settings');
// const stripe = require('stripe')(process.env.STRIPE_SKEY);
// const twilio = require('twilio')(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
// const paypal = require('paypal-rest-sdk');
// const lob = require('lob')(process.env.LOB_KEY);
const javascriptTimeAgo = require('javascript-time-ago');
javascriptTimeAgo.locale(require('javascript-time-ago/locales/en'));
require('javascript-time-ago/intl-messageformat-global');
require('intl-messageformat/dist/locale-data/en');
const timeAgoEnglish = new javascriptTimeAgo('en-US');
if(process.env.THUMBNAIL_SERVER){
console.log(`THUMBNAIL SERVER: ${process.env.THUMBNAIL_SERVER}`);
}
const frontendServer = process.env.FRONTEND_SERVER || '';
const createNotification = require('../../lib/helpers/notifications');
// models
const Upload = require('../../models/index').Upload;
const User = require('../../models/index').User;
const Comment = require('../../models/index').Comment;
const React = require('../../models/index').React;
const Subscription = require('../../models/index').Subscription;
const Notification = require('../../models/index').Notification;
const CreditAction = require('../../models/index').CreditAction;
const Report = require('../../models/index').Report;
const LastWatchedTime = require('../../models/index').LastWatchedTime;
const PushEndpoint = require('../../models/index').PushEndpoint;
const PushSubscription = require('../../models/index').PushSubscription;
const getMediaType = require('../../lib/uploading/media');
const pushNotificationLibrary = require('../../lib/mediaPlayer/pushNotification');
console.log(pushNotificationLibrary);
const ffmpegHelper = require('../../lib/uploading/ffmpeg');
var resumable = require('../../lib/uploading/resumable.js')(__dirname + '/upload');
const accountId = process.env.backBlazeId;
const applicationKey = process.env.backBlazeAppKey;
const bucket = process.env.BACKBLAZE_BUCKET;
var b2 = Promise.promisifyAll(new B2(accountId, applicationKey));
let hostPrepend = '';
if(process.env.NODE_ENV == 'production') hostPrepend = `https://${domainNameAndTLD}`;
var appDir = path.dirname(require.main.filename);
let uploadServer;
// development with no upload server
if(process.env.NODE_ENV !== 'production' && !process.env.UPLOAD_SERVER){
uploadServer = '/uploads';
// development with an upload server
} else if(process.env.NODE_ENV !== 'production' && process.env.UPLOAD_SERVER){
// otherwise load the upload's uploadServer
uploadServer = `https://${process.env.UPLOAD_SERVER}.${domainNameAndTLD}/uploads`;
} else {
uploadServer = `https://${process.env.UPLOAD_SERVER}.${domainNameAndTLD}/uploads`;
}
async function updateUsersUnreadSubscriptions(user){
const subscriptions = await Subscription.find({ subscribedToUser: user._id, active: true });
for(const subscription of subscriptions){
let subscribingUser = await User.findOne({ _id: subscription.subscribingUser });
subscribingUser.unseenSubscriptionUploads = subscribingUser.unseenSubscriptionUploads + 1;
await subscribingUser.save();
}
}
function convertPromise(inputPath, outputPath){
var srtData = fs.readFileSync(inputPath);
// 1 - Create a new Promise
return new Promise(function(resolve, reject){
srt2vtt(srtData, function(err, vttData){
if(err){
reject(err);
} else {
fs.writeFileSync(outputPath, vttData);
resolve(vttData);
}
});
});
}
/**
* POST /api/changeDefaultUserQuality
* Change user's default quality option
*/
exports.changeDefaultUserQuality = async(req, res) => {
const quality = req.params.quality;
let siteVisitor = req.siteVisitor;
let user = req.user;
// save siteVisitor quality
siteVisitor.defaultQuality = quality;
await siteVisitor.save();
// save user default quality
if(user){
user.defaultQuality = quality;
await user.save();
}
res.send('success');
};
exports.blockUser = async(req, res) => {
try {
const blockedUsername = req.body.blockedUsername;
console.log(`blocking ${blockedUsername} for ${req.user.channelUrl}`);
const blockedUser = await User.findOne({channelUrl: blockedUsername}).select('id _id');
let userAlreadyBlocked;
for(let[index, alreadyBlockedUser]of req.user.blockedUsers.entries()){
if(alreadyBlockedUser == blockedUser._id.toString()){
userAlreadyBlocked = true;
}
}
if(userAlreadyBlocked){
console.log('user already blocked');
return res.send('success');
}
req.user.blockedUsers.push(blockedUser._id);
await req.user.save();
res.send('success');
} catch(err){
console.log(err);
res.status(500);
res.send('error');
}
};
exports.unblockUser = async(req, res) => {
try {
const blockedUsername = req.body.blockedUsername;
const blockedUser = await User.findOne({channelUrl: blockedUsername}).select('id _id');
let blockedUserIndex;
for(let[index, alreadyBlockedUser]of req.user.blockedUsers.entries()){
if(alreadyBlockedUser == blockedUser._id.toString()){
blockedUserIndex = index;
}
}
req.user.blockedUsers.splice(blockedUserIndex, 1);
await req.user.save();
res.send('success');
} catch(err){
console.log(err);
res.status(500);
res.send('error');
}
};
/**
* POST /api/report
* Report an upload
*/
exports.reportUpload = async(req, res) => {
let siteVisitor = req.siteVisitor;
let user = req.user;
const uploadId = req.body.uploadId;
const reason = req.body.reason;
const upload = await Upload.findOne({ _id: uploadId });
let report = new Report({
upload,
reason,
reportingingSiteVisitor : siteVisitor,
uploadingUser: upload.uploader
});
if(user){
report.reportingUser = user;
}
await report.save();
console.log('report created');
return res.send('success');
};
/**
* POST /
*
*/
exports.changeUserFilter = async(req, res) => {
let siteVisitor = req.siteVisitor;
let user = req.user;
siteVisitor.filter = req.body.filter;
await siteVisitor.save();
if(user){
user.filter = req.body.filter;
await user.save();
}
console.log('changing sensitivity');
// console.log(siteVisitor, user);
//
// console.log(req.body);
return res.send('success');
};
async function markUploadAsComplete(uniqueTag, channelUrl, user, res){
upload = await Upload.findOne({ uniqueTag });
upload.status = 'completed';
await upload.save();
user.uploads.push(upload._id);
await user.save();
return'success';
}
async function uploadToB2(upload, uploadPath, hostFilePath){
console.log('upload to b2');
if(upload.fileType == 'video'){
upload.fileExtension = '.mp4';
}
const response = await b2.uploadFileAsync(uploadPath, {
name: hostFilePath + upload.fileExtension,
bucket // Optional, defaults to first bucket
});
upload.uploadUrl = response;
await upload.save();
console.log(response);
}
/** delete user/channel upload **/
exports.deleteChannelThumbnail = async(req, res, next) => {
console.log(req.body.uploadToken);
if(!req.user && req.body.uploadToken){
req.user = await User.findOne({ uploadToken : req.body.uploadToken });
}
req.user.thumbnailUrl = undefined;
req.user.customThumbnail = undefined;
await req.user.save();
return res.send('success');
};
/** delete upload thumbnail **/
exports.deleteUploadThumbnail = async(req, res, next) => {
try {
console.log(req.body.uploadToken);
if(!req.user && req.body.uploadToken){
req.user = await User.findOne({ uploadToken : req.body.uploadToken });
}
const upload = await Upload.findOne({ uniqueTag: req.params.uniqueTag }).populate('uploader');
if(!upload){
res.send('no upload');
}
if(upload.uploader.id.toString() !== req.user.id.toString()){
res.send('not authenticated');
}
upload.customThumbnailUrl = undefined;
upload.thumbnails.custom = undefined;
await upload.save();
res.send('success');
console.log(req.body);
} catch(err){
console.log(err);
}
};
exports.subscribeEndpoint = async function(req, res, next){
// get receiving user
let receivingUser = req.body.channelUrl;
const subscribingUser = req.user;
const uniqueTag = req.body.uniqueTag;
let uploadId, upload;
if(uniqueTag){
upload = await Upload.findOne({ uniqueTag });
uploadId = upload._id;
}
// TODO: Add upload and saving as drivingUpload
// user getting new subscription (fallback to _id if channelUrl misses)
receivingUser = await User.findOne({ channelUrl: receivingUser }).populate('receivedSubscriptions');
if(receivingUser == null){
receivingUser = await User.findOne({ _id: receivingUser }).populate('receivedSubscriptions');
}
if(!receivingUser){
return res.send('Couldnt find user');
}
let alreadySubbed = false;
let existingSubscription;
// console.log(receivingUser);
// determine if user is already subscribed and if so load that subscription
for(let subscription of receivingUser.receivedSubscriptions){
// console.log(subscription)
if(subscription.subscribingUser.toString() == req.user._id.toString()){
alreadySubbed = true;
existingSubscription = subscription;
}
}
// create a notification
if(!alreadySubbed){
console.log('not already subbed');
let subscription = new Subscription({
subscribingUser: subscribingUser._id,
subscribedToUser: receivingUser._id,
active: true,
drivingUpload: uploadId
});
await subscription.save();
// TODO: THIS ISNT WORKING
receivingUser.receivedSubscriptions.push(subscription._id);
await receivingUser.save();
subscribingUser.subscriptions.push(subscription._id);
await subscribingUser.save();
// send notification if youre not subscribing to your own channel
console.log(receivingUser._id, req.user._id);
if(receivingUser._id.toString() !== subscribingUser._id.toString()){
console.log('creating sub notification');
const notification = new Notification({
user : receivingUser._id,
sender : subscribingUser._id,
action : 'subscription',
upload: uploadId,
subscription: subscription._id
});
await notification.save();
console.log(notification);
console.log('here');
}
res.send('subscribed');
} else if(existingSubscription.active == true){
existingSubscription.active = false;
await existingSubscription.save();
res.send('unsubscribed');
} else if(existingSubscription.active == false){
existingSubscription.active = true;
await existingSubscription.save();
res.send('resubscribed');
}
};
/** handle react creation/updating **/
exports.react = async(req, res, next) => {
// console.log(req.body);
// console.log(`${req.user._id}` , req.params.user);
// if the user is not authenticated to act on behalf of that user
if(`${req.user._id}` !== req.params.user){
return res.send('Not authorized');
}
// find an existing react per that user and upload
const existingReact = await React.findOne({
upload: req.params.upload,
user: req.params.user
}).populate('upload user');
// find the upload for that react
const upload = await Upload.findOne({
_id : req.params.upload
}).populate('uploader');
if(!upload){
return res.send('Thing');
}
let newReact;
if(!existingReact){
newReact = new React({
upload: req.params.upload,
user: req.params.user,
react: req.body.emoji,
active: true
});
await newReact.save();
upload.reacts.push(newReact._id);
await upload.save();
// if existing react, update or not
} else if(existingReact && existingReact.active){
// user selected the react that was already active (wants to remove)
if(existingReact.react == req.body.emoji){
existingReact.active = false;
await existingReact.save();
return res.send('removed');
} else {
// user changed the react
existingReact.react = req.body.emoji;
await existingReact.save();
return res.send('changed');
}
// otherwise create a new react
} else if(existingReact && !existingReact.active){
// there is a react, but it is inactive
existingReact.active = true;
existingReact.react = req.body.emoji;
await existingReact.save();
} else {
console.log('THIS SHOULDN\'T BE TRIGGERED, THE LOGIC IS OFF');
}
// add a notification
// create notif for comment on your upload if its not your own upload
if(upload.uploader._id.toString() !== req.user._id.toString()){
await createNotification(upload.uploader._id, req.user._id, 'react', upload, newReact);
}
res.send('new react created');
};
/** POST EDIT UPLOAD **/
exports.editUpload = async(req, res, next) => {
// console.log(req.body);
//
// return res.send('hello');
try {
if(!req.user && req.body.uploadToken){
req.user = await User.findOne({uploadToken: req.body.uploadToken});
}
// TODO: Add error handling
const uniqueTag = req.params.uniqueTag;
let upload = await Upload.findOne({
uniqueTag
}).populate({path: 'uploader comments checkedViews', populate: {path: 'commenter'}}).exec();
// determine if its the user of the channel
const isAdmin = req.user && req.user.role == 'admin';
const isModerator = req.user && req.user.role == 'moderator';
const isAdminOrModerator = isAdmin || isModerator;
const isUser = req.user && ( req.user._id.toString() == upload.uploader._id.toString() );
/** If it is an admin or moderator changing the rating, save as adminAction and only change rating, mark as moderated **/
// TODO: pull this logic out of controller
if(!isUser && !isAdmin && !isAdminOrModerator){
return res.render('error/403');
}
const uploadRatingIsChanging = upload.rating !== req.body.rating;
const isModeratorOrAdmin = isModerator || isAdmin;
// if moderator or admin is updating rating
if(isModeratorOrAdmin && uploadRatingIsChanging){
upload.moderated = true;
const data = {
originalRating: upload.rating,
updatedRating: req.body.rating
};
// save admin action for audit
await createAdminAction(req.user, 'changeUploadRating', upload.uploader._id, upload, [], [], data);
}
// load upload changes
upload.title = req.body.title;
upload.description = req.body.description;
if(upload.uploader.plan == 'plus')
upload.visibility = req.body.visibility;
upload.rating = req.body.rating;
upload.category = req.body.category;
upload.subcategory = req.body.subcategory;
// check if there's a thumbnail
let filename, fileType, fileExtension;
if(req.files && req.files.filetoupload){
filename = req.files.filetoupload.originalFilename;
fileType = getMediaType(filename);
fileExtension = path.extname(filename);
}
// console.log(req.files);
// console.log(req.files.length);
//
const fileIsNotImage = req.files && req.files.filetoupload && req.files.filetoupload.size > 0 && fileType && fileType !== 'image';
console.log('req files');
console.log(req.files);
// TODO: you have to make this smarter by checking the FileType
const fileIsImage = req.files && req.files.filetoupload && req.files.filetoupload.size > 0 && fileType == 'image';
const imagePath = req.files && req.files.filetoupload && req.files.filetoupload.path;
// not doing anything just logging it atm
let fileTypeData;
if(imagePath){
const fileTypeData = await FileType.fromFile(imagePath);
console.log(fileTypeData);
}
const webVttPath = req.files && req.files.webvtt && req.files.webvtt.path;
const originalName = req.files && req.files.webvtt && req.files.webvtt.originalFilename;
const webVttFile = req.files && req.files.webvtt;
// if there is a path, and it's not a falsy value, because these empty strings are being regarded as values
if(webVttPath && originalName){
const originalName = webVttFile.originalFilename;
const subtitlefileExtension = path.extname(originalName);
console.log('subtitle');
console.log(subtitlefileExtension);
if(subtitlefileExtension == '.srt'){
// do the convert here
if(subtitlefileExtension == '.srt'){
console.log('SRT FILE!');
const outputPath = `${saveAndServeFilesDirectory}/${req.user.channelUrl}/${upload.uniqueTag}.vtt`;
// convert the srt to vtt
await convertPromise(webVttPath, outputPath);
console.log('apparently done converting');
// TODO: does it delete the old file or should I delete it?
}
} else if(subtitlefileExtension == '.vtt'){
/** the file in the directory **/
const pathToSaveTo = `${saveAndServeFilesDirectory}/${req.user.channelUrl}/${upload.uniqueTag}.vtt`;
/** save the VTT to the directory and mark it on the upload document **/
await fs.move(webVttPath, pathToSaveTo, {overwrite: true});
}
upload.webVTTPath = `${upload.uniqueTag}.vtt`;
}
// console.log(req.files);
// TODO: would be great if this was its own endpoint
// reject the file
if(fileIsNotImage){
return res.send('We cant accept this file');
// gotta save and upload image
} else if(fileIsImage){
await fs.move(req.files.filetoupload.path, `${saveAndServeFilesDirectory}/${req.user.channelUrl}/${upload.uniqueTag}-custom${fileExtension}`, {overwrite: true});
upload.thumbnails.custom = `${upload.uniqueTag}-custom${fileExtension}`;
if(process.env.UPLOAD_TO_B2 == 'true'){
await backblaze.editploadThumbnailToB2(req.user.channelUrl, upload.uniqueTag, fileExtension, upload);
}
// sendUploadThumbnailToB2(args)
await upload.save();
return res.send('success');
} else {
console.log('no thumbnail being saved');
await upload.save();
return res.send('success');
}
} catch(err){
console.log(err);
res.status(500);
res.send('failure');
}
};
/**
* POST /api/comment
* List of API examples.
*/
exports.deleteComment = async(req, res) => {
try {
// double check this comment doesn't already exist
let existingComment = await Comment.findOne({ _id: req.body.commentId }).populate('commenter');
// console.log(existingComment)
// console.log(req.body.upload);
// console.log(req.user._id);
let upload = await Upload.findOne({ _id: req.body.upload }).populate('uploader');
const userIsUploader = upload.uploader._id.toString() == req.user._id.toString();
const userIsCommenter = existingComment.commenter._id.toString() == req.user._id.toString();
console.log(userIsCommenter);
// make sure the user has right to delete that comment
if(!userIsUploader && !userIsCommenter){
throw new Error('not the proper user');
}
existingComment.visibility = 'removed';
await existingComment.save();
res.send('success');
}
catch(err){
console.log(err);
res.status(500);
res.send('failed to post comment');
}
};
/**
* POST /api/comment
* List of API examples.
*/
exports.postComment = async(req, res) => {
if(req.user.status == 'restricted'){
return res.send('Comment failed, please try again.');
}
if(!req.body.comment){
res.status(500);
return res.send('failed to post comment');
}
try {
// note: this functionality is kind of crappy so turning it off
// it was to prevent double posting but if that does come up again make a nicer implementation
// double check this comment doesn't already exist
// const oldComment = await Comment.findOne({
// text: req.body.comment,
// upload: req.body.upload
// });
//
// if(oldComment){
// return res.send('Comment already exists');
// }
let upload = await Upload.findOne({_id: req.body.upload}).populate('uploader');
const blockedUsers = upload.uploader.blockedUsers;
let viewingUserIsBlocked = false;
if(req.user){
const viewingUserId = req.user._id;
for(const blockedUser of blockedUsers){
if(blockedUser.toString() == viewingUserId) viewingUserIsBlocked = true;
}
}
if(viewingUserIsBlocked){
res.status(500);
return res.send('user is blocked from sending comment');
}
// create and save comment
let comment = new Comment({
text: req.body.comment,
upload: req.body.upload,
commenter: req.user._id,
inResponseTo: req.body.commentId
});
await comment.save();
if(req.body.commentId){
let respondedToComment = await Comment.findOne({ _id : req.body.commentId });
respondedToComment.responses.push(comment._id);
await respondedToComment.save();
console.log(respondedToComment);
}
comment = await comment.save();
// CREATE NOTIFICATION
let user = req.user;
user.comments.push(comment._id);
user = await user.save();
upload.comments.push(comment._id);
upload = await upload.save();
// send notification if youre not reacting to your own material
// create notif for comment on your upload if its not your own thing
if(upload.uploader._id.toString() !== req.user._id.toString()){
await createNotification(upload.uploader._id, req.user._id, 'comment', upload, undefined, comment);
}
// if its a reply comment send a notification to the original commenter
if(req.body.commentId){
// find replied to comment and get commenter
const repliedToComment = await Comment.findOne({
_id : req.body.commentId
}).populate('commenter');
const user = repliedToComment.commenter;
if(user._id.toString() !== req.user._id.toString()){
await createNotification(user._id, req.user._id, 'comment', upload, undefined, comment);
}
}
const timeAgo = timeAgoEnglish.format( new Date(comment.createdAt) );
let responseObject = {
text: comment.text,
user: req.user.channelName || req.user.channelUrl,
timeAgo
};
res.json(responseObject);
// res.send('success')
}
catch(err){
console.log(err);
res.status(500);
res.send('failed to post comment');
}
};
/**
* POST /api/credit
* Send credit to another user
*/
exports.sendUserCredit = async(req, res) => {
let sendingUser = req.user;
let amount = req.body.amount;
amount = Math.round(amount);
amount = Math.abs(amount);
const upload = req.body.upload;
const notANumber = isNaN(amount);
if(notANumber){
res.status(400);
return res.send('failure');
}
if(amount > req.user.credit){
res.status(400);
return res.send('failure');
}
console.log('amount ' + amount);
let channelUrl = req.body.channelUrl;
console.log(channelUrl);
let receivingUser = await User.findOne({ channelUrl });
console.log(receivingUser.channelUrl);
console.log(req.body.channelUrl);
if(receivingUser.plan !== 'plus'){
console.log('not plus');
res.status(500);
return res.send('failure');
}
if(receivingUser.channelUrl == sendingUser.channelUrl){
console.log('same user');
res.status(500);
return res.send('failure');
}
console.log(amount);
console.log(typeof amount);
console.log(sendingUser.credit);
const receivingUserInitialCredit = receivingUser.receivedCredit;
const sendingUserInitialCredit = sendingUser.credit;
sendingUser.credit = sendingUser.credit - amount;
console.log(sendingUser.credit);
await sendingUser.save();
console.log(receivingUser.credit);
receivingUser.receivedCredit = receivingUser.receivedCredit + amount;
console.log(receivingUser.credit);
await receivingUser.save();
let creditAction = new CreditAction({
sendingUser,
receivingUser,
amount,
receivingUserInitialCredit,
receivingUserFinalCredit : receivingUser.receivedCredit,
sendingUserInitialCredit,
sendingUserFinalCredit: sendingUser.credit,
upload
});
console.log('credit action');
await creditAction.save();
return res.send('success');
};
/**
* POST /api/upload/:uniqueTag/captions/delete
* Remove the captions from an upload
*/
exports.deleteUploadCaption = async(req, res) => {
try {
console.log(req.body.uploadToken);
// if there's no req.user then load it as if there was one from the upload token
if(!req.user && req.body.uploadToken){
req.user = await User.findOne({ uploadToken : req.body.uploadToken });
}
// req.params coming from the api route that's hit
// get the upload per the unique tag
const upload = await Upload.findOne({ uniqueTag: req.params.uniqueTag }).populate('uploader');
// if there's no upload send 'no upload'
if(!upload){
res.send('no upload');
}
// TODO: does this work for admins?
// only work if the uploader id and req user id are the same
// otherwise send 'not authenticated'
if(upload.uploader.id.toString() !== req.user.id.toString()){