Skip to content

Commit

Permalink
v1.0.1
Browse files Browse the repository at this point in the history
* v1.0.1
  • Loading branch information
realgam3 authored Nov 21, 2022
1 parent 5f84c93 commit 72b1af2
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 74 deletions.
2 changes: 1 addition & 1 deletion addon.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="service.subtitles.bsplayer"
name="BSPlayer"
version="1.0.0"
version="1.0.1"
provider-name="realgam3">
<requires>
<import addon="xbmc.python" version="3.0.0"/>
Expand Down
3 changes: 3 additions & 0 deletions changelog.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
1.0.1 - 21/11/2022
- Fixing regression issue with SMB file opening

1.0.0 - 19/11/2022
- Adding new BSPlayer Engines (OpenSubtitles, GetSubtitle)

Expand Down
2 changes: 1 addition & 1 deletion resources/language/English/strings.po
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ msgid "Password"
msgstr ""

msgctxt "#32005"
msgid "Your OpenSubtitles.org username or password is empty"
msgid "Your OpenSubtitles.org username or password is empty."
msgstr ""

msgctxt "#32006"
Expand Down
48 changes: 23 additions & 25 deletions resources/lib/bsplayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,20 +186,19 @@ def search_subtitles(self, movie_path, language_ids="heb,eng", logout=False):
log("BSPlayer.search_subtitles", f"Status: {status}.")
return []

items = root.findall(".//return/data/item")
items = root.findall(".//return/data/item") or []
subtitles = []
if items:
for item in items:
subtitle = dict(
subID=item.find("subID").text,
subDownloadLink=item.find("subDownloadLink").text,
subLang=item.find("subLang").text,
subName=item.find("subName").text,
subFormat=item.find("subFormat").text,
subRating=item.find("subRating").text or "0"
)
subtitles.append(subtitle)
log("BSPlayer.search_subtitles", f"Subtitles Found: {json.dumps(subtitles)}.")
for item in items:
subtitle = dict(
subID=item.find("subID").text,
subDownloadLink=item.find("subDownloadLink").text,
subLang=item.find("subLang").text,
subName=item.find("subName").text,
subFormat=item.find("subFormat").text,
subRating=item.find("subRating").text or "0"
)
subtitles.append(subtitle)
log("BSPlayer.search_subtitles", f"Subtitles Found: {json.dumps(subtitles)}.")

if logout:
self.logout()
Expand Down Expand Up @@ -332,18 +331,17 @@ def search_subtitles(self, movie_path, language_ids="heb,eng", logout=False):
} for item in root.findall(".//member/value/array/data/value")
]
subtitles = []
if items:
for item in items:
subtitle = dict(
subID=item.get("IDSubtitle"),
subDownloadLink=item.get("SubDownloadLink"),
subLang=item.get("sublanguageid"),
subName=item.get("SubFileName"),
subFormat=item.get("subFormat"),
subRating=item.get("SubRating") or "0"
)
subtitles.append(subtitle)
log("OpenSubtitles.search_subtitles", f"Subtitles Found: {json.dumps(subtitles)}.")
for item in items:
subtitle = dict(
subID=item.get("IDSubtitle"),
subDownloadLink=item.get("SubDownloadLink"),
subLang=item.get("SubLanguageID"),
subName=item.get("SubFileName"),
subFormat=item.get("SubFormat"),
subRating=item.get("SubRating") or "0"
)
subtitles.append(subtitle)
log("OpenSubtitles.search_subtitles", f"Subtitles Found: {json.dumps(subtitles)}.")

if logout:
self.logout()
Expand Down
97 changes: 61 additions & 36 deletions resources/lib/utils.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,39 @@
import io
import sys
import struct
from os import path
from urllib import parse, request
from http.cookiejar import CookieJar
from http.client import HTTPConnection

import xbmc
try:
import xbmc
import xbmcvfs

logger = xbmc.log
LOG_LEVEL = xbmc.LOGDEBUG


class file(xbmcvfs.File):
def __init__(self, filepath, mode="r"):
super(file, self).__init__(filepath, mode)
self.mode = mode

def read(self, numBytes):
if "b" in self.mode:
return self.readBytes(numBytes)
return super(file, self).read(numBytes)

except ModuleNotFoundError:
import logging

logger = logging.getLogger(__name__).log
LOG_LEVEL = logging.DEBUG
file = open


def log(module, msg):
xbmc.log(f"### [BSPlayer::{module}] - {msg}", level=xbmc.LOGDEBUG)
logger(msg=f"### [BSPlayer::{module}] - {msg}", level=LOG_LEVEL)


def notify(script_name, language, string_id):
Expand All @@ -18,22 +42,22 @@ def notify(script_name, language, string_id):

def get_params(params_str=""):
params_str = params_str or sys.argv[2]
return dict(parse.parse_qsl(params_str.lstrip('?')))
return dict(parse.parse_qsl(params_str.lstrip("?")))


def get_video_path(xbmc_path=''):
def get_video_path(xbmc_path=""):
xbmc_path = xbmc_path or parse.unquote(xbmc.Player().getPlayingFile())
if xbmc_path.startswith('rar://'):
return path.dirname(xbmc_path.replace('rar://', ''))
elif xbmc_path.startswith('stack://'):
return xbmc_path.split(" , ")[0].replace('stack://', '')
if xbmc_path.startswith("rar://"):
return path.dirname(xbmc_path.replace("rar://", ""))
elif xbmc_path.startswith("stack://"):
return xbmc_path.split(" , ")[0].replace("stack://", "")

return xbmc_path


def get_languages_dict(languages_param):
langs = {}
for lang in languages_param.split(','):
for lang in languages_param.split(","):
if lang == "Portuguese (Brazil)":
langs["pob"] = lang
elif lang == "Greek":
Expand Down Expand Up @@ -66,47 +90,47 @@ def get_session(proxies=None, cookies=True, http_10=False):


def __get_last_split(firs_rar_file, x):
if firs_rar_file[-3:] == '001':
return firs_rar_file[:-3] + ('%03d' % (x + 1))
if firs_rar_file[-11:-6] == '.part':
return firs_rar_file[0:-6] + ('%02d' % (x + 1)) + firs_rar_file[-4:]
if firs_rar_file[-10:-5] == '.part':
return firs_rar_file[0:-5] + ('%1d' % (x + 1)) + firs_rar_file[-4:]
return firs_rar_file[0:-2] + ('%02d' % (x - 1))
if firs_rar_file[-3:] == "001":
return firs_rar_file[:-3] + ("%03d" % (x + 1))
if firs_rar_file[-11:-6] == ".part":
return firs_rar_file[0:-6] + ("%02d" % (x + 1)) + firs_rar_file[-4:]
if firs_rar_file[-10:-5] == ".part":
return firs_rar_file[0:-5] + ("%1d" % (x + 1)) + firs_rar_file[-4:]
return firs_rar_file[0:-2] + ("%02d" % (x - 1))


def __add_file_hash(name, file_hash, seek):
f = open(name, "rb")
f = file(name, "rb")
f.seek(max(0, seek), 0)
for i in range(8192):
file_hash += struct.unpack('<q', f.read(8))[0]
file_hash += struct.unpack("<q", f.read(8))[0]
file_hash &= 0xffffffffffffffff
f.close()
return file_hash


def __movie_size_and_hash_rar(firs_rar_file):
log('utils.movie_size_and_hash', 'Hashing Rar file...')
f = open(firs_rar_file, 'rb')
log("utils.movie_size_and_hash", "Hashing Rar file...")
f = file(firs_rar_file, "rb")
a = f.read(4)
if a != b'Rar!':
log('utils.movie_size_and_hash', 'ERROR: This is not rar file (%s).' % path.basename(firs_rar_file))
raise Exception('ERROR: This is not rar file.')
if a != b"Rar!":
log("utils.movie_size_and_hash", "ERROR: This is not rar file (%s)." % path.basename(firs_rar_file))
raise Exception("ERROR: This is not rar file.")
seek = 0
for i in range(4):
f.seek(max(0, seek), 0)
a = f.read(100)
tipe, flag, size = struct.unpack('<BHH', a[2:2 + 5])
tipe, flag, size = struct.unpack("<BHH", a[2:2 + 5])
if 0x74 == tipe:
if 0x30 != struct.unpack('<B', a[25:25 + 1])[0]:
if 0x30 != struct.unpack("<B", a[25:25 + 1])[0]:
log('utils.movie_size_and_hash', 'Bad compression method! Work only for "store".')
raise Exception('Bad compression method! Work only for "store".')
s_partiize_body_start = seek + size
s_partiize_body, s_unpack_size = struct.unpack('<II', a[7:7 + 2 * 4])
s_partiize_body, s_unpack_size = struct.unpack("<II", a[7:7 + 2 * 4])
if flag & 0x0100:
s_unpack_size += (struct.unpack('<I', a[36:36 + 4])[0] << 32)
log('utils.movie_size_and_hash',
'WARNING: Hash untested for files biger that 2gb. May work or may generate bad hash.')
s_unpack_size += (struct.unpack("<I", a[36:36 + 4])[0] << 32)
log("utils.movie_size_and_hash",
"WARNING: Hash untested for files biger that 2gb. May work or may generate bad hash.")
last_rar_file = __get_last_split(firs_rar_file, (s_unpack_size - 1) / s_partiize_body)
file_hash = __add_file_hash(firs_rar_file, s_unpack_size, s_partiize_body_start)
file_hash = __add_file_hash(
Expand All @@ -115,25 +139,26 @@ def __movie_size_and_hash_rar(firs_rar_file):
f.close()
return s_unpack_size, "%016x" % file_hash
seek += size
log('utils.movie_size_and_hash', 'ERROR: Not Body part in rar file.')
raise Exception('ERROR: Not Body part in rar file.')
log("utils.movie_size_and_hash", "ERROR: Not Body part in rar file.")
raise Exception("ERROR: Not Body part in rar file.")


def movie_size_and_hash(file_path):
file_ext = path.splitext(file_path)[1]
if file_ext == '.rar' or file_ext == '.001':
if file_ext == ".rar" or file_ext == ".001":
return __movie_size_and_hash_rar(file_path)

longlong_format = '<q' # little-endian long long
longlong_format = "<q" # little-endian long long
byte_size = struct.calcsize(longlong_format)

file_size = path.getsize(file_path)
f = open(file_path, 'rb')
f = file(file_path, "rb")
file_size = f.seek(0, io.SEEK_END)
f.seek(0)
movie_hash = file_size

if file_size < 65536 * 2:
f.close()
log('utils.movie_size_and_hash', "ERROR: SizeError (%d)." % file_size)
log("utils.movie_size_and_hash", "ERROR: SizeError (%d)." % file_size)
raise Exception("SizeError")

for x in range(65536 // byte_size):
Expand Down
24 changes: 13 additions & 11 deletions service.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
__version__ = __addon__.getAddonInfo("version")
__language__ = __addon__.getLocalizedString

__cwd__ = xbmc.translatePath(__addon__.getAddonInfo("path"))
__profile__ = xbmc.translatePath(__addon__.getAddonInfo("profile"))
__resource__ = xbmc.translatePath(path.join(__cwd__, "resources", "lib"))
__temp__ = xbmc.translatePath(path.join(__profile__, "temp", ""))
__cwd__ = xbmcvfs.translatePath(__addon__.getAddonInfo("path"))
__profile__ = xbmcvfs.translatePath(__addon__.getAddonInfo("profile"))
__resource__ = xbmcvfs.translatePath(path.join(__cwd__, "resources", "lib"))
__temp__ = xbmcvfs.translatePath(path.join(__profile__, "temp", ""))

engines = {
"BSPlayer": BSPlayer,
Expand All @@ -44,19 +44,21 @@
log("Service.languages", f"Current Languages: {languages}.")

for engine_name, engine in engines.items():
kwargs = {}
kwargs = {"proxies": {"http": "127.0.0.1:8888"}}
if engine_name == "OpenSubtitles":
username = __addon__.getSetting("OSuser")
password = __addon__.getSetting("OSpass")
kwargs = {"username": username, "password": password}
if not username or not password:
notify(__scriptname__, __language__, 32002)
kwargs.update({"username": username, "password": password})
if not all([username, password]):
notify(__scriptname__, __language__, 32005)
log("Service.subtitles", "OpenSubtitles username or password is empty.")
continue

try:
with engine(**kwargs) as bsp:
subtitles = bsp.search_subtitles(video_path, language_ids=list(languages.keys()))
with engine(**kwargs) as sub:
subtitles = sub.search_subtitles(video_path, language_ids=list(languages.keys()))
log("Service.subtitles", f"Subtitles found: {subtitles}.")
for subtitle in sorted(subtitles, key=lambda s: s['subLang']):
for subtitle in sorted(subtitles, key=lambda s: s["subLang"]):
list_item = xbmcgui.ListItem(
label=engine_name,
label2=subtitle["subName"],
Expand Down

0 comments on commit 72b1af2

Please sign in to comment.