about summary refs log tree commit diff
path: root/app/lib/activitypub/parser/media_attachment_parser.rb
blob: 1798e58a4bfa9b15f89e1a97c238493116fe2937 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true

class ActivityPub::Parser::MediaAttachmentParser
  include JsonLdHelper

  def initialize(json)
    @json = json
  end

  # @param [MediaAttachment] previous_record
  def significantly_changes?(previous_record)
    remote_url != previous_record.remote_url ||
      thumbnail_remote_url != previous_record.thumbnail_remote_url ||
      description != previous_record.description
  end

  def remote_url
    Addressable::URI.parse(@json['url'])&.normalize&.to_s
  rescue Addressable::URI::InvalidURIError
    nil
  end

  def thumbnail_remote_url
    Addressable::URI.parse(@json['icon'].is_a?(Hash) ? @json['icon']['url'] : @json['icon'])&.normalize&.to_s
  rescue Addressable::URI::InvalidURIError
    nil
  end

  def description
    @json['summary'].presence || @json['name'].presence
  end

  def focus
    @json['focalPoint']
  end

  def blurhash
    supported_blurhash? ? @json['blurhash'] : nil
  end

  def file_content_type
    @json['mediaType']
  end

  private

  def supported_blurhash?
    components = begin
      blurhash = @json['blurhash']

      if blurhash.present? && /^[\w#$%*+-.:;=?@\[\]^{|}~]+$/.match?(blurhash)
        Blurhash.components(blurhash)
      end
    end

    components.present? && components.none? { |comp| comp > 5 }
  end
end