hummingbird-me/kitsu-server

View on GitHub
app/services/zorro/wrapper/thread_wrapper.rb

Summary

Maintainability
A
0 mins
Test Coverage
F
45%
module Zorro
  class Wrapper
    # A thread on aozora is a top-level post in one of three places:
    #  (1) implicitly wrapping episode discussion (has no content, is auto-generated)
    #  (2) In an aoDiscussion page
    #  (3) On an anime page (right-most tab)
    class ThreadWrapper < BasePost
      def self.wrap(data)
        new(data)
      end

      def save?
        # Drop autogenerated episodeDiscussion threads
        return false if @data['type'] == 'episodeDiscussion'
        true
      end

      # Aozora has a bunch of "subType" pages which work roughly like Groups on Kitsu, so we map
      # them to Groups during import.
      #
      # @return [Group, nil] the group that this thread will be sent to
      def target_group
        return unless @data['subType']
        return if anime_ids.present?
        Zorro::Groups.by_name(@data['subType'])
      end

      # @return [Anime, nil] the media referenced by the thread
      def media
        Mapping.lookup('aozora', anime_ids.first)
      end

      # Add the thread title to the existing content, and make it **bold** with markdown
      # @return [String] the text content of the post
      def content
        "**#{thread['title']}:**\n\n#{super}"
      end

      def to_h
        super.merge(
          target_group: target_group,
          media: media
        ).compact
      end

      private

      # @return [Array<String>] a list of Aozora anime IDs related to the post
      def anime_ids
        # Extract tags where className is Anime
        anime_tags = @data['tags']&.select { |tag| tag['className'] == 'Anime' } || []
        # Get the ID from those references
        anime_ids = anime_tags.map { |tag| tag['objectId'] }
        # Get the other ID from the _p_anime attribute
        anime_ids += @data['_p_anime'].split('$').last
        anime_ids.uniq
      end
    end
  end
end