forked from jvimedia/AppDotNetAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataaccess.caminte.js
3116 lines (3042 loc) · 113 KB
/
dataaccess.caminte.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
/**
* real long term persistence
* @module dataaccess_camintejs
*/
/**
* http://www.camintejs.com / https://github.com/biggora/caminte
* @type {Object}
*/
var Schema = require('caminte').Schema;
// caminte can support: mysql, sqlite3, riak, postgres, couchdb, mongodb, redis, neo4j, firebird, rethinkdb, tingodb
// however AltAPI will officially support: sqlite, Redis or MySQL for long term storage
//
// @duerig wants Redis for long term storage
// however it requires the entire dataset to be in memory,
// so not all the network data could be store in it, unless you have 128gb+ of memory
// 1gb of memory in redis right now (with Jun 2014 data models) holds roughly:
// ~200k posts (204k annotations, 246k entities) ~10k users (6k follows) 2.4k interactions
//
// so MySQL is good alternative if you want a large dataset
// SQLite is a good incase the user doesn't want to install any extra software
// in memory mode, 400mb holds about 6690U 2694F 84890P 0C 0M 0s 770i 83977a 126741e
// memory mode is only good for dev, after buckets get big the API stops responding
// in sqlite3 mode, 50mb of diskspace holds 3736U 1582F 15437P 0C 0M 0s 175i 14239a 29922e
// set up the (eventually configureable) model pools
// 6379 is default redis port number
/** schema data backend type */
var schemaDataType = 'mysql';
/** set up where we're storing the "network data" */
var configData = { database: '', host: '', username: '', password: '' };
var schemaData = new Schema(schemaDataType, configData); //port number depends on your configuration
/** set up where we're storing the tokens */
var configToken = { database: '', host: '', username: '', password: '' }
var schemaToken = new Schema(schemaDataType, configToken); //port number depends on your configuration
if (schemaDataType==='mysql') {
//console.log('MySQL is active');
//charset: "utf8_general_ci"
// run a query "set names utf8"
schemaData.client.changeUser({ charset: 'utf8mb4' }, function(err) {
if (err) console.error('Couldnt set UTF8mb4', err);
//console.log('Set charset to utf8mb4 on Data');
});
schemaToken.client.changeUser({ charset: 'utf8mb4' }, function(err) {
if (err) console.error('Couldnt set UTF8mb4', err);
//console.log('Set charset to utf8mb4 on Token');
});
}
// Auth models and accessors can be moved into own file?
// so that routes.* can access them separately from everything!
// NOTE: all models automically have a default 'id' field that's an AutoIncrement
/**
* Token Models
*/
/** upstreamUserToken storage model */
var upstreamUserTokenModel = schemaToken.define('upstreamUserToken', {
userid: { type: Number, index: true },
/** comma separate list of scopes. Available scopes:
'basic','stream','write_post','follow','update_profile','public_messages','messages','files' */
scopes: { type: String, length: 255 },
token: { type: String, length: 98, index: true },
});
// scopes 'public_messages','messages','files':*
// but we can be multiple, not just one...
//localUserTokenModel.validatesInclusionOf('scopes', { in: ['basic','stream','write_post','follow','update_profile','public_messages','messages','files']});
upstreamUserTokenModel.validatesUniquenessOf('token', { message:'token is not unique'});
// localTokens
// we could add created_at,updated_at,last_used
// move out scopes to grant and link to grants
var localUserTokenModel = schemaToken.define('localUserToken', {
userid: { type: Number, index: true },
token: { type: String, length: 98, index: true },
client_id: { type: String, length: 32, index: true },
/** comma separate list of scopes. Available scopes:
'basic','stream','write_post','follow','update_profile','public_messages','messages','files' */
scopes: { type: String, length: 255 },
});
// code: { type: String, length: 255 },
// grantid: { type: Number, index: true },
// scopes 'public_messages','messages','files':*
// but we can be multiple, not just one...
//localUserTokenModel.validatesInclusionOf('scopes', { in: ['basic','stream','write_post','follow','update_profile','public_messages','messages','files']});
// token, client_id are unique
//localUserTokenModel.validatesUniquenessOf('token', { message:'token is not unique'});
// local apps
var oauthAppModel = schemaToken.define('oauthApp', {
//accountid: { type: Number, index: true },
client_id: { type: String, length: 32, index: true },
secret: { type: String, length: 255 },
shortname: { type: String, length: 255 },
displayname: { type: String, length: 255 }
});
// authorized local app callbacks
var oauthCallbackModel = schemaToken.define('oauthCallback', {
appid: { type: Number, index: true },
url: { type: String, length: 255 }
});
// I think it's better we have a combined table (localUserToken)
// we could put "code" into the localUserTokenModel
// because we're not going to have more than one token per user
/*
// local app grants (could replace session?)
var oauthGrantModel = schemaToken.define('oauthGrant', {
appid: { type: Number, index: true },
scope: { type: String, length: 255 },
userid: { type: Number, index: true },
code: { type: String, length: 255 },
});
*/
// well localUserToken is a combo of grants and tokens
// DEPRECATE UserTokenModel, it became localUserToken
/** appToken storage model */
var appTokenModel = schemaToken.define('appToken', {
client_id: { type: String, length: 32 },
token: { type: String, lenghh: 98 },
});
appTokenModel.validatesUniquenessOf('token', {message:'token is not unique'});
/**
* Network Data Models
*/
// this data needs to not use internal Pks
// I'd like to be able to copy random tables from one server to another
// to help bootstrap caches
// local clients (upstream is set in config and we can only have one upstream)
/** client storage model */
var clientModel = schemaData.define('client', {
client_id: { type: String, limit: 32, index: true }, // probably should be client_id
secret: { type: String, limit: 32 },
userid: { type: Number },
name: { type: String, limit: 255 },
link: { type: String, limit: 255 }
});
clientModel.validatesUniquenessOf('client_id', {message:'client_id is not unique'});
/** user storage model */
var userModel = schemaData.define('user', {
/* API START */
username: { type: String, length: 21, index: true },
name: { type: String, length: 50 },
description: { type: schemaData.Text },
descriptionhtml: { type: schemaData.Text }, /* cache */
created_at: { type: Date },
timezone: { type: String, length: 64 },
// maybe remove this?
locale: { type: String, length: 16 },
// this will need to change, so we can support multiples?
avatar_image: { type: String, length: 255 },
avatar_width: { type: Number } ,
avatar_height: { type: Number } ,
cover_image: { type: String, length: 255 },
cover_width: { type: Number } ,
cover_height: { type: Number } ,
// is_default?
following: { type: Number, default: 0 }, /* cache */
followers: { type: Number, default: 0 }, /* cache */
posts: { type: Number, default: 0 }, /* cache */
stars: { type: Number, default: 0 }, /* cache */
deleted: { type: Date },
type: { type: String, length: 32 },
canonical_url: { type: String, length: 255 },
verified_domain: { type: String, length: 255 },
verified_link: { type: String, length: 255 },
/* API END */
last_updated: { type: Date },
stars_updated: { type: Date },
language: { type: String, length: 2 },
country: { type: String, length: 2 },
});
userModel.validatesUniquenessOf('username', {message:'username is not unique'});
/** post storage model
* @constructs postModel
*/
var postModel = schemaData.define('post',
/** @lends postModel */
{
/** id of user */
userid: { type: Number, index: true },
/** text of post */
text: { type: schemaData.Text },
/** html of post */
html: { type: schemaData.Text }, /* cache */
/** post flagged as machine_only
* @type boolean */
machine_only: { type: Boolean, default: false, index: true },
/** id of post that it's a reply to
* @type {postid} */
reply_to: { type: Number }, // kind of want to index this
/** root id of post all replies are children of
* @type {postid} */
thread_id: { type: Number, index: true },
/** post flagged as deleted
* @type boolean */
is_deleted: { type: Boolean, default: false, index: true },
/** date/time post was created at
* @type Date */
created_at: { type: Date },
/** apparently we're string the client_id string here, may want an id here in the future */
client_id: { type: String, length: 32, index: true },
/** id of post it is a repost of
* @type {postid} */
repost_of: { type: Number, default: 0, index: true },
/** posts.app.net url */
canonical_url: { type: String },
/** num of replies */
num_replies: { type: Number, default: 0 },
/** num of reposts */
num_reposts: { type: Number, default: 0 },
/** num of stars */
num_stars: { type: Number, default: 0 }
});
// total cache table (since I think we can extract from text),
// we'll have an option to omitted its use
// though we need it for hashtag look ups
/** entity storage model */
var entityModel = schemaData.define('entity', {
idtype: { type: String, length: 16, index: true }, // user, post, channel, message
typeid: { type: Number, index: true }, // causing problems?
type: { type: String, length: 16, index: true }, // link, hashtag, mention
pos: { type: Number },
len: { type: Number },
text: { type: String, length: 255, index: true }, // hashtag is stored here
alt: { type: String, length: 255, index: true },
altnum: { type: Number },
});
/** annotation storage model */
var annotationModel = schemaData.define('annotation', {
idtype: { type: String, index: true }, // user, post, channel, message
typeid: { type: Number, index: true }, // causing problems?
type: { type: String, length: 255, index: true },
value: { type: schemaData.JSON },
});
// maybe not needed with JSON type
/** annotation values storage model */
var annotationValuesModel = schemaData.define('annotationvalues', {
annotationid: { type: Number, index: true },
key: { type: String, length: 255, index: true },
value: { type: schemaData.Text }, // kind of want to index this
memberof: { type: Number, index: true }
});
// inactive?
/** channel storage model */
var channelModel = schemaData.define('channel', {
ownerid: { type: Number, index: true },
type: { type: String, length: 255, index: true },
reader: { type: Number }, // 0=public,1=loggedin,2=selective
writer: { type: Number }, // 1=loggedin,2=selective
// editors are always seletcive
readedit: { type: Boolean, default: true }, // immutable?
writeedit: { type: Boolean, default: true }, // immutable?
editedit: { type: Boolean, default: true }, // immutable?
// could be store as json, since we're parsing either way...
readers: { type: schemaData.Text }, // comma separate list
// can't index because text (, index: true)
writers: { type: schemaData.Text }, // comma separate list (need index for PM channel lookup)
editors: { type: schemaData.Text }, // comma separate list
created_at: { type: Date }, // created_at isn't in the API
inactive: { type: Date }, // date made inactive
last_updated: { type: Date },
});
/** message storage model */
var messageModel = schemaData.define('message', {
channel_id: { type: Number, index: true },
html: { type: schemaData.Text }, /* cache */
text: { type: schemaData.Text },
machine_only: { type: Boolean, index: true },
client_id: { type: String, length: 32 },
thread_id: { type: Number, index: true },
userid: { type: Number, index: true },
reply_to: { type: Number }, // kind of want to index this
is_deleted: { type: Boolean, index: true },
created_at: { type: Date },
});
/** subscription storage model */
var subscriptionModel = schemaData.define('subscriptions', {
channelid: { type: Number, index: true },
userid: { type: Number, index: true },
created_at: { type: Date },
active: { type: Boolean, index: true },
last_updated: { type: Date },
});
/** follow storage model */
var followModel = schemaData.define('follow', {
userid: { type: Number, index: true },
followsid: { type: Number, index: true }, // maybe not index this
active: { type: Boolean, index: true },
// aka pagenationid, we'll need this for meta.id too
referenceid: { type: Number, index: true }, // this only exists in meta.id and is required for deletes for app streaming
created_at: { type: Date }, // or this
last_updated: { type: Date },
});
// split up?
// we don't need reposts here becauses have all that info with a repost_of column
// since an entire post is created on repost
// though repost could also write here in the future, making it easier to pull
// stars are recorded only here
/** interaction storage model */
var interactionModel = schemaData.define('interaction', {
userid: { type: Number, index: true },
type: { type: String, length: 8, index: true }, // star,unstar,repost,unrepost
datetime: { type: Date },
idtype: { type: String, index: true }, // post (what about chnl,msg,user? not for existing types)
typeid: { type: Number, index: true }, // causing problems?
asthisid: { type: Number } // meta.id
});
/** star storage model */
// not currently used
var starModel = schemaData.define('star', {
userid: { type: Number, index: true },
created_at: { type: Date },
postid: { type: Number, index: true },
// I don't think we need soft delets for fars
//is_deleted: { type: Boolean, default: false, index: true },
});
// intermediate cache table for querying (a view of interactionModel)
// we have to denormalize this for performance
// takes more memory/storage but required if you want responsive interactions
var noticeModel = schemaData.define('notice', {
event_date: { type: Date, index: true },
notifyuserid: { type: Number, index: true }, // who should be notified
actionuserid: { type: Number }, // who took an action (star)
type: { type: String, length: 18 }, // welcome,star,repost,reply,follow,broadcast_create,broadcast_subscribe,broadcast_unsubscribe
typeid: { type: Number }, // postid(star,respot,reply),userid(follow)
});
/** file storage model */
var fileModel = schemaData.define('file', {
/* API START */
userid: { type: Number, index: true },
created_at: { type: Date },
client_id: { type: String, length: 32 },
kind: { type: String, length: 255, index: true },
name: { type: String, length: 255 },
type: { type: String, length: 255, index: true }, // com.example.test
complete: { type: Boolean },
sha1: { type: String, length: 255 },
url: { type: String, length: 512 },
total_size: { type: Number },
size: { type: Number },
mime_type: { type: String, length: 255 },
urlexpires: { type: Date },
/* API END */
last_updated: { type: Date },
});
// kind of a proxy cache
// we'll it's valid to check the upstream
// maybe a time out
// actually downloader is in charge of refreshing, as long as we kick that off
// we can still use this
// we know there's no data for this
var emptyModel = schemaData.define('empty', {
type: { type: String, length: 16, index: true }, // repost, replies
typeid: { type: Number, index: true }, // postid
last_updated: { type: Date },
});
//if firstrun (for sqlite3, mysql)
if (schemaDataType=='mysql' || schemaDataType=='sqlite3') {
//schemaData.automigrate(function() {});
//schemaToken.automigrate(function() {});
// don't lose data
schemaData.autoupdate(function() {});
schemaToken.autoupdate(function() {});
}
// Auth Todo: localUser, localClient
// Token Todo: userToken, appToken
// Rate Todo: userTokenLimit, appTokenLimit
// Data Todo: mutes, blocks, upstream_tokens
/*
setInterval(function() {
if (module.exports.connection) {
module.exports.connection.ping(function (err) {
if (err) {
console.log('lets_parser::monitor - reconnecting, no ping');
ref.conn(module.exports.last.host, module.exports.last.user,
module.exports.last.pass, module.exports.last.db);
}
//console.log(Date.now(), 'MySQL responded to ping');
})
}
}, 60000);
*/
/** minutely status report */
// @todo name function and call it on startup
var statusmonitor=function () {
if (schemaDataType=='mysql') {
schemaData.client.ping(function (err) {
if (err) {
console.log('trying to reconnect to data db');
schemaData = new Schema(schemaDataType, configData);
}
})
}
if (schemaDataType=='mysql') {
schemaToken.client.ping(function (err) {
if (err) {
console.log('trying to reconnect to token db');
schemaToken = new Schema(schemaDataType, configToken);
}
})
}
var ts=new Date().getTime();
// this is going to be really slow on innodb
userModel.count({}, function(err, userCount) {
followModel.count({}, function(err, followCount) {
postModel.count({}, function(err, postCount) {
channelModel.count({}, function(err, channelCount) {
messageModel.count({}, function(err, messageCount) {
subscriptionModel.count({}, function(err, subscriptionCount) {
interactionModel.count({}, function(err, interactionCount) {
annotationModel.count({}, function(err, annotationCount) {
entityModel.count({}, function(err, entityCount) {
noticeModel.count({}, function(err, noticeCount) {
// break so the line stands out from the instant updates
// dispatcher's output handles this for now
//process.stdout.write("\n");
// if using redis
if (schemaDataType=='sqlite3') {
schemaData.client.get('PRAGMA page_count;', function(err, crow) {
//console.log('dataaccess.caminte.js::status sqlite3 page_count', row);
schemaData.client.get('PRAGMA page_size;', function(err, srow) {
var cnt=crow['page_count'];
var psize=srow['page_size'];
var size=cnt*psize;
console.log('dataaccess.caminte.js::status sqlite3 data [',cnt,'x',psize,'] size: ', size);
});
});
}
if (schemaDataType=='redis') {
//console.dir(schemaAuth.client.server_info);
// just need a redis info call to pull memory and keys stats
// evicted_keys, expired_keys are interesting, keyspace_hits/misses
// total_commands_proccesed, total_connections_received, connected_clients
// update internal counters
schemaData.client.info(function(err, res) {
schemaData.client.on_info_cmd(err, res);
});
// then pull from counters
console.log("dataaccess.caminte.js::status redis token "+schemaToken.client.server_info.used_memory_human+" "+schemaToken.client.server_info.db0);
console.log("dataaccess.caminte.js::status redis data "+schemaData.client.server_info.used_memory_human+" "+schemaData.client.server_info.db0);
}
console.log('dataaccess.caminte.js::status '+userCount+'U '+followCount+'F '+postCount+'P '+channelCount+'C '+messageCount+'M '+subscriptionCount+'s '+interactionCount+'/'+noticeCount+'i '+annotationCount+'a '+entityCount+'e');
});
});
});
});
});
});
});
});
});
});
};
statusmonitor();
setInterval(statusmonitor, 60*1000);
// Not Cryptographically safe
// FIXME: probably need more of a UUID style generator here...
function generateUUID(string_length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var randomstring = '';
for (var x=0;x<string_length;x++) {
var letterOrNumber = Math.floor(Math.random() * 2);
if (letterOrNumber == 0) {
var newNum = Math.floor(Math.random() * 9);
randomstring += newNum;
} else {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum+1);
}
}
return randomstring;
}
// cheat macros
function db_insert(rec, model, callback) {
//console.log('dataaccess.caminte.js::db_insert - start');
rec.isValid(function(valid) {
//console.log('dataaccess.caminte.js::db_insert - Checked');
if (valid) {
//console.log(typeof(model)+'trying to create ',rec);
// mysql can't handle any undefineds tbh
//console.log('dataaccess.caminte.js::db_insert - Valid', rec, typeof(model));
// sometimes model.create doesn't return...
// maybe a timer to detect this (timeout) and callback
model.create(rec, function(err) {
//console.log('dataaccess.caminte.js::db_insert - created');
if (err) {
console.log(typeof(model)+" insert Error ", err);
}
if (callback) {
//console.log('dataaccess.caminte.js::db_insert - callingback');
if (rec.id) {
// why don't we just return the entire record
// that way we can get access to fields we don't have a getter for
// or are generated on insert
callback(rec, err);
} else {
callback(null, err);
}
}
});
} else {
console.log(typeof(model)+" validation failure");
console.dir(rec.errors);
if (callback) {
// can we tell the different between string and array?
callback(null, rec.errors);
}
}
});
}
// these macros mainly flip the callback to be consistent
function db_delete(id, model, callback) {
model.destroyById(id, function(err, rec) {
if (err) {
console.log("delUser Error ", err);
}
if (callback) {
callback(rec, err);
}
});
}
function db_get(id, model, callback) {
model.findById(id, function(err, rec) {
if (err) {
console.log("db_get Error ", err);
}
// this one is likely not optional...
//if (callback) {
callback(rec, err);
//}
});
}
// if we pass model separately
function applyParams(query, params, callback) {
//console.log('applyParams - params', params);
/*
var idfield='id';
if (query.model.modelName==='entity') {
// typeid is usually the post
//query=query.order('typeid', 'DESC').limit(params.count);
idfield='typeid';
}
// do we need to omit deleted in the results?
// depends on how really maxid is used
// I really don't see it causing any harm
var where={};
if (query.model.modelName==='post' || query.model.modelName==='message') {
//console.log('applyParams - params', params);
if (params.generalParams && !params.generalParams.deleted) {
where.is_deleted=0; // add delete param
}
}
*/
// maybe optimize with all?
//if (where) {
// why do we need max? looks like we don't
// it was linked to min...
var maxid=0;
/*
query.model.find({ where: where, order: idfield+' DESC', limit: 1}, function(err, items) {
if (items.length) {
maxid=items[0][idfield];
}
*/
//console.log('applyParams - maxid', maxid);
setparams(query, params, maxid, callback)
//});
}
function setparams(query, params, maxid, callback) {
// what if we want all, how do we ask for that if not zero?
//if (!params.count) params.count=20;
// can't set API defaults here because the dispatch may operate outside the API limits
// i.e. the dispatch may want all records (Need example, well was getUserPosts of getInteractions)
//console.log('into setparams from',params.since_id,'to',params.before_id,'for',params.count);
// general guard
/*
if (maxid<20) {
// by default downloads the last 20 posts from the id passed in
// so use 20 so we don't go negative
// FIXME: change to scoping in params adjustment
maxid=20;
}
*/
// create a range it will exist in
// redis should be able to decisions about how to best optimize this
// rules out less optimal gambles
// and since it can't use less optimal gambles on failure
// uses the 68s system, ugh
/*
if (!params.since_id) {
params.since_id=0;
}
*/
// well if we have a where on a field, and we ad in id
// then we can't optimize, let's try without this
/*
if (!params.before_id) {
params.before_id=maxid;
}
*/
// bullet 5: Remember, items are always returned from newest to oldest even If count is negative
// if we do our math right, we won't need .limit(params.count);
// redis maybe need the limit to be performant
//console.log('test',query.model.modelName);
// not all objects have id linked to their chronology
var idfield='id';
if (query.model.modelName==='entity') {
// typeid is usually the post
//query=query.order('typeid', 'DESC').limit(params.count);
idfield='typeid';
}
if (query.model.modelName==='post' || query.model.modelName==='message') {
if (!params.generalParams || !params.generalParams.deleted) {
query.where('is_deleted', 0); // add delete param
}
}
// if not already sorted, please sort it
// but some calls request a specific sort
// though there are cases where we need to flip order
//console.log('setparams query order', query.q.params);
//console.log('setparams params', params);
var count = 20;
if (params.pageParams) {
if (params.pageParams.count!==undefined) {
count = params.pageParams.count;
}
} else {
console.log('dataaccess.caminte::setparams - WARNING no pageParams in params');
}
if (!query.q.params.order) {
//console.log('setparams params.count', params.count);
if (count>0) {
//console.log('setparams sorting', idfield, 'desc');
query=query.order(idfield, 'DESC')
}
if (count<0) {
//console.log('setparams sorting', idfield, 'asc');
query=query.order(idfield, 'ASC')
}
}
// add one at the end to check if there's more
var queryCount=Math.abs(count)+1;
//console.log('count', count, 'queryCount', queryCount);
query=query.limit(queryCount);
// this count system only works if we're asking for global
// and there's not garuntee we have all the global data locally
/*
if (params.before_id) {
if (!params.since_id) {
// only asking for before this ID, this only works for global
//params.since_id=Math.max(params.before_id-params.count, 0);
}
} else if (params.since_id) {
// no before but we have since
// it's maxid+1 because before_id is exclusive
// params.count was just count
//params.before_id=Math.min(params.since_id+params.count, maxid+1);
} else {
// none set
// if we have upstream enabled
params.before_id=maxid;
// count only works if contigeous (global)
//params.since_id=maxid-params.count;
// if we don't have upstream disable
// best to proxy global...
}
*/
//console.log(query.model.modelName, 'from', params.since_id, 'to', params.before_id, 'should be a count of', params.count, 'test', params.before_id-params.since_id);
// really won't limit or offset
// count shouldn't exceed the difference between since and before
// using Redis, querying by id range isn't fast enough (60 secs)
//
// I think between is broken in redis:caminte (helper::parseCond doesn't test for indexes right)
// yea now we're only getting a CondIndex of 22
// sunionstore - condIndex 22
// with between we'd get
// sunionstore - condIndex 518656
// both are still around 68s though
/*
if (params.since_id && params.before_id) {
query=query.between('id', [params.since_id, params.before_id]);
} else {
*/
// 0 or 1 of these will be true
// uhm both can be true like a between
// it's not inclusive
if (params.pageParams) {
if (params.pageParams.since_id) {
query=query.gt(idfield, params.pageParams.since_id);
}
if (params.pageParams.before_id) {
// if not before end
if (params.pageParams.before_id!=-1) {
query=query.lt(idfield, params.pageParams.before_id);
}
}
}
//}
/*
if (params.since_id && params.before_id) {
} else if (params.since_id) {
query=query.gt(params.since_id);
} else if (params.before_id) {
query=query.lt(params.before_id);
}
*/
//console.log('dataaccess.caminte.js::setparams query', query.q);
var min_id=Number.MAX_SAFE_INTEGER, max_id=0;
query.run({},function(err, objects) {
//console.log('dataaccess.caminte.js::setparams -', query.model.modelName, 'query got', objects.length, 'only need', params.count);
// first figure out "more"
// if got less than what we requested, we may not have it cached
// we'll have to rely on meta to know if it's proxied or not
//console.log('dataaccess.caminte.js::setparams - got', objects.length, 'queried', queryCount, 'asked_for', count);
var more = objects.length==queryCount;
// restore object result set
// which end to pop, well depends on count
if (more) {
// if we get 21 and we ask for 20
if (count>0) { // id desc
objects.pop();
}
if (count<0) { // id asc
for(var i in objects) {
console.log('dataaccess.caminte.js::setparams - negative count', objects[i].id);
}
objects.pop();
}
}
//console.log('dataaccess.caminte.js::setparams - resultset got', objects.length, 'range:', min_id, 'to', max_id, 'more:', more);
// generate meta, find min/max in set
for(var i in objects) {
var obj=objects[i];
//console.log('dataaccess.caminte.js::setparams - idx', obj[idfield], 'min', min_id, 'max', max_id);
if (obj[idfield]) {
min_id=Math.min(min_id, obj[idfield]);
max_id=Math.max(max_id, obj[idfield]);
}
}
if (min_id==Number.MAX_SAFE_INTEGER) min_id=0;
var imeta={
code: 200,
min_id: min_id,
max_id: max_id,
more: more
};
// was .reverse on posts, but I don't think that's right for id DESC
callback(objects, err, imeta);
});
}
// we need to know if we have upstreaming enabled
/**
* @constructs dataaccess
* @variation camtinejs
*/
module.exports = {
next: null,
/*
* users
*/
/**
* add User camintejs
* @param {string} username - name of user
* @param {string} password - unencrypted password of user
* @param {metaCallback} callback - function to call after completion
*/
addUser: function(username, password, callback) {
if (this.next) {
this.next.addUser(username, password, callback);
} else {
if (callback) {
callback(null, null);
}
}
},
setUser: function(iuser, ts, callback) {
// FIXME: check ts against last_update to make sure it's newer info than we have
// since we have cached fields
//console.log('camtinejs::setUser - iuser', iuser);
// doesn't overwrite all fields
userModel.findOne({ where: { id: iuser.id } }, function(err, user) {
//console.log('camtinejs::setUser - got res', user);
if (user) {
console.log('camtinejs::setUser - updating user', user.id);
userModel.update({ where: { id: iuser.id } }, iuser, function(err, user) {
if (callback) callback(user,err);
});
} else {
console.log('camtinejs::setUser - creating user');
db_insert(new userModel(iuser), userModel, callback);
}
});
},
patchUser: function(userid, changes, callback) {
userModel.update({ where: { id: userid } }, changes, function(err, user) {
if (callback) {
callback(user, err);
}
});
},
delUser: function(userid, callback) {
if (this.next) {
this.next.delUser(userid, callback);
} else {
if (callback) {
callback(null, null);
}
}
},
getUserID: function(username, callback) {
if (!username) {
console.log('dataaccess.caminte.js::getUserID() - username was not set');
callback(null, 'dataaccess.caminte.js::getUserID() - username was not set');
return;
}
if (username[0]==='@') {
username=username.substr(1);
}
//console.log('dataaccess.caminte.js::getUserID(', username, ') - start');
var ref=this;
var username=username.toLowerCase();
userModel.findOne({ where: { username: username }}, function(err, user) {
if (user==null && err==null) {
if (ref.next) {
ref.next.getUserID(username, callback);
return;
}
}
callback(user, err);
});
},
// callback is user, err, meta
getUser: function(userid, callback) {
if (userid==undefined) {
console.log('dataaccess.caminte.js:getUser - userid is undefined');
callback(null, 'dataaccess.caminte.js:getUser - userid is undefined');
return;
}
if (!userid) {
console.log('dataaccess.caminte.js:getUser - userid isn\'t set');
callback(null, 'dataaccess.caminte.js:getUser - userid isn\'t set');
return;
}
if (callback==undefined) {
console.log('dataaccess.caminte.js:getUser - callback is undefined');
callback(null, 'dataaccess.caminte.js:getUser - callback is undefined');
return;
}
//console.log('dataaccess.caminte.js:getUser - userid', userid);
if (userid[0]==='@') {
//console.log('dataaccess.caminte.js:getUser - getting by username');
this.getUserID(userid.substr(1), callback);
return;
}
var ref=this;
//console.log('dataaccess.sequalize.js:getUser - getting', userid);
db_get(userid, userModel, function(user, err) {
//console.log('dataaccess.sequalize.js:getUser - got', user);
if (user==null && err==null) {
if (ref.next) {
ref.next.getUser(userid, callback);
return;
}
}
callback(user, err);
});
},
getUsers: function(userids, params, callback) {
if (!userids.length) {
console.log('dataaccess.caminte::getUsers - no userids passed in');
callback([], 'did not give a list of userids');
return;
}
setparams(userModel.find().where('id', { in: userids }), params, 0, function(posts, err, meta) {
callback(posts, err, meta);
});
},
searchUsers: function(query, params, callback) {
// username, name, description
var userids={};
var done={
username: false,
name: false,
description: false,
}
function setDone(sys) {
var ids=[]
for(var i in userids) {
ids.push(i)
}
//console.log('searchUsers', sys, ids.length);
done[sys]=true;
for(var i in done) {
if (!done[i]) {
//console.log('searchUsers -', i, 'is not done');
return;
}
}
console.log('searchUsers done', ids.length);
if (!ids.length) {
callback([], null, { code: 200, more: false });
return;
}
setparams(userModel.find().where('id', { in: ids }), params, 0, function(posts, err, meta) {
callback(posts, err, meta);
});
}
userModel.find({ where: { username: { like : '%' + query + '%' }} }, function(err, users) {
for(var i in users) {
userids[users[i].id]++;
}
setDone('username');
})
userModel.find({ where: { name: { like : '%' + query + '%' }} }, function(err, users) {
for(var i in users) {
userids[users[i].id]++;
}
setDone('name');
})
userModel.find({ where: { description: { like : '%' + query + '%' }} }, function(err, users) {
for(var i in users) {
userids[users[i].id]++;
}
setDone('description');
})
/*
setparams(userModel.find().where('username', { like: '%' + query + '%' }), params, 0, function(posts, err, meta) {
callback(posts, err, meta);
});
*/
},
/*
* oauth local apps / callbacks
*/
getAppCallbacks: function(client_id, client_secret, callback) {
if (client_id===undefined) {
console.log('dataaccess.caminte::getAppCallbacks - no client_id passed in')
callback(null, 'no client_id');
return;
}
if (!client_secret) {
oauthAppModel.findOne({ where: { client_id: client_id } }, function(err, oauthApp) {
if (err || !oauthApp) {
console.log('getAppCallbacks - err', err)
callback(null, 'err or app not found');
return;
}
oauthCallbackModel.find({ where: { appid: oauthApp.id } }, function(err, callbacks) {
callback(callbacks, err);
})
});
return;
}
oauthAppModel.findOne({ where: { client_id: client_id, secret: client_secret } }, function(err, oauthApp) {
if (err || !oauthApp) {
console.log('getAppCallbacks - err', err)