/
Chat.pm
377 lines (332 loc) · 8.84 KB
/
Chat.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
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
package Chat;
use base 'Squatting';
use AnyEvent;
use Coro;
use Coro::AnyEvent;
use Coro::Signal;
sub service {
my ($app, $c, @args) = @_;
my $v = $c->v;
$v->{listen} = 'null';
$app->next::method($c, @args);
}
#_____________________________________________________________________________
package Chat::Controllers;
use strict;
use warnings;
use Squatting ':controllers';
use Squatting::H;
use JSON::XS;
use Coro;
use Time::HiRes 'time';
use Data::Dump 'pp';
use HTML::Entities;
#### data
# key : channel name
# value : channel object
our %channels;
# generic channel object that you can clone
our $channel = Squatting::H->new({
i => 0,
size => 8,
messages => [],
signal => Coro::Signal->new,
write => sub {
my ($self, @messages) = @_;
my $i = $self->{i};
# warn $i;
my $size = $self->{size};
my $m = $self->{messages};
for (@messages) {
$_->{time} = time;
warn ">> " . $_->{time};
$m->[$i++] = $_;
$i = 0 if ($i >= $size);
}
# warn $i;
$self->{i} = $i;
$self->signal->broadcast;
@messages;
},
read => sub {
my ($self, $y) = @_;
my $size = $self->{size};
my $m = $self->{messages};
my $x;
$y ||= 1;
$y = $size if ($y > $size);
my $i;
$i = $self->{i} - 1;
$i = ($size - 1) if ($i < 0);
my @messages;
for ($x = 0; $x < $y; $x++) {
# warn $i;
unshift @messages, $m->[$i];
$i--;
$i = ($size - 1) if ($i < 0);
}
@messages;
},
read_since => sub {
my ($self, $last) = @_;
grep { defined && ($_->{time} > $last) } $self->read($self->size);
},
});
#### helpers
sub channels_from_input {
my ($channels) = @_;
my @ch;
if ($channels) {
if (ref($channels)) {
@ch = @{ $channels };
} else {
@ch = $channels;
}
}
@ch = keys our %channels unless @ch;
@ch;
}
sub channel {
my ($name) = @_;
$channels{$name} ||= $channel->clone({ name => $name });
}
#### controllers
our @C = (
C(
Home => [ '/' ],
get => sub {
my ($self) = @_;
my $v = $self->v;
$v->{channels} = [ sort keys %channels ];
$self->render('home');
},
post => sub {
my ($self) = @_;
my $input = $self->input;
my $name = $input->{name};
if ($name =~ /^(\w+)$/) {
my $ch = channel($name);
$self->redirect(R('Channel', $name));
} else {
$self->redirect(R('Home'));
}
},
),
C(
Channel => [ '/(\w+)' ],
get => sub {
my ($self, $name) = @_;
my $v = $self->v;
my $ch = channel($name);
$v->{my_name} = $self->state->{name} || "anonymous";
$v->{channel} = $ch;
$v->{listen} = "[ '$name' ]";
$v->{messages} = [ $v->{channel}->read($v->{channel}->size) ];
my $last_ch = $self->state->{last_ch};
if ($last_ch) {
$last_ch->write({ type => 'leave' });
}
$ch->write({ type => 'enter' });
$self->state->{last_ch} = $ch;
$self->render('channel');
},
post => sub {
my ($self, $name) = @_;
my $v = $self->v;
my $input = $self->input;
my $ch = channel($name);
my $handle = encode_entities($input->{name});
my $message = encode_entities($input->{message});
$ch->write({ type => 'message', name => $handle, message => $message });
if ($input->{name}) {
$self->state->{name} = $input->{name};
}
if ($self->env->{'HTTP_X_REQUESTED_WITH'}) {
# for ajax requests
1;
} else {
# for people w/o javascript
$self->redirect(R('Channel', $name));
}
}
),
C(
Event => [ '/@event/(\d+)' ],
get => sub {
warn "coro [$Coro::current]";
my ($self) = shift;
my $input = $self->input;
my $cr = $self->cr;
my @ch = channels_from_input($input->{channels});
my $last = 0;
while (1) {
# Output
warn "top of loop";
my @events =
grep { defined }
map { my $ch = $channels{$_}; $ch->read_since($last) } @ch;
my $x = async {
warn "printing...".encode_json(\@events);
$cr->print(encode_json(\@events));
};
$x->join;
$last = time;
# Hold for a brief moment until the next long poll request comes in.
warn "waiting for next request";
$cr->next;
my $channels = [ $cr->param('channels') ];
@ch = channels_from_input($channels);
# Start 1 coro for each channel we're listening to.
# Each coro will have the same Coro::Signal object, $activity.
my $activity = Coro::Signal->new;
my @coros = map {
my $ch = $channels{$_};
async { $ch->signal->wait; $activity->broadcast };
} @ch;
# The first coro that runs $activity->broadcast wins.
warn "waiting for activity on any of (@ch); last is $last";
$activity->wait;
# Cancel the remaining coros.
for (@coros) { $_->cancel }
}
},
continuity => 1,
),
);
#_____________________________________________________________________________
package Chat::Views;
use strict;
use warnings;
use Squatting ':views';
use HTML::AsSubs;
use Data::Dump 'pp';
sub span { HTML::AsSubs::_elem('span', @_) }
sub thead { HTML::AsSubs::_elem('thead', @_) }
sub tbody { HTML::AsSubs::_elem('tbody', @_) }
sub x { map { HTML::Element->new('~literal', text => $_) } @_ }
our @V = (
V(
'default',
layout => sub {
my ($self, $v, $content) = @_;
html(
head(
title( $v->{title} ),
style(x( $self->_css )),
script({ src => 'jquery.js' }),
script({ src => 'jquery.ev.js' }),
script({ src => 'chat.js' }),
script(x(qq|
\$chat = {
listen: $v->{listen}
};
|)),
),
body(
div({ id => 'factory', style => 'display: none' },
table(
tbody(
&tr({ class => 'message' }, td({ class => 'name' }), td()),
),
),
),
do {
if ($v->{channel}) {
my $ch = $v->{channel};
h1({ id => 'title' }, a({ href => R('Home') }, "Chat"), span(' : '), span('#'.$ch->name));
} else {
h1({ id => 'title' }, a({ href => R('Home') }, "Chat"));
}
},
x( $content )
)
)->as_HTML;
},
_css => sub {qq|
body {
background: #112;
color: #eee;
font-family: "Trebuchet MS", Verdana, sans-serif;
}
#messages {
font-size: 9pt;
}
#title {
font-size: 36pt;
border-bottom: 2px solid #223;
}
a {
color: #ccf;
text-decoration: none;
}
a:hover {
color: #fff;
}
tr.message td.name {
width: 100px;
color: #fe4;
text-align: right;
}
input.name {
width: 100px;
text-align: right;
}
input.name,
input.message {
background: #dde;
color: #112;
border: 1px solid #223;
}
|},
home => sub {
my ($self, $v) = @_;
div({id => 'main'},
h1("Channels"),
form({ method => 'POST' },
ul(
(map { li(a({href=>R('Channel', $_)}, $_)) } @{$v->{channels}}),
li(input({ type => 'text', name => 'name', value => 'channel' }), input({ type => 'submit', value => 'Create Channel' })),
),
),
h1("For Hackers"),
h2('starting the event loop from javascript'),
pre(
'$.ev.loop("/@event", [ 2, 4 ])'."\n",
),
h2('stopping the event loop from javascript'),
pre(
'$.ev.stop()'."\n",
),
#h2('for testing purposes, you can post a dummy event like this.'),
#pre(
# "curl http://localhost:4234/\@event --data-ascii channels=2\n",
#)
)->as_HTML;
},
channel => sub {
my ($self, $v) = @_;
my $ch = $v->{channel};
div(
form({ id => 'chat', name => 'chat', method => 'post' },
table(
tbody({ id => 'messages' },
map {
if (defined $_ && $_->{type} eq 'message') {
&tr({ class => 'message' }, td({ class => 'name' }, x($_->{name})), td(x($_->{message})))
} else {
&tr({ class => 'message' }, td({ class => 'name' }, ""), td(""))
}
} @{ $v->{messages} }
),
),
div(
input({ class => 'name', type => 'text', size => '10', name => 'name', value => $v->{my_name} }),
input({ class => 'message', type => 'text', size => '40', name => 'message' }),
input({ type => 'submit', value => 'Say' }),
),
)
)->as_HTML;
},
)
);
1;