-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkollector.rb
111 lines (91 loc) · 2.26 KB
/
kollector.rb
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 'sinatra/base'
require 'digest'
require 'data_mapper'
require 'json'
require 'uri'
#require 'sinatra/cross_origin'
DataMapper.setup(:default, "sqlite3::memory:")
DataMapper::Model.raise_on_save_failure = true
class Link
include DataMapper::Resource
property :id, Serial
property :tag, String
property :link, String, :length => 255
property :url, Text
end
class Click
include DataMapper::Resource
property :id, Serial
property :timestamp, DateTime
property :tag, String
property :ip, String
property :fingerprint, String
property :referrer, String, :length => 255
end
def fingerprint(request)
Digest::MD5.hexdigest("#{request.ip} #{request.user_agent}").to_s
end
def record_click(tag, ip, fingerprint, referrer)
c = Click.new
c.timestamp = DateTime.now
c.tag = tag
c.ip = ip
c.fingerprint = fingerprint
c.referrer = referrer
c.save
end
def create_tag(url)
hash = Digest::SHA1.hexdigest("#{DateTime.now.to_s} #{url}").to_s[0..5]
link = "#{request.scheme.to_s}://#{request.host.to_s}:#{request.port.to_s}/l/#{hash}"
l = Link.new
l.tag = hash
l.link = link
l.url = url
l.save
return l
end
Link.auto_migrate!
Click.auto_migrate!
class Kollector < Sinatra::Base
set :public_folder, Proc.new { File.join(root, "public") }
set :root_folder, Proc.new { File.join(root) }
set :cross_origin, true
get '/' do
erb :index
end
post '/l' do
begin
u = URI.parse(params[:url])
if u.scheme === nil; puts "scheme was nil"; raise; end
create_tag(params[:url]).to_json
rescue
status 400
end
end
get '/l' do
tags = Link.all
erb :list, :locals => { :tags => tags }
end
get '/l/:tag' do
link = Link.first(:tag => params[:tag])
if not link.nil?
record_click(link.tag, request.ip, fingerprint(request), request.referrer)
redirect(link.url)
else
status 404
end
end
get '/s/:tag' do
link = Link.first(:tag => params[:tag])
if not link.nil?
clicks = Click.all(:tag => params[:tag])
erb :stats, :locals => { :link => link, :clicks => clicks }
else
status 404
end
end
not_found do
status 404
erb :oops
end
end