-
-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathactivity.ts
522 lines (459 loc) · 16.4 KB
/
activity.ts
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
import moment from 'moment';
import { unitOfTime } from 'moment';
import * as _ from 'lodash';
import { map, filter, values, groupBy, sortBy, flow, reverse } from 'lodash/fp';
import { window_events } from '~/util/fakedata';
import queries from '~/queries';
import { getColorFromCategory } from '~/util/color';
import { loadClassesForQuery } from '~/util/classes';
import { get_day_start_with_offset } from '~/util/time';
interface TimePeriod {
start: string;
length: [number, string];
}
function dateToTimeperiod(date: string, duration?: [number, string]): TimePeriod {
return { start: get_day_start_with_offset(date), length: duration || [1, 'day'] };
}
function timeperiodToStr(tp: TimePeriod): string {
const start = moment(tp.start).format();
const end = moment(start)
.add(tp.length[0], tp.length[1] as moment.unitOfTime.DurationConstructor)
.format();
return [start, end].join('/');
}
interface QueryOptions {
host: string;
date?: string;
timeperiod?: TimePeriod;
filterAFK?: boolean;
includeAudible?: boolean;
filterCategories?: string[][];
force?: boolean;
}
// initial state
const _state = {
// set to true once loading has started
loaded: false,
window: {
available: false,
top_apps: [],
top_titles: [],
},
browser: {
available: false,
duration: [],
top_domains: [],
top_urls: [],
},
editor: {
available: false,
duration: [],
top_files: [],
top_languages: [],
top_projects: [],
},
category: {
available: false,
by_hour: [],
top: [],
},
active: {
available: false,
duration: 0,
// non-afk events (no detail data) for the current period
events: [],
// Aggregated events for current and past periods
history: {},
},
android: {
available: false,
},
query_options: {
browser_buckets: 'all',
editor_buckets: 'all',
},
buckets: {
loaded: false,
afk: [],
window: [],
editor: [],
browser: [],
android: [],
},
};
function timeperiodsAroundTimeperiod(timeperiod: TimePeriod): TimePeriod[] {
const periods = [];
for (let i = -15; i <= 15; i++) {
const start = moment(timeperiod.start)
.add(i * timeperiod.length[0], timeperiod.length[1] as moment.unitOfTime.DurationConstructor)
.format();
periods.push({ ...timeperiod, start });
}
return periods;
}
function timeperiodsHoursOfDay(timeperiod: TimePeriod): TimePeriod[] {
const periods = [];
const _length: [number, string] = [1, 'hour'];
for (let i = 0; i < 24; i++) {
const start = moment(timeperiod.start)
.add(i * _length[0], _length[1] as moment.unitOfTime.DurationConstructor)
.format();
periods.push({ start, length: _length });
}
// const periods = _.range(24).map(i => [TimePeriod(moment(i * 1 + dayOffset), [1, 'hour'])]);
return periods;
}
function timeperiodsStrsHoursOfDay(timeperiod: TimePeriod): string[] {
return timeperiodsHoursOfDay(timeperiod).map(timeperiodToStr);
}
function timeperiodStrsAroundTimeperiod(timeperiod: TimePeriod): string[] {
return timeperiodsAroundTimeperiod(timeperiod).map(timeperiodToStr);
}
// getters
const getters = {
getActiveHistoryAroundTimeperiod: state => (timeperiod: TimePeriod) => {
const periods = timeperiodStrsAroundTimeperiod(timeperiod);
const _history = periods.map(tp => {
if (_.has(state.active.history, tp)) {
return state.active.history[tp];
} else {
// A zero-duration placeholder until new data has been fetched
return [{ timestamp: moment(tp.split('/')[0]).format(), duration: 0, data: {} }];
}
});
return _history;
},
};
// actions
const actions = {
async ensure_loaded({ commit, state, dispatch }, query_options: QueryOptions) {
console.info('Query options: ', query_options);
if (!state.loaded || state.query_options !== query_options || query_options.force) {
commit('start_loading', query_options);
if (!query_options.timeperiod) {
query_options.timeperiod = dateToTimeperiod(query_options.date);
}
await dispatch('buckets/ensureBuckets', null, { root: true });
await dispatch('get_buckets', query_options);
// TODO: These queries can actually run in parallel, but since server won't process them in parallel anyway we won't.
await dispatch('set_available', query_options);
if (state.window.available) {
await dispatch('query_desktop_full', query_options);
await dispatch('query_category_time_by_hour', query_options);
} else if (state.android.available) {
await dispatch('query_android', query_options);
} else {
console.log(
'Cannot query windows as we are missing either an afk/window bucket pair or an android bucket'
);
await dispatch('query_window_empty', query_options);
await dispatch('query_browser_empty', query_options);
}
if (state.active.available) {
await dispatch('query_active_history', query_options);
} else if (state.android.available) {
await dispatch('query_active_history_android', query_options);
} else {
console.log('Cannot call query_active_history as we do not have an afk bucket');
await dispatch('query_active_history_empty', query_options);
}
if (state.editor.available) {
await dispatch('query_editor', query_options);
} else {
console.log('Cannot call query_editor as we do not have any editor buckets');
await dispatch('query_editor_empty', query_options);
}
} else {
console.warn(
'ensure_loaded called twice with same query_options but without query_options.force = true, skipping...'
);
}
},
async query_android({ state, commit }, { timeperiod, filterCategories }: QueryOptions) {
const periods = [timeperiodToStr(timeperiod)];
const classes = loadClassesForQuery();
const q = queries.appQuery(state.buckets.android[0], classes, filterCategories);
const data = await this._vm.$aw.query(periods, q).catch(this.errorHandler);
commit('query_window_completed', data[0]);
},
async query_window_empty({ commit }) {
const data = {
app_events: [],
title_events: [],
cat_events: [],
active_events: [],
duration: 0,
};
commit('query_window_completed', data);
},
async query_desktop_full(
{ state, commit, rootState, rootGetters },
{ timeperiod, filterCategories, filterAFK, includeAudible }: QueryOptions
) {
const periods = [timeperiodToStr(timeperiod)];
const classes = loadClassesForQuery();
const q = queries.fullDesktopQuery(
state.buckets.browser,
state.buckets.window[0],
state.buckets.afk[0],
filterAFK,
classes,
filterCategories,
includeAudible
);
const data = await this._vm.$aw.query(periods, q);
const data_window = data[0].window;
const data_browser = data[0].browser;
// Set $color for categories
data_window.cat_events = data[0].window['cat_events'].map(e => {
const cat = rootGetters['categories/get_category'](e.data['$category']);
e.data['$color'] = getColorFromCategory(cat, rootState.categories.classes);
return e;
});
commit('query_window_completed', data_window);
commit('query_browser_completed', data_browser);
},
async query_browser_empty({ commit }) {
const data = {
domains: [],
urls: [],
duration: 0,
};
commit('query_browser_completed', data);
},
async query_editor({ state, commit }, { timeperiod }) {
const periods = [timeperiodToStr(timeperiod)];
const q = queries.editorActivityQuery(state.buckets.editor);
const data = await this._vm.$aw.query(periods, q);
commit('query_editor_completed', data[0]);
},
async query_editor_empty({ commit }) {
const data = {
files: [],
projects: [],
languages: [],
};
commit('query_editor_completed', data);
},
async query_active_history({ commit, state }, { timeperiod }: QueryOptions) {
const periods = timeperiodStrsAroundTimeperiod(timeperiod).filter(tp_str => {
return !_.includes(state.active.history, tp_str);
});
const data = await this._vm.$aw.query(
periods,
queries.dailyActivityQuery(state.buckets.afk[0])
);
const active_history = _.zipObject(
periods,
_.map(data, pair => _.filter(pair, e => e.data.status == 'not-afk'))
);
commit('query_active_history_completed', { active_history });
},
async query_category_time_by_hour(
{ commit, state },
{ timeperiod, filterCategories, filterAFK }: QueryOptions
) {
// TODO: Only works for the 1 day timeperiod
// TODO: Needs to be adapted for Android
const periods = timeperiodsStrsHoursOfDay(timeperiod);
const classes = loadClassesForQuery();
const data = await this._vm.$aw.query(
periods,
// TODO: Clean up call, pass QueryParams in fullDesktopQuery as well
// TODO: Unify QueryOptions and QueryParams
queries.hourlyCategoryQuery({
bid_afk: state.buckets.afk[0],
bid_window: state.buckets.window[0],
bid_browsers: state.buckets.browser,
// bid_android: state.buckets.android,
classes: classes,
filter_afk: filterAFK,
filter_classes: filterCategories,
})
);
const category_time_by_hour = _.zipObject(periods, data);
commit('query_category_time_by_hour_completed', { category_time_by_hour });
},
async query_active_history_android({ commit, state }, { timeperiod }: QueryOptions) {
const periods = timeperiodStrsAroundTimeperiod(timeperiod).filter(tp_str => {
return !_.includes(state.active.history, tp_str);
});
const data = await this._vm.$aw.query(
periods,
queries.dailyActivityQueryAndroid(state.buckets.android[0])
);
let active_history = _.zipObject(periods, data);
active_history = _.mapValues(active_history, (duration, key) => {
return [{ timestamp: key.split('/')[0], duration, data: { status: 'not-afk' } }];
});
commit('query_active_history_completed', { active_history });
},
async query_active_history_empty({ commit }) {
const data = [];
commit('query_active_history_completed', data);
},
async set_available({ commit, state }) {
const window_available = state.buckets.afk.length > 0 && state.buckets.window.length > 0;
const browser_available =
state.buckets.afk.length > 0 &&
state.buckets.window.length > 0 &&
state.buckets.browser.length > 0;
const active_available = state.buckets.afk.length > 0;
const editor_available = state.buckets.editor.length > 0;
const android_available = state.buckets.android.length > 0;
commit('set_available', {
window_available: window_available,
browser_available: browser_available,
active_available: active_available,
editor_available: editor_available,
android_available: android_available,
});
},
async get_buckets({ commit, rootGetters }, { host }) {
const buckets = {
afk: rootGetters['buckets/afkBucketsByHost'](host),
window: rootGetters['buckets/windowBucketsByHost'](host),
android: rootGetters['buckets/androidBucketsByHost'](host),
browser: rootGetters['buckets/browserBuckets'],
editor: rootGetters['buckets/editorBuckets'],
};
console.log('Available buckets: ', buckets);
commit('buckets', buckets);
},
async load_demo({ commit }) {
// A function to load some demo data (for screenshots and stuff)
commit('start_loading', {});
function groupSumEventsBy(events, key, f) {
return flow(
filter(f),
groupBy(f),
values,
map((es: any) => {
return { duration: _.sumBy(es, 'duration'), data: { [key]: f(es[0]) } };
}),
sortBy('duration'),
reverse
)(events);
}
const app_events = groupSumEventsBy(window_events, 'app', (e: any) => e.data.app);
const title_events = groupSumEventsBy(window_events, 'title', (e: any) => e.data.title);
const cat_events = groupSumEventsBy(window_events, '$category', (e: any) => e.data.$category);
const url_events = groupSumEventsBy(window_events, 'url', (e: any) => e.data.url);
const domain_events = groupSumEventsBy(window_events, '$domain', (e: any) =>
e.data.url === undefined ? '' : new URL(e.data.url).host
);
commit('query_window_completed', {
duration: _.sumBy(window_events, 'duration'),
app_events,
title_events,
cat_events,
active_events: [
{ timestamp: new Date().toISOString(), duration: 1.5 * 60 * 60, data: { afk: 'not-afk' } },
],
});
commit('browser_buckets', ['aw-watcher-firefox']);
commit('query_browser_completed', {
duration: _.sumBy(url_events, 'duration'),
domains: domain_events,
urls: url_events,
});
commit('editor_buckets', ['aw-watcher-vim']);
commit('query_editor_completed', {
duration: 30,
files: [{ duration: 10, data: { file: 'test.py' } }],
languages: [{ duration: 10, data: { language: 'python' } }],
projects: [{ duration: 10, data: { project: 'aw-core' } }],
});
function build_active_history() {
const active_history = {};
let current_day = moment(get_day_start_with_offset());
_.map(_.range(0, 30), () => {
const current_day_end = moment(current_day).add(1, 'day');
active_history[`${current_day.format()}/${current_day_end.format()}`] = [
{
timestamp: current_day.format(),
duration: 100 + 900 * Math.random(),
data: { status: 'not-afk' },
},
];
current_day = current_day.add(-1, 'day');
});
return active_history;
}
commit('query_active_history_completed', { active_history: build_active_history() });
},
};
// mutations
const mutations = {
start_loading(state, query_options: QueryOptions) {
state.loaded = true;
state.query_options = query_options;
// Resets the store state while waiting for new query to finish
state.window.top_apps = null;
state.window.top_titles = null;
state.browser.duration = 0;
state.browser.top_domains = null;
state.browser.top_urls = null;
state.editor.duration = 0;
state.editor.top_files = null;
state.editor.top_languages = null;
state.editor.top_projects = null;
state.category.top = null;
state.active.duration = null;
// Ensures that active history isn't being fully reloaded on every date change
// (see caching done in query_active_history and query_active_history_android)
// FIXME: Better detection of when to actually clear (such as on force reload, hostname change)
if (Object.keys(state.active.history).length === 0) {
state.active.history = {};
}
},
set_available(state, data) {
state.window.available = data['window_available'];
state.browser.available = data['browser_available'];
state.active.available = data['active_available'];
state.editor.available = data['editor_available'];
state.category.available = data['window_available'] || data['android_available'];
state.android.available = data['android_available'];
},
query_window_completed(state, data) {
state.window.top_apps = data['app_events'];
state.window.top_titles = data['title_events'];
state.category.top = data['cat_events'];
state.active.duration = data['duration'];
state.active.events = data['active_events'];
},
query_browser_completed(state, data) {
state.browser.top_domains = data.domains;
state.browser.top_urls = data.urls;
state.browser.duration = data.duration;
// FIXME: This one might take up a lot of size in the request, move it to a seperate request
// (or remove entirely, since we have the other timeline now)
state.web_chunks = data['chunks'];
},
query_editor_completed(state, data) {
state.editor.duration = data['duration'];
state.editor.top_files = data['files'];
state.editor.top_languages = data['languages'];
state.editor.top_projects = data['projects'];
},
query_active_history_completed(state, { active_history }) {
state.active.history = {
...state.active.history,
...active_history,
};
},
query_category_time_by_hour_completed(state, { category_time_by_hour }) {
state.category.by_hour = category_time_by_hour;
},
buckets(state, data) {
state.buckets = data;
state.buckets.loaded = true;
},
};
export default {
namespaced: true,
state: _state,
getters,
actions,
mutations,
};