-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
299 lines (250 loc) · 7.28 KB
/
app.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# -*- coding: utf-8 -*-
require 'rubygems'
require 'sinatra'
require 'RMagick'
require 'open-uri'
require 'dm-core'
require 'dm-ar-finders'
require 'base64'
require 'json'
require 'rss'
require 'time'
$LOAD_PATH << 'lib'
require 'my_magick' # for RMagick 1.x
require 'twitter_oauth'
include Magick
DataMapper::setup(:default, ENV['DATABASE_URL'] || 'sqlite3:db.sqlite3')
class Object
def blank?
respond_to?(:empty?) ? empty? : !self
end
def present?
!self.blank?
end
end
module URI
# http://subtech.g.hatena.ne.jp/secondlife/20061115/1163571997
def self.valid_http_uri?(str)
URI.split(str).first == 'http' rescue false
end
end
class DateTime
def to_s_jp
self.new_offset(Rational(9,24)).strftime("at %Y/%m/%d %H:%M:%S")
end
end
class Photo
include DataMapper::Resource
property :id, Serial
property :body, Text
property :created_at, DateTime, :default => DateTime.now
auto_upgrade!
end
class Member
include DataMapper::Resource
property :id, Serial
property :name, String, :unique_index => :idx_member_name, :nullable => false
auto_upgrade!
end
class Card
include Magick
WIDTH = 43.0
HEIGHT = 55.0
RIDERS = %w(decade hibiki kabuto den_o kiva kuuga agito ryuki faiz blade)
def initialize(image)
@image = image
end
def generate(user, opt, client)
return @image if user.blank?
begin
src = ImageList.new(Card::image_src(user, client)).first
src.background_color = "none"
src.resize_to_fill!(Card::WIDTH, Card::HEIGHT).
resize!(opt.width, opt.height).
rotate!(opt.angle)
@image = @image.composite(src, opt.x, opt.y, OverCompositeOp)
rescue
@image
end
end
private
def self.image_src(user, client)
return URI.encode(user) if URI.valid_http_uri?(user)
# get profile_image_url by using OAuth
url = client.show(user)['profile_image_url']
if url.present? and !Member.first(:name => user)
Member.create(:name => user) rescue true
end
URI.encode(url)
end
end
Setting = Struct.new(:x, :y, :width, :height, :angle)
rider_settings = {
:decade => Setting.new(564, 171, Card::WIDTH-1, Card::HEIGHT, -2.5),
:hibiki => Setting.new(402, 432, Card::WIDTH-18, Card::HEIGHT, 13.6),
:kabuto => Setting.new(434, 440, Card::WIDTH-14, Card::HEIGHT, 13.6),
:den_o => Setting.new(475, 447, Card::WIDTH-14, Card::HEIGHT, 13.4),
:kiva => Setting.new(514, 454, Card::WIDTH-10, Card::HEIGHT, 13.4),
:kuuga => Setting.new(567, 460, Card::WIDTH, Card::HEIGHT, 0),
:agito => Setting.new(622, 448, Card::WIDTH, Card::HEIGHT, -12),
:ryuki => Setting.new(676, 436, Card::WIDTH, Card::HEIGHT, -12),
:faiz => Setting.new(737, 428, Card::WIDTH, Card::HEIGHT, -10.3),
:blade => Setting.new(790, 419, Card::WIDTH, Card::HEIGHT, -10.3)
}
configure do
use Rack::Session::Cookie, :secret => Digest::SHA1.hexdigest(rand.to_s)
# set :sessions, true
@@config = YAML.load_file("config.yml") rescue nil || {
:consumer_key => ENV['CONSUMER_KEY'],
:consumer_secret => ENV['CONSUMER_SECRET']
}
end
before do
@user = session[:user]
@client =
TwitterOAuth::Client.new(:consumer_key => @@config['consumer_key'],
:consumer_secret => @@config['consumer_secret'],
:token => session[:access_token],
:secret => session[:secret_token])
@rate_limit_status = @client.rate_limit_status
end
get '/' do
erb :index
end
post '/photo' do
redirect '/connect' unless @user
params.delete_if {|k, v| !Card::RIDERS.include?(k.to_s) }
result = ImageList.new('images/decade.jpg')
rider_settings.each do |k, v|
result = Card.new(result).generate(params[k], v, @client)
end
image = Photo.create(:body => Base64.encode64(result.to_blob),
:created_at => DateTime.now)
Photo.all(:id.lt => (image.id - 50)).each do |photo|
photo.destroy
end
redirect "/show/#{image.id}"
end
delete '/photo/:id' do
begin
Photo.get!(params[:id]).destroy
image_file_path = File.expand_path("tmp/#{params[:id]}.jpg")
if File.exist?(image_file_path)
File.delete(image_file_path)
end
ensure
redirect '/list'
end
end
get '/photo/:id' do
begin
image_file_path = File.expand_path("tmp/#{params[:id]}.jpg")
if File.exist?(image_file_path)
content_type :jpg
return File.open(image_file_path)
end
image = Photo.get!(params[:id])
File.open(image_file_path, "w") do |file|
file.write(Base64.decode64(image.body))
end
content_type :jpg
return Base64.decode64(image.body)
rescue
raise Sinatra::NotFound
end
end
get '/members.json' do
content_type :json
members =
Member.find_by_sql("SELECT * FROM members ORDER BY random() LIMIT 10")
alist = Card::RIDERS.zip(members.map{|m| m.name })
rider_user_mapping = Hash[*alist.flatten]
@members = JSON.unparse(rider_user_mapping)
erb :members, :layout => false
end
post '/member' do
begin
unless params[:name].blank?
Member.create(:name => params[:name].chomp)
end
ensure
redirect '/'
end
end
delete '/member' do
member = Member.first(:name => params[:name].chomp)
unless member.blank?
member.destroy
end
redirect '/'
end
get '/show/:id' do
begin
image = Photo.get!(params[:id])
@id = image.id
erb :show
rescue
redirect '/'
end
end
get '/list' do
@photos = Photo.all(:order => [:id.desc], :limit => 50)
erb :list
end
get '/list.rss' do
photos = Photo.all(:order => [:id.desc], :limit => 15)
server = "http://#{env['SERVER_NAME']}"
if env["SERVER_PORT"] && env["SERVER_PORT"].to_i != 80
server += ":#{env["SERVER_PORT"]}"
end
@rss = RSS::Maker.make("2.0") do |maker|
maker.channel.about = server + "/"
maker.channel.link = server + "/"
maker.channel.title = "コンプリートフォームジェネレータ"
maker.channel.description = "コンプリートフォームジェネレータ"
maker.channel.date = Time.parse(photos.first.created_at.to_s)
photos.each do |photo|
maker.items.new_item do |item|
item.link = server + "/show/#{photo.id}"
item.title = "コンプリートフォーム##{photo.id}"
item.date = Time.parse(photo.created_at.to_s)
item.description = %Q|<img src="#{server}/photo/#{photo.id}" width="1200" height="1600" />|
end
end
end
content_type 'application/rss+xml', :charset => 'utf-8'
erb :rss, :layout => :false
end
get '/connect' do
request_token = @client.request_token(:oauth_callback => '')
session[:request_token] = request_token.token
session[:request_token_secret] = request_token.secret
redirect request_token.authorize_url.gsub('authorize', 'authenticate')
end
get '/auth' do
# Exchange the request token for an access token.
@access_token = @client.authorize(
session[:request_token],
session[:request_token_secret],
:oauth_verifier => params[:oauth_token]
)
if @client.authorized?
session[:access_token] = @access_token.token
session[:secret_token] = @access_token.secret
session[:user] = true
end
redirect '/'
end
get '/disconnect' do
session[:user] = nil
session[:request_token] = nil
session[:request_token_secret] = nil
session[:access_token] = nil
session[:secret_token] = nil
redirect '/'
end
helpers do
def h(str)
Rack::Utils.escape_html(str)
end
end