почистили ещё

sandbox1
inpos 2016-03-12 19:45:18 +03:00
parent 251303c380
commit ccd8fc386a
2 changed files with 30 additions and 47 deletions

View File

@ -1,13 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import json
import os import os
import socket
import stat
import sys import sys
import time import time
import urllib2
import httplib
from os.path import dirname
import pyrrent2http import pyrrent2http
import xbmc import xbmc
from error import Error from error import Error
@ -130,8 +124,6 @@ class Engine:
self.logger = logger self.logger = logger
self.uri = uri self.uri = uri
self.started = False self.started = False
self.fullStart = True
@staticmethod @staticmethod
def _validate_save_path(path): def _validate_save_path(path):
@ -150,7 +142,7 @@ class Engine:
raise Error("Downloading to an unmounted network share is not supported", Error.INVALID_DOWNLOAD_PATH) raise Error("Downloading to an unmounted network share is not supported", Error.INVALID_DOWNLOAD_PATH)
if not os.path.isdir(localize_path(path)): if not os.path.isdir(localize_path(path)):
raise Error("Download path doesn't exist (%s)" % path, Error.INVALID_DOWNLOAD_PATH) raise Error("Download path doesn't exist (%s)" % path, Error.INVALID_DOWNLOAD_PATH)
return path return localize_path(path)
def start(self, start_index=None): def start(self, start_index=None):
""" """
@ -160,6 +152,7 @@ class Engine:
:param start_index: File index to start download instantly, if not specified, downloading will be paused, until :param start_index: File index to start download instantly, if not specified, downloading will be paused, until
any file requested any file requested
""" """
download_path = self._validate_save_path(self.download_path) download_path = self._validate_save_path(self.download_path)
if not can_bind(self.bind_host, self.bind_port): if not can_bind(self.bind_host, self.bind_port):
port = find_free_port(self.bind_host) port = find_free_port(self.bind_host)
@ -232,7 +225,7 @@ class Engine:
self.pyrrent2http_loop.start() self.pyrrent2http_loop.start()
'''start = time.time() start = time.time()
self.started = True self.started = True
initialized = False initialized = False
while (time.time() - start) < self.startup_timeout: while (time.time() - start) < self.startup_timeout:
@ -248,7 +241,7 @@ class Engine:
if not initialized: if not initialized:
self.started = False self.started = False
raise Error("Can't start pyrrent2http, time is out", Error.TIMEOUT)''' raise Error("Can't start pyrrent2http, time is out", Error.TIMEOUT)
self._log("pyrrent2http successfully started.") self._log("pyrrent2http successfully started.")
def check_torrent_error(self, status=None): def check_torrent_error(self, status=None):
@ -295,7 +288,6 @@ class Engine:
res = filter(lambda fs: fs.media_type in media_types, res) res = filter(lambda fs: fs.media_type in media_types, res)
return res return res
def list_from_info(self): def list_from_info(self):
self.fullStart = False
try: try:
info = pyrrent2http.lt.torrent_info(uri2path(self.uri)) info = pyrrent2http.lt.torrent_info(uri2path(self.uri))
except: except:
@ -365,7 +357,7 @@ class Engine:
Shuts down pyrrent2http and stops logging. If wait_on_close() was called earlier, it will wait until Shuts down pyrrent2http and stops logging. If wait_on_close() was called earlier, it will wait until
pyrrent2http successfully exits. pyrrent2http successfully exits.
""" """
if self.fullStart and self.is_alive(): if self.is_alive():
self._log("Shutting down pyrrent2http...") self._log("Shutting down pyrrent2http...")
self.pyrrent2http.shutdown() self.pyrrent2http.shutdown()
finished = False finished = False

View File

@ -142,7 +142,7 @@ class TorrentFile(object):
def __init__(self, tfs, fileEntry, savePath, index): def __init__(self, tfs, fileEntry, savePath, index):
self.tfs = tfs self.tfs = tfs
self.fileEntry = fileEntry self.fileEntry = fileEntry
self.name = self.Name() self.name = self.fileEntry.path
self.unicode_name = self.name.decode(chardet.detect(self.name)['encoding']) self.unicode_name = self.name.decode(chardet.detect(self.name)['encoding'])
self.media_type = detect_media_type(self.unicode_name) self.media_type = detect_media_type(self.unicode_name)
self.save_path = savePath self.save_path = savePath
@ -157,7 +157,7 @@ class TorrentFile(object):
return self.downloaded return self.downloaded
def Progress(self): def Progress(self):
return self.progress return self.progress
def FilePtr(self): def __fileptr_(self):
if self.closed: if self.closed:
return None return None
if self.filePtr is None: if self.filePtr is None:
@ -221,7 +221,7 @@ class TorrentFile(object):
str_ += "#" str_ += "#"
self.log(str_) self.log(str_)
def Read(self, buf): def Read(self, buf):
filePtr = self.FilePtr() filePtr = self.__fileptr_()
if filePtr is None: if filePtr is None:
raise IOError raise IOError
toRead = len(buf) toRead = len(buf)
@ -236,7 +236,7 @@ class TorrentFile(object):
read = filePtr.readinto(buf) read = filePtr.readinto(buf)
return read return read
def Seek(self, offset, whence): def Seek(self, offset, whence):
filePtr = self.FilePtr() filePtr = self.__fileptr_()
if filePtr is None: return if filePtr is None: return
if whence == os.SEEK_END: if whence == os.SEEK_END:
offset = self.size - offset offset = self.size - offset
@ -244,10 +244,6 @@ class TorrentFile(object):
newOffset = filePtr.seek(offset, whence) newOffset = filePtr.seek(offset, whence)
self.log('Seeking to %d/%d' % (newOffset, self.size)) self.log('Seeking to %d/%d' % (newOffset, self.size))
return newOffset return newOffset
def Name(self):
return self.fileEntry.path
def Size(self):
return self.fileEntry.size
def IsComplete(self): def IsComplete(self):
return self.downloaded == self.size return self.downloaded == self.size
@ -270,7 +266,7 @@ class TorrentFS(object):
self.waitForMetadata() self.waitForMetadata()
self.save_path = localize_path(self.root.torrentParams['save_path']) self.save_path = localize_path(self.root.torrentParams['save_path'])
self.priorities = list(self.handle.file_priorities()) self.priorities = list(self.handle.file_priorities())
self.files = [] self.files = self.__files_()
if startIndex < 0: if startIndex < 0:
logging.info('No -file-index specified, downloading will be paused until any file is requested') logging.info('No -file-index specified, downloading will be paused until any file is requested')
for i in range(self.TorrentInfo().num_files()): for i in range(self.TorrentInfo().num_files()):
@ -285,8 +281,6 @@ class TorrentFS(object):
logging.info('Closing %d opened file(s)' % (len(self.openedFiles),)) logging.info('Closing %d opened file(s)' % (len(self.openedFiles),))
for f in self.openedFiles: for f in self.openedFiles:
f.Close() f.Close()
def LastOpenedFile(self):
return self.lastOpenedFile
def addOpenedFile(self, file_): def addOpenedFile(self, file_):
self.openedFiles.append(file_) self.openedFiles.append(file_)
def setPriority(self, index, priority): def setPriority(self, index, priority):
@ -327,21 +321,17 @@ class TorrentFS(object):
except IndexError: except IndexError:
bytes_ = 0 bytes_ = 0
return bytes_ return bytes_
def Files(self): def __files_(self):
if len(self.files) > 0:
return self.files
info = self.TorrentInfo() info = self.TorrentInfo()
for i in range(info.num_files()): for i in range(info.num_files()):
file_ = self.FileAt(i) file_ = self.__file_at_(i)
file_.downloaded = self.getFileDownloadedBytes(i) file_.downloaded = self.getFileDownloadedBytes(i)
if file_.size > 0: if file_.size > 0:
file_.progress = float(file_.downloaded)/float(file_.size) file_.progress = float(file_.downloaded)/float(file_.size)
self.files.append(file_) self.files.append(file_)
return self.files return self.files
def FileAt(self, index): def __file_at_(self, index):
info = self.TorrentInfo() info = self.TorrentInfo()
if index < 0 or index >= info.num_files():
raise IndexError
fileEntry = info.file_at(index) fileEntry = info.file_at(index)
fe_path = fileEntry.path fe_path = fileEntry.path
path = os.path.abspath(os.path.join(self.save_path, localize_path(fe_path))) path = os.path.abspath(os.path.join(self.save_path, localize_path(fe_path)))
@ -353,7 +343,7 @@ class TorrentFS(object):
) )
def FileByName(self, name): def FileByName(self, name):
savePath = os.path.abspath(os.path.join(self.save_path, localize_path(name))) savePath = os.path.abspath(os.path.join(self.save_path, localize_path(name)))
for file_ in self.Files(): for file_ in self.files:
if file_.save_path == savePath: if file_.save_path == savePath:
return file_ return file_
raise IOError raise IOError
@ -401,7 +391,7 @@ def HttpHandlerFactory():
def do_GET(self): def do_GET(self):
#print ('---Headers---\n%s\n' % (self.headers,)) #print ('---Headers---\n%s\n' % (self.headers,))
#print ('---Request---\n%s\n' % (self.path,)) #print ('---Request---\n%s\n' % (self.path,))
if self.path == '/status': '''if self.path == '/status':
self.statusHandler() self.statusHandler()
elif self.path == '/ls': elif self.path == '/ls':
self.lsHandler() self.lsHandler()
@ -417,7 +407,8 @@ def HttpHandlerFactory():
self.server.server_close() self.server.server_close()
self.end_headers() self.end_headers()
self.wfile.write('OK') self.wfile.write('OK')
elif self.path.startswith('/files/'): elif self.path.startswith('/files/'):'''
if self.path.startswith('/files/'):
self.filesHandler() self.filesHandler()
else: else:
self.send_error(404, 'Not found') self.send_error(404, 'Not found')
@ -478,28 +469,28 @@ def HttpHandlerFactory():
self.end_headers() self.end_headers()
#print "Sending Bytes ",start_range, " to ", end_range, "...\n" #print "Sending Bytes ",start_range, " to ", end_range, "...\n"
return (f, start_range, end_range) return (f, start_range, end_range)
def statusHandler(self): '''def statusHandler(self):
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "application/json") self.send_header("Content-type", "application/json")
self.end_headers() self.end_headers()
status = self.server.root_obj.Status() status = self.server.root_obj.Status()
output = json.dumps(status) output = json.dumps(status)
self.wfile.write(output) self.wfile.write(output)'''
def lsHandler(self): '''def lsHandler(self):
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "application/json") self.send_header("Content-type", "application/json")
self.end_headers() self.end_headers()
retFiles = self.server.root_obj.Ls() retFiles = self.server.root_obj.Ls()
output = json.dumps(retFiles) output = json.dumps(retFiles)
self.wfile.write(output) self.wfile.write(output)'''
def peersHandler(self): '''def peersHandler(self):
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "application/json") self.send_header("Content-type", "application/json")
self.end_headers() self.end_headers()
peers = self.server.root_obj.Peers() peers = self.server.root_obj.Peers()
output = json.dumps(peers) output = json.dumps(peers)
self.wfile.write(output) self.wfile.write(output)'''
def trackersHandler(self): '''def trackersHandler(self):
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "application/json") self.send_header("Content-type", "application/json")
self.end_headers() self.end_headers()
@ -527,7 +518,7 @@ def HttpHandlerFactory():
} }
ret.append(pi) ret.append(pi)
output = json.dumps(ret) output = json.dumps(ret)
self.wfile.write(output) self.wfile.write(output)'''
# Вырубаем access-log # Вырубаем access-log
def log_message(self, format, *args): def log_message(self, format, *args):
return return
@ -807,7 +798,7 @@ class Pyrrent2http(object):
def Ls(self): def Ls(self):
retFiles = {'files': []} retFiles = {'files': []}
if self.TorrentFS.HasTorrentInfo(): if self.TorrentFS.HasTorrentInfo():
files = self.TorrentFS.Files() files = self.TorrentFS.files
for file_ in files: for file_ in files:
Url = 'http://' + self.config.bindAddress + '/files/' + urllib.quote(file_.name) Url = 'http://' + self.config.bindAddress + '/files/' + urllib.quote(file_.name)
fi = { fi = {
@ -863,11 +854,11 @@ class Pyrrent2http(object):
) )
if self.config.showFilesProgress or self.config.showAllStats: if self.config.showFilesProgress or self.config.showAllStats:
str_ = 'Files: ' str_ = 'Files: '
for i, f in enumerate(self.TorrentFS.Files()): for i, f in enumerate(self.TorrentFS.files):
str_ += '[%d] %.2f%% ' % (i, f.Progress()*100) str_ += '[%d] %.2f%% ' % (i, f.Progress()*100)
logging.info(str_) logging.info(str_)
if (self.config.showPiecesProgress or self.config.showAllStats) and self.TorrentFS.LastOpenedFile() != None: if (self.config.showPiecesProgress or self.config.showAllStats) and self.TorrentFS.lastOpenedFile != None:
self.TorrentFS.LastOpenedFile().ShowPieces() self.TorrentFS.lastOpenedFile.ShowPieces()
def consumeAlerts(self): def consumeAlerts(self):
alerts = self.session.pop_alerts() alerts = self.session.pop_alerts()
@ -959,7 +950,7 @@ class Pyrrent2http(object):
def filesToRemove(self): def filesToRemove(self):
files = [] files = []
if self.TorrentFS.HasTorrentInfo(): if self.TorrentFS.HasTorrentInfo():
for file in self.TorrentFS.Files(): for file in self.TorrentFS.files:
if (not self.config.keepComplete or not file.IsComplete()) and (not self.config.keepIncomplete or file.IsComplete()): if (not self.config.keepComplete or not file.IsComplete()) and (not self.config.keepIncomplete or file.IsComplete()):
if os.path.exists(file.save_path): if os.path.exists(file.save_path):
files.append(file.save_path) files.append(file.save_path)