forked from jvimedia/AppDotNetAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataaccess.proxy.js
1509 lines (1494 loc) · 50.9 KB
/
dataaccess.proxy.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
/** get request http library */
var request = require('request');
var qs = require('qs');
var downloader=require('./downloader.js');
//var rateLimiter = require('./ratelimiter.js');
//FIXME: 429 handling
// I guess we need some type of throttling
// backwards compatibility to allow us to do the right thing
// this doesn't give us QoS but does allow us to say put in the background
// does defer to immediate IO
require("setimmediate");
// remove 5 connections to upstream at a time
// we definitely want to burst when we need it
// though should set some type of limit, like the max ADN resets
// for what time period though? one frequency?
require('http').globalAgent.maxSockets = Infinity;
require('https').globalAgent.maxSockets = Infinity;
/** @todo make count configureable, low latency=20count, aggressive cache=200count */
var proxycalls=0;
var proxywrites=0;
var lcalls=0;
// minutely status report
setInterval(function () {
var ts=new Date().getTime();
process.stdout.write("\n");
console.log('data.proxy report '+(proxycalls-lcalls)+' proxy recent calls. '+proxycalls+' overall');
// just need a redis info call to pull memory and keys stats
lcalls=proxycalls;
}, 60*1000);
// pass in proxy settings or just conf it?
module.exports = {
next: null,
dispatcher: null,
/*
* users
*/
addUser: function(username, password, callback) {
if (this.next) {
this.next.addUser(username, password, callback);
}
},
setUser: function(iuser, ts, callback) {
if (this.next) {
this.next.setUser(iuser, ts, callback);
}
},
delUser: function(userid, callback) {
if (this.next) {
this.next.delUser(userid, callback);
}
},
getUserID: function(username, callback) {
if (!username) {
callback(null, 'dataccess.proxy.js::getUserID() - username was not set');
return;
}
var ref=this;
console.log('dataccess.proxy.js:getUserID - proxying user @'+username);
proxycalls++;
request.get({
url: ref.apiroot+'/users/@'+username
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
// upload fresh proxy data back into dataSource
ref.dispatcher.updateUser(res.data,new Date().getTime(),function(user,err) {
if (user==null & err==null) {
if (this.next) {
this.next.getUserID(username, callback);
return;
}
} else if (err) {
console.log("dataccess.proxy.js:getUserID - User get err: ",err);
//} else {
//console.log("User Updated");
}
// finally reutrn
callback(user,err,res.meta);
});
} else {
console.log('dataccess.proxy.js:getUserID - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e, null);
}
});
},
// callback is user,err,meta
getUser: function(userid, callback) {
if (userid==undefined) {
callback(null, 'dataccess.proxy.js:getUser - userid is undefined');
return;
}
if (!userid) {
callback(null, 'dataccess.proxy.js:getUser - userid isn\'t set');
return;
}
var ref=this;
console.log('dataccess.proxy.js:getUser - proxying user '+userid);
proxycalls++;
request.get({
url: ref.apiroot+'/users/'+userid
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
// upload fresh proxy data back into dataSource
//console.log('dataccess.proxy.js:getUser - writing to user db ',res.data.id);
ref.dispatcher.updateUser(res.data, new Date().getTime(), function(user, err) {
console.log('dataccess.proxy.js:getUser - proxy response received');
if (user==null & err==null) {
if (this.next) {
this.next.getUser(userid, callback);
return;
}
} else if (err) {
console.log("dataccess.proxy.js:getUser - User Update err: ",err);
//} else {
//console.log("User Updated");
}
// finally reutrn
callback(user, err, res.meta);
});
} else {
console.log('dataccess.proxy.js:getUser - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e, null);
}
});
},
/*
* local user token
*/
// should we really pass token in? it's cleaner separation if we do
// even though this is the only implemention of the abstraction
addAPIUserToken: function(userid, client_id, scopes, token, callback) {
if (this.next) {
this.next.addAPIUserToken(userid, client_id, scopes, token, callback);
}
},
delAPIUserToken: function(token, callback) {
if (this.next) {
this.next.delAPIUserToken(token, callback);
}
},
getAPIUserToken: function(token, callback) {
if (this.next) {
this.next.getAPIUserToken(token, callback);
}
},
/*
* user upstream tokens
*/
setUpstreamUserToken: function(userid, token, scopes, upstreamUserId, callback) {
if (this.next) {
this.next.setUpstreamUserToken(userid, token, scopes, upstreamUserId, callback);
}
},
/*
* local clients
*/
addLocalClient: function(userid, callback) {
if (this.next) {
this.next.addLocalClient(userid, callback);
}
},
getLocalClient: function(client_id, callback) {
if (this.next) {
this.next.getLocalClient(client_id, callback);
}
},
delLocalClient: function(client_id,callback) {
if (this.next) {
this.next.delLocalClient(client_id, callback);
}
},
/*
* clients
*/
addSource: function(client_id, name, link, callback) {
if (this.next) {
this.next.addSource(client_id, name, link, callback);
}
},
getClient: function(client_id, callback) {
if (this.next) {
this.next.getClient(client_id, callback);
}
},
setSource: function(source, callback) {
if (this.next) {
this.next.setSource(source, callback);
}
},
/* client (app) tokens */
addAPIAppToken: function(client_id, token, request) {
console.log('dataccess.proxy.js::addAPIAppToken - write me!');
},
delAPIAppToken: function(client_id, token) {
console.log('dataccess.proxy.js::delAPIAppToken - write me!');
},
getAPIAppToken: function(client_id, token) {
console.log('dataccess.proxy.js::getAPIAppToken - write me!');
},
/* client upstream token */
addUpstreamClientToken: function(token, scopes) {
console.log('dataccess.proxy.js::addUpstreamClientToken - write me!');
},
delUpstreamClientToken: function(token) {
console.log('dataccess.proxy.js::delUpstreamClientToken - write me!');
},
getUpstreamClientToken: function() {
console.log('dataccess.proxy.js::getUpstreamClientToken - write me!');
},
/** user stream */
/** app stream */
/**
* posts
*/
addPost: function(ipost, token, callback) {
var ref=this;
proxywrites++;
proxycalls++;
var postdata={
text: ipost.text,
reply_to: ipost.reply_to
};
if (ipost.entities) {
postdata.entities=ipost.entities;
}
if (ipost.annotations) {
postdata.annotations=ipost.annotations;
}
console.log('proxying post write');
// Authorization: Bearer ?
// or ?access_token=xxx...
request.post({
url: ref.apiroot+'/posts',
method: 'POST',
headers: {
"Authorization": "Bearer "+token,
// two modes, JSON is more comprehensive...
//"Content-Type": "application/x-www-form-urlencoded"
"Content-Type": "application/json"
},
body: JSON.stringify(postdata)
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var data=JSON.parse(body);
if (data.meta.code==200) {
//console.dir(data.data);
console.log('post written to network as '+data.data.id+' as '+data.data.user.id);
// the response can be setPost'd
// the current post isn't in API format
// it's in ADN post
//ipost.id=data.data.id // set it's generated id
ref.dispatcher.setPost(data.data);
// this will convert ADN to DB format, then we don't have to bug the dispatcher
ref.dispatcher.apiToPost(data, data.meta, function(post, err) {
//ref.setPost(post);
// it's formatted as ADN format
// callback needs to expect DB format...
// mainly the created_at
callback(data.data, null);
});
} else {
console.log('failure? ',data.meta);
callback(null, e);
}
} else {
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e);
}
});
/*
if (this.next) {
this.next.addPost(ipost, token, callback);
}
*/
},
setPost: function(ipost, callback) {
if (this.next) {
this.next.setPost(ipost, callback);
}
},
addRepost: function(postid, originalPost, token, callback) {
var ref=this;
console.log('proxying posts/repost '+postid);
proxywrites++;
proxycalls++;
request.post({
url: ref.apiroot+'/posts/'+postid+'/repost',
method: 'POST',
headers: {
"Authorization": "Bearer "+token,
}
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var data=JSON.parse(body);
if (data.meta.code==200) {
//console.dir(data.data);
console.log('post repost written to network as '+data.data.id+' as '+data.data.user.id);
// the response can be setPost'd
//ref.setPost(body);
// it's formatted as ADN format
// callback needs to expect DB format...
// mainly the created_at
callback(data.data, null);
} else {
console.log('failure? ',data.meta);
callback(null, e);
}
} else {
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e);
}
/*
if (this.next) {
this.next.addRepost(postid, originalPost, token, callback);
} else {
console.log('dataaccess.base.js::addRepost - write me!');
callback(null, null);
}
*/
});
},
delRepost: function(postid, token, callback) {
var ref=this;
console.log('proxying posts/repost '+postid);
proxywrites++;
proxycalls++;
request.del({
url: ref.apiroot+'/posts/'+postid+'/repost',
method: 'DELETE',
headers: {
"Authorization": "Bearer "+token,
}
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var data=JSON.parse(body);
if (data.meta.code==200) {
//console.dir(data.data);
console.log('post unrepost written to network as '+data.data.id+' as '+data.data.user.id);
// the response can be setPost'd
//ref.setPost(body);
// it's formatted as ADN format
// callback needs to expect DB format...
// mainly the created_at
callback(data.data, null);
} else {
console.log('failure? ',data.meta);
callback(null, e);
}
} else {
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e);
}
/*
if (this.next) {
this.next.addRepost(postid, token, callback);
} else {
console.log('dataaccess.base.js::delRepost - write me!');
callback(null, null);
}
*/
});
},
getPost: function(id, callback) {
if (id==undefined) {
callback(null, 'dataccess.proxy.js::getPost - id is undefined');
return;
}
if (callback==undefined) {
callback(null, 'dataccess.proxy.js::getPost - callback is undefined');
return;
}
var ref=this;
console.log('proxying post '+id);
proxycalls++;
request.get({
url: ref.apiroot+'/posts/'+id
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
ref.dispatcher.setPost(res.data, function(post, err) {
//console.log('dataccess.proxy.js::getPost - setPost: '+post.id+' ['+id+'/'+res.data.id+'],'+err);
if (post==null && err==null) {
if (this.next) {
this.next.getPost(id, callback);
} else {
callback(res.data, null, res.meta);
}
} else {
callback(post, err, res.meta);
}
});
} else {
console.log('dataccess.proxy.js:getPost - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e, null);
}
});
},
getReposts: function(postid, params, token, callback) {
var ref=this;
console.log('proxying posts reposts '+postid);
proxycalls++;
/*
if (this.next) {
this.next.getReposts(postid, params, callback);
} else {
console.log('dataaccess.proxy.js::getReposts - write me!');
callback(null, null);
}
*/
request.get({
url: ref.apiroot+'/posts/'+postid+'/reposters?count='+params.count,
headers: {
"Authorization": "Bearer "+token,
}
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
//console.log('dataccess.proxy.js::getReposts - data',res.data);
for(var i in res.data) {
var post=res.data[i];
ref.dispatcher.setPost(post);
}
callback(res.data, null, res.meta);
} else {
console.log('dataccess.proxy.js::getReposts - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
/*
error null
statusCode 429
body {"meta":{"code":429,"error_message":"Too many requests"}}
error null
statusCode 401
body {"meta":{"code":401,"error_message":"Call requires authentication: Invalid token.","error_slug":"invalid-token"}}
*/
if (e===null & r.statusCode==401) {
var res=JSON.parse(body);
if (res.meta.error_slug=='invalid-token') {
console.log('dataaccess.proxy.js::getReposts - bad token', token,'is bad');
}
}
callback(null, e, null);
}
});
},
getReplies: function(postid, params, token, callback) {
var ref=this;
console.log('proxying posts replies '+postid);
proxycalls++;
/*
request.post({
url: ref.apiroot+'/posts',
method: 'POST',
headers: {
"Authorization": "Bearer "+token,
// two modes, JSON is more comprehensive...
//"Content-Type": "application/x-www-form-urlencoded"
"Content-Type": "application/json"
},
body: JSON.stringify(postdata)
}, function(e, r, body) {
*/
// 200 or +params.count?
// depends if we're updating or serving a request
// might as well go with params, that way the caller can be explicit
// we don't always want or need all this information
request.get({
url: ref.apiroot+'/posts/'+postid+'/replies?count='+params.count,
headers: {
"Authorization": "Bearer "+token,
}
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
for(var i in res.data) {
var post=res.data[i];
ref.dispatcher.setPost(post);
}
callback(res.data, null, res.meta);
} else {
console.log('dataccess.proxy.js:getReplies - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
/*
error null
statusCode 401
body {"meta":{"code":401,"error_message":"Call requires authentication: Invalid token.","error_slug":"invalid-token"}}
*/
if (e===null & r.statusCode==401) {
var res=JSON.parse(body);
if (res.meta.error_slug=='invalid-token') {
console.log('dataaccess.proxy.js::getReplies - bad token', token,'is bad');
}
}
callback(null, e, null);
}
});
},
getUserStream: function(user, params, token, callback) {
/*
if (this.next) {
this.next.getUserStream(user, params, token, callback);
return;
}
*/
//console.log('dataaccess.proxy.js::getUserStream - write me!');
var ref=this;
var ts=new Date().getTime();
proxycalls++;
console.log('proxying user posts stream '+user);
request.get({
url: ref.apiroot+'/posts/stream',
headers: {
"Authorization": "Bearer "+token,
}
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
console.log('user posts stream retrieved');
// return data immediately
// all posts are ADN format, we need to convert to semi-ADN format
// shouldn't it be our internal format? yes as that's what expected
// from all dataaccess calls...
var dbposts={}, postcounter=0, usercounter=0;
//console.log('dispatcher.js:getReplies - mapping '+posts.length);
if (res.data && res.data.length) {
res.data.map(function(current, idx, Arr) {
// if we don't upload user objects then it'll proxy them when postToAPI is called
ref.dispatcher.updateUser(current.user, ts, function(userobj, err) {
usercounter++;
if (usercounter==res.data.length) {
// still finishes after posts converted (sometimes)
console.log('user posts user upload complete');
}
});
// get the post in DB foromat
ref.dispatcher.apiToPost(current, res.meta, function(post, err, meta) {
// can error out
if (post) {
dbposts[post.id]=post;
}
// always increase counter
postcounter++;
// join
//console.log(apiposts.length+'/'+entities.length);
if (postcounter==res.data.length) {
//console.log('dispatcher.js::getReplies - finishing');
// need to restore original order
var postsres=[];
for(var i in res.data) {
if (res.data[i]) {
postsres.push(dbposts[res.data[i].id]);
}
}
//console.log('dispatcher.js::getReplies - result ',res);
console.log('user posts converted (users updated), sending data');
callback(postsres, null, meta);
}
});
}, ref);
} else {
// no posts
console.log('dispatcher.js:getReplies - no replies ');
callback([], 'no posts for replies', meta);
}
/*
for(var i in res.data) {
res.data[i]=ref.dispatcher.apiToPost(res.data[i]);
// if we don't upload user objects then it'll proxy them when postToAPI is called
ref.dispatcher.updateUser(res.data[i].user, ts);
//res.data[i].created_at=new Date(res.data[i].created_at);
//res.data[i].user.created_at=new Date(res.data[i].user.created_at);
//res.data[i].userid=res.data[i].user.id;
// repost_of?
//console.log('test',res.data[i].created_at);
}
*/
// low priority (makes the respone return so much faster, well sometimes?)
setImmediate(function() {
// save data we have into cache
console.log('preping posts/follow upload');
// dispatcher will fetch it in ADN API format
ref.dispatcher.getUser(user, null, function(self, err) {
//console.log('self',self);
// post process after the fact
for(var i in res.data) {
var post=res.data[i];
//console.log('test',post.created_at);
//console.log('postuser',post.user.avatar_image);
// is this mutating user? not likely
ref.dispatcher.setPost(post);
// could build a fake follow structure here to bridge gaps
// since this is one of the few calls that implies follows
// this isn't that important for now, lower priority it
setImmediate(function() {
var follow={
follows_user: post.user,
user: self
};
// we could set ts to 0, since we don't know when they followed
// but we need to stomp any deleted follows for this pair
// not deleted, no id...
//console.log('setFollow', follow.user.avatar_image, follow.follows_user.avatar_image);
if (typeof(follow.follows_user.avatar_image.width)=='undefined' || typeof(follow.user.avatar_image.width)=='undefined') {
console.log('failure on '+i);
}
ref.dispatcher.setFollows(follow, 0, 0, ts);
});
}
console.log('uploaded scraps');
});
});
} else {
console.log('dataccess.proxy.js:getUserStream - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e, null);
}
});
downloader.dispatcher=ref.dispatcher;
downloader.downloadFollowing(user, token);
/** @todo async processing needed, so we don't lock the API. This all could be sent to a background thread*/
/*
// after the fact processing
// assuming this proxy trigger means we don't have any followers for user
// let's get some users
var downloadfollowers=function(start, ts, self) {
console.log('proxying user '+user+' following before '+start);
proxycalls++;
var str='';
if (start) {
str+='&before_id='+start;
}
var startdelay=0;
var startdelay2=0;
var counter=0;
// if we lower the count, we maybe more responsive...
request.get({
url: ref.apiroot+'/users/'+user+'/following?count=200'+str,
headers: {
"Authorization": "Bearer "+token,
}
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
console.log('retrieved followings '+res.data.length);
// post process
// 200 setFollow subprocess takes a huge toll on node
// really slows the whole thing down...
// this can lock for more than 35s
// and then events/triggers really pile up
for(var i in res.data) {
var follow={
follows_user: res.data[i],
user: self
};
//console.log('follow is ',follow);
//ref.dispatcher.setPost(post);
// ok, let's not spam our workers, we'll slowly deal out this work.
// 100 is too slow on my machine
// 200 is fine
// at 150, we can sync 900 users & follows in under 60s
// probably can be an issue if multiple users are calling this...
// though at 150 starting to see hangs towards the end
startdelay2+=200;
var func2=function(follow) {
// this put it high on the QoS list but delayed...
// so we get some what of a medium priority (not current but not low)
// doesn't the delay cancel whether it's high or low?
// probably...
setTimeout(function() {
// if we can skip the self update, that may help performance
ref.dispatcher.setFollows(follow, 0, 0, ts);
counter++;
if (counter==res.data.length) {
console.log('Following batch complete',counter);
}
}, startdelay2);
};
func2(follow);
*/
/** @todo we need to track usage rate/limits on each token */
// we could also queue up their last 20 posts too...
// it's a little agressive, we have want we need for the user stream
// burns through our token limits and puts unneeded stress on the network
// well as long as we have an upstream we don't need this
// even if we didn't, we'd have to poll global anyways to get all new posts efficently
/*
startdelay+=10*1000; // we get about 20 reads/minute
// 10*200=over 20 minutes to d/l everything
var userid=res.data[i].id;
//console.log('at '+startdelay+'s get user\'s '+userid+' posts');
// scope hacks...
var func=function(userid) {
setTimeout(function() {
ref.getUserPosts(userid, null, function() {});
}, startdelay);
};
func(userid);
*/
/*
}
console.log('Processed all '+res.data.length+' followings');
// dispatcher next io call asap
// need to page results too...
if (res.meta && res.meta.more) {
// in 1s
console.log('dataccess.proxy.js::getUserStream - getting more followings',res.meta.min_id,res.meta.max_id);
// in one second continue
//setTimeout(function() {
// should help the stack, right? we don't need to return any faster here
// lets block until we're done
// but it does yeild for a second
// doesn't work like that in v10
// we don't want to yeild, it's a high priority we get all these
//setImmediate(function() {
downloadfollowers(res.meta.min_id, ts, self);
//});
//}, 1000);
} else {
console.log('dataccess.proxy.js::getUserStream - retrieved all followings',res.meta);
}
} else {
console.log('dataccess.proxy.js:getUserStream followings download - request failure');
// e can be { [Error: socket hang up] code: 'ECONNRESET' }
console.log('error');
console.dir(e);
if (r) {
console.log('statusCode', r.statusCode);
}
console.log('body', body);
}
});
}
// background but at top of queue
// so we get a tick of yeild in there, let's not starve other's requests
// uhm there is no rush to download all the followers
// we've already served the stream
// ah but you can't update the stream until we know everyone that you're following
// so there is a rush
setTimeout(function() {
ref.dispatcher.getUser(user, null, function(self, err) {
//console.log('self',self);
downloadfollowers(0, ts, self);
});
}, 0);
//callback([], null);
*/
},
// user can be an id or @username
getUnifiedStream: function(user, params, token, callback) {
//console.log('dataaccess.proxy.js::getUserStream - write me!');
var ref=this;
var ts=new Date().getTime();
proxycalls++;
console.log('proxying user posts stream '+user);
request.get({
url: ref.apiroot+'/posts/stream',
headers: {
"Authorization": "Bearer "+token,
}
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
console.log('user posts stream retrieved');
// return data immediately
// all posts are ADN format, we need to convert to semi-ADN format
// shouldn't it be our internal format? yes as that's what expected
// from all dataaccess calls...
var dbposts={}, postcounter=0, usercounter=0;
//console.log('dispatcher.js:getReplies - mapping '+posts.length);
if (res.data && res.data.length) {
res.data.map(function(current, idx, Arr) {
// if we don't upload user objects then it'll proxy them when postToAPI is called
ref.dispatcher.updateUser(current.user, ts, function(userobj, err) {
usercounter++;
if (usercounter==res.data.length) {
// still finishes after posts converted (sometimes)
console.log('user posts user upload complete');
}
});
// get the post in DB foromat
ref.dispatcher.apiToPost(current, res.meta, function(post, err, meta) {
// can error out
if (post) {
dbposts[post.id]=post;
}
// always increase counter
postcounter++;
// join
//console.log(apiposts.length+'/'+entities.length);
if (postcounter==res.data.length) {
//console.log('dispatcher.js::getReplies - finishing');
// need to restore original order
var postsres=[];
for(var i in res.data) {
if (res.data[i]) {
postsres.push(dbposts[res.data[i].id]);
}
}
//console.log('dispatcher.js::getReplies - result ',res);
console.log('user posts converted (users updated), sending data');
callback(postsres, null, meta);
}
});
}, ref);
} else {
// no posts
console.log('dispatcher.js:getReplies - no replies ');
callback([], 'no posts for replies', meta);
}
/*
for(var i in res.data) {
res.data[i]=ref.dispatcher.apiToPost(res.data[i]);
// if we don't upload user objects then it'll proxy them when postToAPI is called
ref.dispatcher.updateUser(res.data[i].user, ts);
//res.data[i].created_at=new Date(res.data[i].created_at);
//res.data[i].user.created_at=new Date(res.data[i].user.created_at);
//res.data[i].userid=res.data[i].user.id;
// repost_of?
//console.log('test',res.data[i].created_at);
}
*/
// low priority (makes the respone return so much faster, well sometimes?)
setImmediate(function() {
// save data we have into cache
console.log('preping posts/follow upload');
// dispatcher will fetch it in ADN API format
ref.dispatcher.getUser(user, null, function(self, err) {
//console.log('self',self);
// post process after the fact
for(var i in res.data) {
var post=res.data[i];
//console.log('test',post.created_at);
//console.log('postuser',post.user.avatar_image);
// is this mutating user? not likely
ref.dispatcher.setPost(post);
// could build a fake follow structure here to bridge gaps
// since this is one of the few calls that implies follows
// this isn't that important for now, lower priority it
setImmediate(function() {
var follow={
follows_user: post.user,
user: self
};
// we could set ts to 0, since we don't know when they followed
// but we need to stomp any deleted follows for this pair
// not deleted, no id...
//console.log('setFollow', follow.user.avatar_image, follow.follows_user.avatar_image);
if (typeof(follow.follows_user.avatar_image.width)=='undefined' || typeof(follow.user.avatar_image.width)=='undefined') {
console.log('failure on '+i);
}
ref.dispatcher.setFollows(follow, 0, 0, ts);
});
}
console.log('uploaded scraps');
});
});
} else {
console.log('dataccess.proxy.js:getUserStream - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e, null);
}
});
},
getUserPosts: function(user, params, callback) {
if (user==undefined) {
callback(null, 'dataccess.proxy.js::getUserPosts - user is undefined');
return;
}
if (user==='') {
callback(null, 'dataccess.proxy.js::getUserPosts - user is empty');
return;
}
var ref=this;
console.log('proxying user posts '+user);
proxycalls++;
request.get({
url: ref.apiroot+'/users/'+user+'/posts'
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
for(var i in res.data) {
var post=res.data[i];
ref.dispatcher.setPost(post);
}
callback(res.data, null, res.meta);
} else {
console.log('dataccess.proxy.js:getUserPosts - request failure');
console.log('error', e);
if (r) {
console.log('statusCode', r.statusCode);
}
console.log('body', body);
callback(null, e, null);
}
});
},
getMentions: function(user, params, token, callback) {
//console.log('dataaccess.proxy.js::getMentions - write me');
var ref=this;
proxycalls++;
var querystring='';
if (params.count || params.since_id || params.before_id) {
// convert to array/loop
// 0 is ok, where's isset for JS?
if (params.count!=20) { // if not equal default
querystring+='&count='+params.count;
}
if (params.since_id) {
querystring+='&since_id='+params.since_id;
}
if (params.before_id) {
querystring+='&before_id='+params.before_id;
}
}
console.log('proxying global?'+querystring);
request.get({
url: ref.apiroot+'/users/'+user+'/mentions?'+querystring
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
//console.dir(res);
for(var i in res.data) {
var post=res.data[i];
//console.log('Processing post '+post.id);
ref.dispatcher.setPost(post);
}
callback(res.data, null, res.meta);
} else {
console.log('dataccess.proxy.js:getMentions - request failure');
console.log('error', e);
console.log('statusCode', r.statusCode);
console.log('body', body);
callback(null, e, null);
}
});
},
getGlobal: function(params, callback) {
//console.log('dataaccess.proxy.js::getGlobal - write me');
var ref=this;
proxycalls++;
var querystring='';
if (params.count || params.since_id || params.before_id) {
// convert to array/loop
// 0 is ok, where's isset for JS?
if (params.count!=20) { // if not equal default
querystring+='&count='+params.count;
}
if (params.since_id) {
querystring+='&since_id='+params.since_id;
}
if (params.before_id) {
querystring+='&before_id='+params.before_id;
}
}
console.log('proxying global?'+querystring);
request.get({
url: ref.apiroot+'/posts/stream/global?'+querystring
}, function(e, r, body) {
if (!e && r.statusCode == 200) {
var res=JSON.parse(body);
//console.dir(res);
for(var i in res.data) {
var post=res.data[i];
//console.log('Processing post '+post.id);