The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

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