-
Notifications
You must be signed in to change notification settings - Fork 16
/
vroom
executable file
·2409 lines (2285 loc) · 69.6 KB
/
vroom
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
#!/usr/bin/env perl
# This file is part of the VROOM project
# Released under the MIT licence
# Copyright 2014-2015 Daniel Berteaud <[email protected]>
use lib './lib';
use Mojolicious::Lite;
use Mojolicious::Plugin::Mail;
use Mojolicious::Plugin::Database;
use Mojolicious::Plugin::StaticCompressor;
use Mojo::Redis2;
use Vroom::Constants;
use Vroom::Conf;
use Crypt::SaltedHash;
use Digest::HMAC_SHA1 qw(hmac_sha1);
use MIME::Base64;
use File::stat;
use File::Basename;
use Session::Token;
use Email::Valid;
use Protocol::SocketIO::Handshake;
use Protocol::SocketIO::Message;
use File::Path qw(make_path);
use File::Basename;
use DateTime;
use Array::Diff;
use Encode qw(encode_utf8);
use Data::Dumper;
app->log->level('info');
our $config = Vroom::Conf::get_conf();
# Try to create the directories we need
foreach my $dir (qw/assets/){
if (!-d $config->{'directories.cache'} . '/' . $dir){
make_path($config->{'directories.cache'} . '/' . $dir, { mode => 0770 });
}
elsif (!-w $config->{'directories.cache'} . '/' . $dir){
die $config->{'directories.cache'} . '/' . "$dir is not writable";
}
}
# Optional features
our $optf = {};
# Create etherpad api client if enabled
if ($config->{'etherpad.uri'} =~ m/https?:\/\/.*/ && $config->{'etherpad.api_key'} ne ''){
my $etherpad = eval { require Etherpad };
if ($etherpad){
import Etherpad;
$optf->{etherpad} = Etherpad->new({
url => $config->{'etherpad.uri'},
apikey => $config->{'etherpad.api_key'}
});
if (!$optf->{etherpad}->check_token){
app->log->info("Can't connect to Etherpad-Lite API, check your API key and uri");
$optf->{etherpad} = undef;
}
}
else{
app->log->info("Etherpad perl module not found, disabling Etherpad-Lite support");
}
}
# Check if Excel export is available
my $excel = eval {
require File::Temp;
require Excel::Writer::XLSX;
require Mojolicious::Plugin::RenderFile;
};
if ($excel){
import File::Temp;
import Excel::Writer::XLSX;
import Mojolicious::Plugin::RenderFile;
$optf->{excel} = 1;
}
# Global error check
our $error = undef;
our $listeners = {};
# Initialize localization
plugin I18N => {
namespace => 'Vroom::I18N',
};
# Connect to the database
# Only MySQL supported for now
plugin database => {
dsn => $config->{'database.dsn'},
username => $config->{'database.user'},
password => $config->{'database.password'},
options => {
mysql_enable_utf8 => 1,
mysql_auto_reconnect => 1,
RaiseError => 1,
PrintError => 0
}
};
# Load mail plugin with its default values
plugin mail => {
from => $config->{'email.from'},
type => 'text/html',
};
# Static resources compressor
plugin StaticCompressor => {
url_path_prefix => 'assets',
file_cache_path => $config->{'directories.cache'} . '/assets/',
disable_on_devmode => 1
};
# Stream files
plugin 'RenderFile';
##########################
# Validation helpers #
##########################
# Take a string as argument and check if it's a valid room name
helper valid_room_name => sub {
my $self = shift;
my $name = shift;
my $ret = {};
# A few names are reserved
my @reserved = qw(about help feedback feedback_thanks goodbye admin locales api
missing dies kicked invitation js css img fonts snd documentation);
if (!$name || $name !~ m/^[\w\-]{1,49}$/ || grep { $name eq $_ } @reserved){
return 0;
}
return 1;
};
# Check arg is a valid ID number
helper valid_id => sub {
my $self = shift;
my $id = shift;
if (!$id || $id !~ m/^\d+$/){
return 0;
}
return 1;
};
# Check email address format
helper valid_email => sub {
my $self = shift;
my $email = shift;
return Email::Valid->address($email);
};
# Validate a date in YYYY-MM-DD format
# Also accepts YYYY-MM-DD hh:mm:ss
helper valid_date => sub {
my $self = shift;
my $date = shift;
if ($date !~ m/^\d{4}\-\d{1,2}\-\d{1,2}(\s+\d{1,2}:\d{1,2}:\d{1,2})?$/){
$self->app->log->debug("$date is not a valid date");
return 0;
}
return 1;
};
##########################
# Various helpers #
##########################
# Check if the database schema is the one we expect
helper check_db_version => sub {
my $self = shift;
my $sth = eval {
$self->db->prepare('SELECT `value`
FROM `config`
WHERE `key`=\'schema_version\'');
};
$sth->execute;
my $ver = undef;
$sth->bind_columns(\$ver);
$sth->fetch;
return ($ver eq Vroom::Constants::DB_VERSION) ? '1' : '0';
};
# Helper to access redis objects
helper redis => sub {
my $self = shift;
state $redis = Mojo::Redis2->new(url => $config->{'database.redis'});
};
# Get optional features
helper get_opt_features => sub {
my $self = shift;
return $optf;
};
# Log an event
helper log_event => sub {
my $self = shift;
my $event = shift;
if (!$event->{event} || !$event->{msg}){
$self->app->log->debug("Oops, invalid event received");
return 0;
}
my $addr = $self->tx->remote_address || '127.0.0.1';
my $user = $self->get_name || 'VROOM daemon';
my $sth = eval {
$self->db->prepare('INSERT INTO `audit` (`date`,`event`,`from_ip`,`user`,`message`)
VALUES (CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'),?,?,?,?)');
};
$sth->execute(
$event->{event},
$addr,
$user,
$event->{msg}
);
$self->app->log->info('[' . $addr . '] [' . $user . '] [' . $event->{event} . '] ' . $event->{msg});
return 1;
};
# Return peers from redis
helper get_peers => sub {
my $self = shift;
my $peers = {};
foreach my $id (@{$self->redis->hkeys('peers')}){
my $peer = $self->get_peer($id);
$peers->{$id} = $peer if $peer;
}
return $peers;
};
# Return a single peer
helper get_peer => sub {
my $self = shift;
my $peer = shift;
my $p = $self->redis->hget('peers', $peer);
if ($p){
return Mojo::JSON::from_json($p);
}
return 0;
};
# Store peers in redis
helper add_peer => sub {
my $self = shift;
my $id = shift;
my $peer = shift;
return $self->redis->hset('peers', $id, Mojo::JSON::to_json($peer));
};
# Remove a peer
helper del_peer => sub {
my $self = shift;
my $id = shift;
return $self->redis->hdel('peers', $id);
};
# Return a list of event between 2 dates
helper get_event_list => sub {
my $self = shift;
my $start = shift;
my $end = shift;
# Check both start and end dates seems valid
if (!$self->valid_date($start) || !$self->valid_date($end)){
$self->app->log->debug("Invalid date submitted while looking for events");
return 0;
}
my $sth;
$sth = eval {
$self->db->prepare('SELECT * FROM `audit`
WHERE `date`>=?
AND `date`<=?');
};
# We want both dates to be inclusive, as the default time is 00:00:00
# if not given, append 23:59:59 to the end date
$end .= ' 23:59:59' if ($end !~ /\s+\d{1,2}:\d{1,2}:\d{1,2}$/);
$sth->execute($start, $end);
# Everything went fine, return the list of event as a hashref
return $sth->fetchall_hashref('id');
};
# Generate and manage rotation of session keys
# used to sign cookies
helper update_session_keys => sub {
my $self = shift;
# First, delete obsolete session keys
my $sth = eval {
$self->db->prepare('DELETE FROM `session_keys`
WHERE `date` < DATE_SUB(CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'), INTERVAL 72 HOUR)');
};
$sth->execute;
# Now, retrieve all remaining keys, to check if we have enough of them
$sth = eval {
$self->db->prepare('SELECT `key` FROM `session_keys`
ORDER BY `date` DESC');
};
$sth->execute;
my $keys = $sth->fetchall_hashref('key');
my @keys = keys %$keys;
# Now, check how many keys are less than 24 hours old
$sth = eval {
$self->db->prepare('SELECT COUNT(`key`) FROM `session_keys`
WHERE `date` > DATE_SUB(CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'), INTERVAL 24 HOUR)');
};
$sth->execute;
my $recent_keys = $sth->fetchrow;
if ($recent_keys < 1){
$self->app->log->debug("Generating a new key to sign session cookies");
my $new_key = Session::Token->new(
alphabet => ['a'..'z', 'A'..'Z', '0'..'9', '.:;,/!%$#~{([-_)]}=+*|'],
entropy => 512
)->get;
unshift @keys, $new_key;
$sth = eval {
$self->db->prepare('INSERT INTO `session_keys` (`key`,`date`)
VALUES (?,CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'))');
};
$sth->execute($new_key);
}
$self->app->secrets(\@keys);
return 1;
};
# Return human readable username if it exists, or just the session ID
helper get_name => sub {
my $self = shift;
if ($ENV{'REMOTE_USER'} && $ENV{'REMOTE_USER'} ne ''){
return $ENV{'REMOTE_USER'};
}
return $self->session('id');
};
# Create a cookie based session
# And a new API key
helper login => sub {
my $self = shift;
if ($self->session('id') && $self->session('id') ne ''){
return 1;
}
my $id = $self->get_random(256);
my $key = $self->get_random(256);
my $sth = eval {
$self->db->prepare('INSERT INTO `api_keys`
(`token`,`not_after`)
VALUES (?,DATE_ADD(CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'), INTERVAL 24 HOUR))');
};
$sth->execute($key);
$self->session(
id => $id,
key => $key
);
$self->log_event({
event => 'session_create',
msg => 'User logged in'
});
return 1;
};
# Force the session cookie to expire on logout
helper logout => sub {
my $self = shift;
my $room = shift;
# Logout from etherpad
if ($optf->{etherpad} && $self->session($room) && $self->session($room)->{etherpadSessionId}){
$optf->{etherpad}->delete_session($self->session($room)->{etherpadSessionId});
}
my $sth = eval {
$self->db->prepare('DELETE FROM `api_keys`
WHERE `token`=?');
};
$sth->execute($self->session('key'));
$self->session( expires => 1 );
$self->log_event({
event => 'session_destroy',
msg => 'User logged out'
});
return 1;
};
# Create a new room in the DB
# Requires one arg: the name of the room
helper create_room => sub {
my $self = shift;
my $name = shift;
# Convert room names to lowercase
if ($name ne lc $name){
$name = lc $name;
}
# Check if the name is valid
if (!$self->valid_room_name($name)){
return 0;
}
# Fail if the room already exists
if ($self->get_room_by_name($name)){
return 0;
}
my $sth = eval {
$self->db->prepare('INSERT INTO `rooms`
(`name`,
`create_date`,
`last_activity`)
VALUES (?,
CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'),
CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\')
)');
};
$sth->execute($name);
$self->log_event({
event => 'room_create',
msg => "Room $name created"
});
# Create a pad if enabled
if ($optf->{etherpad}){
$self->create_pad($name);
}
return 1;
};
# Takse a string as argument
# Return a room object if a room with that name is found
# Else return undef
helper get_room_by_name => sub {
my $self = shift;
my $name = shift;
if (!$self->valid_room_name($name)){
return 0;
}
my $sth = eval {
$self->db->prepare('SELECT *
FROM `rooms`
WHERE `name`=?');
};
$sth->execute($name);
return $sth->fetchall_hashref('name')->{$name}
};
# Same as get_room_by_name, but take a room ID as argument
helper get_room_by_id => sub {
my $self = shift;
my $id = shift;
if (!$self->valid_id($id)){
return 0;
}
my $sth = eval {
$self->db->prepare('SELECT *
FROM `rooms`
WHERE `id`=?');
};
$sth->execute($id);
return $sth->fetchall_hashref('id')->{$id};
};
# Update a room, take a room object as argument (hashref)
helper modify_room => sub {
my $self = shift;
my $room = shift;
if (!$self->valid_id($room->{id}) || !$self->valid_room_name($room->{name})){
return 0;
}
my $old_room = $self->get_room_by_id($room->{id});
if (!$old_room){
return 0;
}
if (!$room->{max_members} ||
($room->{max_members} > $config->{'rooms.max_members'} && $config->{'rooms.max_members'} > 0)){
$room->{max_members} = 0;
}
if (($room->{locked} && $room->{locked} !~ m/^0|1$/) ||
($room->{ask_for_name} && $room->{ask_for_name} !~ m/^0|1$/) ||
($room->{persistent} && $room->{persistent} !~ m/^0|1$/) ||
$room->{max_members} !~ m/^\d+$/){
return 0;
}
# Merge old and new params
$room = { %$old_room, %$room };
my $sth = eval {
$self->db->prepare('UPDATE `rooms`
SET `locked`=?,
`ask_for_name`=?,
`join_password`=?,
`owner_password`=?,
`persistent`=?,
`max_members`=?
WHERE `id`=?');
};
$sth->execute(
$room->{locked},
$room->{ask_for_name},
$room->{join_password},
$room->{owner_password},
$room->{persistent},
$room->{max_members},
$room->{id}
);
my $msg = "Room " . $room->{name} ." modified";
my $mods = '';
# Now, log which fields have been modified
foreach my $field (keys %$room){
if (($old_room->{$field} // '' ) ne ($room->{$field} // '')){
# Just hide passwords
if ($field =~ m/_password$/){
$old_room->{$field} = ($old_room->{$field}) ? '<hidden>' : '<unset>';
$room->{$field} = ($room->{$field}) ? '<hidden>' : '<unset>';
}
$mods .= $field . ": " . $old_room->{$field} . ' -> ' . $room->{$field} . "\n";
}
}
if ($mods ne ''){
chomp($mods);
$msg .= "\nModified fields:\n$mods";
$self->log_event({
event => 'room_modify',
msg => $msg
});
}
return 1;
};
# Set the role of a peer
helper set_peer_role => sub {
my $self = shift;
my $data = shift;
# Check the peer exists and is already in the room
if (!$data->{peer_id}){
return 0;
}
my $peer = $self->get_peer($data->{peer_id});
if (!$peer){
return 0;
}
$peer->{role} = $data->{role};
$self->log_event({
event => 'peer_role',
msg => "Peer " . $data->{peer_id} . " has now the " .
$data->{role} . " role in room " . $peer->{room}
});
return $self->add_peer($data->{peer_id}, $peer);
};
# Return the role of a peer, take a peer object as arg ($data = { peer_id => XYZ })
helper get_peer_role => sub {
my $self = shift;
my $peer_id = shift;
return $self->get_peer($peer_id)->{role};
};
# Promote a peer to owner
helper promote_peer => sub {
my $self = shift;
my $peer_id = shift;
return $self->set_peer_role({
peer_id => $peer_id,
role => 'owner'
});
};
# Purge api keys
helper purge_api_keys => sub {
my $self = shift;
$self->app->log->debug('Removing expired API keys');
my $sth = eval {
$self->db->prepare('DELETE FROM `api_keys`
WHERE `not_after` < CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\')');
};
$sth->execute;
return 1;
};
# Purge unused rooms
helper purge_rooms => sub {
my $self = shift;
$self->app->log->debug('Removing unused rooms');
my $sth = eval {
$self->db->prepare('SELECT `name`,`etherpad_group`
FROM `rooms`
WHERE `last_activity` < DATE_SUB(CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'),
INTERVAL ' . $config->{'rooms.inactivity_timeout'} . ' MINUTE)
AND `persistent`=\'0\' AND `owner_password` IS NULL');
};
$sth->execute;
my $toDelete = {};
while (my ($room,$ether_group) = $sth->fetchrow_array){
$toDelete->{$room} = $ether_group;
}
if ($config->{'rooms.reserved_inactivity_timeout'} > 0){
$sth = eval {
$self->db->prepare('SELECT `name`,`etherpad_group`
FROM `rooms`
WHERE `last_activity` < DATE_SUB(CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'),
INTERVAL ' . $config->{'rooms.reserved_inactivity_timeout'} . ' MINUTE)
AND `persistent`=\'0\' AND `owner_password` IS NOT NULL')
};
$sth->execute;
while (my ($room, $ether_group) = $sth->fetchrow_array){
$toDelete->{$room} = $ether_group;
}
}
foreach my $room (keys %{$toDelete}){
$self->log_event({
event => 'room_expire',
msg => "Deleting room $room after inactivity timeout"
});
# Remove Etherpad group
if ($optf->{etherpad}){
$optf->{etherpad}->delete_pad($toDelete->{$room} . '$' . $room);
$optf->{etherpad}->delete_group($toDelete->{$room});
}
}
# Now remove rooms
if (keys %{$toDelete} > 0){
$sth = eval {
$self->db->prepare("DELETE FROM `rooms`
WHERE `name` IN (" . join( ",", map { "?" } keys %{$toDelete} ) . ")");
};
$sth->execute(keys %{$toDelete});
}
return 1;
};
# delete just a specific room, by name
helper delete_room => sub {
my $self = shift;
my $room = shift;
$self->app->log->debug("Removing room $room");
my $data = $self->get_room_by_name($room);
if (!$data){
$self->app->log->debug("Error: room $room doesn't exist");
return 0;
}
if ($optf->{etherpad} && $data->{etherpad_group}){
$optf->{etherpad}->delete_pad($data->{etherpad_group} . '$' . $room);
$optf->{etherpad}->delete_group($data->{etherpad_group});
}
my $sth = eval {
$self->db->prepare('DELETE FROM `rooms`
WHERE `name`=?');
};
$sth->execute($room);
$self->log_event({
event => 'room_delete',
msg => "Deleting room $room"
});
return 1;
};
# Retrieve the list of rooms
helper get_room_list => sub {
my $self = shift;
my $sth = eval {
$self->db->prepare('SELECT *
FROM `rooms`');
};
$sth->execute;
return $sth->fetchall_hashref('name');
};
# Just update the activity timestamp
# so we can detect unused rooms
helper update_room_last_activity => sub {
my $self = shift;
my $name = shift;
my $data = $self->get_room_by_name($name);
if (!$data){
return 0;
}
my $sth = eval {
$self->db->prepare('UPDATE `rooms`
SET `last_activity`=CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\')
WHERE `id`=?');
};
$sth->execute($data->{id});
return 1;
};
# Return an array of supported languages
helper get_supported_lang => sub {
my $self = shift;
return map { basename(s/\.po$//r) } glob('lib/Vroom/I18N/*.po');
};
# Generate a random token
helper get_random => sub {
my $self = shift;
my $entropy = shift;
return Session::Token->new(entropy => $entropy)->get;
};
# Generate a random name
helper get_random_name => sub {
my $self = shift;
my $name = lc $self->get_random(64);
# Get another one if already taken
while ($self->get_room_by_name($name)){
$name = $self->get_random_name();
}
return $name;
};
# Add an email address to the list of notifications
helper add_notification => sub {
my $self = shift;
my $room = shift;
my $email = shift;
my $data = $self->get_room_by_name($room);
if (!$data || !$self->valid_email($email)){
return 0;
}
my $sth = eval {
$self->db->prepare('INSERT INTO `email_notifications`
(`room_id`,`email`)
VALUES (?,?)');
};
$sth->execute(
$data->{id},
$email
);
return 1;
};
# Update the list of notified email for a room in one go
# Take the room and an array ref of emails
helper update_email_notifications => sub {
my $self = shift;
my $room = shift;
my $emails = shift;
my $data = $self->get_room_by_name($room);
if (!$data){
return 0;
}
my $old = $self->get_email_notifications($room);
my @old = sort map { $old->{$_}->{email} } keys $old;
my @new = sort @$emails;
# Remove empty email
@new = grep { $_ ne '' } @new;
my $diff = Array::Diff->diff(\@old, \@new);
# Are we changing the list of email ?
if ($diff->count > 0){
my $msg = "Notification list for room $room has changed\n";
if (scalar @{$diff->deleted} > 0){
$msg .= "Emails being removed: " . join (', ', @{$diff->deleted}) . "\n";
}
if (scalar @{$diff->added} > 0){
$msg .= "Emails being added: " . join (', ', @{$diff->added}) . "\n";
}
$self->log_event({
event => 'email_notification_change',
msg => $msg
});
}
# First, drop all existing notifications
my $sth = eval {
$self->db->prepare('DELETE FROM `email_notifications`
WHERE `room_id`=?');
};
$sth->execute(
$data->{id},
);
# Now, insert new emails
foreach my $email (@new){
$self->add_notification($room,$email) || return 0;
}
return 1;
};
# Return the list of email addresses
helper get_email_notifications => sub {
my $self = shift;
my $room = shift;
$room = $self->get_room_by_name($room);
return 0 if (!$room);
my $sth = eval {
$self->db->prepare('SELECT `id`,`email`
FROM `email_notifications`
WHERE `room_id`=?');
};
$sth->execute($room->{id});
return $sth->fetchall_hashref('id');
};
# Randomly choose a music on hold
helper choose_moh => sub {
my $self = shift;
my @files = (<public/snd/moh/*.*>);
return basename($files[rand @files]);
};
# Add a invitation
helper add_invitation => sub {
my $self = shift;
my $room = shift;
my $email = shift;
my $data = $self->get_room_by_name($room);
return 0 if (!$data);
my $token = $self->get_random(256);
my $sth = eval {
$self->db->prepare('INSERT INTO `email_invitations`
(`room_id`,`from`,`token`,`email`,`date`)
VALUES (?,?,?,?,CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'))');
};
$sth->execute(
$data->{id},
$self->session('id'),
$token,
$email
);
$self->log_event({
event => 'send_invitation',
msg => "Invitation to join room $room sent to $email"
});
return $token;
};
# return a hash with all the invitation param
# just like get_room
helper get_invitation_by_token => sub {
my $self = shift;
my $token = shift;
my $sth = eval {
$self->db->prepare('SELECT *
FROM `email_invitations`
WHERE `token`=?
AND `processed`=\'0\'');
};
$sth->execute($token);
return $sth->fetchall_hashref('token')->{$token};
};
# Find invitations which have a unprocessed repsponse
helper get_invitation_list => sub {
my $self = shift;
my $session = shift;
my $sth = eval {
$self->db->prepare('SELECT *
FROM `email_invitations`
WHERE `from`=?
AND `response` IS NOT NULL
AND `processed`=\'0\'');
};
$sth->execute($session);
return $sth->fetchall_hashref('id');
};
# Got a response from invitation. Store the message in the DB
# so the organizer can get it
helper respond_to_invitation => sub {
my $self = shift;
my $token = shift;
my $response = shift;
my $message = shift;
my $sth = eval {
$self->db->prepare('UPDATE `email_invitations`
SET `response`=?,
`message`=?
WHERE `token`=?');
};
$sth->execute(
$response,
$message,
$token
);
$self->log_event({
event => 'invitation_response',
msg => "Invitation ID $token received a reply"
});
return 1;
};
# Mark a invitation response as processed
helper mark_invitation_processed => sub {
my $self = shift;
my $token = shift;
my $sth = eval {
$self->db->prepare('UPDATE `email_invitations`
SET `processed`=\'1\'
WHERE `token`=?');
};
$sth->execute($token);
$self->log_event({
event => 'invalidate_invitation',
msg => "Marking invitation $token as processed, it won't be usable anymore"
});
return 1;
};
# Purge expired invitation links
# Invitations older than 2 hours really doesn't make a lot of sens
helper purge_invitations => sub {
my $self = shift;
$self->app->log->debug('Removing expired invitations');
my $sth = eval {
$self->db->prepare('DELETE FROM `email_invitations`
WHERE `date` < DATE_SUB(CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\'), INTERVAL 2 HOUR)');
};
$sth->execute;
return 1;
};
# Check an invitation token is valid
helper check_invite_token => sub {
my $self = shift;
my $room = shift;
my $token = shift;
# Expire invitations before checking if it's valid
$self->purge_invitations;
my $ret = 0;
my $data = $self->get_room_by_name($room);
return 0 if (!$data || !$token);
$self->app->log->debug("Checking if invitation with token $token is valid for room $room");
my $sth = eval {
$self->db->prepare('SELECT COUNT(`id`)
FROM `email_invitations`
WHERE `room_id`=?
AND `token`=?
AND (`response` IS NULL
OR `response`=\'later\')');
};
$sth->execute(
$data->{id},
$token
);
my $num;
$sth->bind_columns(\$num);
$sth->fetch;
if ($num != 1){
$self->app->log->debug("Invitation is invalid");
return 0;
}
$self->app->log->debug("Invitation is valid");
return 1;
};
# Create a pad (and the group if needed)
helper create_pad => sub {
my $self = shift;
my $room = shift;
my $data = $self->get_room_by_name($room);
return 0 if (!$optf->{etherpad} || !$data);
# Create the etherpad group if not already done
# and register it in the DB
if (!$data->{etherpad_group} || $data->{etherpad_group} eq ''){
$data->{etherpad_group} = $optf->{etherpad}->create_group();
if (!$data->{etherpad_group}){
return 0;
}
my $sth = eval {
$self->db->prepare('UPDATE `rooms`
SET `etherpad_group`=?
WHERE `id`=?');
};
$sth->execute(
$data->{etherpad_group},
$data->{id}
);
}
$optf->{etherpad}->create_group_pad($data->{etherpad_group}, $room);
$self->log_event({
event => 'pad_create',
msg => "Creating group pad " . $data->{etherpad_group} . " for room $room"
});
return 1;
};
# Create an etherpad session for a user
helper create_etherpad_session => sub {
my $self = shift;
my $room = shift;
my $data = $self->get_room_by_name($room);
if (!$optf->{etherpad} || !$data || !$data->{etherpad_group}){
return 0;
}
my $id = $optf->{etherpad}->create_author_if_not_exists_for($self->get_name);
$self->session($room)->{etherpadAuthorId} = $id;
my $etherpadSession = $optf->{etherpad}->create_session(
$data->{etherpad_group},
$id,
time + 86400
);
$self->session($room)->{etherpadSessionId} = $etherpadSession;
my $etherpadCookieParam = {};
if ($config->{'etherpad.base_domain'} && $config->{'etherpad.base_domain'} ne ''){
$etherpadCookieParam->{domain} = $config->{'etherpad.base_domain'};
}
$self->cookie(sessionID => $etherpadSession, $etherpadCookieParam);
return 1;
};
# Get an API key by token
# just used to check if the key exists
helper get_key_by_token => sub {
my $self = shift;
my $token = shift;
if (!$token || $token eq ''){
return 0;
}
my $sth = eval {
$self->db->prepare('SELECT *
FROM `api_keys`
WHERE `token`=?
AND `not_after` > CONVERT_TZ(NOW(), @@session.time_zone, \'+00:00\')