Created
April 27, 2015 03:07
-
-
Save nomadalex/4115115f44e5c9f74aa5 to your computer and use it in GitHub Desktop.
Fix torrent encoding, convert gbk to utf8, for fix file names.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
# this script used to convert gbk encoding torrent to utf8 encoding | |
require "bencode" | |
def print_files(data) | |
files = data["info"]["files"] | |
files.each do |f| | |
path = f["path"][0] | |
p path | |
p path.encoding | |
p path.force_encoding(Encoding::UTF_8) | |
p path.encoding | |
end | |
end | |
def fix_str(str) | |
str.force_encoding(Encoding::GBK).encode!(Encoding::UTF_8).force_encoding(Encoding::ASCII_8BIT) | |
end | |
def fix_coding(data) | |
files = data["info"]["files"] | |
files.each do |f| | |
fix_str(f["path"][0]) | |
end | |
fix_str(data["comment"]) if data.key? "comment" | |
end | |
def get_out_file(fn) | |
ext = File.extname(fn) | |
bn = File.basename(fn, ext) | |
bn + "_utf8" + ext | |
end | |
fn = ARGV[0] | |
content = File.open(fn, "rb") { |f| f.read } | |
data = BEncode.load(content) | |
fix_coding(data) | |
File.open(get_out_file(fn), "wb") { |f| f.write(data.bencode) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment