-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSession.pm
80 lines (69 loc) · 1.53 KB
/
Session.pm
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
package Session;
use JSON;
use strict;
my $json = JSON->new->utf8;
sub new {
my ($class) = @_;
my $obj = {
clients => {},
ice => {},
status => 'open',
};
return bless $obj, $class;
}
sub add_ice {
my ($self, $c, $ice) = @_;
if (!defined $self->{ice}->{$c}) {
$self->{ice}->{$c} = [];
}
push @{$self->{ice}->{$c}}, $ice;
$self->send_to_peer($c, 'ice', $ice);
}
sub get_ice {
my ($self, $c) = @_;
for my $k (keys %{$self->{clients}}) {
my $oc = $self->{clients}->{$k};
if ($c != $oc) {
for my $ice (@{$self->{ice}->{$oc}}) {
$self->send_to($c, 'ice', $ice);
}
}
}
}
sub add_peer {
my ($self, $c) = @_;
if (keys %{$self->{clients}} == 2) {
warn "Attempted to add a third client to session";
return;
}
$self->{clients}->{$c} = $c;
}
sub remove_peer {
my ($self, $c) = @_;
delete $self->{clients}->{$c};
if (keys %{$self->{clients}} == 0) {
return 1;
}
return 0;
}
sub set_status {
my ($self, $status) = @_;
$self->{status} = $status;
}
sub send_to_peer {
my ($self, $c, $type, $payload) = @_;
if (keys %{$self->{clients}} < 2) {
return;
}
for my $k (keys %{$self->{clients}}) {
my $oc = $self->{clients}->{$k};
if ($c != $oc) {
$oc->send($json->encode([$type, $payload]));
}
}
}
sub send_to {
my ($self, $c, $type, $payload) = @_;
$c->send($json->encode([$type, $payload]));
}
1;