forked from gigablast/open-source-search-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Facebook.cpp
5788 lines (5176 loc) · 160 KB
/
Facebook.cpp
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
#include "Facebook.h"
#include "HttpServer.h"
#include "sort.h"
#include "Repair.h"
// use this to get an access token for the event guru app
// https://graph.facebook.com/oauth/access_token?
// client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
// grant_type=client_credentials
// use this to cache a facebook user's friends, and userid of themselves
Facebookdb g_facebookdb;
Likedb g_likedb;
static void queueSleepWrapper ( int fd, void *state );
bool base64Decode ( char *dst, char *src, int32_t dstSize ) ;
///////////////////////////
//
// FACEBOOKDB
//
///////////////////////////
void Facebookdb::reset() {
m_rdb.reset();
}
bool Facebookdb::init ( ) {
if ( ! g_conf.m_indexEventsOnly ) return true;
// load this here so calling saveQueryLoopState() does not overwrite it
loadQueryLoopState ();
// hit the queue
if ( ! g_loop.registerSleepCallback(500,NULL,queueSleepWrapper))
return false;
/*
char tmp[2048];
char *sr = "eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzMzA0NTkyMDAsImlzc3VlZF9hdCI6MTMzMDQ1Mjk3Miwib2F1dGhfdG9rZW4iOiJBQUFGRWczUUE1eWdCQUg1b3dJTEt6WkNaQ0FDNmNTUVRaQWVaQmE2WkFiT1J2dkllSzc2MktGWFg2RmxaQ29iZWFzcENzWE5BZGh1R2VMQm1VM1hnNmMyTm1JenhxRlZkQ3d1Z0ZLRzVHWkN6WXlWaUpwZkN4UlYiLCJ1c2VyIjp7ImNvdW50cnkiOiJ1cyIsImxvY2FsZSI6ImVuX1VTIiwiYWdlIjp7Im1pbiI6MjF9fSwidXNlcl9pZCI6IjEwMDAwMzUzMjQxMTAxMSJ9";
base64Decode ( tmp , sr , 2040 );
log("facebook: %s",tmp);
*/
// . what's max # of tree nodes?
// . assume avg facebookdb rec size of about 1000 bytes
// . NOTE: 32 bytes of the 1000 are overhead
int32_t maxMem = 5000000;
int32_t maxTreeNodes = maxMem / 1000;//82;
// each entry in the cache is usually just a single record, no lists,
// unless a hostname has multiple sites in it. has 24 bytes more
// overhead in cache.
//int32_t maxCacheNodes = g_conf.m_tagdbMaxCacheMem / 106;
// we now use a page cache for the banned turks table which
// gets hit all the time
//if(! m_pc.init ("facebookdb",RDB_TAGDB,10000000,GB_TFNDB_PAGE_SIZE))
// return log("facebookdb: Tagdb init failed.");
// initialize our own internal rdb
if ( ! m_rdb.init ( g_hostdb.m_dir ,
"facebookdb" ,
true , // dedup same keys?
-1 , // fixed record size
2,//g_conf.m_tagdbMinFilesToMerge ,
maxMem, // 5MB g_conf.m_tagdbMaxTreeMem ,
maxTreeNodes ,
// now we balance so Sync.cpp can ordered huge list
true , // balance tree?
0 , //g_conf.m_tagdbMaxCacheMem ,
0 , //maxCacheNodes ,
false , // half keys?
false , //m_tagdbSaveCache
NULL, // &m_pc ,
false, // is titledb
false, // preload disk page cache
sizeof(key96_t), // key size
false , // bias disk page cache?
true )) // iscollectionless? syncdb,facebookdb,...
return false;
// add the base since it is a collectionless rdb
return m_rdb.addColl ( NULL );
}
bool Facebookdb::addColl ( char *coll, bool doVerify ) {
if ( ! m_rdb.addColl ( coll ) ) return false;
return true;
}
///////////////////////
//
// MSGFB
//
///////////////////////
Msgfb::Msgfb ( ) {
m_facebookReply = NULL;
//m_facebookReply2 = NULL;
m_msg7 = NULL;
m_fbId = 0LL;
m_inProgress = false;
reset();
}
#include "Process.h"
void Msgfb::reset ( ) {
// this can happen if we try to save and exit while in progress
if ( g_process.m_mode != EXIT_MODE &&
m_inProgress ) { char *xx=NULL;*xx=0; }
m_requests = 0;
m_replies = 0;
m_errno = 0;
m_errorCount = 0;
m_fbId = 0;
m_state = NULL;
m_callback = NULL;
m_collnum = 0;
m_niceness = MAX_NICENESS;
m_socket = NULL;
m_retryCount = 0;
m_widgetId = 0;
m_userToUserWidgetId = 0LL;
//m_fbrec.reset();
if ( m_facebookReply ) {
mfree ( m_facebookReply , m_facebookAllocSize ,"msgfb");
m_facebookReply = NULL;
}
//if ( m_facebookReply2 ) {
// mfree ( m_facebookReply2 , m_facebookAllocSize2 ,"msgfb");
// m_facebookReply2 = NULL;
//}
m_rbuf.purge();
if ( m_msg7 ) {
mdelete ( m_msg7, sizeof(Msg7) , "FBInject" );
delete ( m_msg7);
m_msg7 = NULL;
}
m_list1.freeList();
m_list2.freeList();
m_list3.freeList();
m_hr.reset();// = NULL;
m_fbrecPtr = NULL;
m_likedbTable.reset();
m_evPtrBuf.purge();
m_evIdsBuf.purge();
m_fidBuf.purge();
m_eidBuf.purge();
m_dedupEidBuf.reset();
// free mem
m_fullReply.purge();
}
Msgfb::~Msgfb ( ) {
reset();
}
///////////////////////
//
// MSGFB PIPELINE #1
//
///////////////////////
static void gotFBUserRecWrapper ( void *state ) {
Msgfb *mfb = (Msgfb *)state;
if ( ! mfb->gotFBUserRec ( ) ) return;
mfb->m_callback ( mfb->m_state );
}
static void gotFBAccessTokenWrapper ( void *state , TcpSocket *s ) {
Msgfb *mfb = (Msgfb *)state;
if ( ! mfb->gotFBAccessToken( s ) ) return;
mfb->m_callback ( mfb->m_state );
}
// format like strncpy()
bool base64Decode ( char *dst, char *src, int32_t dstSize ) {
// make the map
static unsigned char s_bmap[256];
static bool s_init = false;
if ( ! s_init ) {
s_init = true;
memset ( s_bmap , 0 , 256 );
unsigned char val = 0;
for ( unsigned char c = 'A' ; c <= 'Z'; c++ )
s_bmap[c] = val++;
for ( unsigned char c = 'a' ; c <= 'z'; c++ )
s_bmap[c] = val++;
for ( unsigned char c = '0' ; c <= '9'; c++ )
s_bmap[c] = val++;
if ( val != 62 ) { char *xx=NULL;*xx=0; }
s_bmap['+'] = 62;
s_bmap['/'] = 63;
}
// leave room for \0
char *dstEnd = dst + dstSize - 5;
unsigned char *p = (unsigned char *)src;
unsigned char val;
for ( ; ; ) {
if ( *p ) {val = s_bmap[*p]; p++; } else val = 0;
// copy 6 bits
*dst <<= 6;
*dst |= val;
if ( *p ) {val = s_bmap[*p]; p++; } else val = 0;
// copy 2 bits
*dst <<= 2;
*dst |= (val>>4);
dst++;
// copy 4 bits
*dst = val & 0xf;
if ( *p ) {val = s_bmap[*p]; p++; } else val = 0;
// copy 4 bits
*dst <<= 4;
*dst |= (val>>2);
dst++;
// copy 2 bits
*dst = (val&0x3);
if ( *p ) {val = s_bmap[*p]; p++; } else val = 0;
// copy 6 bits
*dst <<= 6;
*dst |= val;
dst++;
// sanity
if ( dst >= dstEnd ) {
log("facebook: bas64decode breach");
//char *xx=NULL;*xx=0;
*dst = '\0';
return false;
}
if ( ! *p ) break;
}
// null term just in case
dst[1] = '\0';
return true;
}
bool Msgfb::getFacebookUserInfo ( HttpRequest *hr,
TcpSocket *s,
char *coll,
void *state ,
char *redirPath,
void (* callback)(void *state) ,
int32_t niceness ) {
reset();
m_state = state;
m_callback = callback;
//m_hr = hr;
m_oldFbrec = NULL;
m_redirPath = redirPath;
m_socket = s;
m_collnum = g_collectiondb.getCollnum ( coll );
m_retryCount = 0;
// they just logged out
if ( hr->getLong("logout",0 ) ) return true;
// need to make a copy of it so we can access it
m_hr.copy ( hr );
// save this
m_widgetId = hr->getLongLongFromCookie("widgetid",0LL);
// make the facebook key url for tagdb lookup
char *fbidStr = m_hr.getStringFromCookie("fbid",NULL);
// check for "usefbid"
char *useFbid = m_hr.getString("usefbid",NULL);
// that overrides
if ( useFbid ) {
int64_t used = strtoull(useFbid,NULL,10);
int32_t h32a = hash32 ( (char *)&used, 8 );
// this has to be a int64_t because fh is printed as
// an uint32_t and atol() will croak
int32_t h32b = m_hr.getLongLong("fh",0);
if ( h32a != h32b ) {
useFbid = NULL;
log("facebook: bad usefbid=%"INT64" h32=%"UINT32" fh=%"UINT32"",
used,h32a,h32b);
}
else
fbidStr = useFbid;
}
// they've logged in before if we got this cookie, otherwise,
// they got cookies off or they have not logged in ever yet, so
// we gotta ask facebook for the access token.
if ( ! fbidStr )
return downloadAccessToken ( );
// . make the facebook key url for facebook user rec
// . we are here because we are assuming they are already logged in
// at some point in time and we should try to get their list
// of friends from the facebookdb rec so if they click
// to show all the events their friends are going to we can do that
int64_t fbId = strtoull ( fbidStr , NULL, 10 );
// if they come into the canvas page we receive an encoded access
// token and fbid from facebook. so get that and do the lookup.
// if we do not have the username in the facebookdb rec or we do not
// even have a facebook id rec, then we will have to use cmd1 fql
// before they can be logged in.
char *sr = m_hr.getString("signed_request",NULL);
if ( sr ) sr = strchr(sr,'.');
if ( sr ) sr++;
// decode that
char dsr[2048];
if ( sr ) base64Decode ( dsr , sr , 2040 );
// parse that json for fb user id
char *jsonfbid = NULL;
if ( sr ) jsonfbid = strstr ( dsr , "user_id\":\"" );
if ( jsonfbid ) jsonfbid += 10;
if ( jsonfbid ) fbId = atoll(jsonfbid);
// sometimes there's also an access token, if that is the case
// we can just right to the cmd1 fql call downloadFBUserInfo().
char *at = NULL;
if ( dsr ) at = strstr ( dsr , "oauth_token\":\"" );
if ( at ) at += 14;
if ( at && fbId ) {
// copy into m_accessToken
char *p = at;
for ( ; *p && *p != '\"' && *p != ',' ; p++);
*p = '\0';
if ( p - at + 1 < MAX_TOKEN_LEN ) {
strcpy ( m_accessToken , at );
log("facebook: got access token from canvas app");
if ( ! downloadUserToUserRequestInfo() ) return false;
return downloadFBUserInfo();
}
}
// for the facebookdb lookup to be legit this must be non-zero
if ( fbId == 0LL )
return downloadAccessToken ( );
key96_t startKey;
key96_t endKey;
startKey.n1 = 0;
startKey.n0 = fbId;
endKey.n1 = 0;
endKey.n0 = fbId;
startKey.n0 <<= 1;
endKey.n0 <<= 1;
endKey.n0 |= 0x01;
if ( ! m_msg0.getList ( -1, // hostid
0 , // ip
0 , // port
0 , // maxcacheage
false, // addtocache
RDB_FACEBOOKDB,
"",//coll,
&m_list1,
(char *)&startKey,
(char *)&endKey,
10, // minrecsizes
this ,
gotFBUserRecWrapper,
niceness ) )
return false;
// i guess we got it without blocking
return gotFBUserRec();
}
bool Msgfb::gotFBUserRec ( ) {
// . it can be empty if never got saved!
// . or if they logged out then logged back in, fbid will be 0
if ( m_list1.getListSize() <= 0 ) return downloadAccessToken();
// cast the list
FBRec *fbrec = (FBRec *)m_list1.getList();
// save that ptr
m_fbrecPtr = fbrec;
// get timestamp on that
//int32_t now = getTimeGlobal();
//int32_t elapsed = now - fbrec->m_accessTokenCreated;
// if stale, re-get it all from facebook.
//if ( elapsed >= 60*60 ) return downloadAccessToken ( );
// if still fresh, don't bother hitting facebook again, but we
// need to deserialize
deserializeMsg ( sizeof(FBRec) ,
&fbrec->size_accessToken ,
&fbrec->size_friendIds ,
&fbrec->ptr_accessToken ,
fbrec->m_buf );
// need to set this for printBlackBar()
m_fbId = fbrec->m_fbId;
log("facebook: loaded fbrec for fbid=%"UINT64"",fbrec->m_fbId);
log("facebook: loaded emailfreq=%"INT32"",(int32_t)fbrec->m_emailFrequency);
log("facebook: loaded myradius=%"INT32"",(int32_t)fbrec->m_myRadius);
// or if its an hour old i guess, get another token
//int32_t expires = fbrec->m_accessTokenCreated + 3600;
// debug
//expires = 0;
//if ( getTimeGlobal() > expires ) {
// // use this to save again with new access token
// m_oldFbrec = fbrec;
// return downloadAccessToken();
//}
// use the same access token
return true;
}
bool Msgfb::downloadAccessToken ( ) {
//
// ok, no cookie, so see if user just pushed the login button
//
int32_t fbcodeLen = 0;
char *fbcode = m_hr.getString("code", &fbcodeLen, NULL);
// no they did not, no user info is available?
if ( ! fbcode ) return true;
// get current page url (minus the facebook code=)
SafeBuf cup;
m_hr.getCurrentUrl(cup);
//m_hr->getCurrentUrlPath(cup);
// but take out the &code=
char *fix = strstr(cup.getBufStart(),"&code=");
if ( fix ) *fix = 0;
cup.urlEncode();
// use code to get access token
// that calls https://graph.facebook.com/oauth/access_token?
// client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
// client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
char fbuf[1024];
SafeBuf fburl ( fbuf,1024 );
fburl.safePrintf ("https://graph.facebook.com/oauth/access_token?"
"client_id=%s&"
"redirect_uri=%s&"
"client_secret=%s&"
"code=%s"
, APPID
//, APPHOSTENCODEDNOSLASH
//, m_redirPath
//
// KEEP It simple because this redirect_uri
// must EXACTLY match the one we used in
// PageEvents.cpp. and it can't have cgi crap in it
// because facebook strips them out...
//
//, "/"
, cup.getBufStart()
, APPSECRET
, fbcode );
// this fburl must match the previous url i think... i think the
// "page" in it changes up and mess wit hit
log("facebook: getting access token code=%s url=%s",fbcode,
fburl.getBufStart());
// reset
g_errno = 0;
if ( ! g_httpServer.getDoc ( fburl.getBufStart() ,
0 , // urlIp
0 , // offset
-1 ,
0 , // ifModifiedSince ,
this , // state
gotFBAccessTokenWrapper , // callback
10*1000 , // 10 sec timeout
0 , // proxyip
0 , // proxyport
10000 , // maxTextDocLen ,
10000 , // maxOtherDocLen ,
g_conf.m_spiderUserAgent ) )
// return false if blocked
return false;
// error?
if ( ! g_errno ) { char *xx=NULL;*xx=0; }
// let caller know we did not block
return gotFBAccessToken ( NULL );
}
bool Msgfb::gotFBAccessToken ( TcpSocket *s ) {
// some kind of error?
if ( g_errno ) {
log("facebook: error launching read of access token: %s",
mstrerror(g_errno));
m_errno = g_errno;
m_errorCount++;
return true;
}
// the access token should be in the reply
char *reply = s->m_readBuf;
int32_t replySize = s->m_readOffset;
// mime error?
HttpMime mime;
// exclude the \0 i guess. use NULL for url.
mime.set ( reply, replySize - 1, NULL );
// not good?
int32_t httpStatus = mime.getHttpStatus();
if ( httpStatus != 200 ) {
log("facebook: bad access request http status = %"INT32". "
"reply=%s",
httpStatus ,
reply );
g_errno = EBADREPLY;
m_errno = g_errno;
m_errorCount++;
return true;
}
// point to content
char *content = reply + mime.getMimeLen();
// assume no accesstoken provided
//int32_t expires = 0;
m_accessToken[0] = '\0';
// look for access token
//sscanf(content,"access_token=%s&expires=%"INT32"",m_accessToken,&expires);
char *at = strstr(content,"access_token=");
if ( at ) {
char *p = at + 13;
char *start = p;
for ( ; *p && *p != '&' ;p++ );
int32_t len = p - start;
if ( len > MAX_TOKEN_LEN ) { char *xx=NULL;*xx=0; }
gbmemcpy ( m_accessToken , start , len );
m_accessToken [ len ] = '\0';
}
// error?
if ( ! m_accessToken[0] ) {
log("facebook: could not find access token");
g_errno = EBADREPLY;
m_errno = g_errno;
m_errorCount++;
return true;
}
// set this timestamp
//m_accessTokenCreated = getTimeGlobal();
// sanity
if ( gbstrlen(m_accessToken) > MAX_TOKEN_LEN ) { char *xx=NULL;*xx=0;}
if ( ! downloadUserToUserRequestInfo() ) return false;
return downloadFBUserInfo();
}
static void gotFQLUserInfoWrapper ( void *state , TcpSocket *s ) {
Msgfb *mfb = (Msgfb *)state;
// . returns false if it blocks
// . returns true with g_errno set on error
if ( ! mfb->gotFQLUserInfo ( s ) ) return;
// error?
if ( g_errno && mfb->m_retryCount++ < 5 ) {
// retry again. this returns false if blocks;
if ( ! mfb->downloadFBUserInfo() ) return;
// probably an error if it returns true!!
}
mfb->m_callback ( mfb->m_state );
}
////////////////
//
// BEGIN SPECIAL FACEBOOK APPREQUEST parsing for m_userToUserWidgetId
//
///////////////
static void gotFBUserToUserRequestWrapper ( void *state , TcpSocket *s ) {
Msgfb *mfb = (Msgfb *)state;
if ( ! mfb->gotFBUserToUserRequest ( s ) ) return;
mfb->m_callback ( mfb->m_state );
}
// before calling downloadFBUserInfo() call this to set the m_widgetId
// parameter correctly! so we can see which facebook user sent them
// this user_to_user apprequest. we need to do this before downloading
// the user info so we can store the m_originatingWidgetId into the
// FBRec before we save it!
bool Msgfb::downloadUserToUserRequestInfo ( ) {
// hmmm. hr is invalid here.
char *request_ids = m_hr.getString("request_ids",NULL);
if ( ! request_ids ) return true;
// if already got one, forget this...
if ( m_widgetId ) return true;
char fbuf[1024];
SafeBuf fburl ( fbuf,1024 );
fburl.safePrintf ("https://graph.facebook.com/me/apprequests/?"
"request_ids=%s&access_token=%s"
, request_ids
, m_accessToken );
// this fburl must match the previous url i think... i think the
// "page" in it changes up and mess wit hit
log("facebook: getting referral fbid url=%s", fburl.getBufStart());
// reset
g_errno = 0;
if ( ! g_httpServer.getDoc ( fburl.getBufStart() ,
0 , // urlIp
0 , // offset
-1 ,
0 , // ifModifiedSince ,
this , // state
gotFBUserToUserRequestWrapper ,
10*1000 , // 10 sec timeout
0 , // proxyip
0 , // proxyport
10000 , // maxTextDocLen ,
10000 , // maxOtherDocLen ,
g_conf.m_spiderUserAgent ) )
// return false if blocked
return false;
// error?
if ( ! g_errno ) { char *xx=NULL;*xx=0; }
// let caller know we did not block
return gotFBUserToUserRequest ( NULL );
}
bool Msgfb::gotFBUserToUserRequest ( TcpSocket *s ) {
// some kind of error?
if ( g_errno ) {
log("facebook: error launching read of fb request: %s",
mstrerror(g_errno));
m_errno = g_errno;
m_errorCount++;
return true;
}
// the access token should be in the reply
char *reply = s->m_readBuf;
int32_t replySize = s->m_readOffset;
// mime error?
HttpMime mime;
// exclude the \0 i guess. use NULL for url.
mime.set ( reply, replySize - 1, NULL );
// not good?
int32_t httpStatus = mime.getHttpStatus();
if ( httpStatus != 200 ) {
log("facebook: bad fb request reply http status = %"INT32". "
"reply=%s",
httpStatus ,
reply );
g_errno = EBADREPLY;
m_errno = g_errno;
m_errorCount++;
return true;
}
// point to content
char *content = reply + mime.getMimeLen();
// https://graph.facebook.com/me/apprequests/?request_ids=417422284951090&access_token=AAAFEg3QA5ygBALw0wqIMOZAD6zfbZBZBaH9mf7sw92kLtOqVtPjasQibZCo4P5R0HHztOnObBeoDoKbwM1ZChht04JJ7KrgkxcXwtNWcrngZDZD
//{
// "data": [
// {
// "id": "417422284951090_100003381767946",
// "application": {
// "name": "Event Guru",
// "namespace": "eventguru",
// "canvas_name": "eventguru",
// "id": "356806354331432"
// },
// "to": {
// "name": "Jezebel Wells",
// "id": "100003381767946"
// },
// "from": {
// "name": "Matt Wells",
// "id": "100003532411011"
// },
// "data": "100003532411011",
// "message": "Hi my friend, I recommend EventGuru.com for discovering interesting local events. Plus, if you login to Event Guru I make a buck.",
// "created_time": "2012-03-29T02:41:37+0000"
// }
// ],
// "paging": {
// "previous": "https://graph.facebook.com/me/apprequests?request_ids=417422284951090&access_token=AAAFEg3QA5ygBALw0wqIMOZAD6zfbZBZBaH9mf7sw92kLtOqVtPjasQibZCo4P5R0HHztOnObBeoDoKbwM1ZChht04JJ7KrgkxcXwtNWcrngZDZD&limit=50&since=1332988897&__paging_token=417422284951090_100003381767946&__previous=1",
// "next": "https://graph.facebook.com/me/apprequests?request_ids=417422284951090&access_token=AAAFEg3QA5ygBALw0wqIMOZAD6zfbZBZBaH9mf7sw92kLtOqVtPjasQibZCo4P5R0HHztOnObBeoDoKbwM1ZChht04JJ7KrgkxcXwtNWcrngZDZD&limit=50&until=1332988897&__paging_token=417422284951090_100003381767946"
// }
//}
// mine out who sent it
char *from = strstr ( content , "\"from\":" );
int64_t id1 = 0LL;
if ( from ) {
char *ids = strstr ( from , "\"id\":" );
for ( ; ids && *ids && ! is_digit(*ids) ; ids++ );
if ( ids && *ids ) id1 = atoll(ids);
}
// mine out who sent it again... this is only present for paid invites
char *data = NULL;
// start mining AFTER "from" because there is a top "data" field!!
if ( from ) data = strstr ( from , "\"data\":" );
int64_t id2 = 0LL;
if ( data ) {
char *ids = strstr ( data , "\"id\":" );
for ( ; ids && *ids && ! is_digit(*ids) ; ids++ );
if ( ids && *ids ) id2 = atoll(ids);
}
// must match to be an official paid invite. we only include
// the "data" for the paid invites.
if ( id1 == id2 )
// set that to our widgetid then
m_widgetId = id1;
// download facebook info now
return downloadFBUserInfo();
}
////////////////
//
// END SPECIAL FACEBOOK APPREQUEST parsing for user_to_user m_widgetId
//
///////////////
//int64_t mdw = 100003532411011LL; // my uid for Matt Wells
// 100003316058818 // uid for flurbit
// http://graph.facebook.com/502303355/picture shows pics for a uid
bool Msgfb::downloadFBUserInfo ( ) {
log("facebook: downloading user info initial login");
SafeBuf cmd1;
// get your facebook id
cmd1.safePrintf ( "SELECT uid,username,first_name,last_name,name,pic_square,profile_update_time,timezone,religion,birthday,birthday_date,sex,hometown_location,current_location,activities,interests,is_app_user,music,tv,movies,books,about_me,status,online_presence,proxied_email,verified,website,is_blocked,contact_email,email,is_minor,work,education,sports,languages,likes_count,friend_count FROM user where uid=me()");
log("facebook: cmd1 = %s",cmd1.getBufStart());
cmd1.urlEncode();
// www.howtobe.pro/facebook-graph-api-graph-api-for-issuing-fql-queries
// make a url
SafeBuf ubuf;
ubuf.safePrintf("https://api.facebook.com/method/"
"fql.query?query=%s"
"&access_token=%s&format=xml"
, cmd1.getBufStart()
, m_accessToken
);
log("facebook: getting url = %s",ubuf.getBufStart());
// reset
g_errno = 0;
// get the results
if ( ! g_httpServer.getDoc ( ubuf.getBufStart() ,
0 , // urlIp
0 , // offset
-1 ,
0 , // ifModifiedSince ,
this , // state
gotFQLUserInfoWrapper , // callback
40*1000 , // 20 sec timeout
0 , // proxyip
0 , // proxyport
30000000 , // maxTextDocLen ,
30000000 , // maxOtherDocLen ,
g_conf.m_spiderUserAgent ) )
// return false if blocked
return false;
// otherwise, somehow got it without blocking... wtf?
//return gotFQLReply();
if ( ! g_errno ) { char *xx=NULL;*xx=0; }
log("fql: error getting doc: %s",mstrerror(g_errno));
return true;
}
static bool queueFBId ( int64_t fbId , collnum_t collnum );
static void savedFBRecWrapper1 ( void *state ) {
Msgfb *mfb = (Msgfb *)state;
if ( ! g_errno ) queueFBId ( mfb->m_fbId , mfb->m_collnum );
mfb->m_callback ( mfb->m_state );
}
static void doneRecheckingWrapper ( void *state ) {
Msgfb *mfb = (Msgfb *)state;
if ( ! mfb->doneRechecking ( ) ) return;
mfb->m_callback ( mfb->m_state );
}
// returns true with g_errno set on error
bool Msgfb::gotFQLUserInfo ( TcpSocket *s ) {
// bail on error
if ( g_errno ) {
log("fql: %s",mstrerror(g_errno));
m_errno = g_errno;
m_errorCount++;
return true;
}
// get reply
char *reply = s->m_readBuf;
int32_t replySize = s->m_readOffset;
// we reference into this, so do not free it!!
m_facebookReply = s->m_readBuf;
m_facebookReplySize = s->m_readOffset;
m_facebookAllocSize = s->m_readBufSize;
// do not allow tcpsocket to free it. we free it in destructor.
s->m_readBuf = NULL;
// mime error?
HttpMime mime;
// exclude the \0 i guess. use NULL for url.
mime.set ( reply, replySize - 1, NULL );
// not good?
int32_t httpStatus = mime.getHttpStatus();
if ( httpStatus != 200 ) {
log("facebook: bad fql request http status = %"INT32"",
httpStatus );
g_errno = EBADREPLY;
m_errno = g_errno;
m_errorCount++;
return true;
}
// point to content
char *content = reply + mime.getMimeLen();
int32_t contentLen = reply + replySize - content;
// check for error
char *errMsg = strstr(content,"<error_msg>");
if ( errMsg ) {
log("facebook: error in fql reply: %s", content );
g_errno = EBADREPLY;
m_errno = g_errno;
m_errorCount++;
return true;
}
// set it on stack i guess
//FBRec fbrec;
// all the FBRec::ptr_* things reference into "reply"
// import friendids from existing rec if there, we just want to
// save the new access token!!!!
if ( ! setFBRecFromFQLReply ( content,contentLen, &m_fbrecGen) ){
log("fql: error setting fb rec from fql");
g_errno = EBADREPLY;
return true;
}
// must be there!
if ( ! m_fbrecGen.m_fbId ) {
log("fql: failed to get facebook id from reply");
g_errno = EBADENGINEER;
m_errno = g_errno;
m_errorCount++;
return true;
}
// sanity
log("facebook: got initial facebook reply. fbid=%"INT64"",m_fbId);
// point to it!
m_fbrecPtr = &m_fbrecGen;
// now that we got the fbid see if its in facebookdb again
int64_t fbId = m_fbrecGen.m_fbId;
key96_t startKey;
key96_t endKey;
startKey.n1 = 0;
startKey.n0 = fbId;
endKey.n1 = 0;
endKey.n0 = fbId;
startKey.n0 <<= 1;
endKey.n0 <<= 1;
endKey.n0 |= 0x01;
//char *coll = g_collectiondb.getColl(m_collnum);
if ( ! m_msg0.getList ( -1, // hostid
0 , // ip
0 , // port
0 , // maxcacheage
false, // addtocache
RDB_FACEBOOKDB,
"",//coll,
&m_list4,
(char *)&startKey,
(char *)&endKey,
12, // minrecsizes
this ,
doneRecheckingWrapper,
0 ) )//niceness ) )
return false;
// i guess we got it without blocking
return doneRechecking();
}
//
// MERGE/UPDATE the old fbrec with the new fbrec
//
void mergeFBRec ( FBRec *dst , FBRec *src ) {
// if we had a pre-existing fbrec in facebookdb, do not just
// save m_fbrecGen because it does not have ptr_friendIds set!
// so inherit or import the friendIds from the pre-existing
// rec. otherwise we lose the friends until the cmd2 executes
// and that could be a while or that could fail!
if ( dst->size_friendIds <= 0 ) {
dst->ptr_friendIds = src-> ptr_friendIds;
dst->size_friendIds = src->size_friendIds;
}
// also this stuff too!
dst->m_emailFrequency = src->m_emailFrequency;
dst->m_myRadius = src->m_myRadius;
dst->ptr_mergedInterests = src->ptr_mergedInterests;
dst->size_mergedInterests = src->size_mergedInterests;
dst->ptr_myLocation = src->ptr_myLocation;
dst->size_myLocation = src->size_myLocation;
// save this stuff now too for Emailer
dst->m_nextRetry = src->m_nextRetry;
dst->m_timeToEmail = src->m_timeToEmail;
dst->m_lastEmailAttempt = src->m_lastEmailAttempt;
// other stuff
dst->m_eventsDownloaded = src->m_eventsDownloaded;
dst->m_accessTokenCreated = src->m_accessTokenCreated;
// new stuff
dst->m_flags = src->m_flags; // FB_INQUEUE
// for payment info:
dst->m_originatingWidgetId = src->m_originatingWidgetId;
// overwrite it if zero
if ( src->m_firstFacebookLogin )
dst->m_firstFacebookLogin = src->m_firstFacebookLogin;
// if it is zero in the old rec, overwrite it!
if ( src->m_lastLoginIP )
dst->m_lastLoginIP = src->m_lastLoginIP;
//dst-> = src->;
}
// returns false if blocked, true otherwise
bool Msgfb::saveFBRec ( FBRec *fbrec ) {
log("facebook: saving fbrec for fbid=%"INT64"",m_fbId);
log("facebook: saving myradius=%"INT32"",fbrec->m_myRadius);
log("facebook: saving mylocation=%s",fbrec->ptr_myLocation);
log("facebook: saving emailfreq=%"INT32"",(int32_t)fbrec->m_emailFrequency);
// . returns NULL and sets g_errno on error
// . "true" means we should make mr.ptr_* reference into the newly
// serialized buffer
int32_t replySize;
char *reply = serializeMsg ( sizeof(FBRec) ,
&fbrec->size_accessToken,//1stsizeparm
&fbrec->size_friendIds,// lastsizeparm
&fbrec->ptr_accessToken , // firststrptr
fbrec , // thisptr
&replySize ,
NULL ,
0 ,
false ); // true );
if ( ! reply ) {
log("facebook: could not save fbrec: %s",mstrerror(g_errno));
return true;
}
// make the binary tag then for this facebook user
//char *rec = (char *)&m_key;//fbId;
//int32_t recSize = (char *)&m_ids[m_numIds] - rec;
FBRec *serializedRec = (FBRec *)reply;
// set this after we know it
serializedRec->m_dataSize = replySize - sizeof(key96_t) - 4;
//char *coll = g_collectiondb.getColl ( m_collnum );
// use the list we got
key128_t startKey;
key128_t endKey;
startKey.setMin();
endKey.setMax();
// use m_list2 and not m_list since m_fbrecPtr is referencing
// m_list's content from our facebookdb lookup above
m_list2.set ( reply ,
replySize ,
NULL ,
0 ,