accounts_controller.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # frozen_string_literal: true
  2. class Api::V1::Lists::AccountsController < Api::BaseController
  3. before_action -> { doorkeeper_authorize! :read, :'read:lists' }, only: [:show]
  4. before_action -> { doorkeeper_authorize! :write, :'write:lists' }, except: [:show]
  5. before_action :require_user!
  6. before_action :set_list
  7. after_action :insert_pagination_headers, only: :show
  8. def show
  9. @accounts = load_accounts
  10. render json: @accounts, each_serializer: REST::AccountSerializer
  11. end
  12. def create
  13. ApplicationRecord.transaction do
  14. list_accounts.each do |account|
  15. @list.accounts << account
  16. end
  17. end
  18. render_empty
  19. end
  20. def destroy
  21. ListAccount.where(list: @list, account_id: account_ids).destroy_all
  22. render_empty
  23. end
  24. private
  25. def set_list
  26. @list = List.where(account: current_account).find(params[:list_id])
  27. end
  28. def load_accounts
  29. if unlimited?
  30. @list.accounts.without_suspended.includes(:account_stat).all
  31. else
  32. @list.accounts.without_suspended.includes(:account_stat).paginate_by_max_id(limit_param(DEFAULT_ACCOUNTS_LIMIT), params[:max_id], params[:since_id])
  33. end
  34. end
  35. def list_accounts
  36. Account.find(account_ids)
  37. end
  38. def account_ids
  39. Array(resource_params[:account_ids])
  40. end
  41. def resource_params
  42. params.permit(account_ids: [])
  43. end
  44. def insert_pagination_headers
  45. set_pagination_headers(next_path, prev_path)
  46. end
  47. def next_path
  48. return if unlimited?
  49. api_v1_list_accounts_url pagination_params(max_id: pagination_max_id) if records_continue?
  50. end
  51. def prev_path
  52. return if unlimited?
  53. api_v1_list_accounts_url pagination_params(since_id: pagination_since_id) unless @accounts.empty?
  54. end
  55. def pagination_max_id
  56. @accounts.last.id
  57. end
  58. def pagination_since_id
  59. @accounts.first.id
  60. end
  61. def records_continue?
  62. @accounts.size == limit_param(DEFAULT_ACCOUNTS_LIMIT)
  63. end
  64. def pagination_params(core_params)
  65. params.slice(:limit).permit(:limit).merge(core_params)
  66. end
  67. def unlimited?
  68. params[:limit] == '0'
  69. end
  70. end