-
Notifications
You must be signed in to change notification settings - Fork 199
/
app.rb
2093 lines (1958 loc) · 70.5 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
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2011 Salvatore Sanfilippo. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY SALVATORE SANFILIPPO ''AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SALVATORE SANFILIPPO OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of Salvatore Sanfilippo.
require_relative 'app_config'
require 'rubygems'
require 'hiredis'
require 'redis'
require_relative 'page'
require 'sinatra'
require 'json'
require 'digest/sha1'
require 'digest/md5'
require_relative 'comments'
require_relative 'pbkdf2'
require_relative 'mail'
require_relative 'about'
require 'openssl' if UseOpenSSL
require 'uri'
Version = "0.11.0"
def setup_redis(uri=RedisURL)
uri = URI.parse(uri)
$r = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) unless $r
end
before do
setup_redis
H = HTMLGen.new if !defined?(H)
if !defined?(Comments)
Comments = RedisComments.new($r,"comment",proc{|c,level|
c.sort {|a,b|
ascore = compute_comment_score a
bscore = compute_comment_score b
if ascore == bscore
# If score is the same favor newer comments
b['ctime'].to_i <=> a['ctime'].to_i
else
# If score is different order by score.
# FIXME: do something smarter favouring newest comments
# but only in the short time.
bscore <=> ascore
end
}
})
end
$user = nil
auth_user(request.cookies['auth'])
increment_karma_if_needed if $user
end
get '/' do
H.set_title "#{SiteName} - #{SiteDescription}"
news,numitems = get_top_news
H.page {
H.h2 {"Top news"}+news_list_to_html(news)
}
end
get '/rss' do
content_type 'text/xml', :charset => 'utf-8'
news,count = get_latest_news
H.rss(:version => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom") {
H.channel {
H.title {
"#{SiteName}"
} + " " +
H.link {
"#{SiteUrl}"
} + " " +
H.description {
"Description pending"
} + " " +
news_list_to_rss(news)
}
}
end
get '/latest' do
redirect '/latest/0'
end
get '/latest/:start' do
start = params[:start].to_i
H.set_title "Latest news - #{SiteName}"
paginate = {
:get => Proc.new {|start,count|
get_latest_news(start,count)
},
:render => Proc.new {|item| news_to_html(item)},
:start => start,
:perpage => LatestNewsPerPage,
:link => "/latest/$"
}
H.page {
H.h2 {"Latest news"}+
H.section(:id => "newslist") {
list_items(paginate)
}
}
end
get '/saved/:start' do
redirect "/login" if !$user
start = params[:start].to_i
H.set_title "Saved news - #{SiteName}"
paginate = {
:get => Proc.new {|start,count|
get_saved_news($user['id'],start,count)
},
:render => Proc.new {|item| news_to_html(item)},
:start => start,
:perpage => SavedNewsPerPage,
:link => "/saved/$"
}
H.page {
H.h2 {"Your saved news"}+
H.section(:id => "newslist") {
list_items(paginate)
}
}
end
get '/usernews/:username/:start' do
start = params[:start].to_i
user = get_user_by_username(params[:username])
halt(404,"Non existing user") if !user
page_title = "News posted by #{user['username']}"
H.set_title "#{page_title} - #{SiteName}"
paginate = {
:get => Proc.new {|start,count|
get_posted_news(user['id'],start,count)
},
:render => Proc.new {|item| news_to_html(item)},
:start => start,
:perpage => SavedNewsPerPage,
:link => "/usernews/#{URI.encode(user['username'])}/$"
}
H.page {
H.h2 {page_title}+
H.section(:id => "newslist") {
list_items(paginate)
}
}
end
get '/usercomments/:username/:start' do
start = params[:start].to_i
user = get_user_by_username(params[:username])
halt(404,"Non existing user") if !user
H.set_title "#{user['username']} comments - #{SiteName}"
paginate = {
:get => Proc.new {|start,count|
get_user_comments(user['id'],start,count)
},
:render => Proc.new {|comment|
u = get_user_by_id(comment["user_id"]) || DeletedUser
comment_to_html(comment,u)
},
:start => start,
:perpage => UserCommentsPerPage,
:link => "/usercomments/#{URI.encode(user['username'])}/$"
}
H.page {
H.h2 {"#{H.entities user['username']} comments"}+
H.div("id" => "comments") {
list_items(paginate)
}
}
end
get '/replies' do
redirect "/login" if !$user
comments,count = get_user_comments($user['id'],0,SubthreadsInRepliesPage)
H.set_title "Your threads - #{SiteName}"
H.page {
$r.hset("user:#{$user['id']}","replies",0)
H.h2 {"Your threads"}+
H.div("id" => "comments") {
aux = ""
comments.each{|c|
aux << render_comment_subthread(c)
}
aux
}
}
end
get '/login' do
H.set_title "Login - #{SiteName}"
H.page {
H.div(:id => "login") {
H.form(:name=>"f") {
H.label(:for => "username") {"username"}+
H.inputtext(:id => "username", :name => "username")+
H.label(:for => "password") {"password"}+
H.inputpass(:id => "password", :name => "password")+H.br+
H.checkbox(:name => "register", :value => "1")+
"create account"+H.br+
H.submit(:name => "do_login", :value => "Login")
}
}+
H.div(:id => "errormsg"){}+
H.a(:href=>"/reset-password") {"reset password"}+
H.script() {'
$(function() {
$("form[name=f]").submit(login);
});
'}
}
end
get '/reset-password' do
H.set_title "Reset Password - #{SiteName}"
H.page {
H.p {
"Welcome to the password reset procedure. Please specify the username and the email address you used to register to the site. "+H.br+
H.b {"Note that if you did not specify an email it is impossible for you to recover your password."}
}+
H.div(:id => "login") {
H.form(:name=>"f") {
H.label(:for => "username") {"username"}+
H.inputtext(:id => "username", :name => "username")+
H.label(:for => "password") {"email"}+
H.inputtext(:id => "email", :name => "email")+H.br+
H.submit(:name => "do_reset", :value => "Reset password")
}
}+
H.div(:id => "errormsg"){}+
H.script() {'
$(function() {
$("form[name=f]").submit(reset_password);
});
'}
}
end
get '/reset-password-ok' do
H.set_title "Reset link sent to your inbox"
H.page {
H.p {
"We sent an email to your inbox with a link that will let you reset your password."
}+
H.p {
"Please make sure to check the spam folder if the email does not appear in your inbox in a few minutes."
}+
H.p {
"The email contains a link that will automatically log into your account where you can set a new password in the account preferences."
}
}
end
get '/set-new-password' do
redirect '/' if (!check_params "user","auth")
user = get_user_by_username(params[:user])
if !user || user['auth'] != params[:auth]
H.page {
H.p {
"Link invalid or expired."
}
}
else
# Login the user and bring him to preferences to set a new password.
# Note that we update the auth token so this reset link will not
# work again.
update_auth_token(user["id"])
user = get_user_by_id(user["id"])
H.page {
H.script() {"
$(function() {
document.cookie =
'auth=#{user['auth']}'+
'; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/';
window.location.href = '/user/#{user['username']}';
});
"}
}
end
end
get '/submit' do
redirect "/login" if !$user
H.set_title "Submit a new story - #{SiteName}"
H.page {
H.h2 {"Submit a new story"}+
H.div(:id => "submitform") {
H.form(:name=>"f") {
H.inputhidden(:name => "news_id", :value => -1)+
H.label(:for => "title") {"title"}+
H.inputtext(:id => "title", :name => "title", :size => 80, :value => (params[:t] ? H.entities(params[:t]) : ""))+H.br+
H.label(:for => "url") {"url"}+H.br+
H.inputtext(:id => "url", :name => "url", :size => 60, :value => (params[:u] ? H.entities(params[:u]) : ""))+H.br+
"or if you don't have an url type some text"+
H.br+
H.label(:for => "text") {"text"}+
H.textarea(:id => "text", :name => "text", :cols => 60, :rows => 10) {}+
H.button(:name => "do_submit", :value => "Submit")
}
}+
H.div(:id => "errormsg"){}+
H.p {
bl = "javascript:window.location=%22#{SiteUrl}/submit?u=%22+encodeURIComponent(document.location)+%22&t=%22+encodeURIComponent(document.title)"
"Submitting news is simpler using the "+
H.a(:href => bl) {
"bookmarklet"
}+
" (drag the link to your browser toolbar)"
}+
H.script() {'
$(function() {
$("input[name=do_submit]").click(submit);
});
'}
}
end
get '/logout' do
if $user and check_api_secret
update_auth_token($user)
end
redirect "/"
end
get "/news/:news_id" do
news = get_news_by_id(params["news_id"])
halt(404,"404 - This news does not exist.") if !news
# Show the news text if it is a news without URL.
if !news_domain(news) and !news["del"]
c = {
"body" => news_text(news),
"ctime" => news["ctime"],
"user_id" => news["user_id"],
"thread_id" => news["id"],
"topcomment" => true
}
user = get_user_by_id(news["user_id"]) || DeletedUser
top_comment = H.topcomment {comment_to_html(c,user)}
else
top_comment = ""
end
H.set_title "#{news["title"]} - #{SiteName}"
H.page {
H.section(:id => "newslist") {
news_to_html(news)
}+top_comment+
if $user and !news["del"]
H.form(:name=>"f") {
H.inputhidden(:name => "news_id", :value => news["id"])+
H.inputhidden(:name => "comment_id", :value => -1)+
H.inputhidden(:name => "parent_id", :value => -1)+
H.textarea(:name => "comment", :cols => 60, :rows => 10) {}+H.br+
H.button(:name => "post_comment", :value => "Send comment")
}+H.div(:id => "errormsg"){}
else
H.br
end +
render_comments_for_news(news["id"])+
H.script() {'
$(function() {
$("input[name=post_comment]").click(post_comment);
});
'}
}
end
get "/comment/:news_id/:comment_id" do
news = get_news_by_id(params["news_id"])
halt(404,"404 - This news does not exist.") if !news
comment = Comments.fetch(params["news_id"],params["comment_id"])
halt(404,"404 - This comment does not exist.") if !comment
H.set_title "#{news["title"]} - #{SiteName}"
H.page {
H.section(:id => "newslist") {
news_to_html(news)
}+
render_comment_subthread(comment, H.h2 {"Replies"})
}
end
def render_comment_subthread(comment,sep="")
H.div(:class => "singlecomment") {
u = get_user_by_id(comment["user_id"]) || DeletedUser
comment_to_html(comment,u,true)
}+H.div(:class => "commentreplies") {
sep+
render_comments_for_news(comment['thread_id'],comment["id"].to_i)
}
end
get "/reply/:news_id/:comment_id" do
redirect "/login" if !$user
news = get_news_by_id(params["news_id"])
halt(404,"404 - This news does not exist.") if !news
comment = Comments.fetch(params["news_id"],params["comment_id"])
halt(404,"404 - This comment does not exist.") if !comment
user = get_user_by_id(comment["user_id"]) || DeletedUser
H.set_title "Reply to comment - #{SiteName}"
H.page {
news_to_html(news)+
comment_to_html(comment,user)+
H.form(:name=>"f") {
H.inputhidden(:name => "news_id", :value => news["id"])+
H.inputhidden(:name => "comment_id", :value => -1)+
H.inputhidden(:name => "parent_id", :value => params["comment_id"])+
H.textarea(:name => "comment", :cols => 60, :rows => 10) {}+H.br+
H.button(:name => "post_comment", :value => "Reply")
}+H.div(:id => "errormsg"){}+
H.script() {'
$(function() {
$("input[name=post_comment]").click(post_comment);
});
'}
}
end
get "/editcomment/:news_id/:comment_id" do
redirect "/login" if !$user
news = get_news_by_id(params["news_id"])
halt(404,"404 - This news does not exist.") if !news
comment = Comments.fetch(params["news_id"],params["comment_id"])
halt(404,"404 - This comment does not exist.") if !comment
user = get_user_by_id(comment["user_id"]) || DeletedUser
halt(500,"Permission denied.") if $user['id'].to_i != user['id'].to_i
H.set_title "Edit comment - #{SiteName}"
H.page {
news_to_html(news)+
comment_to_html(comment,user)+
H.form(:name=>"f") {
H.inputhidden(:name => "news_id", :value => news["id"])+
H.inputhidden(:name => "comment_id",:value => params["comment_id"])+
H.inputhidden(:name => "parent_id", :value => -1)+
H.textarea(:name => "comment", :cols => 60, :rows => 10) {
H.entities comment['body']
}+H.br+
H.button(:name => "post_comment", :value => "Edit")
}+H.div(:id => "errormsg"){}+
H.note {
"Note: to remove the comment, remove all the text and press Edit."
}+
H.script() {'
$(function() {
$("input[name=post_comment]").click(post_comment);
});
'}
}
end
get "/editnews/:news_id" do
redirect "/login" if !$user
news = get_news_by_id(params["news_id"])
halt(404,"404 - This news does not exist.") if !news
halt(500,"Permission denied.") if $user['id'].to_i != news['user_id'].to_i and !user_is_admin?($user)
if news_domain(news)
text = ""
else
text = news_text(news)
news['url'] = ""
end
H.set_title "Edit news - #{SiteName}"
H.page {
news_to_html(news)+
H.div(:id => "submitform") {
H.form(:name=>"f") {
H.inputhidden(:name => "news_id", :value => news['id'])+
H.label(:for => "title") {"title"}+
H.inputtext(:id => "title", :name => "title", :size => 80,
:value => news['title'])+H.br+
H.label(:for => "url") {"url"}+H.br+
H.inputtext(:id => "url", :name => "url", :size => 60,
:value => H.entities(news['url']))+H.br+
"or if you don't have an url type some text"+
H.br+
H.label(:for => "text") {"text"}+
H.textarea(:id => "text", :name => "text", :cols => 60, :rows => 10) {
H.entities(text)
}+H.br+
H.checkbox(:name => "del", :value => "1")+
"delete this news"+H.br+
H.button(:name => "edit_news", :value => "Edit")
}
}+
H.div(:id => "errormsg"){}+
H.script() {'
$(function() {
$("input[name=edit_news]").click(submit);
});
'}
}
end
get "/user/:username" do
user = get_user_by_username(params[:username])
halt(404,"Non existing user") if !user
posted_news,posted_comments = $r.pipelined {
$r.zcard("user.posted:#{user['id']}")
$r.zcard("user.comments:#{user['id']}")
}
H.set_title "#{user['username']} - #{SiteName}"
owner = $user && ($user['id'].to_i == user['id'].to_i)
H.page {
H.div(:class => "userinfo") {
H.span(:class => "avatar") {
email = user["email"] || ""
digest = Digest::MD5.hexdigest(email)
H.img(:src=>"//gravatar.com/avatar/#{digest}?s=48&d=mm")
}+" "+
H.h2 {H.entities user['username']}+
H.pre {
H.entities user['about']
}+
H.ul {
H.li {
H.b {"created "}+
str_elapsed(user['ctime'].to_i)
}+
H.li {H.b {"karma "}+ "#{user['karma']} points"}+
H.li {H.b {"posted news "}+posted_news.to_s}+
H.li {H.b {"posted comments "}+posted_comments.to_s}+
if owner
H.li {H.a(:href=>"/saved/0") {"saved news"}}
else "" end+
H.li {
H.a(:href=>"/usercomments/"+URI.encode(user['username'])+
"/0") {
"user comments"
}
}+
H.li {
H.a(:href=>"/usernews/"+URI.encode(user['username'])+
"/0") {
"user news"
}
}
}
}+if owner
H.br+H.form(:name=>"f") {
H.label(:for => "email") {
"email (not visible, used for gravatar)"
}+H.br+
H.inputtext(:id => "email", :name => "email", :size => 40,
:value => H.entities(user['email']))+H.br+
H.label(:for => "password") {
"change password (optional)"
}+H.br+
H.inputpass(:name => "password", :size => 40)+H.br+
H.label(:for => "about") {"about"}+H.br+
H.textarea(:id => "about", :name => "about", :cols => 60, :rows => 10){
H.entities(user['about'])
}+H.br+
H.button(:name => "update_profile", :value => "Update profile")
}+
H.div(:id => "errormsg"){}+
H.script() {'
$(function() {
$("input[name=update_profile]").click(update_profile);
});
'}
else "" end
}
end
get '/recompute' do
if $user and user_is_admin?($user)
$r.zrange("news.cron",0,-1).each{|news_id|
news = get_news_by_id(news_id)
score = compute_news_score(news)
rank = compute_news_rank(news)
$r.hmset("news:#{news_id}",
"score",score,
"rank",rank)
$r.zadd("news.top",rank,news_id)
}
H.page {
H.p {"Done."}
}
else
redirect "/"
end
end
get '/admin' do
redirect "/" if !$user || !user_is_admin?($user)
H.set_title "Admin Section - #{SiteName}"
H.page {
H.div(:id => "adminlinks") {
H.h2 {"Admin"}+
H.h3 {"Site stats"}+
generate_site_stats+
H.h3 {"Developer tools"}+
H.ul {
H.li {
H.a(:href=>"/recompute") {
"Recompute news score and rank (may be slow!)"
}
}+
H.li {
H.a(:href=>"/?debug=1") {
"Show annotated home page"
}
}
}
}
}
end
get '/random' do
counter = $r.get("news.count")
random = 1 + rand(counter.to_i)
if $r.exists("news:#{random}")
redirect "/news/#{random}"
else
redirect "/news/#{counter}"
end
end
###############################################################################
# API implementation
###############################################################################
post '/api/logout' do
content_type 'application/json'
if $user and check_api_secret
update_auth_token($user)
return {:status => "ok"}.to_json
else
return {
:status => "err",
:error => "Wrong auth credentials or API secret."
}.to_json
end
end
get '/api/login' do
content_type 'application/json'
if (!check_params "username","password")
return {
:status => "err",
:error => "Username and password are two required fields."
}.to_json
end
auth,apisecret = check_user_credentials(params[:username],
params[:password])
if auth
return {
:status => "ok",
:auth => auth,
:apisecret => apisecret
}.to_json
else
return {
:status => "err",
:error => "No match for the specified username / password pair."
}.to_json
end
end
get '/api/reset-password' do
content_type 'application/json'
if (!check_params "username","email")
return {
:status => "err",
:error => "Username and email are two required fields."
}.to_json
end
user = get_user_by_username(params[:username])
if user && user['email'] && user['email'] == params[:email]
id = user['id']
# Rate limit password reset attempts.
if (user['pwd_reset'] &&
(Time.now.to_i - user['pwd_reset'].to_i) < PasswordResetDelay)
return {
:status => "err",
:error => "Sorry, not enough time elapsed since last password reset request."
}.to_json
end
if send_reset_password_email(user)
# All fine, set the last password reset time to the current time
# for rate limiting purposes, and send the email with the reset
# link.
$r.hset("user:#{id}","pwd_reset",Time.now.to_i)
return {:status => "ok"}.to_json
else
return {
:status => "err",
:error => "Problem sending the email, please contact the site admin."
}.to_json
end
else
return {
:status => "err",
:error => "No match for the specified username / email pair."
}.to_json
end
end
post '/api/create_account' do
content_type 'application/json'
if (!check_params "username","password")
return {
:status => "err",
:error => "Username and password are two required fields."
}.to_json
end
if !params[:username].match(UsernameRegexp)
return {
:status => "err",
:error => "Username must match /#{UsernameRegexp.source}/"
}.to_json
end
if params[:password].length < PasswordMinLength
return {
:status => "err",
:error => "Password is too short. Min length: #{PasswordMinLength}"
}.to_json
end
auth,apisecret,errmsg = create_user(params[:username],params[:password])
if auth
return {:status => "ok", :auth => auth, :apisecret => apisecret}.to_json
else
return {
:status => "err",
:error => errmsg
}.to_json
end
end
post '/api/submit' do
content_type 'application/json'
return {:status => "err", :error => "Not authenticated."}.to_json if !$user
if not check_api_secret
return {:status => "err", :error => "Wrong form secret."}.to_json
end
# We can have an empty url or an empty first comment, but not both.
if (!check_params "title","news_id",:url,:text) or
(params[:url].length == 0 and
params[:text].length == 0)
return {
:status => "err",
:error => "Please specify a news title and address or text."
}.to_json
end
# Make sure the URL is about an acceptable protocol, that is
# http:// or https:// for now.
if params[:url].length != 0
if params[:url].index("http://") != 0 and
params[:url].index("https://") != 0
return {
:status => "err",
:error => "We only accept http:// and https:// news."
}.to_json
end
end
if params[:news_id].to_i == -1
if submitted_recently
return {
:status => "err",
:error => "You have submitted a story too recently, "+
"please wait #{allowed_to_post_in_seconds} seconds."
}.to_json
end
news_id = insert_news(params[:title],params[:url],params[:text],
$user["id"])
else
news_id = edit_news(params[:news_id],params[:title],params[:url],
params[:text],$user["id"])
if !news_id
return {
:status => "err",
:error => "Invalid parameters, news too old to be modified "+
"or url recently posted."
}.to_json
end
end
return {
:status => "ok",
:news_id => news_id.to_i
}.to_json
end
post '/api/delnews' do
content_type 'application/json'
return {:status => "err", :error => "Not authenticated."}.to_json if !$user
if not check_api_secret
return {:status => "err", :error => "Wrong form secret."}.to_json
end
if (!check_params "news_id")
return {
:status => "err",
:error => "Please specify a news title."
}.to_json
end
if del_news(params[:news_id],$user["id"])
return {:status => "ok", :news_id => -1}.to_json
end
return {:status => "err", :error => "News too old or wrong ID/owner."}.to_json
end
post '/api/votenews' do
content_type 'application/json'
return {:status => "err", :error => "Not authenticated."}.to_json if !$user
if not check_api_secret
return {:status => "err", :error => "Wrong form secret."}.to_json
end
# Params sanity check
if (!check_params "news_id","vote_type") or (params["vote_type"] != "up" and
params["vote_type"] != "down")
return {
:status => "err",
:error => "Missing news ID or invalid vote type."
}.to_json
end
# Vote the news
vote_type = params["vote_type"].to_sym
karma,error = vote_news(params["news_id"].to_i,$user["id"],vote_type)
if karma
return { :status => "ok" }.to_json
else
return { :status => "err",
:error => error }.to_json
end
end
post '/api/postcomment' do
content_type 'application/json'
return {:status => "err", :error => "Not authenticated."}.to_json if !$user
if not check_api_secret
return {:status => "err", :error => "Wrong form secret."}.to_json
end
# Params sanity check
if (!check_params "news_id","comment_id","parent_id",:comment)
return {
:status => "err",
:error => "Missing news_id, comment_id, parent_id, or comment
parameter."
}.to_json
end
info = insert_comment(params["news_id"].to_i,$user['id'],
params["comment_id"].to_i,
params["parent_id"].to_i,params["comment"])
return {
:status => "err",
:error => "Invalid news, comment, or edit time expired."
}.to_json if !info
return {
:status => "ok",
:op => info['op'],
:comment_id => info['comment_id'],
:parent_id => params['parent_id'],
:news_id => params['news_id']
}.to_json
end
post '/api/updateprofile' do
content_type 'application/json'
return {:status => "err", :error => "Not authenticated."}.to_json if !$user
if not check_api_secret
return {:status => "err", :error => "Wrong form secret."}.to_json
end
if !check_params(:about, :email, :password)
return {:status => "err", :error => "Missing parameters."}.to_json
end
if params[:password].length > 0
if params[:password].length < PasswordMinLength
return {
:status => "err",
:error => "Password is too short. "+
"Min length: #{PasswordMinLength}"
}.to_json
end
$r.hmset("user:#{$user['id']}","password",
hash_password(params[:password],$user['salt']))
end
$r.hmset("user:#{$user['id']}",
"about", params[:about][0..4095],
"email", params[:email][0..255])
return {:status => "ok"}.to_json
end
post '/api/votecomment' do
content_type 'application/json'
return {:status => "err", :error => "Not authenticated."}.to_json if !$user
if not check_api_secret
return {:status => "err", :error => "Wrong form secret."}.to_json
end
# Params sanity check
if (!check_params "comment_id","vote_type") or
(params["vote_type"] != "up" and
params["vote_type"] != "down")
return {
:status => "err",
:error => "Missing comment ID or invalid vote type."
}.to_json
end
# Vote the news
vote_type = params["vote_type"].to_sym
news_id,comment_id = params["comment_id"].split("-")
if vote_comment(news_id.to_i,comment_id.to_i,$user["id"],vote_type)
return { :status => "ok", :comment_id => params["comment_id"] }.to_json
else
return { :status => "err",
:error => "Invalid parameters or duplicated vote." }.to_json
end
end
get '/api/getnews/:sort/:start/:count' do
content_type 'application/json'
sort = params[:sort].to_sym
start = params[:start].to_i
count = params[:count].to_i
if not [:latest,:top].index(sort)
return {:status => "err", :error => "Invalid sort parameter"}.to_json
end
return {:status => "err", :error => "Count is too big"}.to_json if count > APIMaxNewsCount
start = 0 if start < 0
getfunc = method((sort == :latest) ? :get_latest_news : :get_top_news)
news,numitems = getfunc.call(start,count)
news.each{|n|
['rank','score','user_id'].each{|field| n.delete(field)}
}
return { :status => "ok", :news => news, :count => numitems }.to_json
end
get '/api/getcomments/:news_id' do
content_type 'application/json'
return {
:status => "err",
:error => "Wrong news ID."
}.to_json if not get_news_by_id(params[:news_id])
thread = Comments.fetch_thread(params[:news_id])
top_comments = []
thread.each{|parent,replies|
if parent.to_i == -1
top_comments = replies
end
replies.each{|r|
user = get_user_by_id(r['user_id']) || DeletedUser
r['username'] = user['username']
r['replies'] = thread[r['id']] || []
if r['up']
r['voted'] = :up if $user && r['up'].index($user['id'].to_i)
r['up'] = r['up'].length
end
if r['down']
r['voted'] = :down if $user && r['down'].index($user['id'].to_i)
r['down'] = r['down'].length
end
['id','thread_id','score','parent_id','user_id'].each{|f|
r.delete(f)
}
}
}
return { :status => "ok", :comments => top_comments }.to_json
end
# Check that the list of parameters specified exist.
# If at least one is missing false is returned, otherwise true is returned.
#
# If a parameter is specified as as symbol only existence is tested.
# If it is specified as a string the parameter must also meet the condition
# of being a non empty string.
def check_params *required
required.each{|p|
params[p].strip! if params[p] and params[p].is_a? String
if !params[p] or (p.is_a? String and params[p].length == 0)
return false