status_parser.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # frozen_string_literal: true
  2. class ActivityPub::Parser::StatusParser
  3. include JsonLdHelper
  4. # @param [Hash] json
  5. # @param [Hash] magic_values
  6. # @option magic_values [String] :followers_collection
  7. def initialize(json, magic_values = {})
  8. @json = json
  9. @object = json['object'] || json
  10. @magic_values = magic_values
  11. end
  12. def uri
  13. id = @object['id']
  14. if id&.start_with?('bear:')
  15. Addressable::URI.parse(id).query_values['u']
  16. else
  17. id
  18. end
  19. rescue Addressable::URI::InvalidURIError
  20. id
  21. end
  22. def url
  23. url_to_href(@object['url'], 'text/html') if @object['url'].present?
  24. end
  25. def text
  26. if @object['content'].present?
  27. @object['content']
  28. elsif content_language_map?
  29. @object['contentMap'].values.first
  30. end
  31. end
  32. def spoiler_text
  33. if @object['summary'].present?
  34. @object['summary']
  35. elsif summary_language_map?
  36. @object['summaryMap'].values.first
  37. end
  38. end
  39. def title
  40. if @object['name'].present?
  41. @object['name']
  42. elsif name_language_map?
  43. @object['nameMap'].values.first
  44. end
  45. end
  46. def created_at
  47. @object['published']&.to_datetime
  48. rescue ArgumentError
  49. nil
  50. end
  51. def edited_at
  52. @object['updated']&.to_datetime
  53. rescue ArgumentError
  54. nil
  55. end
  56. def reply
  57. @object['inReplyTo'].present?
  58. end
  59. def sensitive
  60. @object['sensitive']
  61. end
  62. def visibility
  63. if audience_to.any? { |to| ActivityPub::TagManager.instance.public_collection?(to) }
  64. :public
  65. elsif audience_cc.any? { |cc| ActivityPub::TagManager.instance.public_collection?(cc) }
  66. :unlisted
  67. elsif audience_to.include?(@magic_values[:followers_collection])
  68. :private
  69. else
  70. :direct
  71. end
  72. end
  73. def language
  74. if content_language_map?
  75. @object['contentMap'].keys.first
  76. elsif name_language_map?
  77. @object['nameMap'].keys.first
  78. elsif summary_language_map?
  79. @object['summaryMap'].keys.first
  80. end
  81. end
  82. private
  83. def audience_to
  84. as_array(@object['to'] || @json['to']).map { |x| value_or_id(x) }
  85. end
  86. def audience_cc
  87. as_array(@object['cc'] || @json['cc']).map { |x| value_or_id(x) }
  88. end
  89. def summary_language_map?
  90. @object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
  91. end
  92. def content_language_map?
  93. @object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
  94. end
  95. def name_language_map?
  96. @object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
  97. end
  98. end