notifications_controller.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 dismiss
  22. current_account.notifications.find_by!(id: params[:id]).destroy!
  23. render_empty
  24. end
  25. private
  26. def load_notifications
  27. cache_collection paginated_notifications, Notification
  28. end
  29. def paginated_notifications
  30. browserable_account_notifications.paginate_by_max_id(
  31. limit_param(DEFAULT_NOTIFICATIONS_LIMIT),
  32. params[:max_id],
  33. params[:since_id]
  34. )
  35. end
  36. def browserable_account_notifications
  37. current_account.notifications.browserable(exclude_types)
  38. end
  39. def target_statuses_from_notifications
  40. @notifications.reject { |notification| notification.target_status.nil? }.map(&:target_status)
  41. end
  42. def insert_pagination_headers
  43. set_pagination_headers(next_path, prev_path)
  44. end
  45. def next_path
  46. unless @notifications.empty?
  47. api_v1_notifications_url pagination_params(max_id: pagination_max_id)
  48. end
  49. end
  50. def prev_path
  51. unless @notifications.empty?
  52. api_v1_notifications_url pagination_params(since_id: pagination_since_id)
  53. end
  54. end
  55. def pagination_max_id
  56. @notifications.last.id
  57. end
  58. def pagination_since_id
  59. @notifications.first.id
  60. end
  61. def exclude_types
  62. val = params.permit(exclude_types: [])[:exclude_types] || []
  63. val = [val] unless val.is_a?(Enumerable)
  64. val
  65. end
  66. def pagination_params(core_params)
  67. params.slice(:limit, :exclude_types).permit(:limit, exclude_types: []).merge(core_params)
  68. end
  69. end