-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclitools
executable file
·463 lines (392 loc) · 15.4 KB
/
clitools
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
#!/usr/bin/env php
<?php
/*
Copyright (C) 2022 Zero Waste Paris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
require_once __DIR__ . '/vendor/autoload.php';
require_once "inc/slackAPI.php";
require_once "inc/utils.php";
require_once "inc/agenda.php";
require_once "inc/CalDAVClient.php";
$log = new Logger('CLITOOLS');
$log->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG));
$GLOBALS['LOG_HANDLERS'][] = new StreamHandler('php://stdout', Logger::DEBUG);
abstract class Command {
abstract public function run();
abstract public function getHelpMessage();
}
class RemindersLister extends Command {
public function run() {
global $log;
list($slack_credentials, $caldav_credentials, $agenda_args) = read_config_file();
$api = new SlackAPI($slack_credentials['bot_token']);
$user_infos = $api->auth_test();
foreach($api->listScheduledMessages() as $id => $reminder) {
$log->info("Reminder:");
foreach($reminder as $key => $val) {
if(is_null($val)) {
$log->info(" $key = null");
} else {
$log->info(" $key = $val");
}
}
}
}
public function getHelpMessage() {
return "Prints all the future Slack reminders created by this app";
}
}
class RemindersPurger extends Command {
public function run() {
global $log;
list($slack_credentials, $caldav_credentials, $agenda_args) = read_config_file();
$api = new SlackAPI($slack_credentials['bot_token']);
$user_infos = $api->auth_test();
foreach($api->listScheduledMessages() as $id => $reminder) {
$log->info("deleting reminder id: $reminder[id]\n");
$api->deleteScheduledMessage($reminder["channel_id"], $reminder["id"]);
}
}
public function getHelpMessage() {
return "Delete all the slack reminders created by this app";
}
}
class AgendaChecker extends Command {
public function run() {
checkAgenda();
}
public function getHelpMessage() {
return "Update the local database so it matches the content of the remote caldav calendar.\n"
. "Note that this operation is done regularly by the app so you don't really need to run this command.\n"
. "(It may be useful when you just installed the app so the 1st query isn't too slow)";
}
}
class ApiTokensChecker extends Command {
public function run() {
api_checktokens();
}
public function getHelpMessage() {
return "Checks whether the user and bot slack tokens are valid";
}
}
class CaldavClientAuthChecker extends Command {
public function run() {
caldavclient_checkAuth();
}
public function getHelpMessage() {
return "Checks that the caldav credential are valid";
}
}
class ConfigReader extends Command {
public function run() {
config_read();
}
public function getHelpMessage() {
return "Read the config file and run some sanity checks on it";
}
}
class Installer extends Command {
public function run() {
config_read();
caldavclient_checkauth();
api_checktokens();
database_create();
checkAgenda();
}
public function getHelpMessage() {
return "Performs some basic checks, creates the table in database, and fill them with the content of the caldav server.\n"
. "This command is idempotent (as long as the local config and the remote caldav server states don't change).";
}
}
class DatabaseConnectionChecker extends Command {
public function run() {
global $log;
$log->info("Checking database connection... ");
$agenda = open_agenda();
if (!is_a($agenda, 'Agenda')) {
$log->info("could not initiate backend.");
return false;
}
$log->info("Checking database connection - ok.");
return true;
}
public function getHelpMessage() {
return "Checks that the app is able to connect to the database";
}
}
class CSVExport extends Command {
public function run() {
global $log;
$caldav = build_caldavclient();
$salt = random_bytes(40);
$csv = "";
foreach($caldav->fetchEvents(array_keys($caldav->getETags())) as $i => $event) {
$vCalendar = \Sabre\VObject\Reader::read($event['vCalendarRaw']);
$csv .= $vCalendar->VEVENT->DTSTART->getDateTime()->getTimestamp() . ";";
$csv .= $vCalendar->VEVENT->DTEND->getDateTime()->getTimestamp() . ";";
$attendees = [];
if(isset($vCalendar->VEVENT->ATTENDEE)) {
foreach($vCalendar->VEVENT->ATTENDEE as $attendee) {
$attendees[] = anonymizeAttendee($attendee);
}
}
$categories = [];
if(isset($vCalendar->VEVENT->CATEGORIES)) {
foreach($vCalendar->VEVENT->CATEGORIES as $category) {
$categories[] = (string)$category;
}
}
$csv .= implode(",", $attendees) . ";" . implode(",", $categories) . "\n";
}
$date = new DateTimeImmutable();
file_put_contents($date->format('Y-m-d').".csv", $csv, FILE_APPEND | LOCK_EX);
return true;
}
public function getHelpMessage() {
return "Export events into a csv file. Attendees are anonymized.";
}
}
class DatabaseCreator extends Command {
public function run() {
database_create();
}
public function getHelpMessage() {
return "Creates the tables in database. (note that the database itself should already exist)";
}
}
class DatabaseOrphanCategoriesCleaner extends Command {
public function run() {
database_clean_orphan_categories();
}
public function getHelpMessage() {
return "clean the database by removing all the categories that don't exist on any upcoming events.\n"
. "(Running this command is safe, in the sense that if an event uses such categories in the future they will"
. " be recreated on the fly as needed).";
}
}
class DatabaseOrphanAttendeesCleaner extends Command {
public function run() {
$agenda = open_agenda();
$agenda->clean_orphan_attendees(false);
}
public function getHelpMessage() {
return "clean the database by removing all the user that don't attend any upcoming events.\n"
. "(Running this command is safe, in the sense that if one of those user register to an event in the future they will"
. " be recreated on the fly as needed).";
}
}
class DatabaseOrphansCleaner extends Command {
public function run() {
$agenda = open_agenda();
$agenda->clean_orphan_categories(false);
$agenda->clean_orphan_attendees(false);
}
public function getHelpMessage() {
return "Delete all orphan categories and attendees";
}
}
class DatabaseTruncator extends Command {
public function run() {
$agenda = open_agenda();
$agenda->truncate_tables();
$agenda->createDB(); // to insert CTag
}
public function getHelpMessage() {
return "Truncates all sql tables (it does not delete the tables though).\n"
. "This command is rather safe in the sense that all the useful data will be recreated with the next agenda check"
. " (based on the data of the caldav server).\n"
. "However the data related to the existing Slack reminder will be lost.";
}
}
class PseudonymizeAttendeesDataOnCaldav extends Command {
public function run() {
global $log;
$caldav = build_caldavclient();
// // Up to 2 years ago to be compatible with our personal data policy
// // (this duration could eventually be moved to some config file, however:
// // - as long as no one needs it, it's more convenient to have it here
// // - having it hardcoded prevents manual error which could kill recent data
// // )
$upTo = new DateTimeImmutable("-2 years");
$log->info("Will anonymize events up to " . $upTo->format(DateTimeInterface::ISO8601));
$vCalendarFilenames = array();
foreach($caldav->getEtags(null, $upTo) as $vCalendarFilename => $etag) {
$vCalendarFilenames []= $vCalendarFilename;
}
foreach($caldav->fetchEvents($vCalendarFilenames) as $event) {
$vCalendar = \Sabre\VObject\Reader::read($event['vCalendarRaw']);
// Note that we don't need to do anything with the database because we're only updating old events
// and that the database only contains data about event which are at most 1 day old
if (is_null($vCalendar->VEVENT->ATTENDEE)) {
$log->info("Skipping event " . $vCalendar->VEVENT->SUMMARY . " since it does not seem to have any attendee");
continue;
}
$updatedEvent = false;
foreach($vCalendar->VEVENT->ATTENDEE as $attendee) {
$anonymizedAttendee = anonymizeAttendee($attendee);
if ($attendee == $anonymizedAttendee) {
continue;
}
$vCalendar->VEVENT->remove($attendee);
$vCalendar->VEVENT->add('ATTENDEE', $anonymizedAttendee);
$updatedEvent = true;
}
// Query the remote caldav server only if the event was updated, to save resources and time
if ($updatedEvent) {
$log->info("Going to anonymize attendees of event " . $vCalendar->VEVENT->SUMMARY);
if ($caldav->updateEvent($event["vCalendarFilename"], $event["ETag"], $vCalendar->serialize()) === FALSE) {
$log->error("Failed to update the event");
}
} else {
$log->info("No need to anonymize attendees of event " . $vCalendar->VEVENT->SUMMARY);
}
}
}
public function getHelpMessage() {
return "Pseudonymize old personal data on the remote caldav server. To be compatible with GDPR it makes sense to run this regularly\n"
. "In practice attendees are replaced with hashed data which still makes it possible to get stats like"
. " the distribution of time spent by participants";
}
}
function config_read() {
global $log;
$log->info("Try to read config file...");
if(count(read_config_file()) !== 3) {
$log->info("Try to read config file - nok.");
return false;
}
$log->info("Try to read config file - ok.");
return true;
}
function api_checktokens() {
global $log;
list($slack_credentials, $caldav_credentials, $agenda_args) = read_config_file();
$api = new SlackAPI($slack_credentials['bot_token']);
$ok = true;
$log->info("Checking Slack bot token...");
$ret = $api->auth_test();
if(!is_null($ret) && $ret->ok) {
if(isset($ret->bot_id)) {
$log->info("Checking Slack bot token - ok.");
} else {
$log->info("Checking Slack bot token - nok (user token instead)");
}
} else {
$ok = false;
$log->info("Checking Slack bot token - nok.");
}
return $ok;
}
function caldavclient_checkauth() {
global $log;
$log->info("Checking CalDAV client credentials...");
list($slack_credentials, $caldav_credentials, $agenda_args) = read_config_file();
$caldav = new CalDAVClient($caldav_credentials['url'], $caldav_credentials['username'], $caldav_credentials['password']);
if(!is_null($caldav->getctag())) {
$log->info("Checking CalDAV client credentials - ok.");
return true;
} else {
$log->info("Checking CalDAV client credentials - nok.");
return false;
}
}
function open_agenda() {
global $log;
list($slack_credentials, $caldav_credentials, $agenda_args) = read_config_file();
$api = new SlackAPI($slack_credentials['bot_token']);
$agenda = initAgendaFromType($caldav_credentials['url'], $caldav_credentials['username'], $caldav_credentials['password'],
$api, $agenda_args, $log);
return $agenda;
}
function build_caldavclient() {
list($slack_credentials, $caldav_credentials, $agenda_args) = read_config_file();
return new CalDAVClient($caldav_credentials['url'], $caldav_credentials['username'], $caldav_credentials['password']);
}
function database_clean_orphan_categories() {
$agenda = open_agenda();
$agenda->clean_orphan_categories(false);
}
function database_create() {
$agenda = open_agenda();
$agenda->createDB();
}
function checkAgenda() {
global $log;
$agenda = open_agenda();
$log->info("Checking Agenda... ");
$agenda->checkAgenda();
$log->info("Checking Agenda - done");
}
function anonymizeAttendee($attendee) {
$placeholderDomain = "anonymized";
if (str_ends_with("@$attendee", $placeholderDomain)) { // Make this function idempotent
return $attendee;
}
if (!isset($GLOBALS['SALT'])) {
read_config_file();
}
return "mailto:" . hash("sha256", (string) $attendee. $GLOBALS['SALT']) . "@$placeholderDomain";
}
class HelpPrinter extends Command {
public function run() {
echo $this->getHelpMessage();
}
public function getHelpMessage() {
global $cmds;
$message = "Existing commands:\n";
foreach($cmds as $commandName => $commandInstance){
$message .= "- $commandName:\n";
if ($commandInstance instanceof HelpPrinter) {
$message .= " Prints this help";
} else {
$message .= " " . $commandInstance->getHelpMessage();
}
$message .= "\n\n";
}
return $message;
}
}
$cmds = [
"csv-export" => new CSVExport(),
"pseudonymize-old-caldav-data" => new PseudonymizeAttendeesDataOnCaldav(),
"reminders-list" => new RemindersLister(),
"reminders-purge" => new RemindersPurger(),
"checkAgenda" => new AgendaChecker(),
"api-checktokens" => new ApiTokensChecker(),
"caldavclient-checkauth" => new CaldavClientAuthChecker(),
"config-read" => new ConfigReader(),
"install" => new Installer(),
"database-checkconnection" => new DatabaseConnectionChecker(),
"database-create" => new DatabaseCreator(),
"database-clean-orphan_categories" => new DatabaseOrphanCategoriesCleaner(),
"database-clean-orphan_attendees" => new DatabaseOrphanAttendeesCleaner(),
"database-cleanall" => new DatabaseOrphansCleaner(),
"database-truncate" => new DatabaseTruncator(),
"help" => new HelpPrinter()
];
if (count($argv) != 2) {
$log->info("Expecting exactly 1 argument: the name of the command to run");
$helper = new HelpPrinter();
$helper->run();
exit(1);
}
$cmd = $argv[1];
if (! array_key_exists($cmd, $cmds) ){
$log->info("Unknown command $cmd");
$helper = new HelpPrinter();
$helper->run();
exit(1);
}
$cmds[$cmd]->run();