Advertisement
riocampos

gogakuondemand.rb (v2.0)

Jul 29th, 2013
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 6.40 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. # coding: utf-8
  3.  
  4. # 全講座DLで約20分、約557MB(mp4からmp3への変換はPC能力に依存)
  5.  
  6. require 'nokogiri'
  7. require 'net/https'
  8. require 'fileutils'
  9.  
  10. def load_pref
  11.   set_script_dir
  12.   load_pref_file
  13.   load_subjects_file
  14.   set_save_file_dest_dir
  15. end
  16.  
  17. def set_script_dir
  18.   @script_dir = File.expand_path(File.dirname(__FILE__))
  19.   push_dir(@script_dir)
  20. end
  21.  
  22. def load_pref_file
  23.   load './pref.rb'
  24.   @select_subjects_jp = []
  25.   pref.each do |k,v|
  26.     @select_subjects_jp << k if v
  27.   end
  28. end
  29.  
  30. def load_subjects_file
  31.   load './subjects.rb'
  32.   @select_subjects = []
  33.   @subject_urls = subject_urls
  34.   @subjects_jp  = subjects_jp
  35.   @select_subjects_jp.each do |sub_jp|
  36.     @select_subjects << @subjects_jp[sub_jp]
  37.   end
  38. end
  39.  
  40. def set_save_file_dest_dir
  41.   working_dir = save_file_dest_dir ?
  42.                 File.expand_path(File.path(save_file_dest_dir)) :
  43.                 File.expand_path(File.dirname(__FILE__))
  44.   Dir.mkdir(working_dir) unless File.directory?(working_dir)
  45.   push_dir(working_dir)
  46. end
  47.  
  48. def print_download_subjects
  49.   download_subjects = @select_subjects_jp * "、"
  50.   print "ダウンロードする語学講座:#{download_subjects}\n\n"
  51. end
  52.  
  53. def https_body(url)
  54.   uri = URI.parse(url)
  55.   https = Net::HTTP.new(uri.host, uri.port)
  56.   https.use_ssl = true
  57.   https.ssl_version = :TLSv1
  58.   https.verify_mode = OpenSSL::SSL::VERIFY_PEER
  59.   if uri.query
  60.     https.get(uri.path + '?' + uri.query).body
  61.   else
  62.     https.get(uri.path).body
  63.   end
  64. end
  65.  
  66. def get_source_urls
  67.   data_hash ={}
  68.   @select_subjects.each do |sub|
  69.     url = "https://cgi2.nhk.or.jp/gogaku/#{@subject_urls[sub]}/listdataflv.xml"
  70.     doc = Nokogiri.XML(https_body(url))
  71.     data_array = doc.xpath("/musicdata/music")
  72.     date = data_array.map { |d| d["hdate"].scan(/(\d+)(\d+)/)} \
  73.           .map{ |dt| "#{record_year(dt[0][0].to_i)}_%02d_%02d" % dt.flatten}
  74.     data_hash[sub] = {kouza: data_array[0].values[2]}
  75.     data_array.each_with_index do |d, i|
  76.       data_hash[sub][{date: date[i]}] = data_array[i].values[4]
  77.     end
  78.   end
  79.   data_hash
  80. end
  81.  
  82. def record_year(record_month)
  83.   now = Time.now
  84.   this_month = now.month
  85.   this_year = now.year
  86.   @record_year = this_month - record_month < 0 ? this_year - 1 : this_year
  87. end
  88.  
  89. def prepare_download_each_subject(key, value)
  90.   @subject = value[:kouza]
  91.   puts "講座名:#{@subject}"
  92.   subject_dir = File.join(current_dir, key.to_s + "/")
  93.   Dir.mkdir(subject_dir) unless File.directory?(subject_dir)
  94.   subject_dir
  95. end
  96.  
  97. def each_date_process(value)
  98.   value.each do |k, v|
  99.     next if k == :kouza
  100.     @metadata = {}
  101.     date = k[:date]
  102.     @metadata[:subject] = @subject
  103.     @metadata[:title]   = "#{@subject}_#{date}"
  104.     @metadata[:genre]   = "Speech"
  105.     @metadata[:create]  = "NHK"
  106.     @metadata[:year]    = @record_year.to_s
  107.     puts "日付:#{date}"
  108.     merge_list = make_decrypt_key(v)
  109.     print "ファイル変換中...\n"
  110.     merge_mp4(merge_list)
  111.     convert_mp4_mp3
  112.     delete_temp_files
  113.     print "\n"
  114.   end
  115. end
  116.  
  117. def make_decrypt_key(subject_code)
  118.   master_m3u8 = "https://nhk-vh.akamaihd.net/i/gogaku-stream/mp4/#{subject_code}/master.m3u8"
  119.   index_m3u8_url = https_body(master_m3u8)[/http.*/]
  120.   source_urls = https_body(index_m3u8_url).lines.grep(/http/).map{ |url| url.strip }
  121.   crypt_key_url = source_urls.shift[/https:\/\/.*/][0..-2]
  122.   @decrypt_key = https_body(crypt_key_url).unpack('C'*16).inject(''){ |str, hex| str << '%02x' % hex }
  123.   make_merge_list(source_urls)
  124. end
  125.  
  126. def make_merge_list(urls)
  127.   temp_dir = File.join(current_dir, "temp/")
  128.   Dir.mkdir(temp_dir) unless File.directory?(temp_dir)
  129.   download_and_decrypt_gogaku_files(urls, temp_dir)
  130. end
  131.  
  132. def progress_bar(progress, max, unit)
  133.   max_digits = max.to_s.size
  134.   print "\r" + "[#{'%-50s' % ('*' * (progress.to_f / max * 50).to_i)}] #{'%*d' % [max_digits, progress]} / #{max} #{unit}"
  135. end
  136.  
  137. def download_and_decrypt_gogaku_files(urls, temp_dir)
  138.   merge_list = ""
  139.   max = urls.size
  140.   urls.each_with_index do |url, index|
  141.     uri = URI.parse(url)
  142.     http = Net::HTTP.new(uri.host, uri.port)
  143.     ts = http.get(uri.path + '?' + uri.query).body
  144.     iv = '%032x' % (index + 1)
  145.     temp_crypt_ts_path = File.join(temp_dir, "temp_#{index + 1}.crypt.ts")
  146.     temp_mp4_path = temp_crypt_ts_path.sub(/\.crypt\.ts/, '.mp4')
  147.     merge_list << "#{temp_mp4_path} "
  148.     open(temp_crypt_ts_path, "w"){ |f| f.write(ts) }
  149.     decrypt_command = %Q[openssl aes-128-cbc -d -in #{temp_crypt_ts_path} -out #{temp_mp4_path} -p -nosalt -iv #{iv} -K #{@decrypt_key}]
  150.     IO.popen(decrypt_command)
  151.     progress_bar(index + 1, max, "ファイル")
  152.   end
  153.   print "\n"
  154.   merge_list
  155. end
  156.  
  157. def merge_mp4(merge_list)
  158.   IO.popen("cat #{merge_list} > #{title_path}.mp4")
  159. end
  160.  
  161. def convert_mp4_mp3
  162.   command_ffmpeg = %Q[ffmpeg -y -i #{title_path}.mp4 -ab 64k -metadata album="#{@metadata[:subject]}" -metadata title="#{@metadata[:title]}" -metadata genre="#{@metadata[:genre]}" -metadata artist="#{@metadata[:create]}" -metadata date="#{@metadata[:year]}" -id3v2_version 3 #{title_path}.mp3 2>&1]
  163.   IO.popen(command_ffmpeg) do |pipe|
  164.     duration = nil
  165.     progress = 0
  166.     pipe.each("r") do |line|
  167.       if line =~ /: (\d{2}):(\d{2}):(\d{2}).(\d{2}),/
  168.         duration = (($1.to_i * 360000 + $2.to_i * 6000 + $3.to_i * 100 + $4.to_i) / 100.0).round
  169.       end
  170.       if line =~ /time=(\d{2}):(\d{2}):(\d{2}).(\d{2})/
  171.         progress = (($1.to_i * 360000 + $2.to_i * 6000 + $3.to_i * 100 + $4.to_i) / 100.0).round
  172.         progress = duration if duration && progress > duration
  173.       end
  174.       if duration
  175.         progress_bar(progress, duration, "秒")
  176.       end
  177.     end
  178.     print "\n"
  179.   end
  180. end
  181.  
  182. def delete_temp_files
  183.   temp_dir = File.join(current_dir, "temp/")
  184.   temp_mp4 = Dir.glob(File.join(current_dir, "*.mp4"))
  185.   FileUtils.rm_rf(temp_dir)
  186.   FileUtils.rm_f(temp_mp4)
  187. end
  188.  
  189. def current_dir
  190.   @pwd
  191. end
  192.  
  193. def title_path
  194.   File.join(current_dir, @metadata[:title])
  195. end
  196.  
  197. def push_dir(dir)
  198.   @pwds ||= []
  199.   @pwds.push(dir)
  200.   @pwd = @pwds.last
  201.   Dir::chdir(@pwd)
  202.   @pwd
  203. end
  204.  
  205. def pop_dir
  206.   @pwds.pop
  207.   @pwd = @pwds.last
  208.   Dir::chdir(@pwd)
  209.   @pwd
  210. end
  211.  
  212. def gogaku_on_demand
  213.   load_pref
  214.   print_download_subjects
  215.   data_hash = get_source_urls
  216.   data_hash.each do |key, value|
  217.     subject_dir = prepare_download_each_subject(key, value)
  218.     push_dir(subject_dir)
  219.     each_date_process(value)
  220.     pop_dir
  221.   end
  222.   puts "作業終了"
  223. end
  224.  
  225. gogaku_on_demand
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement