media_attachment_parser.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # frozen_string_literal: true
  2. class ActivityPub::Parser::MediaAttachmentParser
  3. include JsonLdHelper
  4. def initialize(json)
  5. @json = json
  6. end
  7. # @param [MediaAttachment] previous_record
  8. def significantly_changes?(previous_record)
  9. remote_url != previous_record.remote_url ||
  10. thumbnail_remote_url != previous_record.thumbnail_remote_url ||
  11. description != previous_record.description
  12. end
  13. def remote_url
  14. Addressable::URI.parse(@json['url'])&.normalize&.to_s
  15. rescue Addressable::URI::InvalidURIError
  16. nil
  17. end
  18. def thumbnail_remote_url
  19. Addressable::URI.parse(@json['icon'].is_a?(Hash) ? @json['icon']['url'] : @json['icon'])&.normalize&.to_s
  20. rescue Addressable::URI::InvalidURIError
  21. nil
  22. end
  23. def description
  24. str = @json['summary'].presence || @json['name'].presence
  25. str = str.strip[0...MediaAttachment::MAX_DESCRIPTION_LENGTH] if str.present?
  26. str
  27. end
  28. def focus
  29. @json['focalPoint']
  30. end
  31. def blurhash
  32. supported_blurhash? ? @json['blurhash'] : nil
  33. end
  34. def file_content_type
  35. @json['mediaType']
  36. end
  37. private
  38. def supported_blurhash?
  39. components = begin
  40. blurhash = @json['blurhash']
  41. if blurhash.present? && /^[\w#$%*+,-.:;=?@\[\]^{|}~]+$/.match?(blurhash)
  42. Blurhash.components(blurhash)
  43. end
  44. end
  45. components.present? && components.none? { |comp| comp > 5 }
  46. end
  47. end