-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.cpp
1794 lines (1525 loc) · 72.3 KB
/
main.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
/*
* Getting timelines by Twitter Streaming API
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sstream>
#include <fstream>
#include <regex>
#include <deque>
#include <map>
#include <unordered_map>
#include <random>
#include <chrono>
using namespace std;
using namespace std::chrono;
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "imgui/imgui_impl_sdl_gl3.h"
#include <GL/glew.h>
#include <SDL.h>
#include <SDL2/SDL_mixer.h>
#include <oauth.h>
#include <curl/curl.h>
#include <range/v3/all.hpp>
#include <rxcpp/rx.hpp>
using namespace rxcpp;
using namespace rxcpp::rxo;
using namespace rxcpp::rxs;
#include <nlohmann/json.hpp>
using json=nlohmann::json;
#include "rxcurl.h"
using namespace rxcurl;
#include "rximgui.h"
using namespace rximgui;
#include "util.h"
using namespace ::util;
#include "model.h"
using namespace model;
#include "tweets.h"
using namespace tweets;
const ImVec4 clear_color = ImColor(114, 144, 154);
const auto length = milliseconds(60000);
// Time granularity for periodicity of tweet groups
const auto every = milliseconds(5000);
// For how long the tweet groups should be retained
auto keep = minutes(10);
// Create tweet groups for the period from 'timestamp'-'windows' till 'timestamp' and
// delete the ones that are too old to keep
template<class F>
inline void updategroups(Model& model, milliseconds timestamp, milliseconds window, F&& f) {
auto& md = model.data;
auto& m = *md;
// We are interested in tweets no older than 'window' milliseconds from 'timestamp' ...
auto searchbegin = duration_cast<minutes>(duration_cast<minutes>(timestamp) - window);
// ... and not newer than 'timestamp'
auto searchend = timestamp;
for (auto offset = milliseconds(0);
searchbegin + offset < searchend;
offset += duration_cast<milliseconds>(every)) {
// Calculate current time period
auto key = TimeRange{searchbegin+offset, searchbegin+offset+length};
auto it = m.groupedtweets.find(key);
// If the current time period does not exist in the groups yet
if (it == m.groupedtweets.end()) {
// Append current group's period to deque of groups in the model
m.groups.push_back(key);
// Ensure the group deque is sorted
m.groups |= ranges::actions::sort(less<TimeRange>{});
// Create a tweet group for the current period and insert it into the map
it = m.groupedtweets.insert(make_pair(key, make_shared<TweetGroup>())).first;
}
// Regardless of whether the group already existed or not, apply f function
// to tweet group.
// TODO: Try to remove the condition as it is an artefact from previous revisions
if (searchbegin+offset <= timestamp && timestamp < searchbegin+offset+length) {
f(*it->second);
}
}
// Drop tweet groups that are older than the period for which tweet groups should be retained
while(!m.groups.empty() && m.groups.front().begin + keep < m.groups.back().begin) {
// remove group
m.groupedtweets.erase(m.groups.front());
m.groups.pop_front();
}
}
string settingsFile;
json settings;
int main(int argc, const char *argv[])
{
// ==== Parse args
auto command = string{};
for(auto cursor=argv,end=argv+argc; cursor!=end; ++cursor) {
command += string{*cursor};
}
cerr << "command = " << command.c_str() << endl;
auto exefile = string{argv[0]};
cerr << "exe = " << exefile.c_str() << endl;
auto exedir = exefile.substr(0, exefile.find_last_of('/'));
cerr << "dir = " << exedir.c_str() << endl;
auto exeparent = exedir.substr(0, exedir.find_last_of('/'));
cerr << "parent = " << exeparent.c_str() << endl;
auto selector = string{tolower(argc > 1 ? argv[1] : "")};
const bool playback = argc == 3 && selector == "playback";
const bool gui = argc == 6;
bool dumpjson = argc == 7 && selector == "dumpjson";
bool dumptext = argc == 7 && selector == "dumptext";
string inifile = exeparent + "/Resources/imgui.ini";
cerr << "dir = " << exedir.c_str() << endl;
bool setting = false;
settingsFile = exedir + "/settings.json";
if (argc == 2 && ifstream(argv[1]).good()) {
setting = true;
settingsFile = argv[1];
} else if (!playback && argc == 3 && selector == "setting") {
setting = true;
settingsFile = argv[2];
} else if (argc == 1 || argc == 2) {
setting = true;
}
if (setting) {
cerr << "settings = " << settingsFile.c_str() << endl;
ifstream i(settingsFile);
if (i.good()) {
i >> settings;
}
}
if (!playback &&
!dumptext &&
!dumpjson &&
!gui &&
!setting) {
printf("twitter <settings file path>\n");
printf("twitter SETTING <settings file path>\n");
printf("twitter PLAYBACK <json file path>\n");
printf("twitter DUMPJSON <CONS_KEY> <CONS_SECRET> <ATOK_KEY> <ATOK_SECRET> [sample.json | filter.json?track=<topic>]\n");
printf("twitter DUMPTEXT <CONS_KEY> <CONS_SECRET> <ATOK_KEY> <ATOK_SECRET> [sample.json | filter.json?track=<topic>]\n");
printf("twitter <CONS_KEY> <CONS_SECRET> <ATOK_KEY> <ATOK_SECRET> [sample.json | filter.json?track=<topic>]\n");
return -1;
}
int argoffset = 1;
if (gui) {
argoffset = 0;
}
if (settings.count("Keep") == 0) {
settings["Keep"] = keep.count();
} else {
keep = minutes(settings["Keep"].get<int>());
}
if (settings.count("Query") == 0) {
settings["Query"] = json::parse(R"({"Action": "sample"})");
}
if (settings.count("WordFilter") == 0) {
settings["WordFilter"] = "-http,-expletive";
}
if (settings.count("TweetFilter") == 0) {
settings["TweetFilter"] = "";
}
if (settings.count("Language") == 0) {
settings["Language"] = "en";
}
// twitter api creds
if (settings.count("ConsumerKey") == 0) {
settings["ConsumerKey"] = string{};
}
if (settings.count("ConsumerSecret") == 0) {
settings["ConsumerSecret"] = string{};
}
if (settings.count("AccessTokenKey") == 0) {
settings["AccessTokenKey"] = string{};
}
if (settings.count("AccessTokenSecret") == 0) {
settings["AccessTokenSecret"] = string{};
}
// azure ml api creds
if (settings.count("SentimentUrl") == 0) {
settings["SentimentUrl"] = string{};
}
if (settings.count("SentimentKey") == 0) {
settings["SentimentKey"] = string{};
}
if (settings.count("SentimentRequests") == 0) {
settings["SentimentRequests"] = "Off";
}
// google api creds
if (settings.count("PerspectiveUrl") == 0) {
settings["PerspectiveUrl"] = string{};
}
if (settings.count("PerspectiveKey") == 0) {
settings["PerspectiveKey"] = string{};
}
if (settings.count("PerspectiveRequests") == 0) {
settings["PerspectiveRequests"] = "Off";
}
//cerr << setw(2) << settings << endl;
// ==== Constants - paths
const string URL = "https://stream.twitter.com/1.1/statuses/";
string url = URL;
string filepath;
if (!playback) {
if (!setting) {
// read from args
url += argv[5 + argoffset];
// ==== Twitter keys
const char *CONS_KEY = argv[1 + argoffset];
const char *CONS_SEC = argv[2 + argoffset];
const char *ATOK_KEY = argv[3 + argoffset];
const char *ATOK_SEC = argv[4 + argoffset];
settings["ConsumerKey"] = string(CONS_KEY);
settings["ConsumerSecret"] = string(CONS_SEC);
settings["AccessTokenKey"] = string(ATOK_KEY);
settings["AccessTokenSecret"] = string(ATOK_SEC);
}
} else {
filepath = argv[1 + argoffset];
cerr << "file = " << filepath.c_str() << endl;
}
// Setup SDL
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) != 0)
{
printf("SDL_Init Error: %s\n", SDL_GetError());
return -1;
}
// Setup audio
if (Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1)
{
printf("Mix_OpenAudio - Error: %s\n", SDL_GetError());
return -1;
}
Mix_Chunk *dot = Mix_LoadWAV((exeparent + "/Resources/dot.wav").c_str());
if (dot == NULL)
{
printf("Mix_LoadWAV dot - Error: %s\n", SDL_GetError());
return -1;
}
// Setup window
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_DisplayMode current;
SDL_GetCurrentDisplayMode(0, ¤t);
SDL_Window *window = SDL_CreateWindow("Twitter Analysis (ImGui SDL2+OpenGL3)", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
glewInit();
// Setup ImGui binding
ImGui_ImplSdlGL3_Init(window);
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = inifile.c_str();
// Setup Fonts
int fontsadded = 0;
static const ImWchar noto[] = {
0x0020, 0x0513,
0x1e00, 0x1f4d,
0x2000, 0x25ca,
0xfb01, 0xfb04,
0xfeff, 0xfffd,
0 };
if (ifstream(exedir + "/NotoMono-Regular.ttf").good()) {
++fontsadded;
io.Fonts->AddFontFromFileTTF((exedir + "/NotoMono-Regular.ttf").c_str(), 13.0f, nullptr, noto);
} else if (ifstream(exeparent + "/Resources/NotoMono-Regular.ttf").good()) {
++fontsadded;
io.Fonts->AddFontFromFileTTF((exeparent + "/Resources/NotoMono-Regular.ttf").c_str(), 13.0f, nullptr, noto);
}
static ImFontConfig config;
config.MergeMode = true;
static const ImWchar symbols[] = {
0x20a0, 0x2e3b,
0x3008, 0x3009,
0x4dc0, 0x4dff,
0xa700, 0xa71f,
0 };
if (ifstream(exedir + "/NotoSansSymbols-Regular.ttf").good()) {
++fontsadded;
io.Fonts->AddFontFromFileTTF((exedir + "/NotoSansSymbols-Regular.ttf").c_str(), 13.0f, &config, symbols);
} else if (ifstream(exeparent + "/Resources/NotoSansSymbols-Regular.ttf").good()) {
++fontsadded;
io.Fonts->AddFontFromFileTTF((exeparent + "/Resources/NotoSansSymbols-Regular.ttf").c_str(), 13.0f, &config, symbols);
}
if (fontsadded) {
io.Fonts->Build();
}
/* Define deinitialization procedure for graphic user interface in a SafeGuard pattern.
The closure supplied as the parameter to unwinder macro is run in a destructor of a
local var when it goes out of scope.
More details on Unwinder (SageGuard pattern implementation):
http://kirkshoop.github.io/2011/09/27/unwinder-should-be-in-standard-library.html
*/
RXCPP_UNWIND_AUTO([&](){
ImGui_ImplSdlGL3_Shutdown();
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
Mix_FreeChunk(dot);
Mix_CloseAudio();
SDL_Quit();
});
/* In Rx concurrency model is defined by scheduling. To specify, which thread on_next() calls are
made on, observe_on_xxx functions are used in RxCpp. These function return 'coordination' factories.
General explanation of schedulers in Rx:
http://reactivex.io/documentation/scheduler.html
Detailed explanation of ObserveOn (C#):
http://www.introtorx.com/Content/v1.0.10621.0/15_SchedulingAndThreading.html#SubscribeOnObserveOn
Details on coordination and how scheduling is implemented in RxCpp:
https://github.com/Reactive-Extensions/RxCpp/blob/master/DeveloperManual.md
More on scheduling design in RxCpp:
https://github.com/Reactive-Extensions/RxCpp/issues/105#issuecomment-87294867
https://github.com/Reactive-Extensions/RxCpp/issues/9
*/
auto mainthreadid = this_thread::get_id();
/* Create coordination for observing on UI thread
Variable rl is defined in rximgui.h
More info on observe_on_run_loop:
https://github.com/Reactive-Extensions/RxCpp/issues/151
https://github.com/Reactive-Extensions/RxCpp/pull/154
*/
auto mainthread = observe_on_run_loop(rl);
/* Thread to download tweets from Twitter and perform initial parsing
Example of observe_on_new_thread with explanation:
http://rxcpp.codeplex.com/discussions/620779
*/
auto tweetthread = observe_on_new_thread();
/* "The event_loop scheduler is a simple round-robin fixed-size thread pool."
http://rxcpp.codeplex.com/discussions/635113
*/
auto poolthread = observe_on_event_loop();
// Create a factory that returns observable of http responses from Twitter
auto factory = create_rxcurl();
composite_subscription lifetime;
/* make changes to settings observable
This allows setting changes to be composed into the expressions to reconfigure them.
*/
rxsub::replay<json, decltype(mainthread)> setting_update(1, mainthread, lifetime);
auto setting_updates = setting_update.get_observable();
auto sendsettings = setting_update.get_subscriber();
auto sf = settingsFile;
// call update_settings() to save changes and trigger parties interested in the change
auto update_settings = [sendsettings, sf](json s){
ofstream o(sf);
o << setw(4) << s;
if (sendsettings.is_subscribed()){
sendsettings.on_next(s);
}
};
// initial update
update_settings(settings);
/* filter settings updates to changes in the sentiment api settings.
debounce is used to wait until the updates pause before signaling a change.
distinct_until_changed is used to filter out settings updates that do not change the value
*/
auto useSentimentApi = setting_updates |
rxo::map([=](const json& settings){
string use = tolower(settings["SentimentRequests"].get<std::string>());
bool haveurl = settings.count("SentimentUrl") > 0 && !settings["SentimentUrl"].get<std::string>().empty();
bool havekey = settings.count("SentimentKey") > 0 && !settings["SentimentKey"].get<std::string>().empty();
return use == "on" && haveurl && havekey;
}) |
debounce(milliseconds(500), mainthread) |
distinct_until_changed() |
replay(1) |
ref_count() |
as_dynamic();
/* filter settings updates to changes in the perspective api settings.
debounce is used to wait until the updates pause before signaling a change.
distinct_until_changed is used to filter out settings updates that do not change the value
*/
auto usePerspectiveApi = setting_updates |
rxo::map([=](const json& settings){
string use = tolower(settings["PerspectiveRequests"].get<std::string>());
bool haveurl = settings.count("PerspectiveUrl") > 0 && !settings["PerspectiveUrl"].get<std::string>().empty();
bool havekey = settings.count("PerspectiveKey") > 0 && !settings["PerspectiveKey"].get<std::string>().empty();
return use == "on" && haveurl && havekey;
}) |
debounce(milliseconds(500), mainthread) |
distinct_until_changed() |
replay(1) |
ref_count() |
as_dynamic();
/* filter settings updates to changes that change the url for the twitter stream.
distinct_until_changed is used to filter out settings updates that do not change the url
debounce is used to wait until the updates pause before signaling the url has changed.
this is important since typing in keywords would cause many intermediate changes to the url
and twitter rate limits the user if there are too many fast restarts.
*/
auto urlchanges = setting_updates |
rxo::map([=](const json& settings){
string url = URL + settings["Query"]["Action"].get<std::string>() + ".json?";
if (settings.count("Language") > 0) {
url += "language=" + settings["Language"].get<std::string>() + "&";
}
if (settings["Query"].count("Keywords") > 0 && settings["Query"]["Keywords"].is_array()) {
url += "track=";
for (auto& kw : settings["Query"]["Keywords"]) {
url += kw.get<std::string>() + ",";
}
}
return url;
}) |
debounce(milliseconds(1000), mainthread) |
distinct_until_changed() |
tap([](string url){
cerr << "url = " << url.c_str() << endl;
}) |
replay(1) |
ref_count() |
as_dynamic();
// ==== Tweets
observable<string> chunks;
// request tweets
if (playback) {
chunks = filechunks(tweetthread, filepath);
} else {
// switch to new connection whenever the url changes
chunks = urlchanges |
rxo::map([&](const string& url){
// ==== Constants - flags
const bool isFilter = url.find("/statuses/filter") != string::npos;
string method = isFilter ? "POST" : "GET";
/* Create new http request for a stream of tweets
If an error is encountered, function on_error_resume_next ensures the error
item is replaced with some correct observable value.
In this case return never, which never completes and never emits a value.
The never will be cancelled when the url changes
*/
return twitterrequest(tweetthread, factory, url, method, settings["ConsumerKey"], settings["ConsumerSecret"], settings["AccessTokenKey"], settings["AccessTokenSecret"]) |
// handle invalid requests by waiting for a trigger to try again
on_error_resume_next([](std::exception_ptr ep){
cerr << rxu::what(ep) << endl;
return rxs::never<string>();
});
}) |
switch_on_next();
}
// parse tweets
auto tweets = chunks |
parsetweets(poolthread, tweetthread) |
rxo::map([](parsedtweets p){
p.errors |
tap([](parseerror e){
cerr << rxu::what(e.ep) << endl;
}) |
subscribe<parseerror>();
return p.tweets;
}) |
merge(tweetthread);
/* Take tweets, make sure that any error is ignored, and publish them
as a stream of observables available to multiple on-demand subscribers.
Publish creates a connectable observable that can be subscribed to later and that
starts operating when a consumer requests it
ref_count provides interface to connectable observable to consumers that
take ordinary observable. It also keeps the track, how many consumers are
connected to the observable, hence the name.
Retry repeats the input given number of times when it fails. When no count is
given it will repeat infinitely when it fails.
OnErrorResumeNext:
https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators
Publish:
http://reactivex.io/documentation/operators/publish.html
RefCount:
http://reactivex.io/documentation/operators/refcount.html
Detailed explanation on Publish and RefCount (C#):
http://www.introtorx.com/content/v1.0.10621.0/14_HotAndColdObservables.html
*/
auto ts = tweets |
retry() |
publish() |
ref_count() |
as_dynamic();
// ==== Model
/* Reducer is a function that takes Model and returns new Model. The operation of taking a sequence of something
and aggregating that sequence into single instance of something, is traditionally called reduce.
In STL traditionally term "accumulate" is used; other languages use term "fold" for similar operation.
Each reducer here represents a mini-pipeline that listens for incomming data of interest and calculates
result from them and/or produce side effect.
Definition of reduce in Rx:
http://reactivex.io/documentation/operators/reduce.html
*/
vector<observable<Reducer>> reducers;
// Create new ofstream with current time epoch as filename. Twits will be dumped there, if the JSON dump mode is activated
auto newJsonFile = [exedir]() -> unique_ptr<ofstream> {
return unique_ptr<ofstream>{new ofstream(exedir + "/" + to_string(time_point_cast<milliseconds>(system_clock::now()).time_since_epoch().count()) + ".json")};
};
// The json dump file is created always
auto jsonfile = newJsonFile();
/* Generate a stream of booleans when the json dumping setting is changed.
Function interval emits incremented long value with time granularity
specified by 'every' with 'tweetthread' scheduler.
Function map converts each long value into bool value equal to
current state of dumpjson variable.
Function distinct_until_changed replaces groups of equal items in the
stream that go together with single item, thus filtering repeated values
Interval:
http://reactivex.io/documentation/operators/interval.html
http://www.introtorx.com/content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableInterval
Map:
http://reactivex.io/documentation/operators/map.html
DistinctUntilChanged:
http://www.introtorx.com/content/v1.0.10621.0/05_Filtering.html#Distinct
*/
auto dumpjsonchanged = interval(every, tweetthread) |
rxo::map([&](long){return dumpjson;}) |
distinct_until_changed() |
publish() |
ref_count();
/* Process tweets grouped by packs arrived during 'every' time granularity,
delaying emission by 'length' time
"publish and connect_forever ensure that the work is done even if nothing subscribes the result'
(http://kirkshoop.github.io/2013/09/05/deferoperation.html)
Detailed explanation of buffering with time:
http://www.introtorx.com/content/v1.0.10621.0/17_SequencesOfCoincidence.html
Delay:
http://reactivex.io/documentation/operators/delay.html
*/
auto delayed_tweets = ts |
buffer_with_time(every, tweetthread) |
delay(length, tweetthread) |
publish(lifetime) |
connect_forever();
/* Whenever jsonchanged becomes true, generate an observable that consists of
of a sequence of packs of tweets. This sequence should continue only until jsonchanged becomes false,
Then such sequence is fed to a reducer that takes tweet data and prints it
to stdout.
filter emits only those elements of input sequence for which the supplied
predicate is true.
take_until passes the elements of input sequence forward until the
it's argument emits an element of it's own or is terminated.
switch_on_next combines sequences into a single sequence, ignoring all the results
that come from sequences that emitted after the first emission of the latest sequence
start_with specifies the first element for the sequence to start with
Filter:
http://reactivex.io/documentation/operators/filter.html
TakeUntil:
http://reactivex.io/documentation/operators/takeuntil.html
Switch (switch_on_next):
http://reactivex.io/documentation/operators/switch.html
http://www.introtorx.com/Content/v1.0.10621.0/12_CombiningSequences.html#Switch
StartWith:
http://reactivex.io/documentation/operators/startwith.html
*/
reducers.push_back(
dumpjsonchanged |
filter([](bool dj){ return dj; }) |
rxo::map([&](bool) -> observable<Reducer> {
return delayed_tweets |
take_until(
dumpjsonchanged |
filter([](bool dj){ return !dj; }) |
delay(length, tweetthread)) |
rxo::map([&](const vector<Tweet>& tws){
return Reducer([&, tws](Model& m){
for (auto& tw: tws) {
auto& tweet = tw.data->tweet;
auto json = tweet.dump();
cout << json << "\r\n";
*jsonfile << json << "\r\n";
}
*jsonfile << flush;
return std::move(m);
});
});
}) |
switch_on_next(tweetthread) |
nooponerror() |
start_with(noop));
/* Store current url in the model
Take changes to the url and save the current url in the model.
*/
reducers.push_back(
urlchanges |
rxo::map([=](string url){
return Reducer([=](Model& m){
m.data->url = url;
return std::move(m);
});
}) |
nooponerror() |
start_with(noop));
/* Dump text to cout
Take tweets, use filter to pass them forward in the chain only if dumptext is true.
Tap (do) function lets the programmer listen to sequence and possibly make side-effects on it.
Here we listen to each tweet and just print them to stdout
Do (aka Tap): http://www.introtorx.com/content/v1.0.10621.0/09_SideEffects.html#Do
*/
reducers.push_back(
ts |
onlytweets() |
filter([&](const Tweet&){
return dumptext;
}) |
tap([=](const Tweet& tw){
auto& tweet = tw.data->tweet;
if (tweet["user"]["name"].is_string() && tweet["user"]["screen_name"].is_string()) {
cout << "------------------------------------" << endl;
cout << tweet["user"]["name"].get<string>() << " (" << tweet["user"]["screen_name"].get<string>() << ")" << endl;
cout << tweettext(tweet) << endl;
}
}) |
noopandignore() |
start_with(noop));
if (!playback) {
// update groups on time interval so that minutes with no tweets are recorded.
reducers.push_back(
observable<>::interval(milliseconds(500), poolthread) |
rxo::map([=](long){
return Reducer([=](Model& m){
auto rangebegin = time_point_cast<milliseconds>(system_clock::now()).time_since_epoch();
updategroups(m, rangebegin, keep, [](TweetGroup&){});
return std::move(m);
});
}) |
nooponerror() |
start_with(noop));
}
//
// send tweet text to sentiment api service.
//
auto sentimentupdates = ts |
onlytweets() |
buffer_with_time(milliseconds(500), tweetthread) |
filter([](const vector<Tweet>& tws){ return !tws.empty(); }) |
rxo::map([=](const vector<Tweet>& tws) -> observable<Reducer> {
vector<string> text = tws |
ranges::views::transform([](Tweet tw){
auto& tweet = tw.data->tweet;
return tweettext(tweet);
}) |
ranges::to_vector;
return sentimentrequest(poolthread, factory, settings["SentimentUrl"].get<string>(), settings["SentimentKey"].get<string>(), text) |
rxo::map([=](const string& body){
auto response = json::parse(body);
return Reducer([=](Model& m){
auto combined = ranges::views::zip(response["Results"]["output1"], tws);
ranges::for_each(combined, [&](const auto& b) {
auto sentiment = get<0>(b);
auto tweet = get<1>(b).data->tweet;
auto ts = timestamp_ms(get<1>(b));
bool isNeg = sentiment["Sentiment"] == "negative";
bool isPos = sentiment["Sentiment"] == "positive";
m.data->sentiment[tweet["id_str"]] = sentiment["Sentiment"];
for (auto& word: get<1>(b).data->words) {
isNeg && ++m.data->negativewords[word];
isPos && ++m.data->positivewords[word];
}
updategroups(m, ts, length, [&](TweetGroup& tg){
isNeg && ++tg.negative;
isPos && ++tg.positive;
});
});
return std::move(m);
});
});
}) |
merge() |
nooponerror("sentiment") |
start_with(noop) |
as_dynamic();
reducers.push_back(
useSentimentApi |
rxo::map([=](bool use){
return use ? sentimentupdates : just(noop) | as_dynamic();
}) |
switch_on_next()
);
//
// send tweet text to perspective api service.
//
auto perspectiveupdates = ts |
onlytweets() |
// perspective api has 10 QPS limit (eval @ 100s)
window_with_time(seconds(1), poolthread) |
rxo::map([](observable<Tweet> tws){
// take only first 10 from each second
return tws.take(10);
}) |
merge() |
rxo::map([=](const Tweet& tw) -> observable<Reducer> {
auto text = tweettext(tw.data->tweet);
auto ts = timestamp_ms(tw);
return perspectiverequest(poolthread, factory, settings["PerspectiveUrl"].get<string>(), settings["PerspectiveKey"].get<string>(), text) |
rxo::map([=](const string& body){
auto response = json::parse(body);
return Reducer([=](Model& m){
auto& scores = response["attributeScores"];
Perspective result{
scores["TOXICITY"]["summaryScore"]["value"].get<float>(),
scores["SPAM"]["summaryScore"]["value"].get<float>(),
scores["INFLAMMATORY"]["summaryScore"]["value"].get<float>()
};
m.data->perspective[tw.data->tweet["id_str"]] = result;
auto toxic = result.toxicity > 0.7f;
for (auto& word: tw.data->words) {
toxic && ++m.data->toxicwords[word];
}
updategroups(m, ts, length, [&](TweetGroup& tg){
toxic && ++tg.toxic;
});
return std::move(m);
});
});
}) |
merge() |
nooponerror("perspective") |
start_with(noop) |
as_dynamic();
reducers.push_back(
usePerspectiveApi |
rxo::map([=](bool use){
return use ? perspectiveupdates : just(noop) | as_dynamic();
}) |
switch_on_next()
);
// group tweets, that arrive, by the timestamp_ms value
reducers.push_back(
ts |
onlytweets() |
observe_on(poolthread) |
rxo::map([=](const Tweet& tw){
auto& tweet = tw.data->tweet;
auto text = tweettext(tweet);
auto words = splitwords(text);
return Reducer([=](Model& m){
auto t = timestamp_ms(tw);
for (auto& word: words) {
++m.data->allwords[word];
}
updategroups(m, t, length, [&](TweetGroup& tg){
tg.tweets.push_back(tw);
for (auto& word: words) {
++tg.words[word];
}
});
return std::move(m);
});
}) |
nooponerror() |
start_with(noop));
// window tweets by the time that they arrive
auto tsw = ts |
onlytweets() |
window_with_time(length, every, poolthread) |
publish() |
ref_count() |
as_dynamic();
reducers.push_back(
tsw |
rxo::map([=](observable<Tweet> source){
auto rangebegin = time_point_cast<seconds>(system_clock::now()).time_since_epoch();
auto tweetsperminute = source |
start_with(Tweet{}) |
rxo::map([=](const Tweet& tw) {
return Reducer([=](Model& md){
auto& m = *(md.data);
auto maxsize = duration_cast<seconds>(keep).count()/duration_cast<seconds>(every).count();
if (m.tweetsperminute.size() == 0) {
m.tweetsstart = duration_cast<seconds>(rangebegin + length);
}
if (static_cast<long long>(m.tweetsperminute.size()) < maxsize) {
// fill in missing history
while (maxsize > static_cast<long long>(m.tweetsperminute.size())) {
m.tweetsperminute.push_front(0);
m.tweetsstart -= duration_cast<seconds>(every);
}
}
if (rangebegin >= m.tweetsstart) {
const auto i = duration_cast<seconds>(rangebegin - m.tweetsstart).count()/duration_cast<seconds>(every).count();
// add future buckets
while(i >= static_cast<long long>(m.tweetsperminute.size())) {
m.tweetsperminute.push_back(0);
}
if (tw.data->words.size() > 0) {
++m.tweetsperminute[i];
}
}
// discard expired data
while(static_cast<long long>(m.tweetsperminute.size()) > maxsize) {
m.tweetsstart += duration_cast<seconds>(every);
m.tweetsperminute.pop_front();
}
return std::move(md);
});
});
return tweetsperminute;
}) |
merge() |
nooponerror() |
start_with(noop));
// window tweets by the timestamp_ms embedded in each tweet
auto window_timestamp = ts |
onlytweets() |
// for each tweet emit duplicates of that tweet for each time window
rxo::map([](Tweet tw){
auto e_s = duration_cast<seconds>(every).count();
auto l_s = duration_cast<seconds>(length).count();
auto t_s = std::chrono::floor<seconds>(timestamp_ms(tw)).count();
auto te_s = t_s - (t_s % e_s);
auto tstart_s = te_s - (l_s - e_s);
auto tfinish_s = te_s + e_s;
int begin = 0;
int end = (tfinish_s - tstart_s) / e_s;
return iterate(
ranges::views::ints(begin, end) |
ranges::views::transform([=](int s){
return make_tuple(tstart_s + (e_s * s), tw);
}));
}) |
merge() |
// group tweets from the same window
group_by(rxu::apply_to([](int64_t s, Tweet){
return s;
}), rxu::apply_to([](int64_t, Tweet tw){
return tw;
})) |
rxo::map([=](grouped_observable<int64_t, Tweet> source){
return source |
// stop each window after a full window interval occurs without a new tweet
timeout(every) |
on_error_resume_next([](std::exception_ptr){
return empty<Tweet>();
});
}) |
publish() |
ref_count() |
as_dynamic();
// play sounds for up and down inflections in the count of tweets per minute
reducers.push_back(window_timestamp |
rxo::map([=](observable<Tweet> source){
return source | count();
}) |
merge() |
rxo::window(6, 1) |
rxo::map([=](observable<int> counts){
return counts | average() |
zip(counts | rxo::last(), counts | rxo::first()) |
filter(rxu::apply_to([](double avg, long last, long first){
// only keep if the average of three counts is less than
// the last count and greater than the first count.
// should only keep when there is a inflection up or down.
return avg < last && avg > first;
})) |
rxo::map(rxu::apply_to([=](double , long , long ){
return Reducer([=](Model& md){