Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4d535d67f | ||
|
|
6e64e0a1f4 | ||
|
|
bf655e3f96 | ||
|
|
b1da58c3b3 | ||
|
|
ca2a815140 | ||
|
|
5a640c4ae4 | ||
|
|
6e04f3fc14 | ||
|
|
f39749807f | ||
|
|
037e32ae9b | ||
|
|
228714810a | ||
|
|
0e81ccf6bc | ||
|
|
04e63d29a0 | ||
|
|
d3baa70ceb | ||
|
|
1733e20b0e | ||
|
|
7683867a4e | ||
|
|
824daed99f | ||
|
|
32777fa959 | ||
|
|
c594801130 | ||
|
|
7557ed8223 | ||
|
|
a65987feea | ||
|
|
e23e447a1b | ||
|
|
0f5c8de27b | ||
|
|
0e541e9a68 | ||
|
|
2f4b1c9577 | ||
|
|
efbfd8beff | ||
|
|
3ecaa41dbb | ||
|
|
ad26862286 |
No files matched your search
@@ -4,3 +4,6 @@ script.module.pyrrent2http
|
||||
This add-on is engine for [plugin.video.torrenter](https://github.com/DiMartinoXBMC/plugin.video.torrenter)
|
||||
|
||||
This add-on can be used to stream media files from torrents without need to download entire files.
|
||||
|
||||
Данный движок для модуля Torrenter v2 медиа-центра KODI (XBMC) появился из-за отсутствия рабочего решения для Raspberry Pi.
|
||||
Сейчас pyrrent2http работает на множестве платформ.
|
||||
@@ -1,8 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<addon id="script.module.pyrrent2http" name="pyrrent2http" version="0.9.0" provider-name="inpos">
|
||||
<addon id="script.module.gorrent2http" name="gorrent2http" version="1.2.3" provider-name="inpos">
|
||||
<requires>
|
||||
<import addon="xbmc.python" version="2.14.0"/>
|
||||
<import addon="script.module.libtorrent" />
|
||||
<import addon="xbmc.python" version="3.0.0"/>
|
||||
<import addon="script.module.chardet" />
|
||||
</requires>
|
||||
<extension point="xbmc.python.module" library="lib"/>
|
||||
@@ -17,5 +16,5 @@
|
||||
<description lang="ru">Обеспечивает последовательную (sequential) загрузку торрентов для потокового онлайн просмотра через HTTP. Основан на библиотеке LibTorrent.</description>
|
||||
<description lang="en">Provides sequential torrent downloading for online streaming video and other media over HTTP.</description>
|
||||
<email>inpos@yandex.ru</email>
|
||||
<source>https://github.com/inpos/script.module.pyrrent2http</source></extension>
|
||||
<source>https://git.ukamnya.ru/ukamnya/script.module.gorrent2http</source></extension>
|
||||
</addon>
|
||||
@@ -1,3 +1,7 @@
|
||||
[B]Version 1.0.0[/B]
|
||||
+ Исправлен механизм добавления трекеров
|
||||
+ Добавлена поддержка прокси SOCKS длч подключения к трекерам
|
||||
|
||||
[B]Version 0.9.0[/B]
|
||||
+ Изменён принцип работы с торрентом
|
||||
|
||||
|
||||
@@ -3,33 +3,6 @@
|
||||
from collections import namedtuple
|
||||
|
||||
|
||||
# noinspection PyClassHasNoInit
|
||||
class State:
|
||||
QUEUED_FOR_CHECKING = 0
|
||||
CHECKING_FILES = 1
|
||||
DOWNLOADING_METADATA = 2
|
||||
DOWNLOADING = 3
|
||||
FINISHED = 4
|
||||
SEEDING = 5
|
||||
ALLOCATING = 6
|
||||
CHECKING_RESUME_DATA = 7
|
||||
|
||||
|
||||
# noinspection PyClassHasNoInit
|
||||
class MediaType:
|
||||
UNKNOWN = None
|
||||
AUDIO = 'audio'
|
||||
VIDEO = 'video'
|
||||
SUBTITLES = 'subtitles'
|
||||
|
||||
|
||||
# noinspection PyClassHasNoInit
|
||||
class Encryption:
|
||||
FORCED = 0
|
||||
ENABLED = 1
|
||||
DISABLED = 2
|
||||
|
||||
|
||||
SessionStatus = namedtuple('SessionStatus', "name, state, state_str, error, progress, download_rate, upload_rate, "
|
||||
"total_download, total_upload, num_peers, num_seeds, total_seeds, "
|
||||
"total_peers")
|
||||
@@ -39,5 +12,5 @@ FileStatus = namedtuple('FileStatus', "name, save_path, url, size, offset, downl
|
||||
PeerInfo = namedtuple('PeerInfo', "ip, flags, source, up_speed, down_speed, total_upload, total_download, "
|
||||
"country, client")
|
||||
|
||||
from engine import Engine
|
||||
from error import Error
|
||||
from .engine import Engine
|
||||
from .error import Error
|
||||
@@ -0,0 +1,285 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
import sys
|
||||
import time
|
||||
import xbmc
|
||||
import xbmcvfs
|
||||
from . import log as logging
|
||||
|
||||
from . import FileStatus, SessionStatus
|
||||
from .error import Error
|
||||
from .structs import Encryption
|
||||
from .util import can_bind, find_free_port, localize_path, uri2path, detect_media_type, get_platform
|
||||
|
||||
platform = get_platform()
|
||||
dirname = os.path.join(xbmcvfs.translatePath('special://temp'), 'xbmcup', 'script.module.gorrent2http')
|
||||
dest_path = os.path.join(dirname, platform['system'])
|
||||
sys.path.insert(0, dest_path)
|
||||
|
||||
try:
|
||||
from gorrent import gorrent as gt
|
||||
|
||||
logging.info(f'Imported gorrent v{gt.Version()}')
|
||||
except Exception:
|
||||
import traceback
|
||||
|
||||
logging.error(f'Error importing gorrent. Exception: {traceback.format_exc()}')
|
||||
raise
|
||||
|
||||
LOGGING = True
|
||||
|
||||
|
||||
class Engine:
|
||||
"""
|
||||
This is python binding class to gorrent2http client.
|
||||
"""
|
||||
|
||||
def _log(self, message):
|
||||
if self.logger:
|
||||
self.logger(message)
|
||||
else:
|
||||
xbmc.log("[gorrent2http] %s" % message)
|
||||
|
||||
def __init__(self, uri=None, download_path=".",
|
||||
bind_host='127.0.0.1', bind_port=5001, connections_limit=200,
|
||||
keep_files=False,
|
||||
listen_port=6881,
|
||||
debug_alerts=False,
|
||||
proxy=None,
|
||||
seed=True,
|
||||
accept_peer_conn=True,
|
||||
startup_timeout=5,
|
||||
logger=None,
|
||||
):
|
||||
|
||||
self.platform = platform
|
||||
self.bind_host = bind_host
|
||||
self.bind_port = bind_port
|
||||
self.download_path = download_path
|
||||
self.connections_limit = connections_limit
|
||||
self.keep_files = keep_files
|
||||
self.listen_port = listen_port
|
||||
self.wait_on_close_timeout = None
|
||||
self.debug_alerts = debug_alerts
|
||||
self.uri = uri
|
||||
self.started = False
|
||||
self.proxy = proxy
|
||||
self.seed = seed
|
||||
self.accept_peer_conn = accept_peer_conn
|
||||
self.startup_timeout = startup_timeout
|
||||
self.logger = logger
|
||||
|
||||
self.message_logger = None
|
||||
self.run_message_logger = True
|
||||
|
||||
@staticmethod
|
||||
def _validate_save_path(path):
|
||||
path = xbmcvfs.translatePath(path)
|
||||
if "://" in path:
|
||||
if sys.platform.startswith('win') and path.lower().startswith("smb://"):
|
||||
path = path.replace("smb:", "").replace("/", "\\")
|
||||
else:
|
||||
raise Error("Downloading to an unmounted network share is not supported", Error.INVALID_DOWNLOAD_PATH)
|
||||
if not os.path.isdir(localize_path(path)):
|
||||
raise Error("Download path doesn't exist (%s)" % path, Error.INVALID_DOWNLOAD_PATH)
|
||||
return localize_path(path)
|
||||
|
||||
def start(self, start_index):
|
||||
download_path = self._validate_save_path(self.download_path)
|
||||
if not can_bind(self.bind_host, self.bind_port):
|
||||
port = find_free_port(self.bind_host)
|
||||
if port is False:
|
||||
raise Error("Can't find port to bind gorrent2http", Error.BIND_ERROR)
|
||||
self._log("Can't bind to %s:%s, so we found another port: %d" % (self.bind_host, self.bind_port, port))
|
||||
self.bind_port = port
|
||||
|
||||
self._log("Invoking gorrent2http")
|
||||
|
||||
class Logging(object):
|
||||
def __init__(self, _log):
|
||||
self._log = _log
|
||||
|
||||
def info(self, message):
|
||||
if LOGGING:
|
||||
self._log('INFO: %s' % (message,))
|
||||
|
||||
def error(self, message):
|
||||
if LOGGING:
|
||||
self._log('ERROR: %s' % (message,))
|
||||
|
||||
gt.logging = Logging(self._log)
|
||||
|
||||
settings = gt.NewSettings()
|
||||
settings.DownloadPath = download_path
|
||||
settings.HttpBindHost = self.bind_host
|
||||
settings.HttpBindPort = self.bind_port
|
||||
settings.ListenPort = self.listen_port
|
||||
settings.TorrentPath = uri2path(self.uri)
|
||||
settings.MaxConnections = self.connections_limit
|
||||
settings.Debug = self.debug_alerts
|
||||
settings.KeepFiles = self.keep_files
|
||||
settings.Proxy = len(self.proxy) > 0 and f'socks5://{self.proxy["host"]}:{self.proxy["port"]}' or ''
|
||||
settings.Seed = self.seed
|
||||
settings.AcceptPeerConnections = self.accept_peer_conn
|
||||
|
||||
self.engine = gt.NewEngine(settings)
|
||||
|
||||
def msg_logger():
|
||||
while self.run_message_logger:
|
||||
msg = self.engine.GetMsg()
|
||||
if msg not in ('__NO_MSG__', '__CLOSED__'):
|
||||
xbmc.log(f'-= GORRENT =-: {msg}')
|
||||
time.sleep(0.1)
|
||||
self.message_logger = threading.Thread(target=msg_logger)
|
||||
self.message_logger.start()
|
||||
|
||||
self._log('starting torrent')
|
||||
|
||||
self.engine.StartTorrent(start_index)
|
||||
|
||||
self._log('waiting alive status set')
|
||||
|
||||
start = time.time()
|
||||
self.started = True
|
||||
initialized = False
|
||||
while (time.time() - start) < self.startup_timeout:
|
||||
time.sleep(0.1)
|
||||
if not self.is_alive():
|
||||
raise Error("Can't start gorrent2http, see log for details", Error.PROCESS_ERROR)
|
||||
try:
|
||||
# self.status(1)
|
||||
initialized = True
|
||||
break
|
||||
except Error:
|
||||
pass
|
||||
|
||||
if not initialized:
|
||||
self.started = False
|
||||
raise Error("Can't start gorrent2http, time is out", Error.TIMEOUT)
|
||||
self._log("gorrent2http successfully started.")
|
||||
|
||||
def pause(self):
|
||||
pass
|
||||
|
||||
def resume(self):
|
||||
pass
|
||||
|
||||
def check_torrent_error(self, status=None):
|
||||
if not status:
|
||||
status = self.status()
|
||||
if status.error:
|
||||
raise Error("Torrent error: %s" % status.error, Error.TORRENT_ERROR, reason=status.error)
|
||||
|
||||
def status(self, timeout=10):
|
||||
stat = self.engine.Status()
|
||||
stat_kw = {
|
||||
'download_rate': stat.DownloadRate,
|
||||
'upload_rate': stat.UploadRate,
|
||||
'num_seeds': stat.Seeds,
|
||||
'name': '',
|
||||
'state': 0,
|
||||
'state_str': '',
|
||||
'error': '',
|
||||
'progress': 0,
|
||||
'total_download': 0,
|
||||
'total_upload': 0,
|
||||
'num_peers': 0,
|
||||
'total_seeds': 0,
|
||||
'total_peers': 0
|
||||
}
|
||||
return SessionStatus(**stat_kw)
|
||||
|
||||
def list_from_info(self, media_types=None):
|
||||
try:
|
||||
info = gt.GetMetaFromFile(uri2path(self.uri))
|
||||
except:
|
||||
import traceback
|
||||
xbmc.log(f'info load exception: {traceback.format_exc()}')
|
||||
return []
|
||||
files = []
|
||||
if len(info.Files) > 0:
|
||||
for i in range(len(info.Files)):
|
||||
f = info.Files[i]
|
||||
|
||||
uri = 'http://' + "%s:%s" % (self.bind_host, self.bind_port) + '/files/' + urllib.parse.quote(
|
||||
'/'.join(f.Path))
|
||||
files.append({
|
||||
'name': localize_path('/'.join(f.Path)),
|
||||
'size': f.Length,
|
||||
'offset': i,
|
||||
'media_type': media_types is not None and detect_media_type(f.Path[-1]) or '',
|
||||
'download': 0,
|
||||
'progress': 0.0,
|
||||
'save_path': '',
|
||||
'url': uri
|
||||
})
|
||||
else:
|
||||
files.append({
|
||||
'name': localize_path(info.Name),
|
||||
'size': info.Length,
|
||||
'offset': 0,
|
||||
'media_type': media_types is not None and detect_media_type(info.Name) or '',
|
||||
'download': 0,
|
||||
'progress': 0.0,
|
||||
'save_path': '',
|
||||
'url': 'http://' + "%s:%s" % (self.bind_host, self.bind_port) + '/files/' + urllib.parse.quote(
|
||||
info.Name)
|
||||
})
|
||||
res = []
|
||||
if len(files) > 0:
|
||||
res = [FileStatus(index=index, **f) for index, f in enumerate(files)]
|
||||
if media_types is not None:
|
||||
res = [fs for fs in res if fs.media_type in media_types]
|
||||
return res
|
||||
|
||||
def file_status(self, file_index, timeout=10):
|
||||
try:
|
||||
efs = self.engine.FileStatus(file_index)
|
||||
fstat = {
|
||||
'name': localize_path('/'.join(efs.Name)),
|
||||
'progress': efs.Progress,
|
||||
'url': efs.Url,
|
||||
'save_path': '',
|
||||
'size': efs.Length,
|
||||
'offset': 0,
|
||||
'download': 0,
|
||||
'media_type': ''
|
||||
}
|
||||
return FileStatus(index=file_index, **fstat)
|
||||
except:
|
||||
raise Error("Requested file index (%d) is invalid" % (file_index,), Error.INVALID_FILE_INDEX,
|
||||
file_index=file_index)
|
||||
|
||||
def is_alive(self):
|
||||
return self.engine.IsAlive()
|
||||
|
||||
def close(self):
|
||||
if self.is_alive():
|
||||
self._log("Shutting down gorrent2http...")
|
||||
self.engine.Stop()
|
||||
finished = False
|
||||
|
||||
self.wait_on_close_timeout = 10
|
||||
|
||||
if self.wait_on_close_timeout is not None:
|
||||
start = time.time()
|
||||
while (time.time() - start) < self.wait_on_close_timeout:
|
||||
time.sleep(0.5)
|
||||
if not self.is_alive():
|
||||
finished = True
|
||||
break
|
||||
if not finished:
|
||||
self._log("PANIC: Timeout occurred while shutting down gorrent2http thread")
|
||||
else:
|
||||
self._log("gorrent2http successfully shut down.")
|
||||
self.wait_on_close_timeout = None
|
||||
self._log("gorrent2http successfully shut down.")
|
||||
if self.message_logger is not None and self.message_logger.is_alive():
|
||||
self.run_message_logger = False
|
||||
self.message_logger = None
|
||||
self.started = False
|
||||
File renamed without changes.
Regular → Executable
+328
-247
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,11 @@
|
||||
import xbmc
|
||||
from typing import Union
|
||||
import chardet
|
||||
|
||||
|
||||
def info(msg : Union[str, bytes]):
|
||||
xbmc.log(f'INFO: {isinstance(msg, bytes) and msg.decode(chardet.detect(msg)["encoding"]) or msg}')
|
||||
|
||||
|
||||
def error(msg: Union[str, bytes]):
|
||||
xbmc.log(f'ERROR: {isinstance(msg, bytes) and msg.decode(chardet.detect(msg)["encoding"]) or msg}')
|
||||
@@ -0,0 +1,22 @@
|
||||
class State:
|
||||
QUEUED_FOR_CHECKING = 0
|
||||
CHECKING_FILES = 1
|
||||
DOWNLOADING_METADATA = 2
|
||||
DOWNLOADING = 3
|
||||
FINISHED = 4
|
||||
SEEDING = 5
|
||||
ALLOCATING = 6
|
||||
CHECKING_RESUME_DATA = 7
|
||||
|
||||
|
||||
class MediaType:
|
||||
UNKNOWN = None
|
||||
AUDIO = 'audio'
|
||||
VIDEO = 'video'
|
||||
SUBTITLES = 'subtitles'
|
||||
|
||||
|
||||
class Encryption:
|
||||
FORCED = 0
|
||||
ENABLED = 1
|
||||
DISABLED = 2
|
||||
@@ -0,0 +1,178 @@
|
||||
import mimetypes
|
||||
import os
|
||||
import socket
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
import chardet
|
||||
import sys
|
||||
import xbmc
|
||||
|
||||
from .structs import MediaType
|
||||
|
||||
SUBTITLES_FORMATS = ['.aqt', '.gsub', '.jss', '.sub', '.ttxt', '.pjs', '.psb', '.rt', '.smi', '.stl',
|
||||
'.ssf', '.srt', '.ssa', '.ass', '.usf', '.idx']
|
||||
VIDEO_FORMATS = ['.mkv', '.mp4', '.avi', '.ogv', '.ts', '.flv', '.webm', '.vob', '.3gp', '.mpg', '.mpeg']
|
||||
|
||||
class Struct(dict):
|
||||
def __getattr__(self, attr):
|
||||
return self[attr]
|
||||
|
||||
def __setattr__(self, attr, value):
|
||||
self[attr] = value
|
||||
|
||||
|
||||
def uri2path(uri: str) -> str:
|
||||
uri_path: str = ''
|
||||
if uri[1] == ':' and sys.platform.startswith('win'):
|
||||
uri = 'file:///' + uri
|
||||
file_uri = urllib.parse.urlparse(uri)
|
||||
if file_uri.scheme == 'file':
|
||||
uri_path = file_uri.path
|
||||
if uri_path != '' and sys.platform.startswith('win') and (os.path.sep == uri_path[0] or uri_path[0] == '/'):
|
||||
uri_path = uri_path[1:]
|
||||
abs_path = os.path.abspath(urllib.parse.unquote(uri_path))
|
||||
return localize_path(abs_path)
|
||||
|
||||
|
||||
def detect_media_type(name):
|
||||
ext = os.path.splitext(name)[1]
|
||||
if ext in SUBTITLES_FORMATS:
|
||||
return MediaType.SUBTITLES
|
||||
else:
|
||||
mime_type = mimetypes.guess_type(name)[0]
|
||||
if mime_type is None:
|
||||
if ext.lower() in VIDEO_FORMATS:
|
||||
return MediaType.VIDEO
|
||||
return MediaType.UNKNOWN
|
||||
mime_type = mime_type.split("/")[0]
|
||||
if mime_type == 'audio':
|
||||
return MediaType.AUDIO
|
||||
elif mime_type == 'video':
|
||||
return MediaType.VIDEO
|
||||
else:
|
||||
return MediaType.UNKNOWN
|
||||
|
||||
|
||||
def unicode_msg(tmpl, args):
|
||||
msg = isinstance(tmpl, str) and tmpl or tmpl.decode(chardet.detect(tmpl)['encoding'])
|
||||
arg_ = []
|
||||
for a in args:
|
||||
arg_.append(isinstance(a, str) and a or a.decode(chardet.detect(a)['encoding']))
|
||||
return msg % tuple(arg_)
|
||||
|
||||
|
||||
def encode_msg(msg):
|
||||
msg = isinstance(msg, str) and msg.encode(
|
||||
sys.getfilesystemencoding() != 'ascii' and sys.getfilesystemencoding() or 'utf-8') or msg
|
||||
return msg
|
||||
|
||||
|
||||
def localize_path(path):
|
||||
if isinstance(path, bytes):
|
||||
path = path.decode(chardet.detect(path)['encoding'])
|
||||
# if not sys.platform.startswith('win'):
|
||||
# path = path.encode(
|
||||
# (sys.getfilesystemencoding() not in ('ascii', 'ANSI_X3.4-1968')) and sys.getfilesystemencoding() or 'utf-8')
|
||||
return path
|
||||
|
||||
|
||||
def can_bind(host, port):
|
||||
"""
|
||||
Checks we can bind to specified host and port
|
||||
|
||||
:param host: Host
|
||||
:param port: Port
|
||||
:return: True if bind succeed
|
||||
"""
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind((host, port))
|
||||
s.close()
|
||||
except socket.error:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def find_free_port(host):
|
||||
"""
|
||||
Finds free TCP port that can be used for binding
|
||||
|
||||
:param host: Host
|
||||
:return: Free port
|
||||
"""
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind((host, 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
except socket.error:
|
||||
return False
|
||||
return port
|
||||
|
||||
|
||||
def ensure_fs_encoding(string):
|
||||
if isinstance(string, bytes):
|
||||
string = string.decode('utf-8')
|
||||
return string.encode(sys.getfilesystemencoding() or 'utf-8')
|
||||
|
||||
|
||||
def get_platform():
|
||||
ret = {
|
||||
"arch": sys.maxsize > 2 ** 32 and "x64" or "x86",
|
||||
}
|
||||
if xbmc.getCondVisibility("system.platform.android"):
|
||||
ret["os"] = "android"
|
||||
if "arm" in os.uname()[4] or "aarch64" in os.uname()[4]:
|
||||
ret["arch"] = "arm"
|
||||
elif xbmc.getCondVisibility("system.platform.linux"):
|
||||
ret["os"] = "linux"
|
||||
uname = os.uname()[4]
|
||||
if "arm" in uname:
|
||||
if "armv7" in uname:
|
||||
ret["arch"] = "armv7"
|
||||
else:
|
||||
ret["arch"] = "armv6"
|
||||
elif "mips" in uname:
|
||||
ret["arch"] = 'mipsel'
|
||||
elif "aarch64" in uname:
|
||||
if sys.maxsize > 2147483647: # is_64bit_system
|
||||
ret["arch"] = 'aarch64'
|
||||
else:
|
||||
ret["arch"] = "armv7" # 32-bit userspace
|
||||
elif xbmc.getCondVisibility("system.platform.windows"):
|
||||
ret["os"] = "windows"
|
||||
elif xbmc.getCondVisibility("system.platform.osx"):
|
||||
ret["os"] = "darwin"
|
||||
elif xbmc.getCondVisibility("system.platform.ios"):
|
||||
ret["os"] = "ios"
|
||||
ret["arch"] = "arm"
|
||||
|
||||
ret = get_system(ret)
|
||||
return ret
|
||||
|
||||
|
||||
def get_system(ret):
|
||||
ret["system"] = ''
|
||||
if ret["os"] == 'windows':
|
||||
ret["system"] = 'windows_' + ret['arch']
|
||||
elif ret["os"] == "linux" and ret["arch"] == "x64":
|
||||
ret["system"] = 'linux_x86_64'
|
||||
elif ret["os"] == "linux" and ret["arch"] == "x86":
|
||||
ret["system"] = 'linux_x86'
|
||||
elif ret["os"] == "linux" and "aarch64" in ret["arch"]:
|
||||
ret["system"] = 'linux_' + ret["arch"]
|
||||
elif ret["os"] == "linux" and ("arm" in ret["arch"] or 'mips' in ret["arch"]):
|
||||
ret["system"] = 'linux_' + ret["arch"]
|
||||
elif ret["os"] == "android":
|
||||
if ret["arch"] == 'arm':
|
||||
ret["system"] = 'android_armv7'
|
||||
else:
|
||||
ret["system"] = 'android_x86'
|
||||
elif ret["os"] == "darwin":
|
||||
ret["system"] = 'darwin'
|
||||
elif ret["os"] == "ios" and ret["arch"] == "arm":
|
||||
ret["system"] = 'ios_arm'
|
||||
return ret
|
||||
@@ -1,383 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import pyrrent2http
|
||||
import xbmc
|
||||
from error import Error
|
||||
from . import SessionStatus, FileStatus, PeerInfo, Encryption
|
||||
from util import can_bind, find_free_port, localize_path, uri2path, detect_media_type
|
||||
import threading
|
||||
import urllib
|
||||
import chardet
|
||||
|
||||
LOGGING = True
|
||||
|
||||
class Engine:
|
||||
"""
|
||||
This is python binding class to pyrrent2http client.
|
||||
"""
|
||||
def _log(self, message):
|
||||
if self.logger:
|
||||
self.logger(message)
|
||||
else:
|
||||
xbmc.log("[pyrrent2http] %s" % message)
|
||||
|
||||
|
||||
def __init__(self, uri=None, platform=None, download_path=".",
|
||||
bind_host='127.0.0.1', bind_port=5001, connections_limit=None, download_kbps=None, upload_kbps=None,
|
||||
enable_dht=True, enable_lsd=True, enable_natpmp=True, enable_upnp=True, enable_scrape=False,
|
||||
log_stats=False, encryption=Encryption.ENABLED, keep_complete=False, keep_incomplete=False,
|
||||
keep_files=False, log_files_progress=False, log_overall_progress=False, log_pieces_progress=False,
|
||||
listen_port=6881, use_random_port=False, max_idle_timeout=None, no_sparse=False, resume_file='',
|
||||
user_agent=None, startup_timeout=5, state_file='', enable_utp=True, enable_tcp=True,
|
||||
debug_alerts=False, logger=None, torrent_connect_boost=50, connection_speed=50,
|
||||
peer_connect_timeout=15, request_timeout=20, min_reconnect_time=60, max_failcount=3,
|
||||
dht_routers=None, trackers=None):
|
||||
"""
|
||||
Creates engine instance. It doesn't do anything except initializing object members. For starting engine use
|
||||
start() method.
|
||||
|
||||
:param uri: Torrent URI (magnet://, file:// or http://)
|
||||
:param binaries_path: Path to torrent2http binaries
|
||||
:param platform: Object with two methods implemented: arch() and system()
|
||||
:param download_path: Torrent download path
|
||||
:param bind_host: Bind host of torrent2http
|
||||
:param bind_port: Bind port of torrent2http
|
||||
:param connections_limit: Set a global limit on the number of connections opened
|
||||
:param download_kbps: Max download rate (kB/s)
|
||||
:param upload_kbps: Max upload rate (kB/s)
|
||||
:param enable_dht: Enable DHT (Distributed Hash Table)
|
||||
:param enable_lsd: Enable LSD (Local Service Discovery)
|
||||
:param enable_natpmp: Enable NATPMP (NAT port-mapping)
|
||||
:param enable_upnp: Enable UPnP (UPnP port-mapping)
|
||||
:param enable_scrape: Enable sending scrape request to tracker (updates total peers/seeds count)
|
||||
:param log_stats: Log all stats (incl. log_overall_progress, log_files_progress, log_pieces_progress)
|
||||
:param encryption: Encryption: 0=forced 1=enabled (default) 2=disabled
|
||||
:param keep_complete: Keep complete files after exiting
|
||||
:param keep_incomplete: Keep incomplete files after exiting
|
||||
:param keep_files: Keep all files after exiting (incl. keep_complete and keep_incomplete)
|
||||
:param log_files_progress: Log files progress
|
||||
:param log_overall_progress: Log overall progress
|
||||
:param log_pieces_progress: Log pieces progress
|
||||
:param listen_port: Use specified port for incoming connections
|
||||
:param use_random_port: Use random listen port (49152-65535)
|
||||
:param max_idle_timeout: Automatically shutdown torrent2http if no connection are active after a timeout
|
||||
:param no_sparse: Do not use sparse file allocation
|
||||
:param resume_file: Use fast resume file
|
||||
:param user_agent: Set an user agent
|
||||
:param startup_timeout: torrent2http startup timeout
|
||||
:param state_file: Use file for saving/restoring session state
|
||||
:param enable_utp: Enable uTP protocol
|
||||
:param enable_tcp: Enable TCP protocol
|
||||
:param debug_alerts: Show debug alert notifications
|
||||
:param logger: Instance of logging.Logger
|
||||
:param torrent_connect_boost: The number of peers to try to connect to immediately when the first tracker
|
||||
response is received for a torrent
|
||||
:param connection_speed: The number of peer connection attempts that are made per second
|
||||
:param peer_connect_timeout: The number of seconds to wait after a connection attempt is initiated to a peer
|
||||
:param request_timeout: The number of seconds until the current front piece request will time out
|
||||
:param min_reconnect_time: The time to wait between peer connection attempts. If the peer fails, the time is
|
||||
multiplied by fail counter
|
||||
:param max_failcount: The maximum times we try to connect to a peer before stop connecting again
|
||||
:param dht_routers: List of additional DHT routers (host:port pairs)
|
||||
:param trackers: List of additional tracker URLs
|
||||
"""
|
||||
self.dht_routers = dht_routers or []
|
||||
self.trackers = trackers or []
|
||||
self.max_failcount = max_failcount
|
||||
self.min_reconnect_time = min_reconnect_time
|
||||
self.request_timeout = request_timeout
|
||||
self.peer_connect_timeout = peer_connect_timeout
|
||||
self.connection_speed = connection_speed
|
||||
self.torrent_connect_boost = torrent_connect_boost
|
||||
self.platform = platform
|
||||
self.bind_host = bind_host
|
||||
self.bind_port = bind_port
|
||||
self.download_path = download_path
|
||||
self.connections_limit = connections_limit
|
||||
self.download_kbps = download_kbps
|
||||
self.upload_kbps = upload_kbps
|
||||
self.enable_dht = enable_dht
|
||||
self.enable_lsd = enable_lsd
|
||||
self.enable_natpmp = enable_natpmp
|
||||
self.enable_upnp = enable_upnp
|
||||
self.enable_scrape = enable_scrape
|
||||
self.log_stats = log_stats
|
||||
self.encryption = encryption
|
||||
self.keep_complete = keep_complete
|
||||
self.keep_incomplete = keep_incomplete
|
||||
self.keep_files = keep_files
|
||||
self.log_files_progress = log_files_progress
|
||||
self.log_overall_progress = log_overall_progress
|
||||
self.log_pieces_progress = log_pieces_progress
|
||||
self.listen_port = listen_port
|
||||
self.use_random_port = use_random_port
|
||||
self.max_idle_timeout = max_idle_timeout
|
||||
self.no_sparse = no_sparse
|
||||
self.resume_file = resume_file
|
||||
self.user_agent = user_agent
|
||||
self.startup_timeout = startup_timeout
|
||||
self.state_file = state_file
|
||||
self.wait_on_close_timeout = None
|
||||
self.enable_utp = enable_utp
|
||||
self.enable_tcp = enable_tcp
|
||||
self.debug_alerts = debug_alerts
|
||||
self.logger = logger
|
||||
self.uri = uri
|
||||
self.started = False
|
||||
|
||||
@staticmethod
|
||||
def _validate_save_path(path):
|
||||
"""
|
||||
Ensures download path can be accessed locally.
|
||||
|
||||
:param path: Download path
|
||||
:return: Translated path
|
||||
"""
|
||||
import xbmc
|
||||
path = xbmc.translatePath(path)
|
||||
if "://" in path:
|
||||
if sys.platform.startswith('win') and path.lower().startswith("smb://"):
|
||||
path = path.replace("smb:", "").replace("/", "\\")
|
||||
else:
|
||||
raise Error("Downloading to an unmounted network share is not supported", Error.INVALID_DOWNLOAD_PATH)
|
||||
if not os.path.isdir(localize_path(path)):
|
||||
raise Error("Download path doesn't exist (%s)" % path, Error.INVALID_DOWNLOAD_PATH)
|
||||
return localize_path(path)
|
||||
|
||||
def start(self, start_index=None):
|
||||
"""
|
||||
Starts pyrrent2http client with specified settings. If it can be started in startup_timeout seconds, exception
|
||||
will be raised.
|
||||
|
||||
:param start_index: File index to start download instantly, if not specified, downloading will be paused, until
|
||||
any file requested
|
||||
"""
|
||||
|
||||
download_path = self._validate_save_path(self.download_path)
|
||||
if not can_bind(self.bind_host, self.bind_port):
|
||||
port = find_free_port(self.bind_host)
|
||||
if port is False:
|
||||
raise Error("Can't find port to bind pyrrent2http", Error.BIND_ERROR)
|
||||
self._log("Can't bind to %s:%s, so we found another port: %d" % (self.bind_host, self.bind_port, port))
|
||||
self.bind_port = port
|
||||
|
||||
kwargs = {
|
||||
'torrentConnectBoost': self.torrent_connect_boost,
|
||||
'trackers': ",".join(self.trackers),
|
||||
'resumeFile': self.resume_file,
|
||||
'minReconnectTime': self.min_reconnect_time,
|
||||
'enableUPNP': self.enable_upnp,
|
||||
'showAllStats': self.log_stats,
|
||||
'debugAlerts': self.debug_alerts,
|
||||
'keepComplete': self.keep_complete,
|
||||
'dhtRouters': ",".join(self.dht_routers),
|
||||
'userAgent': self.user_agent,
|
||||
'enableLSD': self.enable_lsd,
|
||||
'uri': self.uri,
|
||||
'randomPort': self.use_random_port,
|
||||
'noSparseFile': self.no_sparse,
|
||||
'maxUploadRate': self.upload_kbps,
|
||||
'downloadPath': download_path,
|
||||
'showOverallProgress': self.log_overall_progress,
|
||||
'enableDHT': self.enable_dht,
|
||||
'showFilesProgress': self.log_files_progress,
|
||||
'requestTimeout': self.request_timeout,
|
||||
'bindAddress': "%s:%s" % (self.bind_host, self.bind_port),
|
||||
'maxDownloadRate': self.download_kbps,
|
||||
'connectionSpeed': self.connection_speed,
|
||||
'keepIncomplete': self.keep_incomplete,
|
||||
'enableTCP': self.enable_tcp,
|
||||
'listenPort': self.listen_port,
|
||||
'keepFiles': self.keep_files,
|
||||
'stateFile': self.state_file,
|
||||
'peerConnectTimeout': self.peer_connect_timeout,
|
||||
'maxFailCount': self.max_failcount,
|
||||
'showPiecesProgress': self.log_pieces_progress,
|
||||
'idleTimeout': self.max_idle_timeout,
|
||||
'fileIndex': start_index,
|
||||
'connectionsLimit': self.connections_limit,
|
||||
'enableScrape': self.enable_scrape,
|
||||
'enableUTP': self.enable_utp,
|
||||
'encryption': self.encryption,
|
||||
'enableNATPMP': self.enable_natpmp
|
||||
|
||||
}
|
||||
|
||||
self._log("Invoking pyrrent2http")
|
||||
class Logging(object):
|
||||
def __init__(self, _log):
|
||||
self._log = _log
|
||||
def info(self, message):
|
||||
if LOGGING:
|
||||
self._log('INFO: %s' % (message,))
|
||||
def error(self, message):
|
||||
if LOGGING:
|
||||
self._log('ERROR: %s' % (message,))
|
||||
pyrrent2http.logging = Logging(self._log)
|
||||
|
||||
self.pyrrent2http = pyrrent2http.Pyrrent2http(**kwargs)
|
||||
self.pyrrent2http.startSession()
|
||||
self.pyrrent2http.startServices()
|
||||
self.pyrrent2http.addTorrent()
|
||||
self.pyrrent2http.startHTTP()
|
||||
self.pyrrent2http_loop = threading.Thread(target = self.pyrrent2http.loop)
|
||||
self.pyrrent2http_loop.start()
|
||||
|
||||
|
||||
start = time.time()
|
||||
self.started = True
|
||||
initialized = False
|
||||
while (time.time() - start) < self.startup_timeout:
|
||||
time.sleep(0.1)
|
||||
if not self.is_alive():
|
||||
raise Error("Can't start pyrrent2http, see log for details", Error.PROCESS_ERROR)
|
||||
try:
|
||||
#self.status(1)
|
||||
initialized = True
|
||||
break
|
||||
except Error:
|
||||
pass
|
||||
|
||||
if not initialized:
|
||||
self.started = False
|
||||
raise Error("Can't start pyrrent2http, time is out", Error.TIMEOUT)
|
||||
self._log("pyrrent2http successfully started.")
|
||||
|
||||
def check_torrent_error(self, status=None):
|
||||
"""
|
||||
It is recommended to call this method periodically to check if any libtorrent errors occurred.
|
||||
Usually libtorrent sets error if it can't download or parse torrent file by specified URI.
|
||||
Note that pyrrent2http remains started after such error, so you need to shutdown it manually.
|
||||
|
||||
:param status: Pass return of status() method if you don't want status() called twice
|
||||
"""
|
||||
if not status:
|
||||
status = self.status()
|
||||
if status.error:
|
||||
raise Error("Torrent error: %s" % status.error, Error.TORRENT_ERROR, reason=status.error)
|
||||
|
||||
def status(self, timeout=10):
|
||||
"""
|
||||
Returns libtorrent session status. See SessionStatus named tuple.
|
||||
|
||||
:rtype : SessionStatus
|
||||
:param timeout: pyrrent2http client request timeout
|
||||
"""
|
||||
status = self.pyrrent2http.Status()
|
||||
status = SessionStatus(**status)
|
||||
return status
|
||||
|
||||
|
||||
|
||||
def list(self, media_types=None, timeout=10):
|
||||
"""
|
||||
Returns list of files in the torrent (see FileStatus named tuple).
|
||||
Note that it will return None if torrent file is not loaded yet by pyrrent2http client, so you may need to call
|
||||
this method periodically until results are returned.
|
||||
|
||||
:param media_types: List of media types (see MediaType constants)
|
||||
:param timeout: pyrrent2http client request timeout
|
||||
:rtype : list of FileStatus
|
||||
:return: List of files of specified media types or None if torrent is not loaded yet
|
||||
"""
|
||||
files = self.pyrrent2http.Ls()['files']
|
||||
if files:
|
||||
res = [FileStatus(index=index, **f) for index, f in enumerate(files)]
|
||||
if media_types is not None:
|
||||
res = filter(lambda fs: fs.media_type in media_types, res)
|
||||
return res
|
||||
def list_from_info(self, media_types=None):
|
||||
try:
|
||||
info = pyrrent2http.lt.torrent_info(uri2path(self.uri))
|
||||
except:
|
||||
return []
|
||||
files = []
|
||||
for i in range(info.num_files()):
|
||||
f = info.file_at(i)
|
||||
Url = 'http://' + "%s:%s" % (self.bind_host, self.bind_port) + '/files/' + urllib.quote(f.path)
|
||||
files.append({
|
||||
'name': localize_path(f.path),
|
||||
'size': f.size,
|
||||
'offset': f.offset,
|
||||
'media_type': media_types and detect_media_type(f.path.decode(chardet.detect(f.path)['encoding'])) or '',
|
||||
'download': 0,
|
||||
'progress': 0.0,
|
||||
'save_path': '',
|
||||
'url': Url
|
||||
})
|
||||
if files:
|
||||
res = [FileStatus(index=index, **f) for index, f in enumerate(files)]
|
||||
if media_types is not None:
|
||||
res = filter(lambda fs: fs.media_type in media_types, res)
|
||||
return res
|
||||
|
||||
def file_status(self, file_index, timeout=10):
|
||||
"""
|
||||
Returns file in the torrent with specified index (see FileStatus named tuple)
|
||||
Note that it will return None if torrent file is not loaded yet by pyrrent2http client, so you may need to call
|
||||
this method periodically until results are returned.
|
||||
|
||||
:param file_index: Requested file's index
|
||||
:param timeout: pyrrent2http client request timeout
|
||||
:return: File with specified index
|
||||
:rtype: FileStatus
|
||||
"""
|
||||
files = self.pyrrent2http.Ls()['files']
|
||||
if files:
|
||||
for f in files:
|
||||
if f['index'] == file_index:
|
||||
return FileStatus(**f)
|
||||
raise Error("Requested file index (%d) is invalid" % (file_index,), Error.INVALID_FILE_INDEX,
|
||||
file_index=file_index)
|
||||
|
||||
def peers(self, timeout=10):
|
||||
"""
|
||||
Returns list of peers connected (see PeerInfo named tuple).
|
||||
|
||||
:param timeout: pyrrent2http client request timeout
|
||||
:return: List of peers
|
||||
:rtype: list of PeerInfo
|
||||
"""
|
||||
peers = self.pyrrent2http.Peers()['peers']
|
||||
if peers:
|
||||
return [PeerInfo(**p) for p in peers]
|
||||
|
||||
def is_alive(self):
|
||||
return self.pyrrent2http_loop.is_alive()
|
||||
def wait_on_close(self, wait_timeout=10):
|
||||
"""
|
||||
By default, close() method sends shutdown command to pyrrent2http, stops logging and returns immediately, not
|
||||
waiting while pyrrent2http exits. It can be handy to wait pyrrent2http to view log messages during shutdown.
|
||||
So call this method with reasonable timeout before calling close().
|
||||
|
||||
:param wait_timeout: Time in seconds to wait until pyrrent2http client shut down
|
||||
"""
|
||||
self.wait_on_close_timeout = wait_timeout
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
Shuts down pyrrent2http and stops logging. If wait_on_close() was called earlier, it will wait until
|
||||
pyrrent2http successfully exits.
|
||||
"""
|
||||
if self.is_alive():
|
||||
self._log("Shutting down pyrrent2http...")
|
||||
self.pyrrent2http.shutdown()
|
||||
finished = False
|
||||
if self.wait_on_close_timeout is not None:
|
||||
start = time.time()
|
||||
while (time.time() - start) < self.wait_on_close_timeout:
|
||||
time.sleep(0.5)
|
||||
if not self.is_alive():
|
||||
finished = True
|
||||
break
|
||||
if not finished:
|
||||
self._log("PANIC: Timeout occurred while shutting down pyrrent2http thread")
|
||||
else:
|
||||
self._log("pyrrent2http successfully shut down.")
|
||||
self.wait_on_close_timeout = None
|
||||
self._log("pyrrent2http successfully shut down.")
|
||||
self.started = False
|
||||
self.logpipe = None
|
||||
self.process = None
|
||||
@@ -1,613 +0,0 @@
|
||||
"""Guess the MIME type of a file.
|
||||
|
||||
This module defines two useful functions:
|
||||
|
||||
guess_type(url, strict=1) -- guess the MIME type and encoding of a URL.
|
||||
|
||||
guess_extension(type, strict=1) -- guess the extension for a given MIME type.
|
||||
|
||||
It also contains the following, for tuning the behavior:
|
||||
|
||||
Data:
|
||||
|
||||
knownfiles -- list of files to parse
|
||||
inited -- flag set when init() has been called
|
||||
suffix_map -- dictionary mapping suffixes to suffixes
|
||||
encodings_map -- dictionary mapping suffixes to encodings
|
||||
types_map -- dictionary mapping suffixes to types
|
||||
|
||||
Functions:
|
||||
|
||||
init([files]) -- parse a list of files, default knownfiles (on Windows, the
|
||||
default values are taken from the registry)
|
||||
read_mime_types(file) -- parse one file, return a dictionary or None
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import posixpath
|
||||
import urllib
|
||||
try:
|
||||
import _winreg
|
||||
except ImportError:
|
||||
_winreg = None
|
||||
|
||||
__all__ = [
|
||||
"guess_type","guess_extension","guess_all_extensions",
|
||||
"add_type","read_mime_types","init"
|
||||
]
|
||||
|
||||
knownfiles = [
|
||||
"/etc/mime.types",
|
||||
"/etc/httpd/mime.types", # Mac OS X
|
||||
"/etc/httpd/conf/mime.types", # Apache
|
||||
"/etc/apache/mime.types", # Apache 1
|
||||
"/etc/apache2/mime.types", # Apache 2
|
||||
"/usr/local/etc/httpd/conf/mime.types",
|
||||
"/usr/local/lib/netscape/mime.types",
|
||||
"/usr/local/etc/httpd/conf/mime.types", # Apache 1.2
|
||||
"/usr/local/etc/mime.types", # Apache 1.3
|
||||
]
|
||||
|
||||
inited = False
|
||||
_db = None
|
||||
|
||||
|
||||
class MimeTypes:
|
||||
"""MIME-types datastore.
|
||||
|
||||
This datastore can handle information from mime.types-style files
|
||||
and supports basic determination of MIME type from a filename or
|
||||
URL, and can guess a reasonable extension given a MIME type.
|
||||
"""
|
||||
|
||||
def __init__(self, filenames=(), strict=True):
|
||||
if not inited:
|
||||
init()
|
||||
self.encodings_map = encodings_map.copy()
|
||||
self.suffix_map = suffix_map.copy()
|
||||
self.types_map = ({}, {}) # dict for (non-strict, strict)
|
||||
self.types_map_inv = ({}, {})
|
||||
for (ext, type) in types_map.items():
|
||||
self.add_type(type, ext, True)
|
||||
for (ext, type) in common_types.items():
|
||||
self.add_type(type, ext, False)
|
||||
for name in filenames:
|
||||
self.read(name, strict)
|
||||
|
||||
def add_type(self, type, ext, strict=True):
|
||||
"""Add a mapping between a type and an extension.
|
||||
|
||||
When the extension is already known, the new
|
||||
type will replace the old one. When the type
|
||||
is already known the extension will be added
|
||||
to the list of known extensions.
|
||||
|
||||
If strict is true, information will be added to
|
||||
list of standard types, else to the list of non-standard
|
||||
types.
|
||||
"""
|
||||
self.types_map[strict][ext] = type
|
||||
exts = self.types_map_inv[strict].setdefault(type, [])
|
||||
if ext not in exts:
|
||||
exts.append(ext)
|
||||
|
||||
def guess_type(self, url, strict=True):
|
||||
"""Guess the type of a file based on its URL.
|
||||
|
||||
Return value is a tuple (type, encoding) where type is None if
|
||||
the type can't be guessed (no or unknown suffix) or a string
|
||||
of the form type/subtype, usable for a MIME Content-type
|
||||
header; and encoding is None for no encoding or the name of
|
||||
the program used to encode (e.g. compress or gzip). The
|
||||
mappings are table driven. Encoding suffixes are case
|
||||
sensitive; type suffixes are first tried case sensitive, then
|
||||
case insensitive.
|
||||
|
||||
The suffixes .tgz, .taz and .tz (case sensitive!) are all
|
||||
mapped to '.tar.gz'. (This is table-driven too, using the
|
||||
dictionary suffix_map.)
|
||||
|
||||
Optional `strict' argument when False adds a bunch of commonly found,
|
||||
but non-standard types.
|
||||
"""
|
||||
scheme, url = urllib.splittype(url)
|
||||
if scheme == 'data':
|
||||
# syntax of data URLs:
|
||||
# dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
|
||||
# mediatype := [ type "/" subtype ] *( ";" parameter )
|
||||
# data := *urlchar
|
||||
# parameter := attribute "=" value
|
||||
# type/subtype defaults to "text/plain"
|
||||
comma = url.find(',')
|
||||
if comma < 0:
|
||||
# bad data URL
|
||||
return None, None
|
||||
semi = url.find(';', 0, comma)
|
||||
if semi >= 0:
|
||||
type = url[:semi]
|
||||
else:
|
||||
type = url[:comma]
|
||||
if '=' in type or '/' not in type:
|
||||
type = 'text/plain'
|
||||
return type, None # never compressed, so encoding is None
|
||||
base, ext = posixpath.splitext(url)
|
||||
while ext in self.suffix_map:
|
||||
base, ext = posixpath.splitext(base + self.suffix_map[ext])
|
||||
if ext in self.encodings_map:
|
||||
encoding = self.encodings_map[ext]
|
||||
base, ext = posixpath.splitext(base)
|
||||
else:
|
||||
encoding = None
|
||||
types_map = self.types_map[True]
|
||||
if ext in types_map:
|
||||
return types_map[ext], encoding
|
||||
elif ext.lower() in types_map:
|
||||
return types_map[ext.lower()], encoding
|
||||
elif strict:
|
||||
return None, encoding
|
||||
types_map = self.types_map[False]
|
||||
if ext in types_map:
|
||||
return types_map[ext], encoding
|
||||
elif ext.lower() in types_map:
|
||||
return types_map[ext.lower()], encoding
|
||||
else:
|
||||
return None, encoding
|
||||
|
||||
def guess_all_extensions(self, type, strict=True):
|
||||
"""Guess the extensions for a file based on its MIME type.
|
||||
|
||||
Return value is a list of strings giving the possible filename
|
||||
extensions, including the leading dot ('.'). The extension is not
|
||||
guaranteed to have been associated with any particular data stream,
|
||||
but would be mapped to the MIME type `type' by guess_type().
|
||||
|
||||
Optional `strict' argument when false adds a bunch of commonly found,
|
||||
but non-standard types.
|
||||
"""
|
||||
type = type.lower()
|
||||
extensions = self.types_map_inv[True].get(type, [])
|
||||
if not strict:
|
||||
for ext in self.types_map_inv[False].get(type, []):
|
||||
if ext not in extensions:
|
||||
extensions.append(ext)
|
||||
return extensions
|
||||
|
||||
def guess_extension(self, type, strict=True):
|
||||
"""Guess the extension for a file based on its MIME type.
|
||||
|
||||
Return value is a string giving a filename extension,
|
||||
including the leading dot ('.'). The extension is not
|
||||
guaranteed to have been associated with any particular data
|
||||
stream, but would be mapped to the MIME type `type' by
|
||||
guess_type(). If no extension can be guessed for `type', None
|
||||
is returned.
|
||||
|
||||
Optional `strict' argument when false adds a bunch of commonly found,
|
||||
but non-standard types.
|
||||
"""
|
||||
extensions = self.guess_all_extensions(type, strict)
|
||||
if not extensions:
|
||||
return None
|
||||
return extensions[0]
|
||||
|
||||
def read(self, filename, strict=True):
|
||||
"""
|
||||
Read a single mime.types-format file, specified by pathname.
|
||||
|
||||
If strict is true, information will be added to
|
||||
list of standard types, else to the list of non-standard
|
||||
types.
|
||||
"""
|
||||
with open(filename) as fp:
|
||||
self.readfp(fp, strict)
|
||||
|
||||
def readfp(self, fp, strict=True):
|
||||
"""
|
||||
Read a single mime.types-format file.
|
||||
|
||||
If strict is true, information will be added to
|
||||
list of standard types, else to the list of non-standard
|
||||
types.
|
||||
"""
|
||||
while 1:
|
||||
line = fp.readline()
|
||||
if not line:
|
||||
break
|
||||
words = line.split()
|
||||
for i in range(len(words)):
|
||||
if words[i][0] == '#':
|
||||
del words[i:]
|
||||
break
|
||||
if not words:
|
||||
continue
|
||||
type, suffixes = words[0], words[1:]
|
||||
for suff in suffixes:
|
||||
self.add_type(type, '.' + suff, strict)
|
||||
|
||||
def read_windows_registry(self, strict=True):
|
||||
"""
|
||||
Load the MIME types database from Windows registry.
|
||||
|
||||
If strict is true, information will be added to
|
||||
list of standard types, else to the list of non-standard
|
||||
types.
|
||||
"""
|
||||
|
||||
# Windows only
|
||||
if not _winreg:
|
||||
return
|
||||
|
||||
def enum_types(mimedb):
|
||||
i = 0
|
||||
while True:
|
||||
try:
|
||||
ctype = _winreg.EnumKey(mimedb, i)
|
||||
except EnvironmentError:
|
||||
break
|
||||
try:
|
||||
ctype = ctype#.encode(default_encoding) # omit in 3.x!
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
else:
|
||||
yield ctype
|
||||
i += 1
|
||||
|
||||
default_encoding = sys.getdefaultencoding()
|
||||
with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
|
||||
r'MIME\Database\Content Type') as mimedb:
|
||||
for ctype in enum_types(mimedb):
|
||||
try:
|
||||
with _winreg.OpenKey(mimedb, ctype) as key:
|
||||
suffix, datatype = _winreg.QueryValueEx(key,
|
||||
'Extension')
|
||||
except EnvironmentError:
|
||||
continue
|
||||
if datatype != _winreg.REG_SZ:
|
||||
continue
|
||||
try:
|
||||
suffix = suffix.encode(default_encoding) # omit in 3.x!
|
||||
except UnicodeEncodeError:
|
||||
continue
|
||||
self.add_type(ctype, suffix, strict)
|
||||
|
||||
|
||||
def guess_type(url, strict=True):
|
||||
"""Guess the type of a file based on its URL.
|
||||
|
||||
Return value is a tuple (type, encoding) where type is None if the
|
||||
type can't be guessed (no or unknown suffix) or a string of the
|
||||
form type/subtype, usable for a MIME Content-type header; and
|
||||
encoding is None for no encoding or the name of the program used
|
||||
to encode (e.g. compress or gzip). The mappings are table
|
||||
driven. Encoding suffixes are case sensitive; type suffixes are
|
||||
first tried case sensitive, then case insensitive.
|
||||
|
||||
The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
|
||||
to ".tar.gz". (This is table-driven too, using the dictionary
|
||||
suffix_map).
|
||||
|
||||
Optional `strict' argument when false adds a bunch of commonly found, but
|
||||
non-standard types.
|
||||
"""
|
||||
if _db is None:
|
||||
init()
|
||||
return _db.guess_type(url, strict)
|
||||
|
||||
|
||||
def guess_all_extensions(type, strict=True):
|
||||
"""Guess the extensions for a file based on its MIME type.
|
||||
|
||||
Return value is a list of strings giving the possible filename
|
||||
extensions, including the leading dot ('.'). The extension is not
|
||||
guaranteed to have been associated with any particular data
|
||||
stream, but would be mapped to the MIME type `type' by
|
||||
guess_type(). If no extension can be guessed for `type', None
|
||||
is returned.
|
||||
|
||||
Optional `strict' argument when false adds a bunch of commonly found,
|
||||
but non-standard types.
|
||||
"""
|
||||
if _db is None:
|
||||
init()
|
||||
return _db.guess_all_extensions(type, strict)
|
||||
|
||||
def guess_extension(type, strict=True):
|
||||
"""Guess the extension for a file based on its MIME type.
|
||||
|
||||
Return value is a string giving a filename extension, including the
|
||||
leading dot ('.'). The extension is not guaranteed to have been
|
||||
associated with any particular data stream, but would be mapped to the
|
||||
MIME type `type' by guess_type(). If no extension can be guessed for
|
||||
`type', None is returned.
|
||||
|
||||
Optional `strict' argument when false adds a bunch of commonly found,
|
||||
but non-standard types.
|
||||
"""
|
||||
if _db is None:
|
||||
init()
|
||||
return _db.guess_extension(type, strict)
|
||||
|
||||
def add_type(type, ext, strict=True):
|
||||
"""Add a mapping between a type and an extension.
|
||||
|
||||
When the extension is already known, the new
|
||||
type will replace the old one. When the type
|
||||
is already known the extension will be added
|
||||
to the list of known extensions.
|
||||
|
||||
If strict is true, information will be added to
|
||||
list of standard types, else to the list of non-standard
|
||||
types.
|
||||
"""
|
||||
if _db is None:
|
||||
init()
|
||||
return _db.add_type(type, ext, strict)
|
||||
|
||||
|
||||
def init(files=None):
|
||||
global suffix_map, types_map, encodings_map, common_types
|
||||
global inited, _db
|
||||
inited = True # so that MimeTypes.__init__() doesn't call us again
|
||||
db = MimeTypes()
|
||||
if files is None:
|
||||
if _winreg:
|
||||
db.read_windows_registry()
|
||||
files = knownfiles
|
||||
for file in files:
|
||||
if os.path.isfile(file):
|
||||
db.read(file)
|
||||
encodings_map = db.encodings_map
|
||||
suffix_map = db.suffix_map
|
||||
types_map = db.types_map[True]
|
||||
common_types = db.types_map[False]
|
||||
# Make the DB a global variable now that it is fully initialized
|
||||
_db = db
|
||||
|
||||
|
||||
def read_mime_types(file):
|
||||
try:
|
||||
f = open(file)
|
||||
except IOError:
|
||||
return None
|
||||
db = MimeTypes()
|
||||
db.readfp(f, True)
|
||||
return db.types_map[True]
|
||||
|
||||
|
||||
def _default_mime_types():
|
||||
global suffix_map
|
||||
global encodings_map
|
||||
global types_map
|
||||
global common_types
|
||||
|
||||
suffix_map = {
|
||||
'.tgz': '.tar.gz',
|
||||
'.taz': '.tar.gz',
|
||||
'.tz': '.tar.gz',
|
||||
'.tbz2': '.tar.bz2',
|
||||
}
|
||||
|
||||
encodings_map = {
|
||||
'.gz': 'gzip',
|
||||
'.Z': 'compress',
|
||||
'.bz2': 'bzip2',
|
||||
}
|
||||
|
||||
# Before adding new types, make sure they are either registered with IANA,
|
||||
# at http://www.isi.edu/in-notes/iana/assignments/media-types
|
||||
# or extensions, i.e. using the x- prefix
|
||||
|
||||
# If you add to these, please keep them sorted!
|
||||
types_map = {
|
||||
'.3gp' : 'video/3gp',
|
||||
'.a' : 'application/octet-stream',
|
||||
'.ai' : 'application/postscript',
|
||||
'.aif' : 'audio/x-aiff',
|
||||
'.aifc' : 'audio/x-aiff',
|
||||
'.aiff' : 'audio/x-aiff',
|
||||
'.asf' : 'video/x-ms-asf',
|
||||
'.asx' : 'video/x-ms-asf',
|
||||
'.au' : 'audio/basic',
|
||||
'.avi' : 'video/x-msvideo',
|
||||
'.axv' : 'video/annodex',
|
||||
'.bat' : 'text/plain',
|
||||
'.bcpio' : 'application/x-bcpio',
|
||||
'.bin' : 'application/octet-stream',
|
||||
'.bmp' : 'image/x-ms-bmp',
|
||||
'.c' : 'text/plain',
|
||||
# Duplicates :(
|
||||
'.cdf' : 'application/x-cdf',
|
||||
'.cdf' : 'application/x-netcdf',
|
||||
'.cpio' : 'application/x-cpio',
|
||||
'.csh' : 'application/x-csh',
|
||||
'.css' : 'text/css',
|
||||
'.dif' : 'video/dv',
|
||||
'.dl' : 'video/dl',
|
||||
'.dll' : 'application/octet-stream',
|
||||
'.dv' : 'video/dv',
|
||||
'.doc' : 'application/msword',
|
||||
'.dot' : 'application/msword',
|
||||
'.dvi' : 'application/x-dvi',
|
||||
'.eml' : 'message/rfc822',
|
||||
'.eps' : 'application/postscript',
|
||||
'.etx' : 'text/x-setext',
|
||||
'.exe' : 'application/octet-stream',
|
||||
'.fli' : 'video/fli',
|
||||
'.flv' : 'video/x-flv',
|
||||
'.gif' : 'image/gif',
|
||||
'.gl' : 'video/gl',
|
||||
'.gtar' : 'application/x-gtar',
|
||||
'.h' : 'text/plain',
|
||||
'.hdf' : 'application/x-hdf',
|
||||
'.htm' : 'text/html',
|
||||
'.html' : 'text/html',
|
||||
'.ief' : 'image/ief',
|
||||
'.jpe' : 'image/jpeg',
|
||||
'.jpeg' : 'image/jpeg',
|
||||
'.jpg' : 'image/jpeg',
|
||||
'.js' : 'application/x-javascript',
|
||||
'.ksh' : 'text/plain',
|
||||
'.latex' : 'application/x-latex',
|
||||
'.lsf' : 'video/x-la-lsf',
|
||||
'.lsx' : 'video/x-la-lsf',
|
||||
'.m1v' : 'video/mpeg',
|
||||
'.man' : 'application/x-troff-man',
|
||||
'.me' : 'application/x-troff-me',
|
||||
'.mht' : 'message/rfc822',
|
||||
'.mhtml' : 'message/rfc822',
|
||||
'.mif' : 'application/x-mif',
|
||||
'.mng' : 'video/x-mng',
|
||||
'.movie' : 'video/x-sgi-movie',
|
||||
'.mp2' : 'audio/mpeg',
|
||||
'.mp3' : 'audio/mpeg',
|
||||
'.mp4' : 'video/mp4',
|
||||
'.mpa' : 'video/mpeg',
|
||||
'.mpe' : 'video/mpeg',
|
||||
'.mpeg' : 'video/mpeg',
|
||||
'.mpg' : 'video/mpeg',
|
||||
'.mpv' : 'video/matroska',
|
||||
'.mkv' : 'video/matroska',
|
||||
'.mov' : 'video/quicktime',
|
||||
'.ms' : 'application/x-troff-ms',
|
||||
'.nc' : 'application/x-netcdf',
|
||||
'.nws' : 'message/rfc822',
|
||||
'.o' : 'application/octet-stream',
|
||||
'.obj' : 'application/octet-stream',
|
||||
'.oda' : 'application/oda',
|
||||
'.ogv' : 'video/ogg',
|
||||
'.p12' : 'application/x-pkcs12',
|
||||
'.p7c' : 'application/pkcs7-mime',
|
||||
'.pbm' : 'image/x-portable-bitmap',
|
||||
'.pdf' : 'application/pdf',
|
||||
'.pfx' : 'application/x-pkcs12',
|
||||
'.pgm' : 'image/x-portable-graymap',
|
||||
'.pl' : 'text/plain',
|
||||
'.png' : 'image/png',
|
||||
'.pnm' : 'image/x-portable-anymap',
|
||||
'.pot' : 'application/vnd.ms-powerpoint',
|
||||
'.ppa' : 'application/vnd.ms-powerpoint',
|
||||
'.ppm' : 'image/x-portable-pixmap',
|
||||
'.pps' : 'application/vnd.ms-powerpoint',
|
||||
'.ppt' : 'application/vnd.ms-powerpoint',
|
||||
'.ps' : 'application/postscript',
|
||||
'.pwz' : 'application/vnd.ms-powerpoint',
|
||||
'.py' : 'text/x-python',
|
||||
'.pyc' : 'application/x-python-code',
|
||||
'.pyo' : 'application/x-python-code',
|
||||
'.qt' : 'video/quicktime',
|
||||
'.ra' : 'audio/x-pn-realaudio',
|
||||
'.ram' : 'application/x-pn-realaudio',
|
||||
'.ras' : 'image/x-cmu-raster',
|
||||
'.rdf' : 'application/xml',
|
||||
'.rgb' : 'image/x-rgb',
|
||||
'.roff' : 'application/x-troff',
|
||||
'.rtx' : 'text/richtext',
|
||||
'.sgm' : 'text/x-sgml',
|
||||
'.sgml' : 'text/x-sgml',
|
||||
'.sh' : 'application/x-sh',
|
||||
'.shar' : 'application/x-shar',
|
||||
'.snd' : 'audio/basic',
|
||||
'.so' : 'application/octet-stream',
|
||||
'.src' : 'application/x-wais-source',
|
||||
'.sv4cpio': 'application/x-sv4cpio',
|
||||
'.sv4crc' : 'application/x-sv4crc',
|
||||
'.swf' : 'application/x-shockwave-flash',
|
||||
'.t' : 'application/x-troff',
|
||||
'.tar' : 'application/x-tar',
|
||||
'.tcl' : 'application/x-tcl',
|
||||
'.tex' : 'application/x-tex',
|
||||
'.texi' : 'application/x-texinfo',
|
||||
'.texinfo': 'application/x-texinfo',
|
||||
'.tif' : 'image/tiff',
|
||||
'.tiff' : 'image/tiff',
|
||||
'.tr' : 'application/x-troff',
|
||||
'.ts' : 'video/MP2T',
|
||||
'.tsv' : 'text/tab-separated-values',
|
||||
'.txt' : 'text/plain',
|
||||
'.ustar' : 'application/x-ustar',
|
||||
'.vcf' : 'text/x-vcard',
|
||||
'.wav' : 'audio/x-wav',
|
||||
'.webm' : 'video/webm',
|
||||
'.wiz' : 'application/msword',
|
||||
'.wm' : 'video/x-ms-wm',
|
||||
'.wmv' : 'video/x-ms-wmv',
|
||||
'.wmx' : 'video/x-ms-wmx',
|
||||
'.wvx' : 'video/x-ms-wvx',
|
||||
'.wsdl' : 'application/xml',
|
||||
'.xbm' : 'image/x-xbitmap',
|
||||
'.xlb' : 'application/vnd.ms-excel',
|
||||
# Duplicates :(
|
||||
'.xls' : 'application/excel',
|
||||
'.xls' : 'application/vnd.ms-excel',
|
||||
'.xml' : 'text/xml',
|
||||
'.xpdl' : 'application/xml',
|
||||
'.xpm' : 'image/x-xpixmap',
|
||||
'.xsl' : 'application/xml',
|
||||
'.xwd' : 'image/x-xwindowdump',
|
||||
'.zip' : 'application/zip',
|
||||
}
|
||||
|
||||
# These are non-standard types, commonly found in the wild. They will
|
||||
# only match if strict=0 flag is given to the API methods.
|
||||
|
||||
# Please sort these too
|
||||
common_types = {
|
||||
'.jpg' : 'image/jpg',
|
||||
'.mid' : 'audio/midi',
|
||||
'.midi': 'audio/midi',
|
||||
'.pct' : 'image/pict',
|
||||
'.pic' : 'image/pict',
|
||||
'.pict': 'image/pict',
|
||||
'.rtf' : 'application/rtf',
|
||||
'.xul' : 'text/xul'
|
||||
}
|
||||
|
||||
|
||||
_default_mime_types()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import getopt
|
||||
|
||||
USAGE = """\
|
||||
Usage: mimetypes.py [options] type
|
||||
|
||||
Options:
|
||||
--help / -h -- print this message and exit
|
||||
--lenient / -l -- additionally search of some common, but non-standard
|
||||
types.
|
||||
--extension / -e -- guess extension instead of type
|
||||
|
||||
More than one type argument may be given.
|
||||
"""
|
||||
|
||||
def usage(code, msg=''):
|
||||
print USAGE
|
||||
if msg: print msg
|
||||
sys.exit(code)
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], 'hle',
|
||||
['help', 'lenient', 'extension'])
|
||||
except getopt.error, msg:
|
||||
usage(1, msg)
|
||||
|
||||
strict = 1
|
||||
extension = 0
|
||||
for opt, arg in opts:
|
||||
if opt in ('-h', '--help'):
|
||||
usage(0)
|
||||
elif opt in ('-l', '--lenient'):
|
||||
strict = 0
|
||||
elif opt in ('-e', '--extension'):
|
||||
extension = 1
|
||||
for gtype in args:
|
||||
if extension:
|
||||
guess = guess_extension(gtype, strict)
|
||||
if not guess: print "I don't know anything about type", gtype
|
||||
else: print guess
|
||||
else:
|
||||
guess, encoding = guess_type(gtype, strict)
|
||||
if not guess: print "I don't know anything about type", gtype
|
||||
else: print 'type:', guess, 'encoding:', encoding
|
||||
@@ -1,99 +0,0 @@
|
||||
import sys
|
||||
import socket
|
||||
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']
|
||||
|
||||
class Struct(dict):
|
||||
def __getattr__(self, attr):
|
||||
return self[attr]
|
||||
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:
|
||||
return MediaType.SUBTITLES
|
||||
else:
|
||||
mime_type = mimetypes.guess_type(name)[0]
|
||||
if not mime_type:
|
||||
return MediaType.UNKNOWN
|
||||
mime_type = mime_type.split("/")[0]
|
||||
if mime_type == 'audio':
|
||||
return MediaType.AUDIO
|
||||
elif mime_type == 'video':
|
||||
return MediaType.VIDEO
|
||||
else:
|
||||
return MediaType.UNKNOWN
|
||||
def unicode_msg(tmpl, args):
|
||||
msg = isinstance(tmpl, unicode) and tmpl or tmpl.decode(chardet.detect(tmpl)['encoding'])
|
||||
arg_ = []
|
||||
for a in args:
|
||||
arg_.append(isinstance(a, unicode) and a or a.decode(chardet.detect(a)['encoding']))
|
||||
return msg % tuple(arg_)
|
||||
|
||||
def encode_msg(msg):
|
||||
msg = isinstance(msg, unicode) and msg.encode(True and sys.getfilesystemencoding() or 'utf-8') or msg
|
||||
return msg
|
||||
|
||||
|
||||
def localize_path(path):
|
||||
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
|
||||
|
||||
def can_bind(host, port):
|
||||
"""
|
||||
Checks we can bind to specified host and port
|
||||
|
||||
:param host: Host
|
||||
:param port: Port
|
||||
:return: True if bind succeed
|
||||
"""
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind((host, port))
|
||||
s.close()
|
||||
except socket.error:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def find_free_port(host):
|
||||
"""
|
||||
Finds free TCP port that can be used for binding
|
||||
|
||||
:param host: Host
|
||||
:return: Free port
|
||||
"""
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind((host, 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
except socket.error:
|
||||
return False
|
||||
return port
|
||||
|
||||
|
||||
def ensure_fs_encoding(string):
|
||||
if isinstance(string, str):
|
||||
string = string.decode('utf-8')
|
||||
return string.encode(sys.getfilesystemencoding() or 'utf-8')
|
||||
Reference in new issue
Block a user