Skip to content

Instantly share code, notes, and snippets.

@evoL
Created March 11, 2014 16:51
Show Gist options
  • Select an option

  • Save evoL/9489964 to your computer and use it in GitHub Desktop.

Select an option

Save evoL/9489964 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#-*- coding: utf-8 -*-
require 'open-uri'
require 'digest/md5'
class Napiprojekt
DOWNLOAD_URL = 'http://www.napiprojekt.pl/unit_napisy/dl.php?l=%s&f=%s&t=%s&v=other&kolejka=false&nick=%s&pass=%s&napios=%s'
ZIP_PASSWORD = 'iBlm8NTigvru0Jr0'
def initialize(file)
@file = file
@md5 = checksum(file)
@f = f_digest(@md5)
end
def download
# puts "MD5: #{md5}, F: #{f}"
url = DOWNLOAD_URL % [language, @md5, @f, nick, pass, 'Linux/UNIX']
result = open(url, 'r') { |io| io.read }
return nil if result.start_with? 'NPc'
result
end
def extract
dir = File.dirname(File.realpath(@file))
input_subtitle_file = File.join(dir, @md5 + '.txt')
output_subtitle_file = File.join(dir, File.basename(@file).rpartition('.').first + '.txt')
path_7za = `which 7za`.strip
`#{path_7za} x -p#{ZIP_PASSWORD} -o"#{dir}" "#{archive_name}" 2>&1`
File.rename(input_subtitle_file, output_subtitle_file)
output_subtitle_file
end
def get_subtitles
data = download
return nil if data.nil?
File.write(archive_name, data, :mode => 'w')
path = extract
File.delete(archive_name)
path
end
private
def archive_name
@file.sub(/\.\w{2,4}$/, '.7z')
end
def language
'PL'
end
def nick
''
end
def pass
''
end
def checksum(file)
content = open(file, 'r') { |io| io.read(10485760) }
Digest::MD5.hexdigest(content)
end
# WTF
def f_digest(md5sum)
# raise 'Not a MD5 sum' unless md5sum =~ /^[0-9a-f]{32}$/
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0x0, 0xd, 0x10, 0xb, 0x5]
idx.map.with_index do |i, j|
t = add[j] + md5sum[i].to_i(16)
v = md5sum[t, 2].to_i(16)
((v * mul[j]) % 16).to_s(16)
end.join ''
end
end
########################################################
def do_it(filename)
print File.basename(filename) + ": "
np = Napiprojekt.new filename
path = np.get_subtitles
if path.nil?
puts 'NOT FOUND'
else
puts 'OK'
end
end
if ARGV.empty?
ARGF.each { |line| do_it line.strip }
else
ARGV.each { |file| do_it file }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment