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.

78 lines
2.0 KiB

  1. # frozen_string_literal: true
  2. class DeliverToDeviceService < BaseService
  3. include Payloadable
  4. class EncryptedMessage < ActiveModelSerializers::Model
  5. attributes :source_account, :target_account, :source_device,
  6. :target_device_id, :type, :body, :digest,
  7. :message_franking
  8. end
  9. def call(source_account, source_device, options = {})
  10. @source_account = source_account
  11. @source_device = source_device
  12. @target_account = Account.find(options[:account_id])
  13. @target_device_id = options[:device_id]
  14. @body = options[:body]
  15. @type = options[:type]
  16. @hmac = options[:hmac]
  17. set_message_franking!
  18. if @target_account.local?
  19. deliver_to_local!
  20. else
  21. deliver_to_remote!
  22. end
  23. end
  24. private
  25. def set_message_franking!
  26. @message_franking = message_franking.to_token
  27. end
  28. def deliver_to_local!
  29. target_device = @target_account.devices.find_by!(device_id: @target_device_id)
  30. target_device.encrypted_messages.create!(
  31. from_account: @source_account,
  32. from_device_id: @source_device.device_id,
  33. type: @type,
  34. body: @body,
  35. digest: @hmac,
  36. message_franking: @message_franking
  37. )
  38. end
  39. def deliver_to_remote!
  40. ActivityPub::DeliveryWorker.perform_async(
  41. Oj.dump(serialize_payload(ActivityPub::ActivityPresenter.from_encrypted_message(encrypted_message), ActivityPub::ActivitySerializer)),
  42. @source_account.id,
  43. @target_account.inbox_url
  44. )
  45. end
  46. def message_franking
  47. MessageFranking.new(
  48. source_account_id: @source_account.id,
  49. target_account_id: @target_account.id,
  50. hmac: @hmac,
  51. timestamp: Time.now.utc
  52. )
  53. end
  54. def encrypted_message
  55. EncryptedMessage.new(
  56. source_account: @source_account,
  57. target_account: @target_account,
  58. source_device: @source_device,
  59. target_device_id: @target_device_id,
  60. type: @type,
  61. body: @body,
  62. digest: @hmac,
  63. message_franking: @message_franking
  64. )
  65. end
  66. end