tmin 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/.gitignore ADDED
@@ -0,0 +1,49 @@
1
+ # rcov generated
2
+ coverage
3
+ coverage.data
4
+
5
+ # rdoc generated
6
+ rdoc
7
+
8
+ # yard generated
9
+ doc
10
+ .yardoc
11
+
12
+ # bundler
13
+ .bundle
14
+
15
+ # jeweler generated
16
+ pkg
17
+
18
+ # Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore:
19
+ #
20
+ # * Create a file at ~/.gitignore
21
+ # * Include files you want ignored
22
+ # * Run: git config --global core.excludesfile ~/.gitignore
23
+ #
24
+ # After doing this, these files will be ignored in all your git projects,
25
+ # saving you from having to 'pollute' every project you touch with them
26
+ #
27
+ # Not sure what to needs to be ignored for particular editors/OSes? Here's some ideas to get you started. (Remember, remove the leading # of the line)
28
+ #
29
+ # For MacOS:
30
+ #
31
+ #.DS_Store
32
+
33
+ # For TextMate
34
+ #*.tmproj
35
+ #tmtags
36
+
37
+ # For emacs:
38
+ #*~
39
+ #\#*
40
+ #.\#*
41
+
42
+ # For vim:
43
+ #*.swp
44
+
45
+ # For redcar:
46
+ #.redcar
47
+
48
+ # For rubinius:
49
+ #*.rbc
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in firefly.gemspec
4
+ gemspec
5
+
data/Gemfile.lock ADDED
@@ -0,0 +1,77 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ tmin (0.0.1)
5
+ dm-aggregates (~> 1.2.0)
6
+ dm-core (~> 1.2.0)
7
+ dm-migrations (~> 1.2.0)
8
+ dm-mysql-adapter (~> 1.2.0)
9
+ dm-transactions (~> 1.2.0)
10
+ escape_utils (~> 0.2.3)
11
+ haml (~> 3.0.18)
12
+ sinatra (~> 1.2.0)
13
+
14
+ GEM
15
+ remote: http://rubygems.org/
16
+ specs:
17
+ addressable (2.2.7)
18
+ data_objects (0.10.8)
19
+ addressable (~> 2.1)
20
+ database_cleaner (0.6.7)
21
+ diff-lcs (1.1.3)
22
+ dm-aggregates (1.2.0)
23
+ dm-core (~> 1.2.0)
24
+ dm-core (1.2.0)
25
+ addressable (~> 2.2.6)
26
+ dm-do-adapter (1.2.0)
27
+ data_objects (~> 0.10.6)
28
+ dm-core (~> 1.2.0)
29
+ dm-migrations (1.2.0)
30
+ dm-core (~> 1.2.0)
31
+ dm-mysql-adapter (1.2.0)
32
+ dm-do-adapter (~> 1.2.0)
33
+ do_mysql (~> 0.10.6)
34
+ dm-sqlite-adapter (1.2.0)
35
+ dm-do-adapter (~> 1.2.0)
36
+ do_sqlite3 (~> 0.10.6)
37
+ dm-transactions (1.2.0)
38
+ dm-core (~> 1.2.0)
39
+ do_mysql (0.10.8)
40
+ data_objects (= 0.10.8)
41
+ do_sqlite3 (0.10.8)
42
+ data_objects (= 0.10.8)
43
+ escape_utils (0.2.4)
44
+ haml (3.0.25)
45
+ rack (1.4.1)
46
+ rack-test (0.5.7)
47
+ rack (>= 1.0)
48
+ rspec (2.5.0)
49
+ rspec-core (~> 2.5.0)
50
+ rspec-expectations (~> 2.5.0)
51
+ rspec-mocks (~> 2.5.0)
52
+ rspec-core (2.5.2)
53
+ rspec-expectations (2.5.0)
54
+ diff-lcs (~> 1.1.2)
55
+ rspec-mocks (2.5.0)
56
+ sinatra (1.2.8)
57
+ rack (~> 1.1)
58
+ tilt (>= 1.2.2, < 2.0)
59
+ tilt (1.3.3)
60
+
61
+ PLATFORMS
62
+ ruby
63
+
64
+ DEPENDENCIES
65
+ database_cleaner (~> 0.6.6)
66
+ dm-aggregates (~> 1.2.0)
67
+ dm-core (~> 1.2.0)
68
+ dm-migrations (~> 1.2.0)
69
+ dm-mysql-adapter (~> 1.2.0)
70
+ dm-sqlite-adapter (~> 1.2.0)
71
+ dm-transactions (~> 1.2.0)
72
+ escape_utils (~> 0.2.3)
73
+ haml (~> 3.0.18)
74
+ rack-test (~> 0.5.4)
75
+ rspec (~> 2.5.0)
76
+ sinatra (~> 1.2.0)
77
+ tmin!
data/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2012 Duggan Roberts
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,19 @@
1
+ = tmin
2
+
3
+ Description goes here.
4
+
5
+ == Contributing to tmin
6
+
7
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
8
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
9
+ * Fork the project.
10
+ * Start a feature/bugfix branch.
11
+ * Commit and push until you are happy with your contribution.
12
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
13
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2012 Duggan Roberts. See LICENSE.txt for
18
+ further details.
19
+
data/Rakefile ADDED
@@ -0,0 +1,53 @@
1
+ # encoding: utf-8
2
+
3
+ require 'rubygems'
4
+ require 'bundler'
5
+ begin
6
+ Bundler.setup(:default, :development)
7
+ rescue Bundler::BundlerError => e
8
+ $stderr.puts e.message
9
+ $stderr.puts "Run `bundle install` to install missing gems"
10
+ exit e.status_code
11
+ end
12
+ require 'rake'
13
+
14
+ require 'jeweler'
15
+ Jeweler::Tasks.new do |gem|
16
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
17
+ gem.name = "tmin"
18
+ gem.homepage = "http://github.com/kingduggan1/tmin"
19
+ gem.license = "MIT"
20
+ gem.summary = %Q{TODO: one-line summary of your gem}
21
+ gem.description = %Q{TODO: longer description of your gem}
22
+ gem.email = "droberts@quailcreekbank.com"
23
+ gem.authors = ["Duggan Roberts"]
24
+ # dependencies defined in Gemfile
25
+ end
26
+ Jeweler::RubygemsDotOrgTasks.new
27
+
28
+ require 'rake/testtask'
29
+ Rake::TestTask.new(:test) do |test|
30
+ test.libs << 'lib' << 'test'
31
+ test.pattern = 'test/**/test_*.rb'
32
+ test.verbose = true
33
+ end
34
+
35
+ require 'rcov/rcovtask'
36
+ Rcov::RcovTask.new do |test|
37
+ test.libs << 'test'
38
+ test.pattern = 'test/**/test_*.rb'
39
+ test.verbose = true
40
+ test.rcov_opts << '--exclude "gems/*"'
41
+ end
42
+
43
+ task :default => :test
44
+
45
+ require 'rdoc/task'
46
+ Rake::RDocTask.new do |rdoc|
47
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
48
+
49
+ rdoc.rdoc_dir = 'rdoc'
50
+ rdoc.title = "tmin #{version}"
51
+ rdoc.rdoc_files.include('README*')
52
+ rdoc.rdoc_files.include('lib/**/*.rb')
53
+ end
data/config.ru.example ADDED
@@ -0,0 +1,20 @@
1
+ require 'rubygems'
2
+ require 'bundler/setup'
3
+ require 'tminus'
4
+ disable :run
5
+
6
+ app = Firefly::Server.new do
7
+ # The domain you use for shortening.
8
+ set :hostname, "localhost:3000"
9
+
10
+ # Used for authenticating you.
11
+ set :api_key, "oklahoma"
12
+
13
+ # Use Sqlite3 by default
14
+ set :database, "sqlite3://#{Dir.pwd}/firefly.sqlite3"
15
+ # Defaults to 25
16
+ # set :recent_urls, 10
17
+ end
18
+
19
+ run app
20
+
@@ -0,0 +1,27 @@
1
+ # encoding: UTF-8
2
+ module Firefly
3
+ class Base62
4
+
5
+ CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split('')
6
+ BASE = 62
7
+
8
+ def self.encode(value)
9
+ s = []
10
+ while value >= BASE
11
+ value, rem = value.divmod(BASE)
12
+ s << CHARS[rem]
13
+ end
14
+ s << CHARS[value]
15
+ s.reverse.join("")
16
+ end
17
+
18
+ def self.decode(str)
19
+ str = str.split('').reverse
20
+ total = 0
21
+ str.each_with_index do |v,k|
22
+ total += (CHARS.index(v) * (BASE ** k))
23
+ end
24
+ total
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,24 @@
1
+ # encoding: UTF-8
2
+ module Firefly
3
+ class CodeFactory
4
+ include DataMapper::Resource
5
+
6
+ property :id, Serial
7
+ property :count, Integer, :default => 0
8
+
9
+ # Returns the next auto increment value and updates
10
+ # the counter
11
+ def self.next_code!
12
+ code = nil
13
+
14
+ Firefly::CodeFactory.transaction do
15
+ c = Firefly::CodeFactory.first
16
+ code = Firefly::Base62.encode(c.count + 1)
17
+ c.update(:count => c.count + 1)
18
+ end
19
+
20
+ code
21
+ end
22
+
23
+ end
24
+ end
@@ -0,0 +1,28 @@
1
+ # encoding: UTF-8
2
+ module Firefly
3
+ class Config < Hash
4
+
5
+ DEFAULTS = {
6
+ :hostname => "localhost:3000",
7
+ :api_key => "test",
8
+ :database => "sqlite3://#{Dir.pwd}/firefly_#{ENV['RACK_ENV']}.sqlite3",
9
+ :recent_urls => 25,
10
+ :tweet => "Check this out: %short_url%",
11
+ :hyves_title => "Check this out",
12
+ :hyves_body => "Check this out: %short_url%"
13
+ }
14
+
15
+ def initialize obj
16
+ self.update DEFAULTS
17
+ self.update obj
18
+ end
19
+
20
+ def set key, val = nil, &blk
21
+ if val.is_a? Hash
22
+ self[key].update val
23
+ else
24
+ self[key] = block_given?? blk : val
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,330 @@
1
+ # encoding: UTF-8
2
+ require 'sinatra/base'
3
+ require 'haml'
4
+ require 'digest/md5'
5
+
6
+ module Firefly
7
+ class InvalidUrlError < StandardError
8
+ end
9
+
10
+ class InvalidCodeError < StandardError
11
+ end
12
+
13
+ class Server < Sinatra::Base
14
+ enable :sessions
15
+
16
+ if Firefly.environment == "development"
17
+ enable :logging, :dump_errors, :raise_errors
18
+ end
19
+
20
+ dir = File.join(File.dirname(__FILE__), '..', '..')
21
+
22
+ set :views, "#{dir}/views"
23
+ set :public, "#{dir}/public"
24
+ set :haml, {:format => :html5 }
25
+ set :static, true
26
+ set :session_secret, nil
27
+
28
+ attr_accessor :config
29
+
30
+ helpers do
31
+ include Rack::Utils
32
+ alias_method :h, :escape_html
33
+
34
+ def url(*path_parts)
35
+ [ path_prefix, path_parts ].join("/").squeeze('/')
36
+ end
37
+ alias_method :u, :url
38
+
39
+ def path_prefix
40
+ request.env['SCRIPT_NAME']
41
+ end
42
+
43
+ def set_api_cookie(key)
44
+ session["firefly_session"] = Digest::MD5.hexdigest(key)
45
+ end
46
+
47
+ # Taken from Rails
48
+ def truncate(text, length, options = {})
49
+ options[:omission] ||= "..."
50
+
51
+ length_with_room_for_omission = length - options[:omission].length
52
+ chars = text
53
+ stop = options[:separator] ?
54
+ (chars.rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission
55
+
56
+ (chars.length > length ? chars[0...stop] + options[:omission] : text).to_s
57
+ end
58
+
59
+ def has_valid_api_cookie?
60
+ key = session["firefly_session"]
61
+ key == Digest::MD5.hexdigest(config[:api_key])
62
+ end
63
+
64
+ def has_valid_share_key?
65
+ return false unless @config.has_key?(:sharing_key)
66
+ @config[:sharing_key] == params[:key]
67
+ end
68
+
69
+ def has_valid_share_domain?
70
+ return false unless @config.has_key?(:sharing_domains)
71
+ return true if @config[:sharing_domains].empty?
72
+ @config[:sharing_domains].any? { |domain| params[:url].include?(domain) }
73
+ end
74
+
75
+ def has_valid_share_target?
76
+ return false unless @config.has_key?(:sharing_domains)
77
+ @config[:sharing_targets].include?(params[:target].downcase.to_sym)
78
+ end
79
+
80
+ def validate_share_permission
81
+ if has_valid_share_key? && has_valid_share_domain? && has_valid_share_target?
82
+ return true
83
+ else
84
+ status 401
85
+ return false
86
+ end
87
+ end
88
+
89
+ def validate_api_permission
90
+ if !has_valid_api_cookie? && params[:api_key] != config[:api_key]
91
+ status 401
92
+ return false
93
+ else
94
+ return true
95
+ end
96
+ end
97
+
98
+ def short_url(url)
99
+ "http://#{config[:hostname]}/#{url.code}"
100
+ end
101
+
102
+ def generate_short_url(url = nil, requested_code = nil)
103
+ code, result = nil, nil
104
+
105
+ begin
106
+ ff_url = Firefly::Url.shorten(url, requested_code)
107
+ code, result = ff_url.code, "http://#{config[:hostname]}/#{ff_url.code}"
108
+ rescue Firefly::InvalidUrlError
109
+ code, result = nil, "ERROR: The URL you posted is invalid."
110
+ rescue Firefly::InvalidCodeError
111
+ code, result = nil, "ERROR: The code is invalid or already exists."
112
+ rescue
113
+ code, result = nil, "ERROR: An unknown error occured"
114
+ end
115
+
116
+ return code, result
117
+ end
118
+
119
+ def is_highlighted?(url)
120
+ return false unless @highlight
121
+ @highlight == url.code
122
+ end
123
+
124
+ # Format a tweet
125
+ #
126
+ # redirect(URI.escape("http://twitter.com/home?status=#{tweet("http://#{config[:hostname]}/#{@code}", params[:title])}"))
127
+ def tweet(url, message = nil)
128
+ if message.nil? || message == ""
129
+ config[:tweet].gsub('%short_url%', url)
130
+ else
131
+ max_length = 140-1-url.size
132
+ [message.strip.slice(0...max_length), url].join(' ')
133
+ end
134
+ end
135
+
136
+ # Format a hyves post
137
+ # {"http://www.hyves.nl/profielbeheer/toevoegen/tips/?name=#{name_of_titel}&text=#{tekst_met_url)}&type=12&rating=5"
138
+ def hyves_post(url, title = nil, body = nil)
139
+ if title.nil? || title == ""
140
+ title = config[:hyves_title]
141
+ end
142
+
143
+ if body.nil? || body == ""
144
+ body = config[:hyves_body].gsub('%short_url%', url)
145
+ end
146
+
147
+ return "name=#{title.strip}&text=#{body.strip}&type=12&rating=5"
148
+ end
149
+
150
+ def store_api_key(key)
151
+ if key == config[:api_key]
152
+ set_api_cookie(config[:api_key])
153
+ end
154
+ end
155
+ end
156
+
157
+ before do
158
+ @authenticated = has_valid_api_cookie?
159
+ @config = config
160
+ @highlight = nil
161
+ @title = "Firefly at http://#{@config[:hostname]}"
162
+
163
+ set :session_secret, @config[:session_secret]
164
+ end
165
+
166
+ get '/' do
167
+ @highlight = Firefly::Url.first(:code => params[:highlight])
168
+ @error = params[:highlight] == "error"
169
+
170
+ sort_column = params[:s] || 'created_at'
171
+ sort_order = params[:d] || 'desc'
172
+
173
+ @urls = Firefly::Url.all(:limit => config[:recent_urls], :order => [ sort_column.to_sym.send(sort_order.to_sym) ] )
174
+
175
+ haml :index
176
+ end
177
+
178
+ post '/api/set' do
179
+ store_api_key(params[:api_key])
180
+ redirect '/'
181
+ end
182
+
183
+ # GET /add?url=http://ariejan.net&api_key=test
184
+ # POST /add?url=http://ariejan.net&api_key=test
185
+ #
186
+ # Returns the shortened URL
187
+ api_add = lambda {
188
+ validate_api_permission or return "Permission denied: Invalid API key"
189
+
190
+ @url = params[:url]
191
+ @requested_code = params[:short]
192
+ @code, @result = generate_short_url(@url, @requested_code)
193
+ invalid = @code.nil?
194
+
195
+ if params[:visual]
196
+ store_api_key(params[:api_key])
197
+ @code.nil? ? haml(:error) : redirect("/?highlight=#{@code}")
198
+ else
199
+ head 422 if invalid
200
+ @result
201
+ end
202
+ }
203
+
204
+ get '/api/add', &api_add
205
+ post '/api/add', &api_add
206
+
207
+ api_share = lambda {
208
+ validate_share_permission or return "Cannot share that URL."
209
+
210
+ @url = params[:url]
211
+ @code, @result = generate_short_url(@url, nil)
212
+ invalid = @code.nil?
213
+
214
+ params[:title] ||= ""
215
+ title = URI.unescape(params[:title])
216
+
217
+ case (params[:target].downcase.to_sym)
218
+ when :twitter
219
+ redirect(URI.escape("http://twitter.com/home?status=#{tweet("http://#{config[:hostname]}/#{@code}", title)}"))
220
+ when :hyves
221
+ redirect(URI.escape("http://www.hyves.nl/profielbeheer/toevoegen/tips/?#{hyves_post("http://#{config[:hostname]}/#{@code}", title)}"))
222
+ when :facebook
223
+ redirect(URI.escape("http://www.facebook.com/share.php?u=http://#{config[:hostname]}/#{@code}"))
224
+ end
225
+ }
226
+
227
+ get '/api/share', &api_share
228
+ post '/api/share', &api_share
229
+
230
+ # GET /b3d+
231
+ #
232
+ # Show info on the URL
233
+ get '/api/info/:code' do
234
+ validate_api_permission or return "Permission denied: Invalid API key"
235
+
236
+ @url = Firefly::Url.first(:code => params[:code])
237
+
238
+ if @url.nil?
239
+ status 404
240
+ "Sorry, that code is unknown."
241
+ else
242
+ @short_url = "http://#{config[:hostname]}/#{@url.code}"
243
+ haml :info
244
+ end
245
+ end
246
+
247
+ if defined? Barby
248
+ # GET /b3d.png
249
+ #
250
+ # Return a QR code image
251
+ get '/:code.png' do
252
+ @url = Firefly::Url.first(:code => params[:code])
253
+
254
+ if @url.nil?
255
+ status 404
256
+ "Sorry, that code is unknown."
257
+ else
258
+ qr = Barby::QrCode.new(short_url(@url))
259
+ content_type('image/png')
260
+ cache_control :public, :max_age => 2592000 # One month
261
+ body(qr.to_png(:xdim => 15, :margin => 30))
262
+ end
263
+ end
264
+ end
265
+
266
+ # GET /b3d
267
+ #
268
+ # Redirect to the shortened URL
269
+ get '/:code' do
270
+ @url = Firefly::Url.first(:code => params[:code])
271
+
272
+ if @url.nil?
273
+ status 404
274
+ "Sorry, that code is unknown."
275
+ else
276
+ @url.register_click!
277
+ redirect @url.url, 301
278
+ end
279
+ end
280
+
281
+ def initialize config = {}, &blk
282
+ super
283
+ @config = config.is_a?(Config) ? config : Firefly::Config.new(config)
284
+ @config.instance_eval(&blk) if block_given?
285
+
286
+ begin
287
+ DataMapper.setup(:default, @config[:database])
288
+ DataMapper.auto_upgrade!
289
+ check_mysql_collation
290
+ check_code_factory
291
+ rescue
292
+ puts "Error setting up database connection. Please check the `database` setting in config.ru"
293
+ puts $!
294
+ puts "-------"
295
+ puts $!.backtrace
296
+ exit(1)
297
+ end
298
+ end
299
+
300
+ def check_code_factory
301
+ Firefly::CodeFactory.first || Firefly::CodeFactory.create(:count => 0)
302
+ end
303
+
304
+ def check_mysql_collation(first_try = true)
305
+ # Make sure the 'code' column is case-sensitive. This hack is for
306
+ # MySQL only, other database systems don't have this problem.
307
+ if DataMapper.repository(:default).adapter =~ "DataMapper::Adapters::MysqlAdapter"
308
+ query = "SHOW FULL COLUMNS FROM firefly_urls WHERE Field='code';"
309
+ collation = DataMapper.repository(:default).adapter.select(query)[0][:collation]
310
+
311
+ if collation != "utf8_bin"
312
+ if first_try
313
+ puts " ~ Your MySQL database is not using the 'utf8-bin' collation. Trying to fix..."
314
+ DataMapper.repository(:default).adapter.execute("ALTER TABLE firefly_urls MODIFY `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;")
315
+ return check_mysql_collation(false)
316
+ else
317
+ puts " ~ Failed to set the collation for `code` in `firefly_urls`. Please see http://wiki.github.com/ariejan/firefly/faq for details."
318
+ return false
319
+ end
320
+ else
321
+ if !first_try
322
+ puts " ~ Successfully fixed your database."
323
+ end
324
+ return true
325
+ end
326
+ end
327
+ end
328
+ end
329
+ end
330
+