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.

87 lines
2.3 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. DEFAULT_NOTIFICATIONS_LIMIT = 15
  8. def index
  9. @notifications = load_notifications
  10. render json: @notifications, each_serializer: REST::NotificationSerializer, relationships: StatusRelationshipsPresenter.new(target_statuses_from_notifications, current_user&.account_id)
  11. end
  12. def show
  13. @notification = current_account.notifications.without_suspended.find(params[:id])
  14. render json: @notification, serializer: REST::NotificationSerializer
  15. end
  16. def clear
  17. current_account.notifications.delete_all
  18. render_empty
  19. end
  20. def dismiss
  21. current_account.notifications.find_by!(id: params[:id]).destroy!
  22. render_empty
  23. end
  24. private
  25. def load_notifications
  26. cache_collection_paginated_by_id(
  27. browserable_account_notifications,
  28. Notification,
  29. limit_param(DEFAULT_NOTIFICATIONS_LIMIT),
  30. params_slice(:max_id, :since_id, :min_id)
  31. )
  32. end
  33. def browserable_account_notifications
  34. current_account.notifications.without_suspended.browserable(exclude_types, from_account)
  35. end
  36. def target_statuses_from_notifications
  37. @notifications.reject { |notification| notification.target_status.nil? }.map(&:target_status)
  38. end
  39. def insert_pagination_headers
  40. set_pagination_headers(next_path, prev_path)
  41. end
  42. def next_path
  43. unless @notifications.empty?
  44. api_v1_notifications_url pagination_params(max_id: pagination_max_id)
  45. end
  46. end
  47. def prev_path
  48. unless @notifications.empty?
  49. api_v1_notifications_url pagination_params(min_id: pagination_since_id)
  50. end
  51. end
  52. def pagination_max_id
  53. @notifications.last.id
  54. end
  55. def pagination_since_id
  56. @notifications.first.id
  57. end
  58. def exclude_types
  59. val = params.permit(exclude_types: [])[:exclude_types] || []
  60. val = [val] unless val.is_a?(Enumerable)
  61. val
  62. end
  63. def from_account
  64. params[:account_id]
  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