triggers_subscriptions.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. # Trigger GraphQL subscriptions on avatar changes.
  3. module Avatar::TriggersSubscriptions
  4. extend ActiveSupport::Concern
  5. included do
  6. after_update_commit :update_avatar_subscription
  7. after_destroy_commit :destroy_avatar_subscription
  8. end
  9. private
  10. def update_avatar_subscription
  11. return if saved_changes.blank?
  12. return if !saved_changes.key?('default')
  13. # Following logic for checking if the subscription triggering is needed is applied:
  14. # If the default avatar was changed from false to true, we can skip the triggering if
  15. # a) the avatar is not initial.
  16. # b) there is already a default avatar that is not initial.
  17. if saved_changes['default'].first == false && saved_changes['default'].last == true
  18. return if !initial
  19. default_non_initial_avatar = Avatar.find_by(
  20. object_lookup_id:,
  21. o_id:,
  22. default: true,
  23. initial: false,
  24. )
  25. return if default_non_initial_avatar.present?
  26. end
  27. trigger_user_subscription
  28. end
  29. def destroy_avatar_subscription
  30. # We need to check if the default avatar was deleted.
  31. # If yes, there is no need to trigger the subscription,
  32. # because it will be triggered by changing the default state of the remaining avatar.
  33. return if default
  34. trigger_user_subscription
  35. end
  36. def trigger_user_subscription
  37. return if ObjectLookup.by_id(object_lookup_id) != 'User'
  38. Gql::Subscriptions::User::Current::AvatarUpdates.trigger(
  39. nil,
  40. arguments: {
  41. user_id: Gql::ZammadSchema.id_from_internal_id('User', o_id)
  42. }
  43. )
  44. end
  45. end