Phoebe/Chat.pm untested

filter: Statementstmt 0.0% 0 / 133 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 37 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 243 CC 18 SCAR 35.0
CC
18
Cov
0%
chat_register
72.0
process_chat_say
42.0
chat_listen
12.0
CRAP 33.0
1 # -*- mode: perl -*-
2 # Copyright (C) 2017–2021 Alex Schroeder <alex@gnu.org>
3  
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License along
15 # with this program. If not, see <https://www.gnu.org/licenses/>.
16  
17 =encoding utf8
18  
19 =head1 NAME
20  
21 App::Phoebe::Chat - add a Gemini-based chat room for every Phoebe wiki space
22  
23 =head1 DESCRIPTION
24  
25 For every wiki space, this creates a Gemini-based chat room. Every chat client
26 needs two URLs, the "listen" and the "say" URL.
27  
28 The I<Listen URL> is where you need to I<stream>: as people say things in the
29 room, these messages get streamed in one endless Gemini document. You might have
30 to set an appropriate timeout period for your connection for this to work. 1h,
31 perhaps?
32  
33 The URL will look something like this:
34 C<gemini://localhost/do/chat/listen> or
35 C<gemini://localhost/space/do/chat/listen>
36  
37 The I<Say URL> is where you post things you want to say: point your client at
38 the URL, it prompts your for something to say, and once you do, it redirects you
39 to the same URL again, so you can keep saying things.
40  
41 The URL will look something like this: C<gemini://localhost/do/chat/say> or
42 C<gemini://localhost/space/do/chat/say>
43  
44 Your chat nickname is the client certificate's common name. One way to create a
45 client certificate that's valid for five years with an appropriate common name:
46  
47 openssl req -new -x509 -newkey ec \
48 -pkeyopt ec_paramgen_curve:prime256v1 \
49 -subj '/CN=Alex' \
50 -days 1825 -nodes -out cert.pem -keyout key.pem
51  
52 There is no configuration. Simply add it to your F<config> file:
53  
54 use App::Phoebe::Chat;
55  
56 As a user, first connect using a client that can stream:
57  
58 gemini --cert_file=cert.pem --key_file=key.pem \
59 gemini://localhost/do/chat/listen
60  
61 Then connect with a client that let's you post what you type:
62  
63 gemini-chat --cert_file=cert.pem --key_file=key.pem \
64 "gemini://localhost/do/chat/say"
65  
66 =cut
67  
68 package App::Phoebe::Chat;
69 use App::Phoebe qw(@extensions @request_handlers $log
70 success result port space host_regex space_regex);
71 use Modern::Perl '2018';
72 use Encode qw(decode_utf8 encode_utf8);
73 use URI::Escape;
74 use utf8;
75  
76 # Each chat member is {stream => $stream, host => $host, space => $space, name => $name}
77 my (@chat_members, @chat_lines);
78 my $chat_line_limit = 50;
79  
80 # needs a special handler because the stream never closes
81 my $spaces = space_regex();
82 unshift(@request_handlers, '^gemini://([^/?#]*)(?:/$spaces)?/do/chat/listen' => \&chat_listen);
83  
84 sub chat_listen {
85 my $stream = shift;
86 my $data = shift;
87 $log->debug("Handle chat listen request");
88 $log->debug("Discarding " . length($data->{buffer}) . " bytes")
89 if $data->{buffer};
90 my $url = $data->{request};
91 my $hosts = host_regex();
92 my $spaces = space_regex();
93 my $port = port($stream);
94 my ($host, $space);
95 if (($host, $space) =
96 $url =~ m!^(?:gemini:)?//($hosts)(?::$port)?(?:/($spaces))?/do/chat/listen$!) {
97 chat_register($stream, $host, $port, space($stream, $host, $space) || '');
98 # don't lose the stream!
99 } else {
100 result($stream, "59", "Don't know how to handle $url");
101 $stream->close_gracefully();
102 }
103 }
104  
105 sub chat_register {
106 my $stream = shift;
107 my $host = shift;
108 my $port = shift;
109 my $space = shift;
110 my $name = $stream->handle->peer_certificate('cn');
111 if (not $name) {
112 result($stream, "60", "You need a client certificate with a common name to listen to this chat");
113 $stream->close_gracefully();
114 return;
115 }
116 if (grep { $host eq $_->{host} and $space eq $_->{space} and $name eq $_->{name} } @chat_members) {
117 result($stream, "40", "'$name' is already taken");
118 $stream->close_gracefully();
119 return;
120 }
121 # 1h timeout
122 $stream->timeout(3600);
123 # remove from channel members if an error happens
124 $stream->on(close => sub { chat_leave($host, $space, $name) });
125 $stream->on(error => sub { chat_leave($host, $space, $name) });
126 # add myself
127 push(@chat_members, { host => $host, space => $space, name => $name, stream => $stream });
128 # announce myself
129 my @names;
130 for (@chat_members) {
131 next unless $host eq $_->{host} and $space eq $_->{space} and $name ne $_->{name};
132 push(@names, $_->{name});
133 $_->{stream}->write(encode_utf8 "$name joined\n");
134 }
135 # and get a welcome message
136 success($stream);
137 $stream->write(encode_utf8 "# Welcome to $host" . ($space ? "/$space" : "") . "\n");
138 if (@names) {
139 $stream->write(encode_utf8 "Other chat members: @names\n");
140 } else {
141 $stream->write("You are the only one.\n");
142 }
143 $stream->write("Open the following link in order to say something:\n");
144 $stream->write("=> gemini://$host:$port" . ($space ? "/$space" : "") . "/do/chat/say\n");
145 my @lines = grep { $host eq $_->{host} and $space eq $_->{space} } reverse @chat_lines;
146 if (@lines) {
147 $stream->write("Replaying some recent messages:\n");
148 $stream->write(encode_utf8 "$_->{name}: $_->{text}\n") for @lines;
149 $stream->write(encode_utf8 "Welcome! 🥳🚀🚀\n");
150 }
151 $log->debug("Added $name to the chat");
152 }
153  
154 sub chat_leave {
155 my ($host, $space, $name) = @_;
156 $log->debug("Disconnected $name");
157 # remove the chat member from their particular chat
158 @chat_members = grep { not ($host eq $_->{host} and $space eq $_->{space} and $name eq $_->{name}) } @chat_members;
159 for (@chat_members) { # for members of the same chat
160 next unless $host eq $_->{host} and $space eq $_->{space};
161 $_->{stream}->write(encode_utf8 "$name left\n");
162 }
163 }
164  
165 push(@extensions, \&handle_chat_say);
166  
167 sub handle_chat_say {
168 my $stream = shift;
169 my $url = shift;
170 my $hosts = host_regex();
171 my $spaces = space_regex();
172 my $port = port($stream);
173 my ($host, $space, $text);
174 if (($host, $space, $text) =
175 $url =~ m!^gemini://($hosts)(?::$port)?(?:/($spaces))?/do/chat/say(?:\?([^#]*))?$!) {
176 process_chat_say($stream, $host, $port, $space || "", $text);
177 return 1;
178 } elsif ($url =~ m!^gemini://(?:$hosts)(?::$port)?(?:/$spaces)?/do/chat$!) {
179 serve_chat_explanation($stream, $url);
180 return 1;
181 }
182 return 0;
183 }
184  
185 sub serve_chat_explanation {
186 my $stream = shift;
187 my $url = shift;
188 success($stream);
189 $stream->write("# Chat\n");
190 $stream->write(
191 encode_utf8
192 "This server supports a Gemini-based chat. "
193 . "If you don't have a dedicated client, you can use two windows of a regular Gemini client. "
194 . "Visit the following two URLs. "
195 . "The first one allows you “listen” to the channel and the second one allows you to “say” things. "
196 . "The connection to the “listen” channel needs a streaming client. "
197 . "Use a client certificate with the same common name for both connections.\n");
198 $stream->write("=> $url/listen\r\n");
199 $stream->write("=> $url/say\r\n");
200 }
201  
202 sub process_chat_say {
203 my $stream = shift;
204 my $host = shift;
205 my $port = shift;
206 my $space = shift;
207 my $text = shift;
208 my $name = $stream->handle->peer_certificate('cn');
209 if (not $name) {
210 result($stream, "60", "You need a client certificate with a common name to talk on this chat");
211 return;
212 }
213 my @found = grep { $host eq $_->{host} and $space eq $_->{space} and $name eq $_->{name} } @chat_members;
214 if (not @found) {
215 result($stream, "40", "You need to join the chat before you can say anything");
216 return;
217 }
218 if (not $text) {
219 result($stream, "10", encode_utf8 "Post to the channel as $name");
220 return;
221 }
222 $text = decode_utf8(uri_unescape($text));
223 unshift(@chat_lines, { host => $host, space => $space, name => $name, text => $text });
224 splice(@chat_lines, $chat_line_limit); # trim length of history
225 # send message
226 for (@chat_members) {
227 next unless $host eq $_->{host} and $space eq $_->{space};
228 $_->{stream}->write(encode_utf8 "$name: $text\n");
229 }
230 # and ask to send another one
231 result($stream, "31", "gemini://$host:$port" . ($space ? "/$space" : "") . "/do/chat/say");
232 return;
233 }
234  
235 # run every minute and print a timestamp every 5 minutes
236 Mojo::IOLoop->recurring(60 => sub {
237 my $loop = shift;
238 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
239 return unless $min % 5 == 0;
240 $log->debug("Chat ping");
241 my $ts = sprintf("%02d:%02d UTC\n", $hour, $min);
242 for (@chat_members) {
243 $_->{stream}->write($ts);
244 }});