Advertisement
riocampos

gogakuondemand.rb (v3.2)

Aug 2nd, 2013
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 6.04 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. require 'kconv'
  10.  
  11. def check_ffmpeg_status
  12.   IO.popen('ffmpeg -version 2>&1') do |pipe|
  13.     status = pipe.inject('') { |total, line| total << line }
  14.     true if status =~ /openssl|gnutls/
  15.   end
  16. end
  17.  
  18. def load_pref
  19.   set_script_dir
  20.   load_pref_file
  21.   load_subjects_file
  22.   set_save_file_dest_dir
  23. end
  24.  
  25. def set_script_dir
  26.   @script_dir = File.expand_path(File.dirname(__FILE__))
  27.   push_dir(@script_dir)
  28. end
  29.  
  30. def load_pref_file
  31.   load './pref.rb'
  32.   @select_subjects_jp = []
  33.   pref.each do |k,v|
  34.     @select_subjects_jp << k if v
  35.   end
  36. end
  37.  
  38. def load_subjects_file
  39.   load './subjects.rb'
  40.   @select_subjects = []
  41.   @subject_urls = subject_urls
  42.   @subjects_jp  = subjects_jp
  43.   @select_subjects_jp.each do |sub_jp|
  44.     @select_subjects << @subjects_jp[sub_jp]
  45.   end
  46. end
  47.  
  48. def set_save_file_dest_dir
  49.   if save_file_dest_dir
  50.     if is_win?
  51.       dest_dir = save_file_dest_dir.gsub(/\\/, '/')
  52.       dest_dir = dest_dir.tosjis unless dest_dir =~ /^[\x20-\x7E]+$/
  53.     else
  54.       dest_dir = save_file_dest_dir
  55.     end
  56.     working_dir = File.expand_path(File.path(dest_dir))
  57.   else
  58.     working_dir = File.expand_path(File.dirname('.'))
  59.   end
  60.   Dir.mkdir(working_dir) unless File.directory?(working_dir)
  61.   push_dir(working_dir)
  62. end
  63.  
  64. def is_win?
  65.   RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|cygwin|bccwin/ ? true : false
  66. end
  67.  
  68. def print_download_subjects
  69.   download_subjects = @select_subjects_jp * "、"
  70.   print "ダウンロードする語学講座:#{download_subjects}\n\n"
  71. end
  72.  
  73. def https_body(url)
  74.   uri = URI.parse(url)
  75.   https = Net::HTTP.new(uri.host, uri.port)
  76.   https.use_ssl = true
  77.   https.ssl_version = :TLSv1
  78.   https.verify_mode = OpenSSL::SSL::VERIFY_NONE
  79.   if uri.query
  80.     https.get(uri.path + '?' + uri.query).body
  81.   else
  82.     https.get(uri.path).body
  83.   end
  84. end
  85.  
  86. def get_source_urls
  87.   data_hash ={}
  88.   @select_subjects.each do |sub|
  89.     url = "https://cgi2.nhk.or.jp/gogaku/#{@subject_urls[sub]}/listdataflv.xml"
  90.     doc = Nokogiri.XML(https_body(url))
  91.     data_array = doc.xpath("/musicdata/music")
  92.     date = data_array.map { |d| d["hdate"].scan(/(\d+)(\d+)/)} \
  93.           .map{ |dt| "#{record_year(dt[0][0].to_i)}_%02d_%02d" % dt.flatten}
  94.     data_hash[sub] = {kouza: data_array[0].values[2]}
  95.     data_array.each_with_index do |d, i|
  96.       data_hash[sub][{date: date[i]}] = data_array[i].values[4]
  97.     end
  98.   end
  99.   data_hash
  100. end
  101.  
  102. def record_year(record_month)
  103.   now = Time.now
  104.   this_month = now.month
  105.   this_year = now.year
  106.   @record_year = this_month - record_month < 0 ? this_year - 1 : this_year
  107. end
  108.  
  109. def prepare_download_each_subject(key, value)
  110.   @subject = value[:kouza]
  111.   puts "講座名:#{@subject}"
  112.   subject_dir = File.join(current_dir, key.to_s + "/")
  113.   Dir.mkdir(subject_dir) unless File.directory?(subject_dir)
  114.   subject_dir
  115. end
  116.  
  117. def each_date_process(key, value)
  118.   value.each do |k, v|
  119.     next if k == :kouza
  120.     @metadata = {}
  121.     date = k[:date]
  122.     @metadata[:subject]   = @subject
  123.     @metadata[:title]     = "#{key}_#{date}"
  124.     @metadata[:title_jp]  = "#{@subject}_#{date}"
  125.     @metadata[:genre]     = "Speech"
  126.     @metadata[:create]    = "NHK"
  127.     @metadata[:year]      = @record_year.to_s
  128.     puts "日付:#{date}"
  129.     download_ondemand_file(v)
  130.   end
  131. end
  132.  
  133. def download_ondemand_file(subject_code)
  134.   master_m3u8 = "https://nhk-vh.akamaihd.net/i/gogaku-stream/mp4/#{subject_code}/master.m3u8"
  135.   title_path_jp = is_win? ?
  136.                   File.join(current_dir, @metadata[:title_jp].tosjis) :
  137.                   File.join(current_dir, @metadata[:title_jp])
  138.   if is_win?
  139.     command_ffmpeg = %Q[ffmpeg -y -i #{master_m3u8} -ab 64k -metadata album="#{@metadata[:subject].tosjis}" -metadata title="#{@metadata[:title_jp].tosjis}" -metadata genre="#{@metadata[:genre]}" -metadata artist="#{@metadata[:create]}" -metadata date="#{@metadata[:year]}" -id3v2_version 3 "#{title_path_jp}.mp3" > nul 2>&1]
  140.     IO.popen(command_ffmpeg){ print "ダウンロード中...\n" }
  141.   else
  142.     command_ffmpeg = %Q[ffmpeg -y -i #{master_m3u8} -ab 64k -metadata album="#{@metadata[:subject]}" -metadata title="#{@metadata[:title_jp]}" -metadata genre="#{@metadata[:genre]}" -metadata artist="#{@metadata[:create]}" -metadata date="#{@metadata[:year]}" -id3v2_version 3 #{title_path_jp}.mp3 2>&1]
  143.     print "ダウンロード中...\n"
  144.     IO.popen(command_ffmpeg) do |pipe|
  145.       duration = nil
  146.       progress = 0
  147.       pipe.each("r") do |line|
  148.         if line =~ /: (\d{2}):(\d{2}):(\d{2}).(\d{2}),/
  149.           duration = (($1.to_i * 360000 + $2.to_i * 6000 + $3.to_i * 100 + $4.to_i) / 100.0).round
  150.         end
  151.         if line =~ /time=(\d{2}):(\d{2}):(\d{2}).(\d{2})/
  152.           progress = (($1.to_i * 360000 + $2.to_i * 6000 + $3.to_i * 100 + $4.to_i) / 100.0).round
  153.           progress = duration if duration && progress > duration
  154.         end
  155.         if duration
  156.           progress_bar(progress, duration, "秒")
  157.         end
  158.       end
  159.       print "\n"
  160.     end
  161.   end
  162. end
  163.  
  164. def progress_bar(progress, max, unit)
  165.   max_digits = max.to_s.size
  166.   print "\r" + "[#{'%-50s' % ('*' * (progress.to_f / max * 50).to_i)}] #{'%*d' % [max_digits, progress]} / #{max} #{unit}"
  167. end
  168.  
  169. def current_dir
  170.   @pwd
  171. end
  172.  
  173. def push_dir(dir)
  174.   @pwds ||= []
  175.   @pwds.push(dir)
  176.   @pwd = @pwds.last
  177.   Dir::chdir(@pwd)
  178.   @pwd
  179. end
  180.  
  181. def pop_dir
  182.   @pwds.pop
  183.   @pwd = @pwds.last
  184.   Dir::chdir(@pwd)
  185.   @pwd
  186. end
  187.  
  188. def gogaku_on_demand
  189.   unless check_ffmpeg_status
  190.     print "gogakuondemand.rbを実行するには\nOpenSSLまたはGnuTLSに対応しているFFmpegが必要です。\nFFmpegの設定を見直してください。\n"
  191.     return
  192.   end
  193.   load_pref
  194.   print_download_subjects
  195.   data_hash = get_source_urls
  196.   data_hash.each do |key, value|
  197.     subject_dir = prepare_download_each_subject(key, value)
  198.     push_dir(subject_dir)
  199.     each_date_process(key, value)
  200.     pop_dir
  201.   end
  202.   puts "作業終了"
  203. end
  204.  
  205. gogaku_on_demand
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement