1
0

conversations_controller.rb 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 unread
  18. @conversation.update!(unread: true)
  19. render json: @conversation, serializer: REST::ConversationSerializer
  20. end
  21. def destroy
  22. @conversation.destroy!
  23. render_empty
  24. end
  25. private
  26. def set_conversation
  27. @conversation = AccountConversation.where(account: current_account).find(params[:id])
  28. end
  29. def paginated_conversations
  30. AccountConversation.where(account: current_account)
  31. .includes(
  32. account: :account_stat,
  33. last_status: [
  34. :media_attachments,
  35. :preview_cards,
  36. :status_stat,
  37. :tags,
  38. {
  39. active_mentions: [account: :account_stat],
  40. account: :account_stat,
  41. },
  42. ]
  43. )
  44. .to_a_paginated_by_id(limit_param(LIMIT), params_slice(:max_id, :since_id, :min_id))
  45. end
  46. def insert_pagination_headers
  47. set_pagination_headers(next_path, prev_path)
  48. end
  49. def next_path
  50. api_v1_conversations_url pagination_params(max_id: pagination_max_id) if records_continue?
  51. end
  52. def prev_path
  53. api_v1_conversations_url pagination_params(min_id: pagination_since_id) unless @conversations.empty?
  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