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 ;
10 TUPLE: wee-url < dispatcher ;
12 TUPLE: short-url short url ;
14 short-url "SHORT_URLS" {
15 { "short" "SHORT" TEXT +user-assigned-id+ }
16 { "url" "URL" TEXT +not-null+ }
19 : letter-bank ( -- seq )
25 : random-url ( -- string )
26 1 6 [a,b] random [ letter-bank random ] "" replicate-as ;
28 : insert-short-url ( short-url -- short-url )
29 '[ , dup random-url >>short insert-tuple ] 10 retry ;
31 : shorten ( url -- short )
32 short-url new swap >>url dup select-tuple
33 [ ] [ insert-short-url ] ?if short>> ;
35 : short>url ( short -- url )
36 "$wee-url/go/" prepend >url adjust-url ;
38 : expand-url ( string -- url )
39 short-url new swap >>short select-tuple url>> ;
41 : <shorten-action> ( -- action )
43 { wee-url "shorten" } >>template
44 [ { { "url" [ v-url ] } } validate-params ] >>validate
46 "$wee-url/show/" "url" value shorten append >url <redirect>
49 : <show-action> ( -- action )
53 { { "short" [ v-one-word ] } } validate-params
54 "short" value expand-url "url" set-value
55 "short" value short>url "short" set-value
57 { wee-url "show" } >>template ;
59 : <go-action> ( -- action )
62 [ { { "short" [ v-one-word ] } } validate-params ] >>init
63 [ "short" value expand-url <redirect> ] >>display ;
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
71 { wee-url "wee-url" } >>template ;