forked from jvimedia/AppDotNetAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatcher.js
4236 lines (4147 loc) · 152 KB
/
dispatcher.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
/**
* Dispatcher is an internal front-facing API for all functions and services
*
* "Dialects" will call these functions to the data-access chain to store/retrieve data and format
* responses in standard way.
*
* @module dispatcher
*/
var downloader=require('./downloader.js');
var first_post_id;
var last_post_id;
/** for status reports */
var lmem={ heapUsed: 0 };
/**
* Helper function for copying entities around
* @param {string} type - type of entity (mentions, hashtags, links)
* @param {object} src - source entities array
* @param {object} dest - destination entities array
* @param {boolean} postcontext - are we a in a post context (versus user context)
*/
function copyentities(type, src, dest, postcontext) {
if (!dest) {
console.log('dispatcher.js::copyentities - dest not set ', dest);
return;
}
// dest.entities[type]=[];
for(var i in src) {
var res=src[i];
var obj=new Object;
switch(type) {
case 'mentions':
// need is_leading only for post context
if (postcontext && res.altnum!=undefined) {
obj.is_leading=res.altnum?true:false;
}
obj.id=''+res.alt; // could be a hint of future issues here
obj.name=res.text;
break;
case 'hashtags':
obj.name=res.text;
break;
case 'links':
obj.url=res.alt;
obj.text=res.text;
if (res.altnum) {
obj.amended_len=parseInt(0+res.altnum);
}
break;
default:
console.log('unknown type '+type);
break;
}
obj.pos=parseInt(0+res.pos);
obj.len=parseInt(0+res.len);
dest.entities[type].push(obj);
}
}
function normalizeUserID(input, tokenobj, callback) {
//console.log('dispatcher::normalizeUserID', input)
if (input=='me') {
if (tokenobj && tokenobj.userid) {
//console.log('dispatcher.js::getUserStars - me became', tokenobj.userid);
callback(tokenobj.userid, '');
return;
} else {
callback(0, 'no or invalid token');
return;
}
}
var ref=module.exports;
if (input[0]=='@') {
//console.log('dispatcher::normalizeUserID @', input.substr(1))
ref.cache.getUserID(input.substr(1), function(userobj, err) {
if (err) {
console.log('dispatcher.js::normalizeUserID err', err);
}
if (userobj) {
callback(userobj.id, '');
} else {
callback(0, 'no such user');
}
});
} else {
// numeric
callback(input, '');
}
}
// http://stackoverflow.com/a/30970751
function escapeHTML(s) {
return s.replace(/[&"<>]/g, function (c) {
return {
'&': "&",
'"': """,
'<': "<",
'>': ">"
}[c];
});
}
// what calls this?? I think global did
function postsToADN(posts, token) {
// data is an array of entities
var apiposts={}, postcounter=0;
//console.log('dispatcher.js:getUserPosts - mapping '+posts.length);
if (posts && posts.length) {
posts.map(function(current, idx, Arr) {
//console.log('dispatcher.js:getUserPosts - map postid: '+current.id);
// get the post in API foromat
ref.postToAPI(current, {}, token, function(post, err, postmeta) {
apiposts[post.id]=post;
postcounter++;
// join
//console.log(apiposts.length+'/'+entities.length);
if (postcounter==posts.length) {
//console.log('dispatcher.js::getUserPosts - finishing');
var res=[];
for(var i in posts) {
res.push(apiposts[posts[i].id]);
}
callback(res, null, meta);
}
});
}, ref);
} else {
// no posts
callback([], 'no posts for postsToADN', meta);
}
}
var humanFormat=require('human-format');
/** minutely status report */
setInterval(function () {
var ts=new Date().getTime();
var mem=process.memoryUsage();
/*
regarding: the dispatcher stdout writes (isThisDoingAnything)
it's pretty compact, only one or two lines per minute
so finding the exception still shouldn't be an issue
though they will get further and further apart as the quality of the code gets better
either case the exceptions need to be logged in a proper log file
*/
// break so the line stands out from the instant updates
process.stdout.write("\n");
console.log("dispatcher @"+ts+" Memory+["+humanFormat(mem.heapUsed-lmem.heapUsed)+"] Heap["+humanFormat(mem.heapUsed)+"] uptime: "+process.uptime());
lmem=mem;
ts=null;
}, 60*1000);
// cache is available at this.cache
// we set from API to DB format
// we get from DB format to API
// how much error checking do we need in the get callback?
// should we stop the callback on failure? probably not...
/** @constructs dispatcher */
module.exports = {
/**
* cache object for accessing the data store
* @type {object}
*/
cache: null,
/**
* config object for app.net specific configuration
* @type {object}
*/
config: null,
/**
* app config object for accessing the config files
* @type {object}
*/
appConfig: null,
/**
* boolean option for controlling streaming output
* @type {boolean}
*/
notsilent: true,
/** posts */
// tokenObj isn't really used at this point...
// difference between stream and api?
addPost: function(post, tokenObj, callback) {
var ref=this;
function makePost() {
//console.log('dispatcher::addPost annotations - ', post.annotations);
// text, entities, postcontext, callback
ref.cache.addPost(post, tokenObj, function(dbpost, err, meta) {
if (dbpost) {
// FIXME: annotations may not be returned on post creation
if (post.annotations) {
ref.setAnnotations('post', dbpost.id, post.annotations);
}
console.log('dispatcher.js::addPost - GotPost', dbpost.id);
//console.log('dispatcher.js::addPost - postToAPI params', params);
// well we have to wait until we have the post.id and then we can write it
function finishCreatingPost() {
ref.setEntities('post', dbpost.id, post.entities, function() {
//console.log('dispatcher.js::addPost - Entities set', post.entities.links);
ref.postToAPI(dbpost, {}, tokenObj, callback, meta);
});
}
if (post.html.match(/{post_id}/) || post.text.match(/{post_id}/)) {
//console.log('dispatcher.js::addPost - {post_id} live tag detected');
//console.log('dispatcher.js::addPost - reading', dbpost.id, 'got', dbpost.text);
// recalculate entities and html
ref.textProcess(dbpost.text, false, true, function(textProc, err) {
//console.log('dispatcher.js::addPost - got new links', textProc.entities.links);
// need dbpost for the id
//dbpost.html=textProc.html;
//console.log('dispatcher.js::addPost - rewriting HTML to', dbpost.html, 'for', dbpost.id);
//updatePostHTML: function(postid, html, callback) {
//ref.cache.setPost(dbpost, function(fixedPost, err) {
ref.cache.updatePostHTML(dbpost.id, textProc.html, function(fixedPost, err) {
if (err) console.error('dispatcher.js::addPost - fixedPost', err);
if (fixedPost) {
//console.log('dispatcher.js::addPost - fixedPost', fixedPost);
dbpost=fixedPost;
post.entities=textProc.entities;
//console.log('dispatcher.js::addPost - new entity links', post.entities.links);
finishCreatingPost();
}
});
});
} else {
finishCreatingPost();
}
} else {
// may need to delete entities
callback(null, 'empty_result');
}
});
}
var postDone={
html: false,
thread: false,
}
function setDone(type) {
postDone[type]=true;
// if something is not done
//console.log('dispatcher.js::addPost - checking if done');
for(var i in postDone) {
if (!postDone[i]) {
//console.log('dispatcher.js::addPost -', i, 'is not done');
return;
}
}
//console.log('dispatcher.js::addPost - done', data, meta);
//console.log('dispatcher.js::addPost - done, text', data.text);
// everything is done
makePost();
//callback(data, null, meta);
}
function getEntities(post, cb) {
ref.textProcess(post.text, post.entities, true, function(textProc, err) {
console.log('dispatcher.js::addPost - textProc', textProc);
post.entities=textProc.entities;
post.html=textProc.html;
cb();
});
}
// check out postToAPI
// needs to run before textProcess
function checkTagUser(post, cb) {
if (!((post.text && post.text.match(/{username}/)) || (post.html && post.html.match(/{username}/)))) {
cb();
return;
}
ref.cache.getUser(post.userid, function(user, err, meta) {
if (post.text && post.text.match(/{username}/)) {
post.text=post.text.replace(new RegExp('{username}', 'g'), user.username);
}
if (post.html && post.html.match(/{username}/)) {
post.html=post.html.replace(new RegExp('{username}', 'g'), user.username);
}
cb();
});
}
function getThreadID(post, cb) {
// cache expects post to be in our internal db format
console.log('post.reply_to', post.reply_to);
if (post.reply_to) {
ref.cache.getPost(post.reply_to, function(parentPost, err, meta) {
post.thread_id=parentPost.thread_id;
console.log('post.threadid', post.thread_id);
cb();
});
} else {
cb();
}
}
// these both mess with .html / .text
checkTagUser(post, function() {
// after username is in place, we'll have better positions
getEntities(post, function() {
setDone('html');
});
});
getThreadID(post, function() {
setDone('thread');
});
},
delPost: function(postid, token, callback) {
this.cache.delPost(postid, function(post, err, meta) {
console.log('dispatcher.js::delPost - returning', post);
callback(post, err, meta);
});
},
/**
* Add/Update post in data store
* @param {object} post - the new post object (in API format)
* @param {setPostCallback} callback - function to call after completion
*/
setPost: function(post, callback) {
if (!post) {
console.log('dispatcher.js::setPost - post is not set!');
if (callback) {
callback(null, 'setPost - post is not set!');
}
return;
}
if (!post.id) {
console.log('dispatcher.js::setPost - no id in post', post);
if (callback) {
callback(null, 'setPost - no id in post');
}
return;
}
// we're assuming we're getting a contiguous amount of posts...
// get a sample of where the app stream is starting out
if (first_post_id==undefined) {
// not a good way to do this,
// some one can interact (delete?) an older post with a much lower id
console.log("Setting first post to ", post.id);
first_post_id=post.id;
}
post.date=new Date(post.created_at);
post.ts=post.date.getTime();
// update user first, to avoid proxy
if (post.user && post.user.id) {
// update User records
/*
if (post.user.description && post.user.description.entities) {
console.log('disptacher.js::setPost '+post.id+' has user entites');
} else {
console.log('disptacher.js::setPost '+post.id+' has NO user entites');
//console.dir(post.user);
}
*/
this.updateUser(post.user, post.ts, function(user, err) {
if (err) {
console.log("User Update err: "+err);
//} else {
//console.log("User Updated");
}
});
}
if (post.entities) {
this.setEntities('post', post.id, post.entities, function(entities, err) {
if (err) {
console.log("entities Update err: "+err);
//} else {
//console.log("entities Updated");
}
});
}
//console.log('dispatcher.js::setPost post id is '+post.id);
var dataPost=post;
//dataPost.id=post.id; // not needed
if (post.user) {
dataPost.userid=post.user.id;
} else {
// usually on deletes, they don't include the user object
//console.log('No Users on post ', post);
/*
{ created_at: '2013-08-16T01:10:29Z',
num_stars: 0,
is_deleted: true,
num_replies: 0,
thread_id: '9132210',
deleted: '1',
num_reposts: 0,
entities: { mentions: [], hashtags: [], links: [] },
machine_only: false,
source:
{ link: 'http://tapbots.com/software/netbot',
name: 'Netbot for iOS',
client_id: 'QHhyYpuARCwurZdGuuR7zjDMHDRkwcKm' },
reply_to: '9132210',
id: '9185233',
date: Thu Aug 15 2013 18:10:29 GMT-0700 (PDT),
ts: 1376615429000 }
*/
}
dataPost.created_at=new Date(post.created_at); // fix incoming created_at iso date to Date
//console.log('dispatcher::setPost - user is', post.userid);
if (post.source) {
var ref=this;
this.cache.setSource(post.source, function(client, err) {
// param order is correct
//console.log('addPost setSource returned ', client, err, dataPost);
if (err) {
console.log('can\'t setSource', err);
} else {
dataPost.client_id=client.client_id;
}
//console.log('dispatcher.js::setPost datapost id is '+dataPost.id);
ref.cache.setPost(dataPost, callback);
});
} else {
//console.log('dispatcher.js::setPost datapost id is '+dataPost.id);
this.cache.setPost(dataPost, callback);
}
if (post.annotations) {
this.setAnnotations('post', post.id, post.annotations);
}
if (last_post_id==undefined || post.id>last_post_id) {
//console.log("Setting last post to ", post.id);
last_post_id=post.id;
}
// can't clear this because we're still processing it
//dataPost=null;
if (this.notsilent) {
process.stdout.write('P');
}
},
// set shit like you_starred, you_reposted, etc
contextualizePostRepsonse: function(post, token, callback) {
//
},
// convert ADN format to DB format
apiToPost: function(api, meta, callback) {
if (!api.user) {
console.log('apiToPost - api user is missing', api.user,api);
if (callback) {
callback(null, 'no api user');
}
return;
}
// copy api
var post=JSON.parse(JSON.stringify(api));
post.date=new Date(api.created_at);
post.ts=post.date.getTime();
post.user.created_at=new Date(api.user.created_at);
post.userid=api.user.id;
// repost_of?
// it's an object in api and an numericid in DB
if (api.repost_of) {
// is this right in the case of repost of a repost?
post.repost_of=api.repost_of.id
}
// source
if (post.source) {
var ref=this;
// find it (or create it for caching later)
this.cache.setSource(post.source, function(client, err) {
if (err) {
console.log('can\'t setSource ', err);
} else {
post.client_id=client.client_id;
}
callback(post, err, meta);
});
} else {
callback(post, null, meta);
}
//return post;
},
/**
* convert DB format to API structure
* @param {object} post - the new post object
* @param {object} params - the request parameters (load annotations)
* @param {object} token - the request context (which user/client)
* @param {setPostCallback} callback - function to call after completion
* @param {object} meta - the meta data
*/
postToAPI: function(post, params, tokenObj, callback, meta) {
//console.log('dispatcher.js::postToAPI('+post.id+') - start');
if (!post) {
console.log('dispatcher.js::postToAPI - no post data passed in');
callback(null, 'no_post');
return;
}
if (!post.userid) {
console.log('dispatcher.js::postToAPI - no userid', post);
callback(null, 'no_userid');
return;
}
var ref=this; // back it up
// set up new final object for collection
var data={};
// , 'source', 'user'
var postFields=['id', 'text', 'html', 'canonical_url', 'created_at',
'machine_only', 'num_replies', 'num_reposts', 'num_stars', 'thread_id',
'entities'];
for(var i in postFields) {
var f=postFields[i];
data[f]=post[f];
}
// hack
if (data.text===undefined && data.html===undefined) {
console.log('dispatcher.js::postToAPI('+post.id+') - no text or html');
data.text='';
data.html='';
}
if (data.html && !data.text) data.text=data.html;
if (!data.html && data.text) data.html=data.text;
//if (typeof(data.created_at)!=='object') {
//console.log('dispatcher::postToAPI - created_at isnt a date', typeof(data.created_at), data.created_at);
if (!data.created_at) {
console.log('dispatcher::postToAPI - created_at isnt object', data.created_at);
data.created_at=new Date(data.created_at);
console.log('dispatcher::postToAPI - created_at converted to', data.created_at.toString());
}
// convert TS to date object
//console.log('dispatcher::postToAPI - created_at check', data.created_at);
if (isNaN(data.created_at.getTime())) {
//delete data.created_at
data.created_at='2000-01-01T00:00:00.000Z';
data.is_deleted=true
} else {
data.created_at=new Date(data.created_at);
}
//console.log(post.num_replies+' vs '+data.num_replies);
//'repost_of'
var postFieldOnlySetIfValue=['reply_to'];
for(var i in postFieldOnlySetIfValue) {
var f=postFieldOnlySetIfValue[i];
if (post[f]) {
data[f]=post[f];
}
}
//data.user=user;
//console.log('dispatcher.js::postToAPI - return check', data);
var postDone={
client: false,
user: false,
entities: false,
repostOf: false,
annotation: false,
context: false,
}
if (params && params.generalParams) {
if (params.generalParams.starred_by) {
//console.log('dispatcher.js::postToAPI('+post.id+') - include_starred_by - write me!');
postDone.starred_by=false;
this.cache.getPostStars(post.id, {}, function(interactions, err, meta) {
if (!interactions || !interactions.length) {
data.starred_by=[];
setDone('starred_by');
return;
}
var userids=[];
for(var i in interactions) {
var action=interactions[i]
userids.push(action.userid);
}
//console.log('dispatcher.js::postToAPI('+post.id+') - include_starred_by - getting users', userids);
ref.cache.getUsers(userids, params, function(userObjs, userErr, meta) {
//console.log('dispatcher.js::postToAPI('+post.id+') - include_starred_by - got', userObjs.length);
var rUsers=[]
for(var i in userObjs) {
ref.userToAPI(userObjs[i], tokenObj, function(adnUserObj, err) {
//console.log('dispatcher.js::postToAPI - got', adnUserObj, 'for', users[i])
rUsers.push(adnUserObj)
//console.log('dispatcher.js::postToAPI('+post.id+') - include_starred_by - ', rUsers.length, 'vs', userids.length);
if (rUsers.length==userids.length) {
data.starred_by=rUsers;
//console.log('marking starred_by done');
setDone('starred_by');
}
}, meta);
}
});
});
}
if (params.generalParams.reposters) {
//console.log('dispatcher.js::postToAPI('+post.id+') - include_reposters - write me!');
postDone.reposters=false;
this.cache.getReposts(post.id, {}, tokenObj, function(posts, err, meta) {
if (!posts || !posts.length) {
data.reposters=[];
setDone('reposters');
return;
}
var userids=[];
for(var i in posts) {
var post=posts[i]
if (userids.indexOf(post.userid)==-1) {
userids.push(post.userid);
}
}
//console.log('dispatcher.js::postToAPI('+post.id+') - include_reposters - getting users', userids);
ref.cache.getUsers(userids, params, function(userObjs, userErr, meta) {
//console.log('dispatcher.js::postToAPI('+post.id+') - include_reposters - got', userObjs.length);
var rUsers=[]
for(var i in userObjs) {
ref.userToAPI(userObjs[i], tokenObj, function(adnUserObj, err) {
//console.log('dispatcher.js::postToAPI - got', adnUserObj, 'for', adnUserObj.id)
rUsers.push(adnUserObj)
//console.log('dispatcher.js::postToAPI('+post.id+') - include_reposters - ', rUsers.length, 'vs', userids.length);
if (rUsers.length==userids.length) {
//callback(rUsers, '');
data.reposters=rUsers;
//console.log('marking reposters done');
setDone('reposters');
}
}, meta);
}
});
});
}
} else {
if (params != {}) {
console.log('dispatcher.js::postToAPI('+post.id+') - params dont have generalParams');
}
}
function setDone(type) {
postDone[type]=true;
// if something is not done
//console.log('dispatcher.js::postToAPI('+post.id+') - checking if done');
for(var i in postDone) {
if (!postDone[i]) {
//console.log('dispatcher.js::postToAPI('+post.id+') -', i, 'is not done');
return;
}
}
//console.log('dispatcher.js::postToAPI('+post.id+') - done', data, meta);
//console.log('dispatcher.js::postToAPI('+post.id+') - done, text', data.text);
//console.log('dispatcher.js::postToAPI('+post.id+') - params', params);
// everything is done
callback(data, null, meta);
}
function loadClient(post, cb) {
if (post.repost_of) { // no need to look up client of a repost (atm but eventually should probably)
// Alpha does need this
var source={
link: 'https://sapphire.moe/',
name: 'Unknown',
client_id: 'Unknown',
}
cb(source); // was just ()
return;
}
ref.getClient(post.client_id, function(client, clientErr, clientMeta) {
//console.log('dispatcher.js::postToAPI('+post.id+') - gotClient');
var source={
link: 'https://sapphire.moe/',
name: 'Unknown',
client_id: 'Unknown',
}
if (client) {
source={
link: client.link,
name: client.name,
client_id: client.client_id
};
} else {
console.log('dispatcher.js::postToAPI('+post.id+') - client is', client, clientErr);
}
cb(source, clientErr, clientMeta);
}); // getClient
}
function loadUser(userid, params, cb) {
//console.log('dispatcher.js::postToAPI('+post.id+') - getting user '+post.userid);
ref.getUser(userid, params, function(user, userErr, userMeta) {
//console.log('dispatcher.js::postToAPI('+post.id+') - got user '+post.userid, err);
if (!user) {
user={
id: 0,
username: 'likelydeleted',
created_at: '2014-10-24T17:04:48Z',
avatar_image: {
url: ''
},
cover_image: {
url: ''
},
counts: {
following: 0,
}
}
}
cb(user, userErr, userMeta);
}); // getUser
}
var loadRepostOf=function(post, tokenObj, cb) {
//console.log('dispatcher.js::postToAPI - return check', data);
//console.log('dispatcher.js::postToAPI - Done, calling callback');
// now fix up reposts
if (post.repost_of) {
//console.log('converting repost_of from ', post.repost_of);
// use thread_id because we need a direct path back to the original
// and we can use repost_of to find the share tree
ref.getPost(post.thread_id, { tokenobj: tokenObj }, function(repost, repostErr, repostMeta) {
//console.log('converting repost_of to', repostapi.id);
//data.repost_of=repost;
//callback(data, err, meta);
cb(repost, repostErr, repostMeta);
})
} else {
//callback(data, err, meta);
cb(null, null, null);
}
}
var loadAnnotation=function(post, cb) {
ref.getAnnotation('post', post.id, function(dbNotes, err, noteMeta) {
var apiNotes=[];
for(var j in dbNotes) {
var note=dbNotes[j];
//console.log('got note', j, '#', note.type, '/', note.value, 'for', post.id);
apiNotes.push({
type: note.type,
value: note.value,
});
}
cb(apiNotes, err, noteMeta);
});
}
function loadEntites(post, cb) {
// use entity cache (DB read or CPU calculate)
if (1) {
//console.log('dispatcher.js::postToAPI('+post.id+') - getEntity post. post.userid:', post.userid);
ref.getEntities('post', post.id, function(entities, entitiesErr, entitiesMeta) {
//console.log('dispatcher.js::postToAPI('+post.id+') - gotEntities');
data.entities={
mentions: [],
hashtags: [],
links: [],
};
copyentities('mentions', entities.mentions, data, 1);
copyentities('hashtags', entities.hashtags, data, 1);
copyentities('links', entities.links, data, 1);
// use html cache?
if (1) {
//console.log('dispatcher.js::postToAPI('+post.id+') - calling final comp');
//finalcompsite(post, user, client, callback, err, meta);
cb();
} else {
// generate HTML
// text, entities, postcontext, callback
ref.textProcess(post.text, post.entities, true, function(textProcess, err) {
//console.dir(textProcess);
data.html=textProcess.html;
//finalcompsite(post, user, client, callback, err, meta);
cb();
});
}
}); // getEntities
} else {
ref.textProcess(post.text, post.entities, true, function(textProcess, err) {
data.entities=textProcess.entities;
data.html=textProcess.html;
//finalcompsite(post, user, client, callback, err, meta);
cb();
});
}
}
// any value into breaking into 3 functions?
// removed another checkDone style function
var loadContext=function(post, tokenObj, cb) {
// these will need to be queried:
// reposters
// Not completet & only included if include_reposters=1 is passed to App.net
// starred_by
// include_starred_by=1
// so we have to query:
// ok if token is a string we need to resolve it
// otherwise we're good to go with an object
//console.log('dispatcher.js::postToAPI:::loadContext - tokenObj', tokenObj)
//console.log('dispatcher.js::postToAPI post', post.id, 'data', data.id, 'id', id);
if (tokenObj && tokenObj.userid) {
// if this post is a report that we reposted
//if (post.repost_of && post.userid==token.userid) data.you_reposted=true;
var starDone=false
var repostRepostDone=false
var repostPostDone=false
var checkDone=function() {
//console.log('dispatcher.js::postToAPI:::loadContext - checkDone', starDone, repostRepostDone, repostPostDone);
if (starDone && repostRepostDone && repostPostDone) {
cb();
}
}
ref.cache.getUserStarPost(tokenObj.userid, data.id, function(res, err) {
//console.log('dispatcher.js::postToAPI - getUserStarPost got', res);
starDone=true;
//repostDone=true
data.you_starred=false; // needs to be defined (if token only?)
if (res && res.id) data.you_starred=true;
checkDone();
})
//console.log('is this post', data.id, 'by', tokenObj.userid);
// what if this isn't repost but we did retweet
ref.cache.getUserRepostPost(tokenObj.userid, post.id, function(res, err) {
//console.log('dispatcher.js::postToAPI:::loadContext -', post.id, 'hasRepost', res.id);
data.you_reposted=false;
if (res && res.id) {
//console.log(post.id, 'not a repost but look up says ', tokenObj.userid, 'has reposted as', res.id);
data.you_reposted=true;
}
repostPostDone=true;
checkDone();
});
// well we only need if this is a repost
if (post.repost_of) {
// we'll need to look at it
ref.cache.getUserRepostPost(tokenObj.userid, post.thread_id, function(res, err) {
//console.log('dispatcher.js::postToAPI:::loadContext -', post.id, 'isRepost', res.id);
repostRepostDone=true;
data.you_reposted=false;
if (res && res.id) {
//console.log(tokenObj.userid, 'has reposted', post.repost_of, 'as', res.id);
data.you_reposted=true;
}
checkDone();
});
} else {
repostRepostDone=true;
checkDone();
}
//
} else {
cb();
}
}
// post.client_id is string(32)
//console.log('dispatcher.js::postToAPI - gotUser. post.client_id:', post.client_id);
loadClient(post, function(source, clientErr, clientMeta) {
data.source=source;
setDone('client');
});
//console.log('dispatcher.js::postToAPI - gotPost. post.userid:', post.userid);
loadUser(post.userid, params, function(user, userErr, userMeta) {
data.user=user;
setDone('user');
});
loadRepostOf(post, tokenObj, function(repost, repostErr, repostMeta) {
if (repost) data.repost_of=repost;
setDone('repostOf');
});
loadAnnotation(post, function(apiNotes, notesErr, notesMeta) {
data.annotations=apiNotes;
setDone('annotation');
});
// writes to data
loadEntites(post, function() {
setDone('entities');
});
loadContext(post, tokenObj, function(post, contextErr, contextMeta) {
setDone('context');
});
// these are stored in the db
// num_stars
// num_reposts
// num_replies
// we need post, entities, annotations
// user, entities, annotations
// and finally client
// could dispatch all 3 of these in parallel
// shouldAdd but can't no name/link data
//console.log('dispatcher.js::postToAPI - is ref this?', ref);
},
// take a list of IDs and lookup posts
idsToAPI: function(posts, params, callback, meta) {
//console.log('dispatcher.js::idsToAPI(', posts.length, 'posts,...,...,', meta, ') - start');
var ref=this;
// definitely need this system
var apiposts={};
var counts=0;
//var apiposts=[];
if (posts.length) {
posts.map(function(current, idx, Arr) {
// get the post in API foromat
//console.log('getting', current.id);
// params && params.tokenobj?params.tokenobj:null
ref.getPost(current.id, params, function(post, err, postMeta) {
if (post && post.text) {
//apiposts.push(post);
apiposts[post.id]=post;
} else {
// reposts are an example of a post without text
console.log('dispatcher.js::idsToAPI - no post or missing text', post, err, meta, current.id);
// with counts we don't need to do this
//posts.pop(); // lower needed
}
counts++;
// join
//console.log(apiposts.length+'/'+entities.length);
//console.log(counts+'/'+posts.length);
if (counts===posts.length) {
//if (apiposts.length===posts.length) {
//console.log('dispatcher.js::idsToAPI - finishing');
var res=[]
for(var i in posts) {
var id=posts[i].id;
if (apiposts[id]) {
//console.log('final', id);
res.push(apiposts[id]);
}
}
callback(res, null, meta);
/*
for(var i in apiposts) {
var id=apiposts[i].id;
console.log('final', id);
}
callback(apiposts, null, meta);
*/
}
});
}, ref);
} else {
// no entities
// this can be normal, such as an explore feed that's being polled for since_id
//console.log('dispatcher.js::idsToAPI - no posts');
callback([], 'idsToAPI no posts', meta);
}
},
addRepost: function(postid, tokenObj, callback) {
//console.log('dispatcher.js::addRepost - start', postid);
var ref=this;
// if postid is a repost_of
this.cache.getPost(postid, function(srcPost, err) {
var originalPost=postid
if (srcPost.repost_of) {
originalPost=srcPost.thread_id
}
ref.cache.addRepost(postid, originalPost, tokenObj, function(dbPost, err, meta) {
if (err) {
console.error('dispatcher.js::addRepost - err', err);
}
//console.log('dispatcher.js::addRepost - dbPost', dbPost);
// postToAPI function(post, params, token, callback, meta) {
ref.postToAPI(dbPost, {}, tokenObj, callback, meta);
});
});
},
delRepost: function(postid, tokenObj, callback) {
this.cache.delRepost(postid, tokenObj, function(dbPost, err, meta) {
// postToAPI function(post, params, token, callback, meta) {
ref.postToAPI(dbPost, {}, tokenObj, callback, meta);
});
},
/**
* get single post from data access
* @param {number} id - the new post object
* @param {object} params - the options context
* @param {metaCallback} callback - function to call after completion
*/
// what params here?? all
// we need to ignore any paging parameter, likely from the parent call
getPost: function(id, params, callback) {
// probably should just exception and backtrace
if (callback==undefined) {
console.log('dispatcher.js::getPost - callback undefined');
return;
}
if (id==undefined) {
callback(null, 'dispatcher.js::getPost - id is undefined');
return;
}