require 'cgi' require 'digest' require 'erb' require 'pathname' require 'uri' # A deliberately small current-state projection, always under public authority. class StaticMirror ORIGIN = 'https://hub.nizika.monster'.freeze PUBLICATION_POLICY = 'static-mirror-public-projection-1'.freeze DATA_AT_BASIS = 'capture_started_at'.freeze RESOURCE_LIMIT = 100 NAME_LIMIT = 2_000 MAX_BYTES = 8.megabytes EXCLUSIONS = [ 'historical_state', 'unversioned_resources', 'tag_descriptions', 'help', 'materials', 'external_tags', 'parent_relations', 'tag_sections', 'users', 'audit_data', 'authentication', 'editing', 'images', 'videos', 'resources_beyond_limits'].freeze class TooLarge < StandardError; end class UnsafeUrl < StandardError; end attr_reader :data_at, :authority, :counts def initialize(locale:, origin: ORIGIN) @locale = locale @origin = validated_url(origin).sub(%r{/+\z}, '') end def export(&progress) @files = { } @bytes = 0 HistoryAccess.set(user: nil) do capture progress&.call(0, @posts.length + @tags.length) generate_pages(&progress) raise HistoryAccess::Forbidden unless self.class.authorised_artifact?(authority) generated_at = Time.current.utc manifest = { format_version: 1, generated_at: generated_at.iso8601(6), data_at:, data_at_basis: DATA_AT_BASIS, locale: @locale.code, resources: counts, exclusions: EXCLUSIONS, fields: { posts: ['id', 'title', 'url', 'tags'], tags: ['id', 'category', 'names'] }, limits: { posts: RESOURCE_LIMIT, tags: RESOURCE_LIMIT, names: NAME_LIMIT, bytes: MAX_BYTES }, external_assets: 'not_included', checksum_scope: 'all_files_except_manifest.json', files: @files.map { |path, data| { path:, sha256: Digest::SHA256.hexdigest(data) } } } add_file('manifest.json', JSON.pretty_generate(manifest)) entries = @files.map do |path, data| MaterialZipExporter::Entry.new(path: "archive/#{ path }", data:, mtime: generated_at) end bytes = MaterialZipExporter::ZipWriter.write(entries) raise TooLarge if bytes.bytesize > MAX_BYTES bytes end end # Static distribution has no admin mode or Counts aggregate exception. # Recheck the exact public projection, including edits without a new discard. def self.authorised_artifact?(metadata) return false unless metadata['publication_policy'] == PUBLICATION_POLICY ids = metadata.values_at('post_ids', 'tag_ids') unless ids.all? { |values| values.is_a?(Array) && values.length <= RESOURCE_LIMIT && values.all? { _1.is_a?(Integer) && _1.positive? } } return false end HistoryAccess.set(user: nil) do ApplicationRecord.uncached do CountsExporter.with_read_snapshot do Locale.where(code: metadata['locale'], deprecated_at: nil).exists? && metadata['history_revision'] == HistoryAccess.revision && metadata['content_digest'] == projection_digest( read_projection(post_ids: ids[0], tag_ids: ids[1])) end end end rescue TooLarge false end def self.read_projection(post_ids: nil, tag_ids: nil) posts = confirmed(Post, PostVersion, :post_versions) tags = confirmed(Tag, TagVersion, :tag_versions).where(deprecated_at: nil) posts = posts.where(id: post_ids) unless post_ids.nil? tags = tags.where(id: tag_ids) unless tag_ids.nil? posts = posts.order(:id).limit(RESOURCE_LIMIT).select(:id, :version_no, :title, :url).to_a tags = tags.order(:id).limit(RESOURCE_LIMIT).select(:id, :version_no, :category).to_a names = TagName.where(tag_id: tags.map(&:id)).order(:tag_id, :language_code, :id) .limit(NAME_LIMIT + 1).pluck(:tag_id, :language_code, :script_code, :name, :primary_flg) raise TooLarge if names.length > NAME_LIMIT relations = PostTag.where(post_id: posts.map(&:id), tag_id: tags.map(&:id)) .order(:post_id, :tag_id).pluck(:post_id, :tag_id) [posts, tags, names, relations] end def self.confirmed(model, version_model, association) # Requiring a matching immutable revision closes the legacy unversioned gap. HistoryAccess.current(model.all, version_model).joins(association) .where("#{ version_model.table_name }.version_no = #{ model.table_name }.version_no") end def self.projection_digest(projection) posts, tags, names, relations = projection Digest::SHA256.hexdigest(JSON.generate( [posts.map(&:attributes), tags.map(&:attributes), names, relations])) end private_class_method :confirmed private def capture # Server clock at capture entry; MySQL establishes the read view later. @data_at = Time.current.utc.iso8601(6) CountsExporter.with_read_snapshot do projection = self.class.read_projection @posts, @tags, names, @relations = projection @authority = { 'publication_policy' => PUBLICATION_POLICY, 'locale' => @locale.code, 'history_revision' => HistoryAccess.revision, 'post_ids' => @posts.map(&:id), 'tag_ids' => @tags.map(&:id), 'content_digest' => self.class.projection_digest(projection) } @names = names.group_by(&:first) @counts = { posts: @posts.length, tags: @tags.length } end end def generate_pages assets = Rails.root.join('app/views/static_mirror') ['archive.css', 'archive.js'].each do |name| add_file("assets/#{ name }", assets.join(name).read) end add_file('robots.txt', "User-agent: *\nDisallow: /\n") add_file('archive-config.js', 'window.archiveConfig = { origin: null };') page('index.html', 'Static Mirror 生成機能', '', search_form + limitations) page("#{ @locale.code }/posts/index.html", 'Post', '/posts', post_list(@posts)) page("#{ @locale.code }/tags/index.html", 'Tag', '/tags', tag_list(@tags)) processed = 0 @posts.each do |post| tags = @tags.select { |tag| @relations.include?([post.id, tag.id]) } content = "
#{ external_link(post.url) }
#{ tag_list(tags) }" page(resource_path('posts', post.id), post.title.presence || post.id.to_s, "/posts/#{ post.id }", content) processed += 1 yield(processed, @posts.length + @tags.length) if block_given? end @tags.each do |tag| posts = @posts.select { |post| @relations.include?([post.id, tag.id]) } names = @names.fetch(tag.id, []).map do |_, language, script, name, _primary| "#{ h(tag.category) }
Tag Description, Help, Material, 外部タグ, 親子関係, 区間, 履歴, ログイン, 作成, 編輯
Post: #{ RESOURCE_LIMIT }, Tag: #{ RESOURCE_LIMIT }
TagName: #{ NAME_LIMIT }, #{ MAX_BYTES } B
ローカルへ取り込めていない資産: 外部画像や動画
公開抑止、除票、非公開情報、認証情報、監査専用情報を ZIP に含めない。
今回は現在状態のみの対応
HTML end end