You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.5 KiB

  1. # frozen_string_literal: true
  2. class Api::V1::NotificationsController < Api::BaseController
  3. before_action -> { doorkeeper_authorize! :read, :'read:notifications' }, except: [:clear, :dismiss]
  4. before_action -> { doorkeeper_authorize! :write, :'write:notifications' }, only: [:clear, :dismiss]
  5. before_action :require_user!
  6. after_action :insert_pagination_headers, only: :index
  7. respond_to :json
  8. DEFAULT_NOTIFICATIONS_LIMIT = 15
  9. def index
  10. @notifications = load_notifications
  11. render json: @notifications, each_serializer: REST::NotificationSerializer, relationships: StatusRelationshipsPresenter.new(target_statuses_from_notifications, current_user&.account_id)
  12. end
  13. def show
  14. @notification = current_account.notifications.find(params[:id])
  15. render json: @notification, serializer: REST::NotificationSerializer
  16. end
  17. def clear
  18. current_account.notifications.delete_all
  19. render_empty
  20. end
  21. def destroy
  22. dismiss
  23. end
  24. def dismiss
  25. current_account.notifications.find_by!(id: params[:id]).destroy!
  26. render_empty
  27. end
  28. def destroy_multiple
  29. current_account.notifications.where(id: params[:ids]).destroy_all
  30. render_empty
  31. end
  32. private
  33. def load_notifications
  34. cache_collection paginated_notifications, Notification
  35. end
  36. def paginated_notifications
  37. browserable_account_notifications.paginate_by_max_id(
  38. limit_param(DEFAULT_NOTIFICATIONS_LIMIT),
  39. params[:max_id],
  40. params[:since_id]
  41. )
  42. end
  43. def browserable_account_notifications
  44. current_account.notifications.browserable(exclude_types)
  45. end
  46. def target_statuses_from_notifications
  47. @notifications.reject { |notification| notification.target_status.nil? }.map(&:target_status)
  48. end
  49. def insert_pagination_headers
  50. set_pagination_headers(next_path, prev_path)
  51. end
  52. def next_path
  53. unless @notifications.empty?
  54. api_v1_notifications_url pagination_params(max_id: pagination_max_id)
  55. end
  56. end
  57. def prev_path
  58. unless @notifications.empty?
  59. api_v1_notifications_url pagination_params(since_id: pagination_since_id)
  60. end
  61. end
  62. def pagination_max_id
  63. @notifications.last.id
  64. end
  65. def pagination_since_id
  66. @notifications.first.id
  67. end
  68. def exclude_types
  69. val = params.permit(exclude_types: [])[:exclude_types] || []
  70. val = [val] unless val.is_a?(Enumerable)
  71. val
  72. end
  73. def pagination_params(core_params)
  74. params.slice(:limit, :exclude_types).permit(:limit, exclude_types: []).merge(core_params)
  75. end
  76. end