]> gitweb.factorcode.org Git - factor.git/blob - extra/webapps/wee-url/wee-url.factor
Updating code for make and fry changes
[factor.git] / extra / webapps / wee-url / wee-url.factor
1 ! Copyright (C) 2007 Doug Coleman.
2 ! Copyright (C) 2008 Slava Pestov.
3 ! See http://factorcode.org/license.txt for BSD license.
4 USING: math.ranges sequences random accessors combinators.lib
5 kernel namespaces fry db.types db.tuples urls validators
6 html.components html.forms http http.server.dispatchers furnace
7 furnace.actions furnace.boilerplate furnace.redirection ;
8 IN: webapps.wee-url
9
10 TUPLE: wee-url < dispatcher ;
11
12 TUPLE: short-url short url ;
13
14 short-url "SHORT_URLS" {
15     { "short" "SHORT" TEXT +user-assigned-id+ }
16     { "url" "URL" TEXT +not-null+ }
17 } define-persistent
18
19 : letter-bank ( -- seq )
20     CHAR: a CHAR: z [a,b]
21     CHAR: A CHAR: Z [a,b]
22     CHAR: 1 CHAR: 0 [a,b]
23     3append ; foldable
24
25 : random-url ( -- string )
26     1 6 [a,b] random [ letter-bank random ] "" replicate-as ;
27
28 : insert-short-url ( short-url -- short-url )
29     '[ _ dup random-url >>short insert-tuple ] 10 retry ;
30
31 : shorten ( url -- short )
32     short-url new swap >>url dup select-tuple
33     [ ] [ insert-short-url ] ?if short>> ;
34
35 : short>url ( short -- url )
36     "$wee-url/go/" prepend >url adjust-url ;
37
38 : expand-url ( string -- url )
39     short-url new swap >>short select-tuple url>> ;
40
41 : <shorten-action> ( -- action )
42     <page-action>
43         { wee-url "shorten" } >>template
44         [ { { "url" [ v-url ] } } validate-params ] >>validate
45         [
46             "$wee-url/show/" "url" value shorten append >url <redirect>
47         ] >>submit ;
48
49 : <show-action> ( -- action )
50     <page-action>
51         "short" >>rest
52         [
53             { { "short" [ v-one-word ] } } validate-params
54             "short" value expand-url "url" set-value
55             "short" value short>url "short" set-value
56         ] >>init
57         { wee-url "show" } >>template ;
58
59 : <go-action> ( -- action )
60     <action>
61         "short" >>rest
62         [ { { "short" [ v-one-word ] } } validate-params ] >>init
63         [ "short" value expand-url <redirect> ] >>display ;
64
65 : <wee-url> ( -- wee-url )
66     wee-url new-dispatcher
67         <shorten-action> "" add-responder
68         <show-action> "show" add-responder
69         <go-action> "go" add-responder
70     <boilerplate>
71         { wee-url "wee-url" } >>template ;