Source

web-paste-simple / lib / Web / Paste / Simple.pm

Full commit
Toby Inkster 15218da 


Toby Inkster d12855e 


Toby Inkster 15218da 

Toby Inkster 7cb041d 

Toby Inkster 15218da 


Toby Inkster 7cb041d 

Toby Inkster 15218da 






Toby Inkster 7cb041d 
Toby Inkster d12855e 
Toby Inkster 15218da 



Toby Inkster 7cb041d 
Toby Inkster d12855e 
Toby Inkster 15218da 

Toby Inkster 7cb041d 
Toby Inkster 15218da 






Toby Inkster 7cb041d 
Toby Inkster d12855e 
Toby Inkster 7cb041d 
Toby Inkster 15218da 


Toby Inkster 7cb041d 
Toby Inkster d12855e 

Toby Inkster 15218da 


Toby Inkster 7cb041d 
Toby Inkster d12855e 


Toby Inkster 15218da 


Toby Inkster 7cb041d 
Toby Inkster d12855e 
Toby Inkster 15218da 









Toby Inkster 7cb041d 
Toby Inkster d12855e 

Toby Inkster 15218da 










Toby Inkster d12855e 
Toby Inkster 15218da 


Toby Inkster d12855e 


















Toby Inkster 15218da 






Toby Inkster d12855e 
Toby Inkster 15218da 

Toby Inkster d12855e 
Toby Inkster 15218da 






Toby Inkster c485a58 
Toby Inkster 15218da 




Toby Inkster d12855e 
Toby Inkster 15218da 


Toby Inkster d12855e 
Toby Inkster 15218da 

Toby Inkster c088685 

Toby Inkster d12855e 
Toby Inkster 15218da 

Toby Inkster d12855e 
Toby Inkster 15218da 

Toby Inkster c088685 







Toby Inkster d12855e 

Toby Inkster c088685 
Toby Inkster 15218da 
Toby Inkster c088685 
Toby Inkster 15218da 

Toby Inkster d12855e 






Toby Inkster 15218da 







Toby Inkster d12855e 







Toby Inkster 15218da 

Toby Inkster d12855e 




























































































































































Toby Inkster 15218da 






Toby Inkster d12855e 



Toby Inkster 15218da 




























Toby Inkster e504e28 
Toby Inkster 15218da 








Toby Inkster 7cb041d 

Toby Inkster 15218da 













  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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package Web::Paste::Simple;

use 5.010;
use Moo;
use MooX::Types::MooseLike::Base qw( Str CodeRef ArrayRef InstanceOf );
use Carp qw( confess );
use JSON qw( from_json to_json );
use HTML::HTML5::Entities qw( encode_entities_numeric );
use constant read_only => 'ro';
use aliased 'Text::Template';
use aliased 'Data::UUID';
use aliased 'Plack::Request';
use aliased 'Plack::Response';
use aliased 'Path::Class::Dir';
use aliased 'Path::Class::File';

BEGIN {
	$Web::Paste::Simple::AUTHORITY = 'cpan:TOBYINK';
	$Web::Paste::Simple::VERSION   = '0.001';
}

has uuid_gen => (
	is      => read_only,
	isa     => InstanceOf[UUID],
	default => sub { UUID->new },
);

has template => (
	is      => read_only,
	isa     => InstanceOf[Template],
	lazy    => 1,
	default => sub {
		return Template->new(
			TYPE   => 'FILEHANDLE',
			SOURCE => \*DATA,
		);
	},
);

has storage => (
	is      => read_only,
	isa     => InstanceOf[Dir],
	default => sub { Dir->new('/tmp/perl-web-paste-simple/') },
);

has codemirror => (
	is      => read_only,
	isa     => Str,
	default => sub { 'http://buzzword.org.uk/2012/codemirror-2.36' },
);

has app => (
	is      => read_only,
	isa     => CodeRef,
	lazy    => 1,
	builder => '_build_app',
);

has modes => (
	is      => read_only,
	isa     => ArrayRef[Str],
	default => sub {
		[qw(
			htmlmixed xml css javascript
			clike perl php ruby python lua haskell
			diff sparql ntriples plsql
		)]
	},
);

has default_mode => (
	is      => read_only,
	isa     => Str,
	default => sub { 'perl' },
);

sub _build_app
{
	my $self = shift;
	
	$self->storage->mkpath unless -d $self->storage;
	confess "@{[$self->storage]} is not writeable" unless -w $self->storage;
		
	return sub {
		my $req = Request->new(shift);
		$self->dispatch($req)->finalize;
	};
}

sub dispatch
{
	my ($self, $req) = @_;
	
	if ($req->method eq 'POST') {
		return $self->create_paste($req);
	}
	elsif ($req->path =~ m{^/([^.]+)}) {
		return $self->retrieve_paste($req, $1);
	}
	elsif ($req->path eq '/') {
		return $self->show_template($req, {});
	}
	else {
		return $self->show_error("Bad URI", 404);
	}
}

sub make_paste_id
{
	my $id = shift->uuid_gen->create_b64;
	$id =~ tr{+/}{-_};
	$id =~ s{=+$}{};
	return $id;
}

sub create_paste
{
	my ($self, $req) = @_;
	my $id = $self->make_paste_id;
	$self->storage->file("$id.paste")->spew(
		to_json( +{ %{$req->parameters} } ),
	);
	return Response->new(
		302,
		[
			'Content-Type' => 'text/plain',
			'Location'     => $req->base . "/$id",
		],
		"Yay!",
	);
}

sub retrieve_paste
{
	my ($self, $req, $id) = @_;
	my $file = $self->storage->file("$id.paste");
	-r $file or return $self->show_error("Bad file", 404);
	my $data = from_json($file->slurp);
	
	exists $req->parameters->{raw}
		? Response->new(200, ['Content-Type' => 'text/plain'], $data->{paste})
		: $self->show_template($req, $data);
}

sub show_template
{
	my ($self, $req, $data) = @_;
	my $page = $self->template->fill_in(
		HASH => {
			DATA       => encode_entities_numeric($data->{paste} // ''),
			MODE       => encode_entities_numeric($data->{mode}  // $self->default_mode),
			MODES      => $self->modes,
			PACKAGE    => ref($self),
			VERSION    => $self->VERSION,
			CODEMIRROR => $self->codemirror,
			APP        => $self,
			REQUEST    => $req,
		},
	);
	Response->new(200, ['Content-Type' => 'text/html'], $page);
}

sub show_error
{
	my ($self, $err, $code) = @_;
	Response->new(($code//500), ['Content-Type' => 'text/plain'], "$err\n");
}


1;

=head1 NAME

Web::Paste::Simple - simple PSGI-based pastebin-like website

=head1 SYNOPSIS

	#!/usr/bin/plackup
	use Web::Paste::Simple;
	Web::Paste::Simple->new(
		storage    => Path::Class::Dir->new(...),
		codemirror => "...",
		template   => Text::Template->new(...),
	)->app;

=head1 DESCRIPTION

Web::Paste::Simple is a lightweight PSGI app for operating a
pastebin-like website. It provides syntax highlighting via the
L<CodeMirror|http://codemirror.net/> Javascript library. It
should be fast enough for deployment via CGI.

It does not provide any authentication facilities or similar,
instead relying on you to use subclassing/roles or L<Plack>
middleware to accomplish such things.

=head2 Constructor

=over

=item C<< new(%attrs) >>

Standard Moose-style constructor.

This class is not based on Moose though; instead it uses L<Moo>.

=back

=head2 Attributes

The following attributes are defined:

=over

=item C<storage>

A L<Path::Class::Dir> indicating the directory where pastes
should be stored. Pastes are kept indefinitely. Each is a single
file.

=item C<codemirror>

Path to the CodeMirror syntax highlighter as a string. For example,
if CodeMirror is available at C<< http://example.com/js/lib/codemirror.js >>
then this string should be C<< http://example.com/js >> with no trailing
slash.

This defaults to an address on my server, but for production sites,
I<please> set up your own copy: it only takes a couple of minutes;
just a matter of unzipping a single archive. I offer no guarantees
about the continued availability of my copy of CodeMirror.

Nothing is actually done with this variable, but it's passed to the
template.

=item C<template>

A L<Text::Template> template which will be used for I<all> HTML output.
The following variables are available to the template...

=over

=item *

C<< $DATA >> - the text pasted on the curent page (if any), already HTML escaped

=item *

C<< $MODE >> - the currently selected syntax highlighting mode (if any), already HTML escaped

=item *

C<< @MODES >> - all configured highlighting modes

=item *

C<< $CODEMIRROR >> - the path to codemirror

=item *

C<< $APP >> - the blessed Web::Paste::Simple object

=item *

C<< $REQUEST >> - a blessed L<Plack::Request> for the current request

=item *

C<< $PACKAGE >> - the string "Web::Paste::Simple"

=item *

C<< $VERSION >> - the Web::Paste::Simple version number

=back

The default template is minimal, but works.

=item C<modes>

The list of CodeMirror highlighting modes to offer to the user.

Nothing is actually done with this variable, but it's passed to the
template.

=item C<default_mode>

The default highlighting mode.

=item C<uuid_gen>

A L<Data::UUID> object used to generate URIs. The default should be fine.

=back

=head2 Methods

The following methods may be of interest to people subclassing
L<Web::Paste::Simple>.

=over

=item C<app>

Technically this is another attribute, but one that should not be set
in the constructor. Call this method to retrieve the L<PSGI> coderef.

This coderef is built by C<_build_app> (a Moo lazy builder).

=item C<dispatch>

Basic request router/dispatcher. Given a L<Plack::Request>, returns a
L<Plack::Response>.

=item C<create_paste>

Given a L<Plack::Request> corresponding to an HTTP C<POST> request,
saves the paste and returns a L<Plack::Reponse>. The response may
be an arror message, success message, or (as per the current
implementation) a redirect to the paste's URI.

=item C<retrieve_paste>

Given a L<Plack::Request> and a paste ID, returns a L<Plack::Response>
with a representation of the paste, or an error message.

=item C<show_error>

Given an error string and optionally an HTTP status code, returns a
L<Plack::Response>.

=item C<show_template>

Given a L<Plack::Request> and a hashref of data (possibly including
C<paste> and C<mode> keys) returns a L<Plack::Response> with the rendered
template, and the pasted data plugged into it.

=item C<make_paste_id>

Returns a unique ID string for a paste. The current implementation is
a base64-encoded UUID.

=back

=head1 BUGS

Please report any bugs to
L<http://rt.cpan.org/Dist/Display.html?Queue=Web-Paste-Simple>.

=head1 SEE ALSO

L<Plack>,
L<Moo>,
L<CodeMirror|http://codemirror.net/>.

=head1 AUTHOR

Toby Inkster E<lt>tobyink@cpan.orgE<gt>.

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2012 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=head1 DISCLAIMER OF WARRANTIES

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.

=cut

__DATA__
<!doctype html>
<title>{$PACKAGE} {$VERSION}</title>
<link rel="stylesheet" href="{$CODEMIRROR}/lib/codemirror.css">
<script src="{$CODEMIRROR}/lib/codemirror.js"></script>
{
	for my $m (@MODES) {
		$OUT .= qq[<script src="$CODEMIRROR/mode/$m/$m.js"></script>\n]
	}
}
<form action="" method="post">
	<div>
		<select name="mode" onchange="change_mode();">
			{
				for my $m (@MODES) {
					$OUT .= qq[<option @{[$m eq $MODE ? 'selected':'']}>$m</option>\n]
				}
			}
		</select>
		<input type="submit" value=" Paste ">
		<br>
		<textarea name="paste">{$DATA}</textarea>
	</div>
</form>
<script>
var ta = document.getElementsByTagName("textarea");
var editor = CodeMirror.fromTextArea(ta[0], \{
	lineNumbers: true,
	matchBrackets: true,
	indentUnit: 4,
	mode: "{$MODE}",
\});
function change_mode () \{
	var s = document.getElementsByTagName("select");
	editor.setOption("mode", s[0].options[s[0].selectedIndex].value);
\}
</script>