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.

88 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. 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. notifications = browserable_account_notifications.includes(from_account: :account_stat).to_a_paginated_by_id(
  27. limit_param(DEFAULT_NOTIFICATIONS_LIMIT),
  28. params_slice(:max_id, :since_id, :min_id)
  29. )
  30. Notification.preload_cache_collection_target_statuses(notifications) do |target_statuses|
  31. cache_collection(target_statuses, Status)
  32. end
  33. end
  34. def browserable_account_notifications
  35. current_account.notifications.without_suspended.browserable(exclude_types, from_account)
  36. end
  37. def target_statuses_from_notifications
  38. @notifications.reject { |notification| notification.target_status.nil? }.map(&:target_status)
  39. end
  40. def insert_pagination_headers
  41. set_pagination_headers(next_path, prev_path)
  42. end
  43. def next_path
  44. unless @notifications.empty?
  45. api_v1_notifications_url pagination_params(max_id: pagination_max_id)
  46. end
  47. end
  48. def prev_path
  49. unless @notifications.empty?
  50. api_v1_notifications_url pagination_params(min_id: pagination_since_id)
  51. end
  52. end
  53. def pagination_max_id
  54. @notifications.last.id
  55. end
  56. def pagination_since_id
  57. @notifications.first.id
  58. end
  59. def exclude_types
  60. val = params.permit(exclude_types: [])[:exclude_types] || []
  61. val = [val] unless val.is_a?(Enumerable)
  62. val
  63. end
  64. def from_account
  65. params[:account_id]
  66. end
  67. def pagination_params(core_params)
  68. params.slice(:limit, :exclude_types).permit(:limit, exclude_types: []).merge(core_params)
  69. end
  70. end