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.

74 lines
2.1 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: relays
  5. #
  6. # id :bigint(8) not null, primary key
  7. # inbox_url :string default(""), not null
  8. # enabled :boolean default(FALSE), not null
  9. # follow_activity_id :string
  10. # created_at :datetime not null
  11. # updated_at :datetime not null
  12. #
  13. class Relay < ApplicationRecord
  14. PRESET_RELAY = 'https://relay.joinmastodon.org/inbox'
  15. validates :inbox_url, presence: true, uniqueness: true, url: true, if: :will_save_change_to_inbox_url?
  16. scope :enabled, -> { where(enabled: true) }
  17. before_destroy :ensure_disabled
  18. def enable!
  19. activity_id = ActivityPub::TagManager.instance.generate_uri_for(nil)
  20. payload = Oj.dump(follow_activity(activity_id))
  21. ActivityPub::DeliveryWorker.perform_async(payload, some_local_account.id, inbox_url)
  22. update(enabled: true, follow_activity_id: activity_id)
  23. end
  24. def disable!
  25. activity_id = ActivityPub::TagManager.instance.generate_uri_for(nil)
  26. payload = Oj.dump(unfollow_activity(activity_id))
  27. ActivityPub::DeliveryWorker.perform_async(payload, some_local_account.id, inbox_url)
  28. update(enabled: false, follow_activity_id: nil)
  29. end
  30. private
  31. def follow_activity(activity_id)
  32. {
  33. '@context': ActivityPub::TagManager::CONTEXT,
  34. id: activity_id,
  35. type: 'Follow',
  36. actor: ActivityPub::TagManager.instance.uri_for(some_local_account),
  37. object: ActivityPub::TagManager::COLLECTIONS[:public],
  38. }
  39. end
  40. def unfollow_activity(activity_id)
  41. {
  42. '@context': ActivityPub::TagManager::CONTEXT,
  43. id: activity_id,
  44. type: 'Undo',
  45. actor: ActivityPub::TagManager.instance.uri_for(some_local_account),
  46. object: {
  47. id: follow_activity_id,
  48. type: 'Follow',
  49. actor: ActivityPub::TagManager.instance.uri_for(some_local_account),
  50. object: ActivityPub::TagManager::COLLECTIONS[:public],
  51. },
  52. }
  53. end
  54. def some_local_account
  55. @some_local_account ||= Account.local.find_by(suspended: false)
  56. end
  57. def ensure_disabled
  58. return unless enabled?
  59. disable!
  60. end
  61. end