Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 111 lines (85 sloc) 2.172 kb
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
require 'rubygems'
require 'sinatra'
require 'sequel'
require 'uri'
require 'haml'

configure do
  Sequel::Model.plugin(:schema)
  Sequel.connect(ENV['DATABASE_URL'] || 'sqlite://shorten.db')
  
  set :sass, :style => :compact

require 'ostruct'
Shorten = OpenStruct.new(
:base_url => ENV['url'],
:service_name => "108th.name",
:button_text => "➼",
:path_size => 4
)

$LOAD_PATH.unshift(File.dirname(__FILE__) + '/lib')
end

$LOAD_PATH.unshift(File.dirname(__FILE__) + '/lib')

require 'shortenurl'

helpers do
def show_information
haml :information, :layout => false
end

def validate_link(link)
halt 401, 'We do not accept local URLs to be shortened' unless valid_url? link
end

# Determine if a URL is valid. We run it through
def valid_url?(url)
if url.include? "%3A"
url = URI.unescape(url)
end

retval = true

begin
uri = URI.parse(URI.escape(url))
if uri.class != URI::HTTP
retval = false
end

host = (URI.split(url))[2]
if host =~ /^(localhost|192\.168\.\d{1,3}\.\d{1,3}|127\.0\.0\.1|172\.((1[6-9])|(2[0-9])|(3[0-1])).\d{1,3}\.\d{1,3}|10.\d{1,3}\.\d{1,3}.\d{1,3})/
retval = false
end
rescue URI::InvalidURIError
retval = false
end

retval
end
end

get '/screen.css' do
  sass :screen # sass stylesheet
end

get '/' do
@information = show_information
haml :new, :locals => { :type => "main" }
end

get %r(/(api-){0,1}create/(.*)) do |api, link|
validate_link link

url = ShortenUrl.create_url(link)

if api == "api-"
"#{url.short_url}"
else
haml :finished, :locals => { :url => url, :type => "finished" }
end
end

get %r(/(api-){0,1}create) do |api|
if request['url']
validate_link request['url']
url = ShortenUrl.create_url(request['url'])
if api == "api-"
"#{url.short_url}"
else
haml :finished, :locals => { :url => url, :type => "finished" }
end
end
end

post '/' do
validate_link params[:url]

url = ShortenUrl.create_url(params[:url])

haml :finished, :locals => { :url => url, :type => "finished" }
end

get '/:short' do

url = ShortenUrl.find(:key => params[:short])

halt 404, "Page not found" unless url

  redirect url.url
end
Something went wrong with that request. Please try again.