Skip to content

Instantly share code, notes, and snippets.

@rotaliator
Created June 19, 2019 18:53
Show Gist options
  • Save rotaliator/3b49d26f3458bc18f7109ba2aebfc24a to your computer and use it in GitHub Desktop.
Save rotaliator/3b49d26f3458bc18f7109ba2aebfc24a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#
# Script downloads subtitles from napiprojekt
# python3 and Windows compatible
#
# based on older script
# by gim,krzynio,dosiu,hash 2oo8.
# last modified: 19-VI-2o19
# 4pc0h f0rc3
from hashlib import md5
import sys
import urllib.request
import os
from uuid import uuid4
from tempfile import NamedTemporaryFile, gettempdir
from subprocess import Popen, PIPE
class Un7ZipError(Exception):
pass
class NoMatchingSubtitle(Exception):
pass
def f(z):
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
b = []
for i in range(len(idx)):
a = add[i]
m = mul[i]
i = idx[i]
t = a + int(z[i], 16)
v = int(z[t:t + 2], 16)
b.append(("%x" % (v * m))[-1])
return "".join(b)
def napiurl(path):
h = md5(open(path, "rb").read(10485760)).hexdigest()
return "http://napiprojekt.pl/unit_napisy/dl.php?l=PL&" + \
"f=" + h + "&t=" + f(h) + \
"&v=other&kolejka=false&nick=&pass=&napios=posix"
def un7zip(archive, password=None, tmpfileprefix="un7zip", tmpfilesuffix=".7z"):
tmpfilename = str(uuid4()) + ".7z"
with open(tmpfilename, "wb") as tmpfile:
tmpfile.write(archive)
cmd = ["7z", "x", "-y", "-so"]
if password is not None:
cmd += ["-p" + password]
cmd += [tmpfilename]
sp = Popen(cmd, stdout=PIPE, stderr=PIPE)
content, err = sp.communicate()
if sp.wait() != 0:
print(err)
raise Un7ZipError("Invalid archive")
os.unlink(tmpfile.name) # deletes the file
return content
def subtitlepath(moviepath):
filename, fileext = os.path.splitext(moviepath)
return filename + ".txt"
def download_subtitle(filename):
url = napiurl(filename)
print("URL:", url)
content_7z = urllib.request.urlopen(url).read()
try:
content = un7zip(content_7z, password="iBlm8NTigvru0Jr0")
except Un7ZipError:
# raise NoMatchingSubtitle("No matching subtitle")
raise Exception("Un7Zip error")
# Don't override the same subtitles
try:
same = open(subtitlepath(filename), "rb").read() == content
except IOError:
same = False
if not same:
open(subtitlepath(filename), "wb").write(content)
def main():
if len(sys.argv) < 2:
sys.stderr.write("\nUSAGE:\n\t" +
sys.argv[0] + " moviefile [moviefile, ...]\n\n")
exit(1)
failed = False
try:
for arg in sys.argv[1:]:
try:
download_subtitle(arg)
print("OK " + arg)
except NoMatchingSubtitle:
failed = True
print("NOSUBS " + arg)
except IOError:
sys.stderr.write("Cannot read file " + arg + "\n")
exit(2)
except OSError:
print("OS error. Is 7z in PATH?")
exit(4)
if failed:
exit(8)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment