plugin.video.torrenter/Libtorrent.py

608 lines
26 KiB
Python
Raw Normal View History

2015-01-09 14:11:21 +03:00
# -*- coding: utf-8 -*-
'''
2015-06-30 18:08:57 +03:00
Torrenter v2 plugin for XBMC/Kodi
Copyright (C) 2012-2015 Vadim Skorba v1 - DiMartino v2
2016-02-13 20:33:16 +03:00
https://forums.tvaddons.ag/addon-releases/29224-torrenter-v2.html
2015-06-30 18:08:57 +03:00
2015-01-09 14:11:21 +03:00
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import thread
import os
import urllib2
import hashlib
import re
from StringIO import StringIO
import gzip
2015-07-26 21:44:46 +03:00
import sys
2015-01-09 14:11:21 +03:00
import xbmc
import xbmcgui
import xbmcvfs
import Localization
2016-02-09 18:54:06 +03:00
from functions import file_encode, isSubtitle, DownloadDB, log, debug, is_writable, vista_check, windows_check
from platform_pulsar import get_platform
2015-06-23 23:00:27 +03:00
2015-01-09 14:11:21 +03:00
class Libtorrent:
magnetLink = None
startPart = 0
endPart = 0
partOffset = 0
torrentHandle = None
session = None
downloadThread = None
threadComplete = False
lt = None
2015-12-15 17:09:25 +03:00
save_resume_data = None
2016-02-09 18:54:06 +03:00
__settings__ = sys.modules["__main__"].__settings__
2015-08-04 20:52:52 +03:00
2015-01-09 14:11:21 +03:00
def __init__(self, storageDirectory='', torrentFile='', torrentFilesDirectory='torrents'):
self.platform = get_platform()
2015-07-26 21:44:46 +03:00
self.storageDirectory = storageDirectory
self.torrentFilesPath = os.path.join(self.storageDirectory, torrentFilesDirectory) + os.sep
if not is_writable(self.storageDirectory):
xbmcgui.Dialog().ok(Localization.localize('Torrenter v2'),
Localization.localize('Your storage path is not writable or not local! Please change it in settings!'),
Localization.localize(self.storageDirectory))
sys.exit(1)
try:
from python_libtorrent import get_libtorrent
libtorrent=get_libtorrent()
2015-08-02 16:48:41 +03:00
log('Imported libtorrent v%s from python_libtorrent/%s' %(libtorrent.version, self.platform['system']))
2015-08-02 19:41:19 +03:00
module=True
2015-08-02 16:48:41 +03:00
except Exception, e:
2015-08-02 19:41:19 +03:00
module=False
2015-08-02 16:48:41 +03:00
log('Error importing python_libtorrent.%s. Exception: %s' %(self.platform['system'], str(e)))
import libtorrent
2015-06-13 00:46:15 +03:00
try:
2015-08-02 19:41:19 +03:00
if not module: log('Imported libtorrent v' + libtorrent.version + ' from system')
2015-06-13 00:46:15 +03:00
self.lt = libtorrent
del libtorrent
2015-08-02 16:48:41 +03:00
except Exception, e:
2015-08-02 16:48:41 +03:00
log('Error importing from system. Exception: ' + str(e))
2016-02-09 18:54:06 +03:00
xbmcgui.Dialog().ok(Localization.localize('python-libtorrent Not Found'),
2015-06-23 23:00:27 +03:00
Localization.localize(self.platform["message"][0]),
Localization.localize(self.platform["message"][1]))
2015-06-13 00:46:15 +03:00
return
2015-01-09 14:11:21 +03:00
if xbmcvfs.exists(torrentFile):
self.torrentFile = torrentFile
2015-07-24 20:22:30 +03:00
e=self.lt.bdecode(xbmcvfs.File(self.torrentFile,'rb').read())
self.torrentFileInfo = self.lt.torrent_info(e)
2015-01-09 14:11:21 +03:00
elif re.match("^magnet\:.+$", torrentFile):
self.magnetLink = torrentFile
def saveTorrent(self, torrentUrl):
if re.match("^magnet\:.+$", torrentUrl):
self.magnetLink = torrentUrl
self.magnetToTorrent(torrentUrl)
2015-06-23 23:00:27 +03:00
self.magnetLink = None
2015-01-09 14:11:21 +03:00
return self.torrentFile
else:
2015-01-10 18:47:07 +03:00
if not xbmcvfs.exists(self.torrentFilesPath):
xbmcvfs.mkdirs(self.torrentFilesPath)
torrentFile = self.torrentFilesPath + self.md5(
2015-01-09 14:11:21 +03:00
torrentUrl) + '.torrent'
try:
if not re.match("^http\:.+$", torrentUrl):
2015-07-24 20:22:30 +03:00
content = xbmcvfs.File(torrentUrl, "rb").read()
2015-01-09 14:11:21 +03:00
else:
request = urllib2.Request(torrentUrl)
request.add_header('Referer', torrentUrl)
request.add_header('Accept-encoding', 'gzip')
result = urllib2.urlopen(request)
if result.info().get('Content-Encoding') == 'gzip':
buf = StringIO(result.read())
f = gzip.GzipFile(fileobj=buf)
content = f.read()
else:
content = result.read()
localFile = xbmcvfs.File(torrentFile, "w+b")
localFile.write(content)
localFile.close()
except Exception, e:
2015-12-23 18:26:19 +03:00
log('Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(e))
2015-01-09 14:11:21 +03:00
return
if xbmcvfs.exists(torrentFile):
try:
2015-07-24 20:22:30 +03:00
e=self.lt.bdecode(xbmcvfs.File(torrentFile,'rb').read())
self.torrentFileInfo = self.lt.torrent_info(e)
2015-01-09 14:11:21 +03:00
except Exception, e:
2015-12-23 18:26:19 +03:00
log('Exception: ' + str(e))
2015-01-09 14:11:21 +03:00
xbmcvfs.delete(torrentFile)
return
2015-03-19 23:29:04 +03:00
baseName = file_encode(os.path.basename(self.getFilePath()))
2015-01-10 18:47:07 +03:00
if not xbmcvfs.exists(self.torrentFilesPath):
xbmcvfs.mkdirs(self.torrentFilesPath)
2015-06-23 23:00:27 +03:00
newFile = self.torrentFilesPath + self.md5(baseName) + '.' + self.md5(
torrentUrl) + '.torrent' # + '.'+ baseName
2015-07-23 18:23:22 +03:00
if xbmcvfs.exists(newFile):
2015-03-19 23:29:04 +03:00
xbmcvfs.delete(newFile)
2015-01-09 14:11:21 +03:00
if not xbmcvfs.exists(newFile):
try:
xbmcvfs.rename(torrentFile, newFile)
except Exception, e:
2016-03-07 20:58:43 +03:00
log('Unable to rename torrent file from %s to %s in Torrent::renameTorrent. Exception: %s' %
(torrentFile, newFile, str(e)))
2015-01-09 14:11:21 +03:00
return
self.torrentFile = newFile
if not self.torrentFileInfo:
2015-07-24 20:22:30 +03:00
e=self.lt.bdecode(xbmcvfs.File(self.torrentFile,'rb').read())
self.torrentFileInfo = self.lt.torrent_info(e)
2015-01-09 14:11:21 +03:00
return self.torrentFile
def getMagnetInfo(self):
magnetSettings = {
2015-08-04 17:26:35 +03:00
'url': self.magnetLink,
2015-01-09 14:11:21 +03:00
'save_path': self.storageDirectory,
'storage_mode': self.lt.storage_mode_t(0),
'paused': True,
2015-08-04 20:47:39 +03:00
#'auto_managed': True,
#'duplicate_is_error': True
2015-01-09 14:11:21 +03:00
}
progressBar = xbmcgui.DialogProgress()
2015-07-19 00:44:38 +03:00
progressBar.create(Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting'))
2015-08-08 23:22:15 +03:00
#try:
2015-08-04 17:26:35 +03:00
self.torrentHandle = self.session.add_torrent(magnetSettings)
2015-08-08 23:22:15 +03:00
#except:
# self.torrentHandle = self.lt.add_magnet_uri(self.session, self.magnetLink, magnetSettings)
2015-01-09 14:11:21 +03:00
iterator = 0
2015-07-19 00:44:38 +03:00
while iterator < 100:
xbmc.sleep(500)
self.torrentHandle.force_dht_announce()
2015-07-19 00:44:38 +03:00
progressBar.update(iterator, Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting')+'.' * (iterator % 4), ' ')
2015-01-09 14:11:21 +03:00
iterator += 1
if progressBar.iscanceled():
progressBar.update(0)
progressBar.close()
return
2015-08-04 17:47:34 +03:00
if self.torrentHandle.status().has_metadata:
2015-07-19 00:44:38 +03:00
iterator = 100
2015-01-09 14:11:21 +03:00
progressBar.update(0)
progressBar.close()
2015-08-04 17:47:34 +03:00
if self.torrentHandle.status().has_metadata:
2015-08-08 23:22:15 +03:00
try:
info = self.torrentHandle.torrent_file()
except:
info = self.torrentHandle.get_torrent_info()
return info
2015-01-09 14:11:21 +03:00
def magnetToTorrent(self, magnet):
self.magnetLink = magnet
self.initSession()
torrentInfo = self.getMagnetInfo()
2015-08-04 20:47:39 +03:00
if torrentInfo:
try:
torrentFile = self.lt.create_torrent(torrentInfo)
baseName = os.path.basename(self.storageDirectory + os.sep + torrentInfo.files()[0].path)
if not xbmcvfs.exists(self.torrentFilesPath):
xbmcvfs.mkdirs(self.torrentFilesPath)
self.torrentFile = self.torrentFilesPath + self.md5(baseName) + '.torrent'
torentFileHandler = xbmcvfs.File(self.torrentFile, "w+b")
torentFileHandler.write(self.lt.bencode(torrentFile.generate()))
torentFileHandler.close()
e=self.lt.bdecode(xbmcvfs.File(self.torrentFile,'rb').read())
self.torrentFileInfo = self.lt.torrent_info(e)
except:
xbmc.executebuiltin("Notification(%s, %s, 7500)" % (Localization.localize('Error'), Localization.localize(
'Can\'t download torrent, probably no seeds available.')))
self.torrentFileInfo = torrentInfo
finally:
self.session.remove_torrent(self.torrentHandle)
self.torrentHandle = None
2015-01-09 14:11:21 +03:00
def getUploadRate(self):
if None == self.torrentHandle:
return 0
else:
return self.torrentHandle.status().upload_payload_rate
def getDownloadRate(self):
if None == self.torrentHandle:
return 0
else:
return self.torrentHandle.status().download_payload_rate
def getPeers(self):
if None == self.torrentHandle:
return 0
else:
return self.torrentHandle.status().num_peers
def getSeeds(self):
if None == self.torrentHandle:
return 0
else:
return self.torrentHandle.status().num_seeds
def getFileSize(self, contentId=0):
return self.getContentList()[contentId]['size']
def getFilePath(self, contentId=0):
2015-06-23 23:00:27 +03:00
return os.path.join(self.storageDirectory, self.getContentList()[contentId]['title']) # .decode('utf8')
2015-01-09 14:11:21 +03:00
def getContentList(self):
filelist = []
2015-06-28 18:04:09 +03:00
for contentId, contentFile in enumerate(self.torrentFileInfo.files()):
stringdata = {"title": contentFile.path, "size": contentFile.size, "ind": int(contentId),
'offset': contentFile.offset}
filelist.append(stringdata)
return filelist
2015-06-13 00:46:15 +03:00
2015-01-09 14:11:21 +03:00
def getSubsIds(self, filename):
2015-06-23 23:00:27 +03:00
subs = []
2015-01-09 14:11:21 +03:00
for i in self.getContentList():
if isSubtitle(filename, i['title']):
subs.append((i['ind'], i['title']))
return subs
def setUploadLimit(self, bytesPerSecond):
2015-07-26 21:44:46 +03:00
try:
session_settings = self.session.get_settings()
session_settings['upload_rate_limit'] = int(bytesPerSecond)
self.session.set_settings(session_settings)
except:
#0.16 compatibility
self.session.set_upload_rate_limit(int(bytesPerSecond))
2015-01-09 14:11:21 +03:00
def setDownloadLimit(self, bytesPerSecond):
2015-07-26 21:44:46 +03:00
try:
session_settings = self.session.get_settings()
session_settings['download_rate_limit'] = int(bytesPerSecond)
self.session.set_settings(session_settings)
except:
#0.16 compatibility
self.session.set_download_rate_limit(int(bytesPerSecond))
2015-01-09 14:11:21 +03:00
def md5(self, string):
hasher = hashlib.md5()
try:
hasher.update(string)
except:
hasher.update(string.encode('utf-8', 'ignore'))
return hasher.hexdigest()
2015-06-28 18:04:09 +03:00
def downloadProcess(self, contentId, encrytion=True):
self.initSession()
if encrytion:
self.encryptSession()
2015-01-12 23:10:20 +03:00
self.startSession()
2015-06-23 23:00:27 +03:00
self.paused = False
db = DownloadDB()
ContentList = self.getContentList()
if contentId != None: contentId = int(contentId)
if len(ContentList) == 1 or contentId not in [None, -1]:
if not contentId: contentId = 0
title = os.path.basename(ContentList[contentId]['title'])
path = os.path.join(self.storageDirectory, ContentList[contentId]['title'])
type = 'file'
2015-01-12 23:10:20 +03:00
else:
2015-06-23 23:00:27 +03:00
contentId = -1
title = ContentList[0]['title'].split('\\')[0]
path = os.path.join(self.storageDirectory, title)
type = 'folder'
add = db.add(title, path, type, {'progress': 0}, 'downloading', self.torrentFile, contentId,
self.storageDirectory)
get = db.get(title)
if add or get[5] == 'stopped':
if get[5] == 'stopped':
db.update_status(get[0], 'downloading')
if contentId not in [None, -1]:
2015-01-12 23:10:20 +03:00
self.continueSession(int(contentId), Offset=0, seeding=False)
else:
for i in range(self.torrentFileInfo.num_pieces()):
self.torrentHandle.piece_priority(i, 6)
thread.start_new_thread(self.downloadLoop, (title,))
def downloadLoop(self, title):
2015-06-23 23:00:27 +03:00
db = DownloadDB()
status = 'downloading'
while db.get(title) and status != 'stopped':
2015-01-14 23:24:01 +03:00
xbmc.sleep(3000)
2015-06-23 23:00:27 +03:00
status = db.get_status(title)
2015-01-13 17:24:53 +03:00
if not self.paused:
2015-06-23 23:00:27 +03:00
if status == 'pause':
self.paused = True
2015-01-13 17:24:53 +03:00
self.session.pause()
else:
2015-06-23 23:00:27 +03:00
if status != 'pause':
self.paused = False
2015-01-13 17:24:53 +03:00
self.session.resume()
s = self.torrentHandle.status()
2015-06-23 23:00:27 +03:00
info = {}
info['upload'] = s.upload_payload_rate
info['download'] = s.download_payload_rate
info['peers'] = s.num_peers
info['seeds'] = s.num_seeds
2015-01-13 17:24:53 +03:00
iterator = int(s.progress * 100)
2015-06-23 23:00:27 +03:00
info['progress'] = iterator
2015-01-12 23:10:20 +03:00
db.update(title, info)
self.debug()
self.session.remove_torrent(self.torrentHandle)
2015-01-18 20:29:38 +03:00
return
2015-01-09 14:11:21 +03:00
def initSession(self):
self.session = self.lt.session()
2015-06-28 18:04:09 +03:00
self.session.set_alert_mask(self.lt.alert.category_t.error_notification | self.lt.alert.category_t.status_notification | self.lt.alert.category_t.storage_notification)
2015-07-26 21:44:46 +03:00
#self.session.set_alert_mask(self.lt.alert.category_t.all_categories)
2015-01-09 14:11:21 +03:00
self.session.add_dht_router("router.bittorrent.com", 6881)
self.session.add_dht_router("router.utorrent.com", 6881)
2015-08-02 15:26:16 +03:00
self.session.start_dht()
self.session.start_lsd()
self.session.start_upnp()
self.session.start_natpmp()
2015-10-17 21:17:17 +03:00
try:
2016-02-13 20:33:16 +03:00
port = int(self.__settings__.getSetting('listen_port'))
self.session.listen_on(port, port+10)
2015-10-17 21:17:17 +03:00
except:
2016-02-13 20:33:16 +03:00
try:
log('listen_on(%d, %d) error' %(port, port+10))
except:
log('listen_port %s error' %(self.__settings__.getSetting('listen_port')))
2015-06-28 18:04:09 +03:00
2016-02-09 18:54:06 +03:00
pc_config = int(self.__settings__.getSetting('pc_config'))
2015-07-15 19:14:22 +03:00
2015-06-28 18:04:09 +03:00
# Session settings
2015-07-26 21:44:46 +03:00
try:
session_settings = self.session.get_settings()
#
session_settings['announce_to_all_tiers'] = True
session_settings['announce_to_all_trackers'] = True
session_settings['peer_connect_timeout'] = 2
session_settings['rate_limit_ip_overhead'] = True
session_settings['request_timeout'] = 1
2016-02-09 18:54:06 +03:00
session_settings['torrent_connect_boost'] = 50
2015-08-02 15:26:16 +03:00
session_settings['user_agent'] = 'uTorrent/2200(24683)'
2016-02-09 18:54:06 +03:00
if pc_config == 0:
#good pc
session_settings['connections_limit'] = 200
session_settings['unchoke_slots_limit'] = 10
session_settings['connection_speed'] = 200
session_settings['file_pool_size'] = 40
elif pc_config == 1:
#bad pc/router
session_settings['connections_limit'] = 100
session_settings['half_open_limit'] = (lambda: windows_check() and
(lambda: vista_check() and 4 or 8)() or 50)()
session_settings['unchoke_slots_limit'] = 4
session_settings['connection_speed'] = 100
session_settings['file_pool_size'] = 40
2015-07-26 21:44:46 +03:00
#session_settings['cache_size'] = 0
#session_settings['use_read_cache'] = False
except:
#0.15 compatibility
log('[initSession]: Session settings 0.15 compatibility')
session_settings = self.session.settings()
session_settings.announce_to_all_tiers = True
session_settings.announce_to_all_trackers = True
session_settings.connection_speed = 100
session_settings.peer_connect_timeout = 2
session_settings.rate_limit_ip_overhead = True
session_settings.request_timeout = 1
session_settings.torrent_connect_boost = 100
2015-08-02 15:26:16 +03:00
session_settings.user_agent = 'uTorrent/2200(24683)'
2015-07-23 18:23:22 +03:00
#
2015-07-24 20:22:30 +03:00
self.session.set_settings(session_settings)
2015-06-28 18:04:09 +03:00
def encryptSession(self):
# Encryption settings
2015-07-26 21:44:46 +03:00
log('Encryption enabling...')
try:
encryption_settings = self.lt.pe_settings()
encryption_settings.out_enc_policy = self.lt.enc_policy(self.lt.enc_policy.forced)
encryption_settings.in_enc_policy = self.lt.enc_policy(self.lt.enc_policy.forced)
encryption_settings.allowed_enc_level = self.lt.enc_level.both
encryption_settings.prefer_rc4 = True
self.session.set_pe_settings(encryption_settings)
2015-07-26 21:44:46 +03:00
log('Encryption on!')
except Exception, e:
2015-07-26 21:44:46 +03:00
log('Encryption failed! Exception: ' + str(e))
pass
2015-01-09 14:11:21 +03:00
def startSession(self):
2015-07-26 21:44:46 +03:00
if self.magnetLink:
2015-01-09 14:11:21 +03:00
self.torrentFileInfo = self.getMagnetInfo()
2015-07-26 21:44:46 +03:00
torrent_info={'ti': self.torrentFileInfo,
'save_path': self.storageDirectory,
2015-12-15 17:09:25 +03:00
'flags': 0x300,
2015-07-26 21:44:46 +03:00
#'storage_mode': self.lt.storage_mode_t(1),
'paused': False,
2015-12-15 17:09:25 +03:00
#'auto_managed': False,
'duplicate_is_error': False
2015-07-26 21:44:46 +03:00
}
2016-02-25 22:29:18 +03:00
if self.save_resume_data:
log('loading resume data')
torrent_info['resume_data']=self.save_resume_data
2016-03-06 11:04:51 +03:00
else:
resume_file=self.resume_data_path()
if xbmcvfs.exists(resume_file):
2016-03-07 20:58:43 +03:00
log('loading resume data from file '+resume_file)
2016-03-06 11:04:51 +03:00
try:
resumDataFile=xbmcvfs.File(resume_file,'rb')
self.save_resume_data=resumDataFile.read()
resumDataFile.close()
torrent_info['resume_data']=self.save_resume_data
except:
2016-03-07 20:58:43 +03:00
log('Failed to load resume data from file '+ resume_file)
2015-07-26 21:44:46 +03:00
self.torrentHandle = self.session.add_torrent(torrent_info)
2015-01-09 14:11:21 +03:00
self.torrentHandle.set_sequential_download(True)
2015-07-23 18:23:22 +03:00
self.torrentHandle.set_max_connections(60)
self.torrentHandle.set_max_uploads(-1)
2015-01-09 14:11:21 +03:00
self.stopSession()
def stopSession(self):
for i in range(self.torrentFileInfo.num_pieces()):
self.torrentHandle.piece_priority(i, 0)
2015-06-08 21:17:37 +03:00
def continueSession(self, contentId=0, Offset=0, seeding=False, isMP4=False):
2015-01-09 14:11:21 +03:00
self.piece_length = self.torrentFileInfo.piece_length()
selectedFileInfo = self.getContentList()[contentId]
if not Offset:
Offset = selectedFileInfo['size'] / (1024 * 1024)
self.partOffset = (Offset * 1024 * 1024 / self.piece_length) + 1
self.startPart = selectedFileInfo['offset'] / self.piece_length
self.endPart = int((selectedFileInfo['offset'] + selectedFileInfo['size']) / self.piece_length)
2015-06-23 23:00:27 +03:00
multiplier = self.partOffset / 5
2015-07-23 18:23:22 +03:00
log('continueSession: multiplier ' + str(multiplier))
2015-01-09 14:11:21 +03:00
for i in range(self.startPart, self.startPart + self.partOffset):
if i <= self.endPart:
self.torrentHandle.piece_priority(i, 7)
2015-06-23 23:00:27 +03:00
if isMP4 and i % multiplier == 0:
self.torrentHandle.piece_priority(self.endPart - i / multiplier, 7)
if multiplier >= i:
2015-06-08 21:17:37 +03:00
self.torrentHandle.piece_priority(self.endPart - i, 7)
2015-01-09 14:11:21 +03:00
def checkThread(self):
if self.threadComplete == True:
2016-03-07 20:58:43 +03:00
self.resume_data()
2015-07-20 19:31:37 +03:00
log('checkThread KIIIIIIIIIIILLLLLLLLLLLLLLL')
try:
self.session.remove_torrent(self.torrentHandle)
except:
log('RuntimeError: invalid torrent handle used')
2015-08-02 15:26:16 +03:00
self.session.stop_natpmp()
self.session.stop_upnp()
self.session.stop_lsd()
2015-06-28 18:04:09 +03:00
self.session.stop_dht()
2015-01-09 14:11:21 +03:00
2016-02-25 22:29:18 +03:00
def resume_data(self):
2016-03-07 20:58:43 +03:00
wasPaused=self.session.is_paused()
2016-03-06 11:04:51 +03:00
self.session.pause()
self.save_resume_data=None
try:
if not self.torrentHandle.is_valid():
return
status = self.torrentHandle.status()
if not status.has_metadata:
return
if not status.need_save_resume:
return
log('[save_resume_data]: waiting for alert...')
2016-03-07 20:58:43 +03:00
self.torrentHandle.save_resume_data(self.lt.save_resume_flags_t.flush_disk_cache)
2016-03-06 11:04:51 +03:00
received=False
while not received:
self.session.wait_for_alert(1000)
a = self.session.pop_alert()
log('[save_resume_data]: ['+str(type(a))+'] the alert '+str(a)+' is received')
if type(a) == self.lt.save_resume_data_alert:
received = True
debug('[save_resume_data]: '+str(dir(a)))
self.save_resume_data=self.lt.bencode(a.resume_data)
log('[save_resume_data]: the torrent resume data are received')
try:
resumeFileHandler = xbmcvfs.File(self.resume_data_path(), "w+b")
resumeFileHandler.write(self.save_resume_data)
resumeFileHandler.close()
log('[save_resume_data]: the torrent resume data to file' + self.resume_data_path())
except:
log('[save_resume_data]: failed to save the torrent resume data to file')
elif type(a) == self.lt.save_resume_data_failed_alert:
received = True
log('[save_resume_data]: save_resume_data() failed')
log('[save_resume_data]: done.')
finally:
2016-03-07 20:58:43 +03:00
if not wasPaused:
self.session.resume()
2016-02-25 22:29:18 +03:00
2015-01-14 23:24:01 +03:00
def debug(self):
2015-08-20 18:07:03 +03:00
#try:
if 1==1:
2016-03-07 20:58:43 +03:00
# log(str(self.getFilePath(0)))
2015-01-14 23:24:01 +03:00
s = self.torrentHandle.status()
2015-07-26 21:44:46 +03:00
#get_cache_status=self.session.get_cache_status()
#log('get_cache_status - %s/%s' % (str(get_cache_status.blocks_written), str(get_cache_status.blocks_read)))
2015-06-23 23:00:27 +03:00
# get_settings=self.torrentHandle.status
2016-03-07 20:58:43 +03:00
# log(s.num_pieces)
2015-12-15 17:09:25 +03:00
#priorities = self.torrentHandle.piece_priorities()
2016-03-07 20:58:43 +03:00
#log(str(priorities))
2015-01-09 14:11:21 +03:00
state_str = ['queued', 'checking', 'downloading metadata',
2015-08-20 18:07:03 +03:00
'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']
2015-08-11 18:14:23 +03:00
log('[%s] %.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
2015-01-14 23:24:01 +03:00
(self.lt.version, s.progress * 100, s.download_rate / 1000,
2015-08-11 18:14:23 +03:00
s.upload_rate / 1000, s.num_peers, state_str[s.state]))
2015-07-26 21:44:46 +03:00
#log('%s %s' % (self.get_debug_info('dht_state'), self.get_debug_info('trackers_sum')))
2015-08-11 18:14:23 +03:00
#debug('TRACKERS:' +str(self.torrentHandle.trackers()))
#received=self.session.pop_alert()
#while received:
# debug('[debug]: ['+str(type(received))+'] the alert '+str(received)+' is received')
# #if type(received) == self.lt.torrent_finished_alert:
# # self.session.pause()
# received = self.session.pop_alert()
2015-07-26 21:44:46 +03:00
2015-07-24 20:22:30 +03:00
#log('is_dht_running:' +str(self.session.is_dht_running()))
#log('dht_state:' +str(self.session.dht_state()))
2015-07-23 18:23:22 +03:00
#i = 0
2015-06-23 23:00:27 +03:00
# for t in s.pieces:
2015-01-09 14:11:21 +03:00
# if t: i=i+1
2016-03-07 20:58:43 +03:00
#log(str(self.session.pop_alert())
# log(str(s.pieces[self.startPart:self.endPart]))
# log('True pieces: %d' % i)
# log(s.current_tracker)
# log(str(s.pieces))
2015-08-20 18:07:03 +03:00
#except:
else:
2015-12-23 18:26:19 +03:00
log('debug error')
2015-01-09 14:11:21 +03:00
pass
2015-07-24 20:22:30 +03:00
def get_debug_info(self, info):
result=''
if info in ['trackers_full','trackers_sum']:
trackers=[]
for tracker in self.torrentHandle.trackers():
trackers.append((tracker['url'], tracker['fails'], tracker['verified']))
if info=='trackers_full':
for url, fails, verified in trackers:
result=result+'%s: f=%d, v=%s' %(url, fails, str(verified))
if info=='trackers_sum':
fails_sum, verified_sum = 0, 0
for url, fails, verified in trackers:
fails_sum+=fails
if verified: verified_sum+=1
2015-07-26 21:44:46 +03:00
result=result+'Trackers: verified %d/%d, fails=%d' %(verified_sum, len(trackers)-1, fails_sum)
2015-07-24 20:22:30 +03:00
if info=='dht_state':
is_dht_running='ON' if self.session.is_dht_running() else 'OFF'
2015-12-15 17:09:25 +03:00
try:
nodes=self.session.dht_state().get('nodes')
except:
nodes=None
nodes=len(nodes) if nodes else 0
2015-07-24 20:22:30 +03:00
result='DHT: %s (%d)' % (is_dht_running, nodes)
return result
2015-01-09 14:11:21 +03:00
def dump(self, obj):
for attr in dir(obj):
try:
2015-12-23 18:26:19 +03:00
log("'%s':'%s'," % (attr, getattr(obj, attr)))
2015-01-09 14:11:21 +03:00
except:
2015-06-23 23:00:27 +03:00
pass
2016-03-06 11:04:51 +03:00
def resume_data_path(self):
path=self.torrentFile + ".resume_data"
return path