-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodealike.js
More file actions
763 lines (635 loc) · 21.3 KB
/
codealike.js
File metadata and controls
763 lines (635 loc) · 21.3 KB
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
"use strict";
var configuration = require("./configuration");
var logger = require("./logger/logger").Logger;
var recorder = require("./recorder/recorder").Recorder;
var activityType = require("./types/activityType").ActivityType;
var api = require("./api/codealikeApi.js").Api;
var fs = require("fs");
var path = require("path");
const uuidv1 = require("uuid");
const os = require("os");
const moment = require("moment");
const hostNameHelpers = require("./hostNameHelper");
var Codealike = {
isInitialized: false,
isTracking: false,
flushInterval: null,
idleCheckInterval: null,
instanceId: "",
hostFQDN: null,
/*
* stateSubscribers:
* This collection manages all subscribed to plugin state changes.
*/
stateSubscribers: [],
/*
* stateSubscribers:
* This collection manages all subscribed to plugin state changes.
*/
connectionSubscription: null,
/*
* stateBeforeIdle:
* In case of going idle, we have to save the current state
* so when leaving iddle state, we can resume last known state.
*/
stateBeforeIdle: null,
/*
* currentProject:
* CurrentProject has the information about the current project being tracked
* by codealike. It should at least have a registered projectId.
* The desirable structure is :
* { projectId: <UUID>, projectName: <string> }
*/
currentProject: null,
/*
* initialize:
* Initialize process should configure api and recorder instances
* to be prepared to connect and start tracking if required.
* Api initialization requires a 'cliendId' to identificate requests
* in name of 'client' and 'clientVersion'.
*/
initialize: function (clientId, clientVersion) {
if (!clientId)
throw new Error("Codealike initialization requires a client Id'");
if (!clientVersion)
throw new Error("Codealike initialization requires a client Version");
// initialize instance value as new timestamp
let instanceId = moment().unix().toString();
// initialize codealike configuration and load global settings
configuration.initialize(clientId, clientVersion, instanceId);
// initialize logger
logger.initialize(configuration.instancePath);
// try fetch plugin configuration from server
// if retrieved, apply it. Else use defaults
api
.getPluginConfiguration()
.then(
(result) => {
logger.log("Plugin settings retrieved", result);
configuration.loadPluginSettings(result);
},
(error) => {
// nothing to do, configuration will
// fallback to base settings
logger.log("Plugin settings could not been retreived", error);
}
)
.catch((error) => {
logger.log("Puglin settings could not been retrieved", error);
});
// load user preferences from global settings file
configuration.loadGlobalSettings();
// initialize api
api.initialize(clientId);
// subscribes to network changes
Codealike.connectionSubscription = api.registerConnectionStateSubscriber(
this.connectionStateSubscriber
);
// initialize recorder
recorder.initialize();
// get the host name for currrent running environment
// try to get full name, if failed got for os hostname
hostNameHelpers.getHostFQDN().then(
(hostname) => {
Codealike.hostFQDN = hostname;
// log host fqdn obtained for recording activities
logger.info(
"Codealike initialized with host name " + Codealike.hostFQDN
);
},
(error) => {
// host name will default to os.hostname()
Codealike.hostFQDN = os.hostname();
// log host fqdn obtained for recording activities
logger.info(
"Codealike initialized with host name " + Codealike.hostFQDN
);
}
);
// set initialized flag as true
this.isInitialized = true;
logger.info("Codealike initialized with instance id " + instanceId);
},
connectionStateSubscriber: function (state) {
if (Codealike.stateSubscribers) {
Codealike.stateSubscribers.forEach((callback) => {
callback(
Object.assign({}, state, { isTracking: Codealike.isTracking })
);
});
}
},
registerStateSubscriber: function (subscriber) {
return this.stateSubscribers.push(subscriber) - 1;
},
unregisterStateSubscriber: function (position) {
this.stateSubscribers.splice(position, 1);
},
hasUserToken: function () {
return configuration.globalSettings.userToken != null;
},
getUserToken: function () {
return configuration.getUserToken();
},
setUserToken: function (userToken) {
configuration.setUserToken(userToken);
configuration.savelGlobalSettings();
logger.info(`Codealike user token set to ${userToken}`);
},
/*
* dispose:
* Dispose process should dispose api and recorder instances
* If tracking, should stop tracking before releasing recorder and api
*/
dispose: function () {
// if tracking, stop it
if (this.isTracking) this.stopTracking();
// dispose recorder
recorder.dispose();
// dispose api
api.dispose();
// set initialized as false
this.stateSubscribers = [];
this.isInitialized = false;
this.isConfigured = false;
logger.info(`Codealike disposed`);
// dispose logger
logger.dispose();
},
/*
* connect:
* Connect process should try to authenticate user with given token
* If authenticated, api should be configured to be able to perform
* further requests in users name (by keeping user authentication info).
*/
connect() {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
logger.info(`Codealike is connecting`);
return new Promise(function (resolve, reject) {
api
.authenticate(configuration.globalSettings.userToken)
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
});
},
/*
* getProfile:
* GetProfile process should return authenticated user profile information.
* It requires api to be already connected and configured with valid token,
* client and user id.
*/
getProfile() {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
return api.getProfile();
},
/*
* disconnect:
* Disconnect process should stop tracking (if already doing that)
* and disconnect api.
* Codealike instance should be safe for disposing after this mathod.
*/
disconnect() {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
// if tracking, stop doing that
this.stopTracking();
// clear api connection data
api.disconnect();
logger.info(`Codealike is disconnected`);
},
/*
* configure:
* Configure proces consists in
* 1- verify if codelike configuration file exists for project
* 2- if there, get project id from file
* 3- if not, generate a new id and register on codealike server
* 4- if registered save to configuration file
*/
configure(projectFolderPath) {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
return new Promise(function (resolve, reject) {
// generate codealike json configuration file path
let codealikeProjectFile = path.join(projectFolderPath, "codealike.json");
// try to get project configuration from file
let existingConfiguration = null;
if (fs.existsSync(codealikeProjectFile)) {
existingConfiguration = JSON.parse(
fs.readFileSync(codealikeProjectFile, "utf8")
);
}
// if no configuration was retrieved
// we have to assign a project id and create configuration file for project
if (existingConfiguration == null || !existingConfiguration.projectId) {
// create unique id
let projectId = uuidv1.v1();
let projectName = path.basename(projectFolderPath);
// register project
api.registerProjectContext(projectId, projectName).then(
(result) => {
// create project configuration
let configuration = {
projectId: projectId,
projectName: projectName,
};
// convert object to string
let jsonString = JSON.stringify(configuration);
// if registered, save configuration file
// have to save configuration file
fs.writeFile(
codealikeProjectFile,
jsonString,
"utf8",
function (error) {
if (error) {
reject("Could not save project configuration file.");
}
resolve(configuration);
}
);
},
(error) => {
reject("Could not register project in codealike server.");
}
);
} else {
resolve(existingConfiguration);
}
});
},
/*
* startTracking:
* StartTracking activates all required functionalities to start
* tracking events and state changes in a given project.
* It must receive the project configuration of the project being tracked
*/
startTracking: function (
projectConfiguration,
workspaceStartTime = new Date()
) {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (!projectConfiguration)
throw new Error(
"Codealike project configuration is required to start tracking"
);
// sets internal state to indicate tracking is in progress
this.isTracking = true;
// saves current project reference for tracking purposes
this.currentProject = projectConfiguration;
// tracks system state and open solution events
this.trackSystemState(workspaceStartTime);
this.trackOpenSolutionEvent(workspaceStartTime);
this.flushInterval = setInterval(
this.flushData,
configuration.pluginSettings.flushInterval
);
this.idleCheckInterval = setInterval(
this.checkIdle,
configuration.pluginSettings.idleCheckInterval
);
// verify if there are local files to send
this.flushPendingFiles();
logger.info("Codealike started tracking");
},
stopTracking: function () {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (this.isTracking) {
clearInterval(this.flushInterval);
clearInterval(this.idleCheckInterval);
this.checkIdle();
this.flushData(true);
}
this.isTracking = false;
logger.info("Codealike stoped tracking");
},
checkIdle: function () {
if (!recorder.lastState) return;
// if last state was idle, it seems to be still idle
if (recorder.lastState.type === activityType.Idle) {
recorder.updateLastState();
} else {
var currentTime = new Date();
var elapsedFromLastEventInSeconds = currentTime - recorder.lastEventTime;
if (
elapsedFromLastEventInSeconds >=
configuration.pluginSettings.idleMaxPeriod
) {
// save last state type before going iddle
Codealike.stateBeforeIdle = recorder.lastState.type;
// record idle state
recorder.recordState({
type: activityType.Idle,
start: currentTime,
});
}
}
},
getDataToFlush: function () {
if (!recorder.isInitialized) return null;
// gets data to be sent to the server
var dataToSend = recorder.getLastBatch();
if (dataToSend.events.length === 0) {
logger.info("No tracked data to send is available");
return null;
}
if (dataToSend.states.every((state) => state.type === activityType.Idle)) {
logger.info("Only idle data tracked. Batch discarded");
return null;
}
// generate data package to be sent to the server
let data = {
machine: Codealike.hostFQDN,
client: configuration.instanceSettings.clientId,
solutionId: Codealike.currentProject.projectId,
batchId: uuidv1.v1(),
extension: configuration.instanceSettings.clientVersion,
instance: configuration.instanceSettings.instanceId,
projects: [
{
projectId: Codealike.currentProject.projectId,
name: Codealike.currentProject.projectName,
},
],
states: dataToSend.states.map((state) => {
let startTime = moment(state.start).format();
let endTime = moment(state.end).format();
let duration = moment
.utc(moment(state.end).diff(moment(state.start)))
.format("HH:mm:ss.SSS");
return {
parentId: state.projectId,
type: state.type,
start: startTime,
end: endTime,
duration: duration,
};
}),
events: dataToSend.events.map((event) => {
let startTime = moment(event.start).format();
let endTime = moment(event.end).format();
let duration = moment
.utc(moment(event.end).diff(moment(event.start)))
.format("HH:mm:ss.SSS");
return {
parentId: event.projectId,
type: event.type,
start: startTime,
end: endTime,
duration: duration,
context: {
member: event.member || "",
namespace: event.namespace || "",
projectId: event.projectId,
file: event.file,
class: event.className || "",
line: event.line,
},
};
}),
};
return data;
},
saveLocalCache: function (data) {
// if there is data to flush, save it to disk
let flushFilePath = path.join(
configuration.cachePath,
configuration.instanceSettings.clientId +
"-" +
moment().format("YYYYMMDDhhmmss") +
".json"
);
fs.writeFile(flushFilePath, JSON.stringify(data), "utf8", function (error) {
if (error) {
throw new Error("Could not save local cache file.");
}
});
},
sendDataToCodealike: function (data, saveLocalIfFailed = true) {
return new Promise(function (resolve, reject) {
// try to send data to server
api.postActivity(data).then(
(result) => {
// data sent
logger.trace("Data successfully sent to server");
resolve();
},
(error) => {
// if failed, save data local to be sent next opportunity
if (saveLocalIfFailed) {
Codealike.saveLocalCache(data);
}
logger.trace("Data not sent to server", error);
reject(error);
}
);
});
},
flushPendingFiles: function () {
fs.readdir(configuration.cachePath, function (err, filenames) {
if (err) {
//throw new Error('Could not load local cache path.');
return;
}
// process files and mark them to be removed
filenames.forEach(function (filename) {
Codealike.flushLocalFile(filename);
});
});
},
flushLocalFile: function (fileName) {
if (!fileName) return;
fs.readFile(
path.join(configuration.cachePath, fileName),
"utf-8",
function (err, content) {
logger.trace(fileName + " picked to be flushed");
if (err) {
logger.log(
"File picked to be flushed not available anymore",
fileName
);
return;
}
// if content is empty, nothing to do
if (!content) return;
// parse data as json
let data = "";
try {
data = JSON.parse(content);
} catch (error) {
logger.log("File " + fileName + " content is corrupt");
}
// try to send data to server
Codealike.sendDataToCodealike(data, false).then(
() => {
// if finished ok, move the file to history
// remove the file (it will be created again if sending fails)
fs.rename(
path.join(configuration.cachePath, fileName),
path.join(configuration.historyPath, fileName),
(err) => {
if (err) {
logger.log("Error moving " + fileName + " to history folder");
}
logger.log(
"File " + fileName + " succesfully moved to history folder"
);
}
);
},
(error) => {
logger.trace(
"Could not send " + fileName + " information to server",
error
);
}
);
}
);
},
flushData: function (localOnly = false) {
logger.info("Codealike is sending data");
// get data pending to be flushed
let data = Codealike.getDataToFlush();
// if no data found to flush, just return
if (!data) {
// nothing else to do here
return;
}
if (localOnly) {
// if local only, just save cache to disk
Codealike.saveLocalCache(data);
} else {
// try to send data to server
Codealike.sendDataToCodealike(data, true);
}
},
updateOrChangeStateOnEvent: function (proposedNewState) {
var newState = proposedNewState;
// if there is an state before idle, it means
// we left idle state with current event and
// we have to resume that state
if (
this.stateBeforeIdle !== null &&
this.stateBeforeIdle !== activityType.System
) {
newState = this.stateBeforeIdle;
this.stateBeforeIdle = null;
} else {
// verify if status should be updated or changed
// this is because when debugging, focus or coding
// events must not change the current status.
// So, if last state was debugging, state should be
// just updated.
if (
proposedNewState === activityType.Coding &&
recorder.lastState.type === activityType.Debugging
) {
newState = activityType.Debugging;
}
}
// record status
recorder.recordState({
projectId: this.currentProject.projectId,
type: newState,
start: new Date(),
});
},
trackFocusEvent: function (context) {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (!this.isTracking) return;
// completes event information
context.projectId = this.currentProject.projectId;
context.type = activityType.DocumentFocus;
context.start = new Date();
// check whether or not state should be changed or updated
this.updateOrChangeStateOnEvent(activityType.Coding);
// record current event
recorder.recordEvent(context);
logger.info("Codealike Tracked Focus", context);
},
trackCodingEvent: function (context) {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (!this.isTracking) return;
// completes event information
context.projectId = this.currentProject.projectId;
context.type = activityType.DocumentEdit;
context.start = new Date();
// check whether or not state should be changed or updated
this.updateOrChangeStateOnEvent(activityType.Coding);
// record current event
recorder.recordEvent(context);
logger.info("Codealike Tracked Event", context);
},
trackSystemState: function (start) {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (!this.isTracking) return;
// generate state context
let context = {
projectId: this.currentProject.projectId,
type: activityType.System,
start: start,
};
// record system state, started when workspace started
recorder.recordState(context);
logger.info("Codealike Tracked System state", context);
},
trackOpenSolutionEvent: function (start) {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (!this.isTracking) return;
// generate event context
let context = {
projectId: this.currentProject.projectId,
type: activityType.OpenSolution,
start: start,
};
// record open solution event, started when workspace started
recorder.recordEvent(context);
logger.info("Codealike Tracked Open Solution", context);
},
trackDebuggingState: function () {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (!this.isTracking) return;
// when state is reported, state before idle should be cleaned up
this.stateBeforeIdle = null;
// generate event context
let context = {
projectId: this.currentProject.projectId,
type: activityType.Debugging,
start: new Date(),
};
// record open solution event, started when workspace started
recorder.recordState(context);
logger.info("Codealike Tracked Debugging state", context);
},
trackCodingState: function () {
if (!this.isInitialized)
throw new Error("Codealike should be initialized before used");
if (!this.isTracking) return;
// when state is reported, state before idle should be cleaned up
this.stateBeforeIdle = null;
// generate event context
let context = {
projectId: this.currentProject.projectId,
type: activityType.Coding,
start: new Date(),
};
// record open solution event, started when workspace started
recorder.recordState(context);
logger.info("Codealike Tracked Coding state", context);
},
};
module.exports = { Codealike };