Advertisement
riocampos

gogakuondemand.rb (v3.1)

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