conversations_controller.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, relationships: StatusRelationshipsPresenter.new(@conversations.map(&:last_status), current_user&.account_id)
  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. .includes(
  28. account: :account_stat,
  29. last_status: [
  30. :media_attachments,
  31. :preview_cards,
  32. :status_stat,
  33. :tags,
  34. {
  35. active_mentions: [account: :account_stat],
  36. account: :account_stat,
  37. },
  38. ]
  39. )
  40. .to_a_paginated_by_id(limit_param(LIMIT), params_slice(:max_id, :since_id, :min_id))
  41. end
  42. def insert_pagination_headers
  43. set_pagination_headers(next_path, prev_path)
  44. end
  45. def next_path
  46. if records_continue?
  47. api_v1_conversations_url pagination_params(max_id: pagination_max_id)
  48. end
  49. end
  50. def prev_path
  51. unless @conversations.empty?
  52. api_v1_conversations_url pagination_params(min_id: pagination_since_id)
  53. end
  54. end
  55. def pagination_max_id
  56. @conversations.last.last_status_id
  57. end
  58. def pagination_since_id
  59. @conversations.first.last_status_id
  60. end
  61. def records_continue?
  62. @conversations.size == limit_param(LIMIT)
  63. end
  64. def pagination_params(core_params)
  65. params.slice(:limit).permit(:limit).merge(core_params)
  66. end
  67. end