This repository has been archived by the owner on Apr 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kimai-cmd.js
482 lines (416 loc) · 14.8 KB
/
kimai-cmd.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//variables
var verbose = false;
var endHang = false;
//global variables
var apiKey;
var projects = [];
var projectIDs = [];
var tasks = [];
var taskIDs = [];
var active = {};
var isActive = false;
var fullUrl;
var homepageUrl;
//for settings
var settings = {};
//for rainmter
var rainmeterOption;
// for rpc
var client;
//node modules
//json rpc 2
const RpcClient = require('node-json-rpc2').Client;
//File system, path, child process
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
//ini
const ini = require('ini');
//commander
var program = require('commander');
//reading version number from package.json
var pjson = require('./package.json');
//functions
//wrap in quotes
String.prototype.qWrap = function () {
var target = this;
return '"' + target + '"';
};
//calling the server
function kimaiCall(method, param, callback) {
console.log("Calling " + fullUrl + " Method: " + method);
client.call(
{ "jsonrpc": "2.0", "method": method, "params": param, "id": 0 },
function (err, res) {
if (err) {
console.log("Error: " + err);
return false;
} else {
if (res && res.result.success) {
console.log("->Success")
} else {
console.log("->Negative")
if (typeof callback === "function") {
callback(res);
}
return
}
if (res.result.items && verbose) {
for (var i = 0; i < res.result.items.length; i++) {
var element = res.result.items[i];
var itemKeys = Object.keys(element);
for (var j = 0; j < itemKeys.length; j++) {
var elem = itemKeys[j];
console.log(" " + elem + " " + element[elem])
}
console.log();
}
} else if (res.result.error && verbose) {
console.log("Message: " + res.result.error.msg)
}
if (typeof callback === "function") {
callback(res);
}
}
}
)
}
//reading settings file, starting rpc, calling authentication
function kimaiAuthenticate(callback) {
if (program.verbose) {
verbose = true;
}
if (verbose) {
var currDate = new Date()
console.log(currDate.toString())
}
//different settings.ini path for developement and pkg version
var settingsPath;
var settingsPathPkg = path.join(path.dirname(process.execPath), '/settings.ini')
var settingsPathNode = path.join(__dirname, '/settings.ini')
if (fs.existsSync(settingsPathPkg)) {
var settingsPath = settingsPathPkg
} else if (fs.existsSync(settingsPathNode)) {
var settingsPath = settingsPathNode
} else {
console.log("Error: settings.ini not found!")
if (verbose) {
console.log("Searched locations:")
console.log(settingsPathPkg)
console.log(settingsPathNode)
}
return
}
settings = ini.parse(fs.readFileSync(settingsPath, 'utf-8'))
var jsonPath;
var homePath;
if (verbose) {
console.log("Reading settings.ini from " + settingsPath)
}
if (settings.kimai.subfolder) {
var subf = settings.kimai.subfolder
var subfolderArr = settings.kimai.subfolder.split("")
if (subfolderArr[0] == "/") {
var subf = subf.substr(1)
}
if (subfolderArr[subfolderArr.length - 1] == "/") {
var subf = subf.slice(0, -1)
}
jsonPath = '/' + subf + '/core/json.php'
homePath = '/' + subf
} else {
jsonPath = '/core/json.php'
homePath = ''
}
fullUrl = settings.kimai.protocol + "://" + settings.kimai.serverUrl + ":" + settings.kimai.serverPort + jsonPath
homepageUrl = settings.kimai.protocol + "://" + settings.kimai.serverUrl + ":" + settings.kimai.serverPort + homePath
if (verbose) {
console.log("full url: " + fullUrl)
}
var options = {
protocol: settings.kimai.protocol,
port: settings.kimai.serverPort,
host: settings.kimai.serverUrl,
path: jsonPath
};
client = new RpcClient(options);
kimaiCall("authenticate", [settings.kimai.username, settings.kimai.password], function (res) {
if (res && res.result.success) {
apiKey = res.result.items[0].apiKey;
if (verbose) {
console.log("apiKey: " + apiKey)
}
if (typeof callback === "function") {
callback();
}
} else {
console.log("Authentication error!!!")
}
})
}
//calling, get projects
function kimaiGetProjects(callback) {
kimaiCall("getProjects", [apiKey], function (res) {
if (res.result.success) {
for (var i = 0; i < res.result.items.length; i++) {
var element = res.result.items[i];
projects[i] = element.name;
projectIDs[i] = element.projectID;
}
if (typeof callback === "function") {
callback();
}
} else {
console.log("getProject error!!")
}
})
}
//calling, get tasks
function kimaiGetTasks(callback) {
kimaiCall("getTasks", [apiKey], function (res) {
if (res.result.success) {
for (var i = 0; i < res.result.items.length; i++) {
var element = res.result.items[i];
tasks[i] = element.name;
taskIDs[i] = element.activityID;
}
if (typeof callback === "function") {
callback();
}
} else {
console.log("getTasks error!!")
}
})
}
//calling, get active project and task
function kimaiGetActive(callback) {
kimaiCall("getActiveRecording", [apiKey], function (res) {
if (res.result.success) {
// console.log(res.result.items[0].projectName)
active.projectName = res.result.items[0].projectName;
active.activityName = res.result.items[0].activityName;
isActive = true;
if (typeof callback === "function") {
callback();
}
} else if (res.result.success == false && res.result.error.msg == 'No active recording.') {
isActive = false;
if (typeof callback === "function") {
callback();
}
} else {
console.log("getActiveRecording error!!")
}
})
}
//write rainmeter files
//This function needs a total rewrite, very chaotic and not enough options
function writeRainmeter() {
// var writeFileData = "apiKey:" + apiKey + "\r\nprojects:" + projects + "\r\ntasks:" + tasks + "\r\nisActive:" + isActive + "\r\nactive:" + active;
// fs.writeFile('kimaiStatus.ini', writeFileData, (err) => {
// if (err) throw err;
// console.log('The file has been saved!');
// });
console.log("\nChecking rainmeter files")
if (fs.existsSync('kimaiData.inc') && fs.existsSync('kimaiVars.inc')) {
console.log("->Positive")
console.log("Deleting previous rainmeter files")
fs.unlinkSync('kimaiData.inc', (err) => {
if (err) throw err;
});
fs.unlinkSync('kimaiVars.inc', (err) => {
if (err) throw err;
});
if (!fs.existsSync('kimaiData.inc') && !fs.existsSync('kimaiVars.inc')) {
console.log("Files deleted successfully")
}
} else {
console.log("->Negative")
}
console.log("\nWriting rainmeter files")
var rainProject;
var rainTask
if (isActive == false) {
rainProject = "No project"
rainTask = "No task"
} else {
rainProject = active.projectName.qWrap()
rainTask = active.activityName.qWrap()
}
var rainVars = "[Variables]\r\nserverUrl=" + homepageUrl + "\r\nactiveProject=" + rainProject + "\r\nactiveTask=" + rainTask + "\r\n\r\n"
var rainData = "";
rainData += "[MeterProjectTitle]\r\nMeter=String\r\nMeterStyle=" + settings.rainmeter.rainmeterStyleProjectsTitle + "\r\nDynamicVariables=1\r\nHidden=#MenuVis#\r\nText=Projects\r\n\r\n"
for (var index = 0; index < projects.length; index++) {
var element = projects[index].qWrap();
rainData += "[MeterProject" + index + "]\r\nMeter=String\r\nMeterStyle=" + settings.rainmeter.rainmeterStyleProjects + "\r\nDynamicVariables=1\r\nHidden=#MenuVis#\r\nText=" + element
+ "\r\nleftmouseupaction=[!SetOption MeterProject" + index + " Prefix > ][!SetOption #activeProjectMeter# Prefix \"\"][!SetVariable activeProjectMeter MeterProject" + index + "][!SetVariable activeProject " + element + "]\r\n"
if (element == rainProject) {
rainData += "Prefix=>"
rainVars += "activeProjectMeter=MeterProject" + index + "\r\n\r\n"
}
rainData += "\r\n"
// rainData = rainData + "project" + index + "=" + element + "\r\n"
}
rainData += "[MeterTaskTitle]\r\nMeter=String\r\nMeterStyle=" + settings.rainmeter.rainmeterStyleTasksTitle + "\r\nDynamicVariables=1\r\nHidden=#MenuVis#\r\nText=Tasks\r\n"
for (var index = 0; index < tasks.length; index++) {
var element = tasks[index].qWrap();
rainData += "[MeterTask" + index + "]\r\nMeter=String\r\nMeterStyle=" + settings.rainmeter.rainmeterStyleTasks + "\r\nDynamicVariables=1\r\nHidden=#MenuVis#\r\nText=" + element
+ "\r\nleftmouseupaction=[!SetOption MeterTask" + index + " Prefix > ][!SetOption #activeTaskMeter# Prefix \"\"][!SetVariable activeTaskMeter MeterTask" + index + "][!SetVariable activeTask " + element + "]\r\n"
if (element == rainTask) {
rainData += "Prefix=>"
rainVars += "activeTaskMeter=MeterTask" + index + "\r\n\r\n"
}
rainData += "\r\n"
// rainData = rainData + "task" + index + "=" + element + "\r\n"
}
if (!isActive) {
rainVars += "activeProjectMeter=\r\n\r\n"
rainVars += "activeTaskMeter=\r\n\r\n"
rainVars += "stopHidden=1\r\nstartHidden=0\r\n\r\n"
} else {
rainVars += "stopHidden=0\r\nstartHidden=1"
}
fs.writeFile('kimaiVars.inc', rainVars, 'utf-16le', (err) => {
if (err) throw err;
console.log('kimaiVars.inc saved.');
});
fs.writeFile('kimaiData.inc', rainData, 'utf-16le', (err) => {
if (err) throw err;
console.log('kimaiData.inc saved.');
});
}
//stops current recording
function kimaiStop(callback) {
kimaiCall("stopRecord", [apiKey], function (res) {
if (typeof callback === "function") {
callback();
}
})
}
//prints nice lists in the console :)
function niceLog(varArray) {
for (var i = 0; i < varArray.length; i++) {
console.log(" " + varArray[i])
}
}
//prints all project, task, actives
function kimaiList(rainmeter) {
kimaiGetProjects(function () {
kimaiGetTasks(function () {
kimaiGetActive(function () {
console.log("\nProjects:")
niceLog(projects)
console.log("\nTasks:")
niceLog(tasks)
if (isActive && active) {
console.log("\nActive: " + active.projectName + " - " + active.activityName)
} else {
console.log("\nNo active recording.")
}
if (rainmeter) {
writeRainmeter();
exec('"' + settings.rainmeter.rainmeterExePath + '" !RefreshApp', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log("Refreshing rainmeter")
});
if (endHang) {
exec('pause');
}
}
})
})
})
}
function kimaiStart(project, task, callback) {
if (verbose) {
console.log("Starting... Project: " + project + " Task: " + task)
}
var projectNum;
var taskNum;
for (var i = 0; i < projects.length; i++) {
var element = projects[i];
if (verbose) {
console.log("checking: " + element)
}
if (project == element) {
projectNum = projectIDs[i];
if (verbose) {
console.log("found: " + projectIDs[i] + " - " + element)
}
}
}
for (var i = 0; i < tasks.length; i++) {
var element = tasks[i];
if (verbose) {
console.log("checking: " + element)
}
if (task == element) {
taskNum = taskIDs[i];
if (verbose) {
console.log("found: " + taskIDs[i] + " - " + element)
}
}
}
if (verbose) {
console.log(project, projectNum, task, taskNum);
}
kimaiStop(function () {
kimaiCall("startRecord", [apiKey, projectNum, taskNum], function (res) {
if (verbose) {
console.log(res);
}
if (typeof callback === "function") {
callback();
}
})
})
}
//commands, options
program
.version(pjson.version)
.description("Command line client for Kimai, the open source self-hosted timetracker")
.option('-r, --rainmeter', '(re)write the rainmeter meters')
.option('-v, --verbose', 'verbose, longer logging')
.option('-e, --end', 'ctrl+c to exit, only works with -r')
program.command('start [project] [task]')
.description('start selected project and task.')
.action(function (startproject, starttask) {
console.log("starting: " + startproject + ", " + starttask + " ");
kimaiAuthenticate(function () {
kimaiGetProjects(function () {
kimaiGetTasks(function () {
kimaiStart(startproject, starttask, function () {
kimaiList(rainmeterOption);
})
})
})
})
})
program.command('stop')
.description('stop current timer')
.action(function () {
kimaiAuthenticate(function () {
kimaiStop(function () {
kimaiList(rainmeterOption);
});
})
})
program.command('list')
.description('list all projects, tasks and actives')
.action(function () {
kimaiAuthenticate(function () {
kimaiList(rainmeterOption);
})
})
program.parse(process.argv);
if (!program.args.length) program.help();
//verbose var moved to kimaiAuthenticate()
if (program.end) {
endHang = true;
}
if (program.rainmeter) {
rainmeterOption = true;
}