This commit is contained in:
2025-07-02 23:34:46 +09:00
parent e211d0ff52
commit 42cf25246f
+38 -7
View File
@@ -2,6 +2,16 @@ namespace :nico do
desc 'ニコニコ DB 同期' desc 'ニコニコ DB 同期'
task sync: :environment do task sync: :environment do
require 'open3' require 'open3'
require 'open-uri'
require 'nokogiri'
fetch_thumbnail = -> url {
html = URI.open(url, read_timeout: 60, 'User-Agent' => 'Mozilla/5.0').read
doc = Nokogiri::HTML(html)
doc.at('meta[name="thumbnail"]')&.[]('content').presence
}
mysql_user = ENV['MYSQL_USER'] mysql_user = ENV['MYSQL_USER']
mysql_pass = ENV['MYSQL_PASS'] mysql_pass = ENV['MYSQL_PASS']
nizika_nico_path = ENV['NIZIKA_NICO_PATH'] nizika_nico_path = ENV['NIZIKA_NICO_PATH']
@@ -18,18 +28,39 @@ namespace :nico do
unless post unless post
title = datum['title'] title = datum['title']
url = "https://www.nicovideo.jp/watch/#{ datum['code'] }" url = "https://www.nicovideo.jp/watch/#{ datum['code'] }"
post = Post.new(title:, url:, thumbnail_base: '', uploaded_user: nil) thumbnail_base = fetch_thumbnail.(url) || '' rescue ''
post = Post.new(title:, url:, thumbnail_base:, uploaded_user: nil)
if thumbnail_base.present?
post.thumbnail.attach(
io: URI.open(thumbnail_base),
filename: File.basename(URI.parse(thumbnail_base).path),
content_type: 'image/jpeg')
end
post.save! post.save!
post.resized_thumbnail!
end end
post.tags.destroy(post.tags.where(category: 'nico')) current_tags = post.tags.where(category: 'nico').pluck(:name).sort
datum['tags'].each do |name| new_tags = datum['tags'].map { |tag| "nico:#{ tag }" }.sort
name = "nico:#{ name }" if current_tags != new_tags
tag = Tag.find_or_initialize_by(name:, category: 'nico') post.tags.destroy(post.tags.where(name: current_tags))
post.tags << tag new_tags.each do |name|
post.tags << Tag.find_or_initialize_by(name:, category: 'nico')
end
if post.tags.size < 20
name = 'タグ希望'
post.tags.destroy(post.tags.find_by(name:))
post.tags << Tag.find_or_initialize_by(name:) { |tag|
tag.category = 'meta'
}
end
name = 'bot操作'
post.tags.destroy(post.tags.find_by(name:))
post.tags << Tag.find_or_initialize_by(name:) { |tag|
tag.category = 'meta'
}
end end
end end
end end
end end
end end