conversations_controller.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # frozen_string_literal: true
  2. class Api::V1::ConversationsController < Api::BaseController
  3. LIMIT = 20
  4. before_action -> { doorkeeper_authorize! :read, :'read:statuses' }, only: :index
  5. before_action -> { doorkeeper_authorize! :write, :'write:conversations' }, except: :index
  6. before_action :require_user!
  7. before_action :set_conversation, except: :index
  8. after_action :insert_pagination_headers, only: :index
  9. def index
  10. @conversations = paginated_conversations
  11. render json: @conversations, each_serializer: REST::ConversationSerializer
  12. end
  13. def read
  14. @conversation.update!(unread: false)
  15. render json: @conversation, serializer: REST::ConversationSerializer
  16. end
  17. def destroy
  18. @conversation.destroy!
  19. render_empty
  20. end
  21. private
  22. def set_conversation
  23. @conversation = AccountConversation.where(account: current_account).find(params[:id])
  24. end
  25. def paginated_conversations
  26. AccountConversation.where(account: current_account)
  27. .to_a_paginated_by_id(limit_param(LIMIT), params_slice(:max_id, :since_id, :min_id))
  28. end
  29. def insert_pagination_headers
  30. set_pagination_headers(next_path, prev_path)
  31. end
  32. def next_path
  33. if records_continue?
  34. api_v1_conversations_url pagination_params(max_id: pagination_max_id)
  35. end
  36. end
  37. def prev_path
  38. unless @conversations.empty?
  39. api_v1_conversations_url pagination_params(min_id: pagination_since_id)
  40. end
  41. end
  42. def pagination_max_id
  43. @conversations.last.last_status_id
  44. end
  45. def pagination_since_id
  46. @conversations.first.last_status_id
  47. end
  48. def records_continue?
  49. @conversations.size == limit_param(LIMIT)
  50. end
  51. def pagination_params(core_params)
  52. params.slice(:limit).permit(:limit).merge(core_params)
  53. end
  54. end