ускорил список файлов

sandbox1
inpos 2016-03-12 02:29:23 +03:00
parent b52e975c03
commit f8c956ab0b
4 changed files with 56 additions and 33 deletions

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="script.module.pyrrent2http" name="pyrrent2http" version="0.7.3" provider-name="inpos">
<addon id="script.module.pyrrent2http" name="pyrrent2http" version="0.7.4" provider-name="inpos">
<requires>
<import addon="xbmc.python" version="2.14.0"/>
<import addon="script.module.libtorrent" />

View File

@ -12,7 +12,7 @@ import pyrrent2http
import xbmc
from error import Error
from . import SessionStatus, FileStatus, PeerInfo, Encryption
from util import can_bind, find_free_port, localize_path
from util import can_bind, find_free_port, localize_path, uri2path
import threading
LOGGING = True
@ -130,6 +130,7 @@ class Engine:
self.logger = logger
self.uri = uri
self.started = False
self.fullStart = True
@staticmethod
@ -293,6 +294,28 @@ class Engine:
if media_types is not None:
res = filter(lambda fs: fs.media_type in media_types, res)
return res
def list_from_info(self):
self.fullStart = False
try:
info = pyrrent2http.lt.torrent_info(uri2path(self.uri))
except:
return []
files = []
for i in range(info.num_files()):
f = info.file_at(i)
files.append({
'name': localize_path(f.path),
'size': f.size,
'offset': f.offset,
'media_type': '',
'download': 0,
'progress': 0.0,
'save_path': '',
'url': ''
})
if files:
res = [FileStatus(index=index, **f) for index, f in enumerate(files)]
return res
def file_status(self, file_index, timeout=10):
"""
@ -342,7 +365,7 @@ class Engine:
Shuts down pyrrent2http and stops logging. If wait_on_close() was called earlier, it will wait until
pyrrent2http successfully exits.
"""
if self.is_alive():
if self.fullStart and self.is_alive():
self._log("Shutting down pyrrent2http...")
self.pyrrent2http.shutdown()
finished = False

View File

@ -24,7 +24,7 @@ import BaseHTTPServer
import SocketServer
import threading
import io
from util import localize_path, Struct, detect_media_type
from util import localize_path, Struct, detect_media_type, uri2path, normalize_msg
######################################################################################
@ -601,34 +601,15 @@ class Pyrrent2http(object):
raise Exception('Не должно быть файла восстановления, если мы не храним файлы')
def buildTorrentParams(self, uri):
if uri[1] == ':' and sys.platform.startswith('win'):
uri = 'file:///' + uri
fileUri = urlparse.urlparse(uri)
torrentParams = {}
if self.magnet:
torrentParams['url'] = uri
elif fileUri.scheme == 'file':
uriPath = fileUri.path
if uriPath != '' and sys.platform.startswith('win') and (os.path.sep == uriPath[0] or uriPath[0] == '/'):
uriPath = uriPath[1:]
try:
absPath = os.path.abspath(urllib.unquote(uriPath))
logging.info('Opening local torrent file: %s' % (absPath,))
absPath = uri2path(uri)
logging.info(normalize_msg('Opening local torrent file: %s', absPath))
torrent_info = lt.torrent_info(absPath)
except Exception as e:
strerror = e.args
logging.error('Build torrent params error is (%s)' % (strerror,))
raise
torrentParams['ti'] = torrent_info
else:
logging.info('Will fetch: %s' % (uri,))
try:
torrent_raw = urllib.urlopen(uri).read()
torrent_info = lt.torrent_info(torrent_raw, len(torrent_raw))
except Exception as e:
strerror = e.args
logging.error(strerror)
raise
torrentParams = {}
torrentParams['ti'] = torrent_info
logging.info('Setting save path: %s' % (self.config.downloadPath,))
torrentParams['save_path'] = self.config.downloadPath

View File

@ -4,6 +4,7 @@ import chardet
import os
from . import MediaType
import mimetypes
import urlparse, urllib
SUBTITLES_FORMATS = ['.aqt', '.gsub', '.jss', '.sub', '.ttxt', '.pjs', '.psb', '.rt', '.smi', '.stl',
'.ssf', '.srt', '.ssa', '.ass', '.usf', '.idx']
@ -14,6 +15,17 @@ class Struct(dict):
def __setattr__(self, attr, value):
self[attr] = value
def uri2path(uri):
if uri[1] == ':' and sys.platform.startswith('win'):
uri = 'file:///' + uri
fileUri = urlparse.urlparse(uri)
if fileUri.scheme == 'file':
uriPath = fileUri.path
if uriPath != '' and sys.platform.startswith('win') and (os.path.sep == uriPath[0] or uriPath[0] == '/'):
uriPath = uriPath[1:]
absPath = os.path.abspath(urllib.unquote(uriPath))
return localize_path(absPath)
def detect_media_type(name):
ext = os.path.splitext(name)[1]
if ext in SUBTITLES_FORMATS:
@ -29,9 +41,16 @@ def detect_media_type(name):
return MediaType.VIDEO
else:
return MediaType.UNKNOWN
def normalize_msg(tmpl, *args):
msg = tmpl.decode(chardet.detect(tmpl)['encoding'])
arg_ = []
for a in args:
if not isinstance(a, unicode): arg_.append(a.decode(chardet.detect(a)['encoding']))
return msg % tuple(arg_)
def localize_path(path):
path = path.decode(chardet.detect(path)['encoding'])
if not isinstance(path, unicode): path = path.decode(chardet.detect(path)['encoding'])
if not sys.platform.startswith('win'):
path = path.encode(True and sys.getfilesystemencoding() or 'utf-8')
return path