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
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 furnace.utilities continuations ;
11 TUPLE: wee-url < dispatcher ;
13 TUPLE: short-url short url ;
15 short-url "SHORT_URLS" {
16 { "short" "SHORT" TEXT +user-assigned-id+ }
17 { "url" "URL" TEXT +not-null+ }
20 : letter-bank ( -- seq )
26 : random-url ( -- string )
27 1 6 [a,b] random [ letter-bank random ] "" replicate-as ;
29 : insert-short-url ( short-url -- short-url )
30 '[ _ dup random-url >>short insert-tuple ] 10 retry ;
32 : shorten ( url -- short )
33 short-url new swap >>url dup select-tuple
34 [ ] [ insert-short-url ] ?if short>> ;
36 : short>url ( short -- url )
37 "$wee-url/go/" prepend >url adjust-url ;
39 : expand-url ( string -- url )
40 short-url new swap >>short select-tuple url>> ;
42 : <shorten-action> ( -- action )
44 { wee-url "shorten" } >>template
45 [ { { "url" [ v-url ] } } validate-params ] >>validate
47 "$wee-url/show/" "url" value shorten append >url <redirect>
50 : <show-action> ( -- action )
54 { { "short" [ v-one-word ] } } validate-params
55 "short" value expand-url "url" set-value
56 "short" value short>url "short" set-value
58 { wee-url "show" } >>template ;
60 : <go-action> ( -- action )
63 [ { { "short" [ v-one-word ] } } validate-params ] >>init
64 [ "short" value expand-url <redirect> ] >>display ;
66 : <wee-url> ( -- wee-url )
67 wee-url new-dispatcher
68 <shorten-action> "" add-responder
69 <show-action> "show" add-responder
70 <go-action> "go" add-responder
72 { wee-url "wee-url" } >>template ;