#!/usr/bin/ruby
require 'narou'
require 'fileutils'
$: << File.join(Narou.get_script_dir, "lib")
require 'downloader'
require 'helper'
abort "Usage: $myepubsplit.rb novel_id split_size" if ARGV.size == 0
novel_id = Integer(ARGV[0])
data = Downloader.get_data_by_target novel_id
abort "novel_id #{novel_id} が見つかりません" if data == nil
narou_root = Narou.get_root_dir
abort ".narou ディレクトリが見つかりません" if narou_root == nil
narou_dir = File.join(narou_root, ".narou")
author, title = %w(author title).map {|k|
Helper.replace_filename_special_chars(data[k], true)
}
novel_root = Downloader.get_novel_data_dir_by_target novel_id
novel_size = data['general_all_no']
if ARGV.size < 2
glob_pattern = File.join(novel_root, "raw", "*.txt")
sum_text = Dir.glob(glob_pattern).inject(0){|sum, x| sum += File.stat(x).size }
sum_text_mb = sum_text / 1024.0 / 1024
puts "#{'%4d'%novel_id} | #{'%4d'%novel_size} | #{'%6.3f'%sum_text_mb} | #{data['author']} | #{data['file_title']}"
exit
end
split_size = Integer(ARGV[1])
author_title = "[#{author}] #{title}"
full_author_title = File.join(novel_root, author_title)
# backup
latest_convert_yaml = File.join(narou_dir, "latest_convert.yaml")
latest_convert_yaml_backup = File.join(narou_dir, "latest_convert.yaml.backup")
converter_rb = File.join(novel_root, "converter.rb")
chosalog_txt = File.join(novel_root, "調査ログ.txt")
[latest_convert_yaml, latest_convert_yaml_backup, converter_rb, chosalog_txt].each {|target|
FileUtils.cp(target, target + ".orig") unless File.exists?(target + ".orig")
}
exts = %w(.txt .epub .mobi .kepub.epub .zip)
exts.each {|ext|
full_author_title_ext = full_author_title + ext
unless File.exists?(full_author_title_ext + ".orig")
FileUtils.mv(full_author_title_ext, full_author_title_ext + ".orig") if File.exists?(full_author_title_ext)
end
}
# convert
(1..novel_size).each_slice(split_size).each_with_index {|x, i|
File.open(converter_rb, "wb") {|f|
s = <<-"EOS"
converter \"#{data['file_title']}\" do
def before(io, text_type) super; @subtitles.select!{|t| #{x}.include?(t['index'].to_i)}; io; end
def after(io, text_type) super; io; end
end
EOS
f.write(s)
}
system("narou c #{novel_id}")
exts.each {|ext|
full_author_title_ext = full_author_title + ext
if File.exists?(full_author_title_ext)
FileUtils.mv(full_author_title_ext,
"#{author_title}_#{'%04d'%x[0]}-#{'%04d'%x[-1]}#{ext}")
end
}
}
# recovery
[latest_convert_yaml, latest_convert_yaml_backup, converter_rb, chosalog_txt].each {|target|
FileUtils.mv(target + ".orig", target) if File.exists?(target + ".orig")
}
exts.each {|ext|
full_author_title_ext = full_author_title + ext
FileUtils.mv(full_author_title_ext + ".orig", full_author_title_ext) if File.exists?(full_author_title_ext + ".orig")
}