From e739fa77012ccd31d7b92bbd7dd51f12461b41d6 Mon Sep 17 00:00:00 2001 From: antirez Date: Sun, 30 Oct 2011 14:17:01 +0100 Subject: [PATCH] getcomments API --- app.rb | 31 +++++++++++++++++++++++++++++++ comments.rb | 7 ++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/app.rb b/app.rb index b443f12..19573f5 100644 --- a/app.rb +++ b/app.rb @@ -726,6 +726,37 @@ def render_comment_subthread(comment,sep="") return { :status => "ok", :news => news, :count => numitems }.to_json end +get '/api/getcomments/:news_id' do + 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. # diff --git a/comments.rb b/comments.rb index ed72335..8e59c90 100644 --- a/comments.rb +++ b/comments.rb @@ -82,7 +82,7 @@ def del_comment(thread_id,comment_id) self.edit(thread_id,comment_id,{"del" => 1}) end - def render_comments(thread_id,root=-1,&block) + def fetch_thread(thread_id) byparent = {} @r.hgetall(thread_key(thread_id)).each{|id,comment| next if id == "nextid" @@ -93,6 +93,11 @@ def render_comments(thread_id,root=-1,&block) byparent[parent_id] = [] if !byparent.has_key?(parent_id) byparent[parent_id] << c } + byparent + end + + def render_comments(thread_id,root=-1,&block) + byparent = fetch_thread(thread_id) render_comments_rec(byparent,root,0,block) if byparent[-1] end