forked from hotsh/rstat.us
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rstatus.rb
604 lines (489 loc) · 16.6 KB
/
rstatus.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
require 'bundler'
Bundler.require
require_relative 'models/all'
module Sinatra
module UserHelper
# This incredibly useful helper gives us the currently logged in user. We
# keep track of that by just setting a session variable with their id. If it
# doesn't exist, we just want to return nil.
def current_user
return User.first(:id => session[:user_id]) if session[:user_id]
nil
end
# This very simple method checks if we've got a logged in user. That's pretty
# easy: just check our current_user.
def logged_in?
current_user != nil
end
# Our `admin_only!` helper will only let admin users visit the page. If
# they're not an admin, we redirect them to either / or the page that we
# specified when we called it.
def admin_only!(opts = {:return => "/"})
unless logged_in? && current_user.admin?
flash[:error] = "Sorry, buddy"
redirect opts[:return]
end
end
# Similar to `admin_only!`, `require_login!` only lets logged in users access
# a particular page, and redirects them if they're not.
def require_login!(opts = {:return => "/"})
unless logged_in?
flash[:error] = "Sorry, buddy"
redirect opts[:return]
end
end
end
helpers UserHelper
end
class Rstatus < Sinatra::Base
set :port, 8088
# The `PONY_VIA_OPTIONS` hash is used to configure `pony`. Basically, we only
# want to actually send mail if we're in the production environment. So we set
# the hash to just be `{}`, except when we want to send mail.
configure :test do
PONY_VIA_OPTIONS = {}
end
configure :development do
PONY_VIA_OPTIONS = {}
end
# We're using [SendGrid](http://sendgrid.com/) to send our emails. It's really
# easy; the Heroku addon sets us up with environment variables with all of the
# configuration options that we need.
configure :production do
PONY_VIA_OPTIONS = {
:address => "smtp.sendgrid.net",
:port => "25",
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => ENV['SENDGRID_DOMAIN']
}
end
use Rack::Session::Cookie, :secret => ENV['COOKIE_SECRET']
set :root, File.dirname(__FILE__)
set :haml, :escape_html => true
set :method_override, true
require 'rack-flash'
use Rack::Flash
configure do
if ENV['MONGOHQ_URL']
MongoMapper.config = {ENV['RACK_ENV'] => {'uri' => ENV['MONGOHQ_URL']}}
MongoMapper.database = ENV['MONGOHQ_DATABASE']
MongoMapper.connect("production")
else
MongoMapper.connection = Mongo::Connection.new('localhost')
MongoMapper.database = "rstatus-#{settings.environment}"
end
end
helpers Sinatra::UserHelper
helpers Sinatra::ContentFor
helpers do
[:development, :production, :test].each do |environment|
define_method "#{environment.to_s}?" do
return settings.environment == environment.to_sym
end
end
end
use OmniAuth::Builder do
provider :twitter, ENV["CONSUMER_KEY"], ENV["CONSUMER_SECRET"]
provider :facebook, ENV["APP_ID"], ENV["APP_SECRET"]
end
get '/' do
if logged_in?
params[:page] ||= 1
params[:per_page] ||= 25
params[:page] = params[:page].to_i
params[:per_page] = params[:per_page].to_i
@next_page = "?#{Rack::Utils.build_query :page => params[:page] + 1}"
if params[:page] > 1
@prev_page = "?#{Rack::Utils.build_query :page => params[:page] - 1}"
end
@updates = current_user.timeline(params)
@timeline = true
@update_text = ""
@update_id = ""
if params[:reply]
u = Update.first(:id => params[:reply])
@update_text = "@#{u.author.username} "
@update_id = u.id
elsif params[:share]
u = Update.first(:id => params[:share])
@update_text = "RT @#{u.author.username}: #{u.text}"
@update_id = u.id
end
if params[:status]
@update_text = @update_text + params[:status]
end
haml :dashboard
else
haml :index, :layout => false
end
end
get '/home' do
haml :index, :layout => false
end
get '/replies' do
if logged_in?
params[:page] ||= 1
params[:per_page] ||= 25
params[:page] = params[:page].to_i
params[:per_page] = params[:per_page].to_i
@next_page = "?#{Rack::Utils.build_query :page => params[:page] + 1}"
if params[:page] > 1
@prev_page = "?#{Rack::Utils.build_query :page => params[:page] - 1}"
end
@replies = current_user.at_replies(params)
haml :replies
else
haml :index, :layout => false
end
end
get '/auth/:provider/callback' do
auth = request.env['omniauth.auth']
unless @auth = Authorization.find_from_hash(auth)
if User.first :username => auth['user_info']['nickname']
#we have a username conflict!
#let's store their oauth stuff so they don't have to re-login after
session[:oauth_token] = auth['credentials']['token']
session[:oauth_secret] = auth['credentials']['secret']
session[:uid] = auth['uid']
session[:provider] = auth['provider']
session[:name] = auth['user_info']['name']
session[:nickname] = auth['user_info']['nickname']
session[:website] = auth['user_info']['urls']['Website']
session[:description] = auth['user_info']['description']
session[:image] = auth['user_info']['image']
flash[:notice] = "Sorry, someone has that name."
redirect '/users/new'
return
else
@auth = Authorization.create_from_hash(auth, uri("/"), current_user)
end
end
session[:oauth_token] = auth['credentials']['token']
session[:oauth_secret] = auth['credentials']['secret']
session[:user_id] = @auth.user.id
flash[:notice] = "You're now logged in."
redirect '/'
end
get '/users/new' do
haml :"users/new"
end
post '/users' do
user = User.new params
if user.save
#this is really stupid.
auth = {}
auth['uid'] = session[:uid]
auth['provider'] = session[:provider]
auth['user_info'] = {}
auth['user_info']['name'] = session[:name]
auth['user_info']['nickname'] = session[:nickname]
auth['user_info']['urls'] = {}
auth['user_info']['urls']['Website'] = session[:website]
auth['user_info']['description'] = session[:description]
auth['user_info']['image'] = session[:image]
Authorization.create_from_hash(auth, uri("/"), user)
flash[:notice] = "Thanks! You're all signed up with #{user.username} for your username."
session[:user_id] = user.id
redirect '/'
else
flash[:notice] = "Oops! That username was taken. Pick another?"
redirect '/users/new'
end
end
get "/logout" do
session[:user_id] = nil
flash[:notice] = "You've been logged out."
redirect '/'
end
# show user profile
get "/users/:slug" do
params[:page] ||= 1
params[:per_page] ||= 20
params[:page] = params[:page].to_i
params[:per_page] = params[:per_page].to_i
user = User.first :username => params[:slug]
@author = user.author
#XXX: the following doesn't work for some reasond
# @updates = user.feed.updates.sort{|a, b| b.created_at <=> a.created_at}.paginate(:page => params[:page], :per_page => params[:per_page])
#XXX: this is not webscale
@updates = Update.where(:feed_id => user.feed.id).order(['created_at', 'descending']).paginate(:page => params[:page], :per_page => params[:per_page])
@next_page = nil
@prev_page = nil
@next_page = "?#{Rack::Utils.build_query :page => params[:page] + 1}"
if params[:page] > 1
@prev_page = "?#{Rack::Utils.build_query :page => params[:page] - 1}"
end
haml :"users/show"
end
# subscriber receives updates
# should be 'put', PuSH sucks at REST
post "/feeds/:id.atom" do
feed = Feed.first :id => params[:id]
feed.update_entries(request.body.read, request.url, url(feed.url), request.env['HTTP_X_HUB_SIGNATURE'])
end
# unsubscribe from a feed
delete '/subscriptions/:id' do
require_login! :return => "/subscriptions/#{params[:id]}"
feed = Feed.first :id => params[:id]
@author = feed.author
redirect "/" and return if @author.user == current_user
#make sure we're following them already
unless current_user.following? feed.url
flash[:notice] = "You're not following #{@author.username}."
redirect "/"
return
end
#unfollow them!
current_user.unfollow! feed
flash[:notice] = "No longer following #{@author.username}."
redirect "/"
end
post "/subscriptions" do
require_login! :return => "/subscriptions"
feed_url = params[:url]
if feed_url[0..3] == "feed"
feed_url = "http" + feed_url[4..-1]
end
#make sure we're not following them already
if current_user.following? feed_url
# which means it exists
feed = Feed.first(:remote_url => feed_url)
if feed.nil? and feed_url[0] == "/"
feed_id = feed_url[/^\/feeds\/(.+)$/,1]
feed = Feed.first(:id => feed_id)
end
flash[:notice] = "You're already following #{feed.author.username}."
if feed.local
redirect "/users/#{feed.author.username}"
else
redirect "/"
end
return
end
# follow them!
f = current_user.follow! feed_url
unless f
flash[:notice] = "The was a problem following #{params[:url]}."
redirect "/follow"
return
end
if not f.local
# remote feeds require some talking to a hub
hub_url = f.hubs.first
sub = OSub::Subscription.new(url("/feeds/#{f.id}.atom"), f.url, f.secret)
sub.subscribe(hub_url, f.verify_token)
name = f.author.username
flash[:notice] = "Now following #{name}."
redirect "/"
else
# local feed... redirect to that user's profile
flash[:notice] = "Now following #{f.author.username}."
redirect "/users/#{f.author.username}"
end
end
# publisher will feed the atom to a hub
# subscribers will verify a subscription
get "/feeds/:id.atom" do
feed = Feed.first :id => params[:id]
if params['hub.challenge']
sub = OSub::Subscription.new(request.url, feed.url, nil, feed.verify_token)
# perform the hub's challenge
respond = sub.perform_challenge(params['hub.challenge'])
# verify that the random token is the same as when we
# subscribed with the hub initially and that the topic
# url matches what we expect
verified = params['hub.topic'] == feed.url
if verified and sub.verify_subscription(params['hub.verify_token'])
if development?
puts "Verified"
end
body respond[:body]
status respond[:status]
else
if development?
puts "Verification Failed"
end
# if the verification fails, the specification forces us to
# return a 404 status
status 404
end
else
# TODO: Abide by headers that supply cache information
body feed.atom(uri("/"))
end
end
# user edits own profile
get "/users/:username/edit" do
@user = User.first :username => params[:username]
if @user == current_user
haml :"users/edit"
else
redirect "/users/#{params[:username]}"
end
end
# user updates own profile
put "/users/:username" do
@user = User.first :username => params[:username]
if @user == current_user
@user.author.name = params[:name]
@user.author.email = params[:email]
@user.author.website = params[:website]
@user.author.bio = params[:bio]
@user.author.save
flash[:notice] = "Profile saved!"
redirect "/users/#{params[:username]}"
return
else
redirect "/users/#{params[:username]}"
end
end
# an alias for the route of the feed
get "/users/:name/feed" do
feed = User.first(:username => params[:name]).feed
redirect "/feeds/#{feed.id}.atom"
end
# This lets us see who is following.
get '/users/:name/following' do
params[:page] ||= 1
params[:per_page] ||= 20
params[:page] = params[:page].to_i
params[:per_page] = params[:per_page].to_i
feeds = User.first(:username => params[:name]).following
@users = feeds.paginate(:page => params[:page], :per_page => params[:per_page])
@next_page = nil
@prev_page = nil
if params[:page]*params[:per_page] < feeds.count
@next_page = "?#{Rack::Utils.build_query :page => params[:page] + 1}"
end
if params[:page] > 1
@prev_page = "?#{Rack::Utils.build_query :page => params[:page] - 1}"
end
haml :"users/list", :locals => {:title => "Following"}
end
get '/users/:name/followers' do
params[:page] ||= 1
params[:per_page] ||= 20
params[:page] = params[:page].to_i
params[:per_page] = params[:per_page].to_i
feeds = User.first(:username => params[:name]).followers
@users = feeds.paginate(:page => params[:page], :per_page => params[:per_page])
@next_page = nil
@prev_page = nil
if params[:page]*params[:per_page] < feeds.count
@next_page = "?#{Rack::Utils.build_query :page => params[:page] + 1}"
end
if params[:page] > 1
@prev_page = "?#{Rack::Utils.build_query :page => params[:page] - 1}"
end
haml :"users/list", :locals => {:title => "Followers"}
end
post '/updates' do
u = Update.new(:text => params[:text],
:referral_id => params[:referral_id],
:author => current_user.author,
:oauth_token => session[:oauth_token],
:oauth_secret => session[:oauth_secret])
# and entry to user's feed
current_user.feed.updates << u
current_user.feed.save
current_user.save
# tell hubs there is a new entry
current_user.feed.ping_hubs(url(current_user.feed.url))
flash[:notice] = "Update created."
redirect "/"
end
get '/updates/:id' do
@update = Update.first :id => params[:id]
@referral = @update.referral
haml :"updates/show", :layout => :'updates/layout'
end
post '/signup' do
u = User.create(:email => params[:email],
:status => "unconfirmed")
u.set_perishable_token
if development?
puts uri("/") + "confirm/#{u.perishable_token}"
else
Notifier.send_signup_notification(params[:email], u.perishable_token)
end
haml :"signup/thanks"
end
get "/confirm/:token" do
@user = User.first :perishable_token => params[:token]
# XXX: Handle user being nil (invalid confirmation)
@username = @user.email.match(/^([^@]+?)@/)[1]
@valid_username = false
unless User.first :username => @username
@valid_username = true
end
haml :"signup/confirm"
end
post "/confirm" do
user = User.first :perishable_token => params[:perishable_token]
user.username = params[:username]
user.password = params[:password]
user.status = "confirmed"
user.author = Author.create(:username => user.username,
:email => user.email)
# propagate the authorship to their feed as well
user.feed.author = user.author
user.feed.save
user.save
session[:user_id] = user.id.to_s
flash[:notice] = "Thanks for signing up!"
redirect '/'
end
get "/login" do
haml :"login"
end
post "/login" do
if user = User.authenticate(params[:username], params[:password])
session[:user_id] = user.id
flash[:notice] = "Login successful."
redirect "/"
else
flash[:notice] = "The username or password you entered was incorrect"
redirect "/login"
end
end
delete '/updates/:id' do |id|
update = Update.first :id => params[:id]
if update.author == current_user.author
update.destroy
flash[:notice] = "Update Baleeted!"
redirect "/"
else
flash[:notice] = "I'm afraid I can't let you do that, " + current_user.name + "."
redirect back
end
end
not_found do
haml :'404', :layout => false
end
get "/hashtags/:tag" do
@hashtag = params[:tag]
params[:page] ||= 1
params[:per_page] ||= 25
params[:page] = params[:page].to_i
params[:per_page] = params[:per_page].to_i
@next_page = "?#{Rack::Utils.build_query :page => params[:page] + 1}"
if params[:page] > 1
@prev_page = "?#{Rack::Utils.build_query :page => params[:page] - 1}"
end
@updates = Update.hashtag_search(@hashtag, params)
@timeline = true
@update_text = params[:status]
haml :dashboard
end
get "/open_source" do
haml :opensource
end
get "/follow" do
haml :external_subscription
end
get "/contact" do
haml :contact
end
end