81 lines
3.1 KiB
Ruby
81 lines
3.1 KiB
Ruby
require 'json'
|
|
require 'tempfile'
|
|
require 'open3'
|
|
require 'fileutils'
|
|
require 'open-uri'
|
|
|
|
module JamRuby
|
|
|
|
# Interact with external python tools to create the JKZ
|
|
class JamTracksManager
|
|
class << self
|
|
def save_jam_track_jkz(user, jam_track)
|
|
jam_track_right = jam_track.right_for_user(user)
|
|
raise ArgumentError if jam_track_right.nil?
|
|
save_jam_track_right_jkz(jam_track_right)
|
|
end
|
|
|
|
def save_jam_track_right_jkz(jam_track_right)
|
|
jam_track = jam_track_right.jam_track
|
|
py_root = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "..", "..", "jamtracks"))
|
|
|
|
Dir.mktmpdir do |tmp_dir|
|
|
jam_file_opts=""
|
|
jam_track.jam_track_tracks.each do |jam_track_track|
|
|
nm=jam_track_track.filename
|
|
nm.gsub!(" ", "_")
|
|
track_filename = File.join(tmp_dir, nm)
|
|
track_url = jam_track_track.sign_url
|
|
copy_url_to_file(track_url, track_filename)
|
|
jam_file_opts << " -i '#{track_filename}+#{jam_track_track.part}'"
|
|
end
|
|
|
|
sku=jam_track.id
|
|
title=jam_track.name
|
|
output_jkz=File.join(tmp_dir, "#{title.parameterize}.jkz")
|
|
py_file = File.join(py_root, "jkcreate.py")
|
|
puts "Executing python source in #{py_file}, outputting to #{tmp_dir} (#{output_jkz})"
|
|
|
|
# From http://stackoverflow.com/questions/690151/getting-output-of-system-calls-in-ruby/5970819#5970819:
|
|
cli = "python #{py_file} -D -k #{sku} -p #{tmp_dir}/pkey.pem -s #{tmp_dir}/skey.pem #{jam_file_opts} -o #{output_jkz} -t '#{title}'"
|
|
Open3.popen3(cli) do |stdin, stdout, stderr, wait_thr|
|
|
pid = wait_thr.pid
|
|
exit_status = wait_thr.value
|
|
err = stderr.read(1000)
|
|
out = stdout.read(1000)
|
|
#puts "stdout: #{out}, stderr: #{err}"
|
|
raise ArgumentError, "Error calling python script: #{out}" if out && (out.index("No track files specified") || out.index("Cannot find file"))
|
|
raise ArgumentError, "Error calling python script: #{err}" if err.present?
|
|
jam_track_right[:url]
|
|
|
|
jam_track_right.url.store!(File.open(output_jkz))
|
|
jam_track_right.signed=true
|
|
jam_track_right.downloaded_since_sign=false
|
|
jam_track_right.save!
|
|
end
|
|
end # mktmpdir
|
|
jam_track_right
|
|
end # save_jam_track_jkz
|
|
|
|
def copy_url_to_file(url, filename)
|
|
uri = URI(url)
|
|
open(filename, 'wb') do |io|
|
|
Net::HTTP.start(uri.host, uri.port) do |http|
|
|
request = Net::HTTP::Get.new uri
|
|
http.request request do |response|
|
|
response_code = response.code.to_i
|
|
unless response_code >= 200 && response_code <= 299
|
|
raise "bad status code: #{response_code}. body: #{response.body}"
|
|
end
|
|
response.read_body do |chunk|
|
|
io.write chunk
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end # copy_url_to_file
|
|
|
|
end # self
|
|
end # class
|
|
end # module
|