1 ! Copyright (C) 2007 Doug Coleman.
2 ! Copyright (C) 2008 Slava Pestov.
3 ! See http://factorcode.org/license.txt for BSD license.
4 USING: accessors continuations db.tuples db.types fry furnace.actions
5 furnace.boilerplate furnace.redirection furnace.utilities html.forms
6 http.server.dispatchers kernel math ranges random random.data
7 sequences urls validators ;
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 : random-url ( -- string )
20 6 random 1 + random-string ;
22 : retry ( quot: ( -- ? ) n -- )
23 swap [ drop ] prepose attempt-all ; inline
25 : insert-short-url ( short-url -- short-url )
26 '[ _ dup random-url >>short insert-tuple ] 10 retry ;
28 : shorten ( url -- short )
29 short-url new swap >>url dup select-tuple
30 [ ] [ insert-short-url ] ?if short>> ;
32 : short>url ( short -- url )
33 "$wee-url/go/" prepend >url adjust-url ;
35 : expand-url ( string -- url )
36 short-url new swap >>short select-tuple url>> ;
38 : <shorten-action> ( -- action )
40 { wee-url "shorten" } >>template
41 [ { { "url" [ v-url ] } } validate-params ] >>validate
43 "$wee-url/show/" "url" value shorten append >url <redirect>
46 : <show-action> ( -- action )
50 { { "short" [ v-one-word ] } } validate-params
51 "short" value expand-url "url" set-value
52 "short" value short>url "short" set-value
54 { wee-url "show" } >>template ;
56 : <go-action> ( -- action )
59 [ { { "short" [ v-one-word ] } } validate-params ] >>init
60 [ "short" value expand-url <redirect> ] >>display ;
62 : <wee-url> ( -- wee-url )
63 wee-url new-dispatcher
64 <shorten-action> "" add-responder
65 <show-action> "show" add-responder
66 <go-action> "go" add-responder
68 { wee-url "wee-url" } >>template ;