This repository was archived by the owner on May 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathlogbot-web
More file actions
executable file
·341 lines (287 loc) · 8.86 KB
/
logbot-web
File metadata and controls
executable file
·341 lines (287 loc) · 8.86 KB
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
#!/usr/bin/perl
# mojolicious web handler
# must set env var LOGBOT_CONFIG to config filename
#
# in production runs as a daemon behind a reverse proxy, which handles requests
# for static assets (web/public/static)
#
# use `dev-make` to build static assets
use local::lib;
use v5.10;
use strict;
use warnings;
use FindBin qw( $RealBin );
use lib "$RealBin/lib";
BEGIN { $ENV{TZ} = 'UTC' }
use DateTime ();
use IO::Compress::Gzip qw( gzip );
use LogBot::Config qw( find_config load_all_configs load_config reload_config );
use LogBot::MemCache ();
use LogBot::Util qw( file_for file_time time_to_ymd );
use LogBot::Web::Util qw( channel_from_param channel_topics linkify render_init rewrite_old_urls );
use Mojo::ByteStream ();
use Mojo::Log ();
use Mojo::Util qw( dumper );
use Mojolicious::Lite qw( app );
# load networks
my $networks = [];
{
if (my $config = $ENV{LOGBOT_CONFIG}) {
# load specific networks (mostly for dev)
foreach my $network (split(/,/, $config)) {
push @{$networks}, load_config(find_config($network), web => 1);
}
} else {
# load all networks
foreach my $network (values %{ load_all_configs(web => 1) }) {
push @{$networks}, $network;
}
}
$networks = [sort { $a->{name} cmp $b->{name} } @{$networks}];
}
# configure mojo
my $is_production = app->mode() eq 'production';
app->secrets('!logbot!');
app->renderer->paths([$RealBin . '/web/templates']);
app->static->paths([$RealBin . '/web/public']);
app->config(
hypnotoad => {
listen => ['http://127.0.0.1:' . ($ENV{LOGBOT_PORT} // 3001)],
pid_file => ($ENV{LOGBOT_PID_FILE} // ($RealBin . '/logbot-web.pid')),
},
);
app->log(Mojo::Log->new(path => $is_production ? '/var/log/logbot/mojo.log' : 'log/mojo.log'));
plugin AccessLog => {
log => ($is_production ? '/var/log/logbot/access.log' : 'log/access.log'),
format => '%h %{X-Network}o - %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"',
};
plugin 'Status' => {
route => app->routes->under(
'_status' => sub {
my ($c) = @_;
my $password = $ENV{'LOGBOT_STATUS_PASSWORD'} // 'status';
return 1 if $password eq '';
return 1 if ($c->req->url->to_abs->userinfo // '') eq 'logbot:' . $password;
$c->res->headers->www_authenticate('Basic');
$c->render(text => 'Authentication required', status => 401);
return undef;
}
)
};
my $memcache = LogBot::MemCache->new(binary => $is_production);
render_init($RealBin);
# per-request initialisation
under sub {
my ($c) = @_;
# determine current config
my $config_index = 0;
if (scalar(@{$networks}) > 1) {
my $host = lc($c->req->url->to_abs->host);
my $dot_posn = index($host, '.');
if ($dot_posn != -1) {
$host = substr($host, 0, $dot_posn);
for (my $i = 0; $i < scalar(@{$networks}); $i++) {
next unless $networks->[$i]->{name} eq $host;
$config_index = $i;
last;
}
}
}
# reload config
$networks->[$config_index] = reload_config($networks->[$config_index]);
my $config = $networks->[$config_index];
# store network name in response header for logging
$c->res->headers->add('X-Network' => $config->{name});
# for client-side list cache
my $topics_lastmod = file_time(file_for($config, 'topics_lastmod')) // 0;
$c->stash(
config => $config,
networks => $networks,
network => $config->{name},
channels => $config->{_derived}->{visible_channels},
topics => channel_topics($config),
channel => '',
date => '',
error => '',
event_count => 0,
bot_event_count => 0,
page => '',
today => DateTime->now()->truncate(to => 'day'),
is_today => 0,
cache_prefix => $config->{_derived}->{time} . '.' . $config->{name} . '.',
channel_list_id => $config->{_derived}->{time} . '.' . $topics_lastmod,
topics_lastmod => $topics_lastmod,
);
return 1;
};
#
# default => about logbot || search
get '/' => sub {
my ($c) = @_;
# redirect old urls
if (my $url = rewrite_old_urls($c)) {
# url was formed server-side, no need to bounce through js redirect
if ($url !~ /#/) {
return $c->redirect_to($url);
}
$c->stash(redirect_to => $url);
return $c->render('redirect');
}
# search
my $q = $c->req->query_params->param('q');
if (defined($q)) {
LogBot::Web::Search::render($c, $q);
} else {
# index
LogBot::Web::Index::render($c);
}
};
# config
get '/_config' => sub {
my ($c) = @_;
LogBot::Web::Config::render($c);
};
# channel list
get '/_channels' => sub {
my ($c) = @_;
LogBot::Web::List::render($c);
};
get '/_channels_body' => sub {
my ($c) = @_;
LogBot::Web::List::render($c, { body_only => 1 });
};
# network stats
get '/_stats' => sub {
my ($c) = @_;
LogBot::Web::Stats::render($c);
};
get '/_stats/meta' => sub {
my ($c) = @_;
LogBot::Web::Stats::render_meta($c);
};
get '/_stats/hours' => sub {
my ($c) = @_;
LogBot::Web::Stats::render_hours($c);
};
# debugging
if (!$is_production) {
get '/_stash' => sub {
my ($c) = @_;
$c->stash(today => $c->stash('today')->ymd());
$c->render(text => dumper($c->stash), format => 'txt');
};
}
# robots.txt
my $robots_txt = <<'EOF';
# http://law.di.unimi.it/BUbiNG.html
# 20% of my traffic was from this bot
User-agent: BUbiNG
Disallow: /
# Marketing/SEO bot
User-agent: SemrushBot
Disallow: /
User-agent: SemrushBot-SA
Disallow: /
EOF
get '/robots.txt' => sub {
my ($c) = @_;
$c->render(text => $robots_txt, format => 'txt');
};
# /channel => redirect to current date
get '/#channel' => sub {
my ($c) = @_;
my $channel = channel_from_param($c) // return;
# redirect to current date
my $path = $c->req->url->path;
$path .= '/' unless substr($path, -1) eq '/';
$c->redirect_to($path . time_to_ymd(time()));
};
# /channel/date => show logs
get '/#channel/:date' => [date => qr/\d{8}/] => sub {
my ($c) = @_;
LogBot::Web::Channel::render_logs($c);
};
get '/#channel/:date/raw' => [date => qr/\d{8}/] => sub {
my ($c) = @_;
LogBot::Web::Channel::render_raw($c);
};
get '/#channel/link/:time/:nick' => [time => qr /\d+/] => sub {
my ($c) = @_;
LogBot::Web::Channel::redirect_to($c);
};
get '/#channel/stats' => sub {
my ($c) = @_;
LogBot::Web::Stats::render($c, require_channel => 1);
};
get '/#channel/stats/meta' => sub {
my ($c) = @_;
LogBot::Web::Stats::render_meta($c, require_channel => 1);
};
get '/#channel/stats/hours' => sub {
my ($c) = @_;
LogBot::Web::Stats::render_hours($c);
};
get '/#channel/stats/nicks' => sub {
my ($c) = @_;
LogBot::Web::Stats::render_nicks($c);
};
# 404 handler
any '*' => sub {
my ($c) = @_;
$c->res->code(404);
$c->res->message('Not Found');
LogBot::Web::Index::render($c, { error => 'Not Found.' });
};
my %cache;
# static file with timestamp
helper static => sub {
my ($c, $file) = @_;
return $cache{static}->{$file} //= '/static/' . $file . '?' . file_time($RealBin . '/web/public/static/' . $file);
};
# inline svg
helper svg => sub {
my ($c, $file) = @_;
return $cache{svg}->{$file} //= Mojo::ByteStream->new(slurp($RealBin . '/web/svg/' . $file . '.svg'));
};
# linkify text
helper linkify => sub {
my ($c, $text) = @_;
return linkify($text);
};
# cache
helper cached => sub {
my ($c, $key, $callback) = @_;
return $key eq ''
? $callback->()
: Mojo::ByteStream->new($memcache->cached($c->stash('cache_prefix') . $key, $callback));
};
hook after_render => sub {
my ($c, $output, $format) = @_;
my $headers = $c->res->headers;
# CSP
state $csp = join(
'; ',
q{default-src 'self'},
q{object-src 'none'},
q{frame-ancestors 'none'},
q{base-uri 'none'},
q{style-src 'self' 'unsafe-inline'}, # unsafe-inline for chosen, top-nick graph
q{img-src 'self' data:}, # data: for pikaday
);
$headers->header('Content-Security-Policy' => $csp);
# preload fonts
state $link = join(', ',
map { '<' . $c->url_for($_)->to_abs . '>; rel=preload; as=font' }
qw( /static/hind-regular.ttf /static/hind-medium.ttf /static/hind-bold.ttf ));
$headers->header(Link => $link);
# no need to expose this info
$headers->remove('Server');
# gzip compression
if (($c->req->headers->accept_encoding // '') =~ /gzip/i) {
$headers->append(Vary => 'Accept-Encoding');
$headers->content_encoding('gzip');
gzip($output, \my $compressed);
${$output} = $compressed;
}
};
app->start;