Login
improve colors and fix linking
[Web-Paste-Viewer.git] / lib / Web / Paste / Viewer.pm
CommitLineData
d623334f
GK
1package Web::Paste::Viewer;
2use strict;
3use warnings;
4
5use parent qw(Plack::Component);
6
7use HTML::Entities;
8use Plack::Request;
9use Plack::Util;
10use namespace::clean;
11
12use Plack::Util::Accessor qw(dir);
13
14sub call {
15 my $self = shift;
16 my $env = shift;
5c8ffe07 17 $env = { %$env };
d623334f
GK
18 my $req = Plack::Request->new($env);
19 my $dir = $self->dir;
20 my $file = $req->path_info;
21 $file =~ s{^/}{};
22 ($file, my $path) = split m{[/\\]}, $file;
23 my $full_file = File::Spec->catfile($dir, $file);
24 open my $fh, '<', $full_file
25 or return $self->_not_found;
26 -f $fh or return $self->_not_found;
27 if ($path && $path eq 'raw') {
28 Plack::Util::set_io_path($fh, $full_file);
29 return [200, ['Content-Type' => 'text/plain'], $fh];
30 }
31
32 return sub {
33 my $responder = shift;
34 my $writer = $responder->([ 200, [ 'Content-Type', 'text/html' ] ]);
35
36 $self->send_content(
37 send => sub { $writer->write(@_) },
38 req => $req,
39 file => $file,
40 handle => $fh,
41 );
42 $writer->close;
43 };
44}
45
46sub _not_found {
47 [404, ['Content-Type' => 'text/plain'], ['not found']];
48}
49
50sub send_content {
51 my $self = shift;
52 my %opts = @_;
53 my $send = $opts{send};
54 my $fh = $opts{handle};
55 my $file = $opts{file};
56 my $req = $opts{req};
57 my $raw_link = $req->base;
5c8ffe07 58 $raw_link->path($raw_link->path . "/$file/raw");
d623334f
GK
59 $send->(sprintf <<'END_HEADER', $file, $raw_link);
60<!DOCTYPE html>
61<html>
62<head>
63 <title>paste viewer: %s</title>
64 <style type="text/css">
65body {
66 font-family: sans-serif;
67}
68ol.file-content {
69 font-family: monospace;
70 list-style-type: none;
71 counter-reset: level1;
72 padding-left: 0px;
73}
74ol.file-content li {
75 white-space: pre;
76}
77ol.file-content li:before {
78 content: counter(level1) " ";
79 counter-increment: level1;
80 display: inline-block;
81 text-align: right;
82 width: 5em;
83 border-right: 1px solid #222;
84 margin-right: 5px;
85}
86ol.file-content li:nth-child(odd):before {
87 background-color: #eeeeee;
88}
89ol.file-content li:nth-child(odd) {
90 background-color: #f4f4f4;
91}
92ol.file-content li:nth-child(even):before {
93 background-color: #e0e0ff;
94}
95ol.file-content li:nth-child(even) {
5c8ffe07 96 background-color: #eeeeff;
d623334f
GK
97}
98 </style>
99</head>
100<body>
101 <div>
102 <p><a href="%s">View Raw</a></p>
103 <ol class="file-content">
104END_HEADER
105 while (my $line = readline $fh) {
106 $line =~ s/[\r\n]+$//;
107 $send->('<li>' . $line . '</li>');
108 }
109 $send->(<<'END_FOOTER');
110 </ol>
111 </div>
112</body>
113</html>
114END_FOOTER
115}
116
1171;