yenu/_scripts/migrate.rb

58 lines
2.4 KiB
Ruby
Executable file

#!/usr/bin/env ruby
require "rubygems"
require "sqlite3"
require "pp"
require "date"
require "reverse_markdown"
require "fileutils"
mg_db = SQLite3::Database.new "baby-mediagoblin/mediagoblin.db"
yenu_db = SQLite3::Database.new "yenu_dev.db"
data_dir = 'baby-mediagoblin/user_dev/media/public/media_entries'
target_data_dir = '/home/aaron/workbench/yenu/data/to-process'
# Read all images, comments, tags
# Associate the image, build the hash, move to target
mg_db.execute("SELECT id, title, created, description FROM core__media_entries ORDER BY created ASC") do |entry|
entry_id, title, created, description = entry
created = DateTime.parse(created).strftime('%F %T')
description = ReverseMarkdown.convert(description)
comments = mg_db.execute("SELECT user.username, c.created, c.content FROM core__media_comments AS c INNER JOIN core__users AS user ON user.id = c.author WHERE c.media_entry = "+entry_id.to_s+" ORDER BY c.created ASC")
tags = mg_db.execute("SELECT name FROM core__media_tags WHERE media_entry = "+entry_id.to_s).flatten
filepath = nil
Dir.glob(data_dir + '/' + entry_id.to_s + '/*').each do |file|
next if file =~ /.*(thumbnail|medium)\..*/
filepath = file
end
yenu_db.execute("INSERT INTO images (hash, title, description, created_at)
VALUES ('<"+entry_id.to_s+">', '"+SQLite3::Database.quote(title)+"', '"+SQLite3::Database.quote(description)+"', '"+created+"')")
new_id = yenu_db.last_insert_row_id
comments.each do |comment|
username, created, content = comment
created = DateTime.parse(created).strftime('%F %T')
yenu_db.execute("INSERT INTO comments (image_id, author, comment, created_at)
VALUES ('"+new_id.to_s+"', '"+username+"', '"+SQLite3::Database.quote(content)+"', '"+created+"')")
end
tags.each do |tag|
yenu_db.execute('INSERT OR IGNORE INTO tags (tagname)
VALUES ("'+tag+'")')
tag_id = yenu_db.execute('SELECT id FROM tags WHERE tagname = "'+tag+'"')[0][0]
yenu_db.execute('INSERT INTO image_tags (image_id, tag_id)
VALUES ("'+new_id.to_s+'", "'+tag_id.to_s+'")')
end
if filepath and ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG'].include?(File.extname(filepath))
new_filename = new_id.to_s + File.extname(filepath)
puts "#{filepath} => #{new_filename}"
FileUtils.cp(filepath, File.join(target_data_dir, new_filename))
else
puts "ERROR: File not imported: #{filepath}"
end
end