watched history, torr2http dialog

pull/1/head
DiMartinoXBMC 2015-12-24 20:17:39 +03:00
parent de2323f7af
commit a5704f7cc3
6 changed files with 630 additions and 422 deletions

File diff suppressed because it is too large Load Diff

View File

@ -37,7 +37,7 @@ import sys
from contextlib import contextmanager, closing, nested
from functions import calculate, showMessage, clearStorage, DownloadDB, get_ids_video, log, debug
from functions import calculate, showMessage, clearStorage, WatchedHistoryDB, get_ids_video, log, debug
from torrent2http import State, Engine, MediaType
@ -253,6 +253,10 @@ class AnteoPlayer(xbmc.Player):
seeding_run = False
ids_video = None
episodeId = None
fullSize = 0
watchedTime = 0
totalTime = 1
seek = 0
basename = ''
def __init__(self, userStorageDirectory, torrentUrl, params={}):
@ -263,6 +267,8 @@ class AnteoPlayer(xbmc.Player):
self.params = params
self.get = self.params.get
self.contentId = int(self.get("url"))
if self.get("seek"):
self.seek = int(self.get("seek"))
#self.torrent = AnteoLoader(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory)
self.init()
self.setup_engine()
@ -275,6 +281,7 @@ class AnteoPlayer(xbmc.Player):
if self.setup_play():
self.setup_subs()
self.loop()
WatchedHistoryDB().add(self.basename, self.watchedTime, self.totalTime, self.contentId, self.fullSize)
else:
log('[AnteoPlayer]: ************************************* break')
break
@ -379,22 +386,25 @@ class AnteoPlayer(xbmc.Player):
xbmc.sleep(500)
status = self.engine.status()
self.print_debug(status)
#self.print_fulldebug()
self.engine.check_torrent_error(status)
file_status = self.engine.file_status(self.contentId)
if not file_status:
continue
fullSize = file_status.size / 1024 / 1024
self.fullSize = int(file_status.size / 1024 / 1024)
downloadedSize = status.total_download / 1024 / 1024
getDownloadRate = status.download_rate / 1024 * 8
getUploadRate = status.upload_rate / 1024 * 8
getSeeds, getPeers = status.num_seeds, status.num_peers
iterator = int(round(float(file_status.download) / self.pre_buffer_bytes, 2) * 100)
if iterator > 99: iterator = 99
if status.state == State.QUEUED_FOR_CHECKING:
if status.state == State.CHECKING_FILES:
iterator = int(status.progress*100)
if iterator > 99: iterator = 99
progressBar.update(iterator, self.localize('Checking preloaded files...'), ' ', ' ')
elif status.state == State.DOWNLOADING:
dialogText = self.localize('Preloaded: ') + "%d MB / %d MB" % \
(int(downloadedSize), int(fullSize))
(int(downloadedSize), self.fullSize)
peersText = ' [%s: %s; %s: %s]' % (
self.localize('Seeds'), getSeeds, self.localize('Peers'), getPeers)
speedsText = '%s: %d Mbit/s; %s: %d Mbit/s' % (
@ -443,6 +453,8 @@ class AnteoPlayer(xbmc.Player):
def setup_play(self):
file_status = self.engine.file_status(self.contentId)
self.iterator = 0
self.watchedTime = 0
self.totalTime = 1
url = file_status.url
label = os.path.basename(file_status.name)
self.basename = label
@ -487,6 +499,12 @@ class AnteoPlayer(xbmc.Player):
player.play(url, listitem)
xbmc.sleep(2000) # very important, do not edit this, podavan
if self.seek > 0:
while not self.isPlaying():
xbmc.sleep(200)
log('seekTime')
log('[AnteoPlayer]: seekTime - '+str(self.seek))
self.seekTime(self.seek)
return True
def setup_subs(self):
@ -515,6 +533,8 @@ class AnteoPlayer(xbmc.Player):
#self.print_fulldebug()
status = self.engine.status()
file_status = self.engine.file_status(self.contentId)
self.watchedTime = xbmc.Player().getTime()
self.totalTime = xbmc.Player().getTotalTime()
if self.iterator == 100 and debug_counter < 100:
debug_counter += 1
else:

101
Core.py
View File

@ -54,12 +54,13 @@ class Core:
def sectionMenu(self):
if self.__settings__.getSetting('plugin_name') != self.__plugin__:
#Every update run
first_run_242()
self.__settings__.setSetting('plugin_name', self.__plugin__)
#check_network_advancedsettings()
check_download_dir()
if self.__plugin__ == 'Torrenter v.2.4.1b':
first_run_241()
pass
#if self.__plugin__ == 'Torrenter v.2.4.1b':
# first_run_242()
# pass
ListString = 'XBMC.RunPlugin(%s)' % (sys.argv[0] + '?action=%s&action2=%s&%s=%s')
contextMenu = [(self.localize('Search Control Window'),
@ -88,6 +89,13 @@ class Core:
contextMenu=DLScontextMenu, replaceMenu=False)
self.drawItem('< %s >' % self.localize('Torrent-client Browser'), 'uTorrentBrowser',
image=self.ROOT + '/icons/' + self.getTorrentClientIcon())
if self.history_bool:
WatchedHistorycontextMenu=[]
WatchedHistorycontextMenu.extend(contextMenu)
WatchedHistorycontextMenu.append(
(self.localize('Clear %s') % self.localize('Watched History'), ListString % ('WatchedHistory', 'clear', 'addtime', '')))
self.drawItem('< %s >' % self.localize('Watched History'), 'WatchedHistory',
image=self.ROOT + '/icons/watched.png', contextMenu=WatchedHistorycontextMenu, replaceMenu=False)
self.drawItem('< %s >' % self.localize('.torrent Player'), 'torrentPlayer',
image=self.ROOT + '/icons/torrentPlayer.png')
self.drawItem('< %s >' % self.localize('Search Control Window'), 'controlCenter',
@ -233,23 +241,27 @@ class Core:
lockView('wide')
def test(self, params={}):
from Anteoloader import AnteoPlayer
torrentUrl='D:\\test.torrent'
params['url']='0'
if not xbmcvfs.exists(torrentUrl):
action = xbmcgui.Dialog()
torrentUrl = action.browse(1, self.localize('Choose .torrent in video library'), 'video', '.torrent')
if torrentUrl and xbmcvfs.exists(torrentUrl):
if 0 != len(torrentUrl):
self.Downloader = Downloader.Torrent(self.userStorageDirectory, torrentUrl)
else:
log(self.__plugin__ + " Unexpected access to method Anteoloader() without torrent content")
#from Anteoloader import AnteoPlayer
#torrentUrl='D:\\test.torrent'
#params['url']='0'
#if not xbmcvfs.exists(torrentUrl):
# action = xbmcgui.Dialog()
# torrentUrl = action.browse(1, self.localize('Choose .torrent in video library'), 'video', '.torrent')
#if torrentUrl and xbmcvfs.exists(torrentUrl):
# if 0 != len(torrentUrl):
# self.Downloader = Downloader.Torrent(self.userStorageDirectory, torrentUrl)
# else:
# log(self.__plugin__ + " Unexpected access to method Anteoloader() without torrent content")
#if self.Downloader:
# x=self.Downloader.getContentList()
# print str(x)
# xbmc.sleep(1000)
# self.Downloader.__exit__()
self.Player = AnteoPlayer(userStorageDirectory=self.userStorageDirectory, torrentUrl=torrentUrl, params=params)
#self.Player = AnteoPlayer(userStorageDirectory=self.userStorageDirectory, torrentUrl=torrentUrl, params=params)
yes=xbmcgui.Dialog().yesno('< %s >' % (Localization.localize('Torrenter Update ') + '2.4.2'),
Localization.localize('New player to Torrenter v2 - Torrent2HTTP! It should be faster, '
'stable and better with Android, also seeking works in it.'),
Localization.localize('Would you like to try it?'),)
def DownloadStatus(self, params={}):
db = DownloadDB()
@ -449,6 +461,65 @@ class Core:
view_style('History')
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
def WatchedHistory(self, params={}):
db = WatchedHistoryDB()
get = params.get
action2 = get('action2')
url = get('url')
addtime = get('addtime')
if action2 == 'add':
db.add(url)
xbmc.executebuiltin('Container.Refresh')
showMessage(self.localize('Watched History'), self.localize('Added!'))
if action2 == 'delete':
db.delete(addtime)
xbmc.executebuiltin('Container.Refresh')
showMessage(self.localize('Watched History'), self.localize('Deleted!'))
if action2 == 'play':
filename, path, url, seek, length, ind = db.get('filename, path, url, seek, length, ind', 'addtime', str(addtime))
seek = int(seek) if int(seek) > 3*60 else 0
if seek > 0:
seek = seeking_warning(seek)
if os.path.exists(path):
self.__settings__.setSetting("lastTorrent", path)
else:
torrent = Downloader.Torrent(self.userStorageDirectory, torrentFilesDirectory=self.torrentFilesDirectory)
self.__settings__.setSetting("lastTorrent", torrent.saveTorrent(url))
xbmc.executebuiltin('xbmc.RunPlugin("plugin://plugin.video.torrenter/?action=playTorrent&url='+str(ind)+'&seek='+str(seek)+'")')
if action2 == 'clear':
db.clear()
showMessage(self.localize('Watched History'), self.localize('Clear!'))
if not action2:
items = db.get_all()
debug('[WatchedHistory]: items - '+str(items))
#favlist = [(1, '[B]%s[/B]'), (0, '%s')]
if items:
ListString = 'XBMC.RunPlugin(%s)' % (sys.argv[0] + '?action=%s&action2=%s&%s=%s')
#for favbool, bbstring in favlist:
for addtime, filename, path, url, seek, length, ind, size in items:
watchedPercent = int((float(seek) / float(length)) * 100)
duration = '%02d:%02d:%02d' % ((length / (60*60)), (length / 60) % 60, length % 60)
title = '[%d%%][%s] %s [%d MB]' % (watchedPercent, duration, filename.encode('utf-8'), int(size))
contextMenu = [(self.localize('Search Control Window'),
'xbmc.RunScript(%s,)' % os.path.join(ROOT, 'controlcenter.py'))]
if watchedPercent >= 85:
img = self.ROOT + '/icons/stop-icon.png'
else:
img = self.ROOT + '/icons/pause-icon.png'
contextMenu.append((self.localize('Delete from %s') % self.localize('Watched History'),
ListString % ('WatchedHistory', 'delete', 'addtime', str(addtime))))
link = {'url': str(ind), 'action2': 'play', 'addtime': str(addtime)}
self.drawItem(title, 'WatchedHistory', link, image=img, contextMenu=contextMenu, replaceMenu=False)
view_style('History')
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)
def List(self, params={}):
db = ListDB()
get = params.get

View File

@ -175,6 +175,9 @@ def localize(text):
'Added!': 'Добавлено',
'Deleted!': 'Удалено!',
'Search History': 'История Поиска',
' History ':' История ',
'Torrent History':'История Торрентов',
'Watched History':'История Просмотров',
'Favourites': 'Избранное',
'Favourites SH': 'Избранное ИП',
'Clear %s': 'Очистить %s',
@ -273,8 +276,13 @@ def localize(text):
'Please, restart Kodi now!':'Теперь перезагрузите Коди, пожалуйста!',
'./ (Root folder)':'./ (Корневой каталог)',
'Opening torrent file':'Открытие torrent-файла',
'New player to Torrenter v2 - Torrent2HTTP! It can be enabled in settings.':'В Torrenter новый плеер - Torrent2HTTP! Включить его можно в настройках.',
'It should be faster, stable and better with Android, also seeking works in it.':'Он стабильнее, быстрее и отлично ладит с Android, в нем работает перемотка.',
'New player to Torrenter v2 - Torrent2HTTP! It should be faster, stable and better with Android, also seeking works in it.':'В Torrenter новый плеер - Torrent2HTTP! Он стабильнее, быстрее и отлично ладит с Android, в нем работает перемотка.',
'Would you like to try it?':'Хотите его попробовать?',
'Torrent2HTTP enabled! Can be changed in Settings.':'Torrent2HTTP включен! Можно изменить в Настройках.',
'Seeking':'Перемотка',
'Would you like to resume from %s?':'Хотите начать проигрывать с %s?',
'Seeking is working only with player Torrent2HTTP.':'Перемотка работает только с плеером Torrent2HTTP.',
},
'uk': {
'Seeds searching.': 'Йде пошук сідів.',

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="plugin.video.torrenter" name="Torrenter" version="2.4.1b" provider-name="vadim.skorba, DiMartino">
<addon id="plugin.video.torrenter" name="Torrenter" version="2.4.2" provider-name="vadim.skorba, DiMartino">
<requires>
<import addon="xbmc.python" version="2.1.0"/>
<import addon="script.module.libtorrent"/>

View File

@ -1000,6 +1000,102 @@ class HistoryDB:
self.db.close()
class WatchedHistoryDB:
def __init__(self, version=1.2):
self.name = 'watched_history.db3'
self.version = version
self.history_bool = __settings__.getSetting('history') == 'true'
def get_all(self):
self._connect()
self.cur.execute('select addtime,filename,path,url,seek,length,ind,size from history order by addtime DESC')
x = self.cur.fetchall()
self._close()
return x if x else None
def get(self, get, by, equal):
self._connect()
self.cur.execute('select '+get+' from history where '+by+'="' + equal + '"')
x = self.cur.fetchone()
self._close()
return x if x else None
def add(self, filename, seek = 0, length = 1, ind = 0, size = 0):
if self.history_bool:
self._connect()
url = __settings__.getSetting("lastTorrentUrl")
path = __settings__.getSetting("lastTorrent")
self.cur.execute('delete from history where filename="' + decode(filename) + '"')
self.cur.execute('insert into history(addtime,filename,path,url,seek,length,ind,size)'
' values(?,?,?,?,?,?,?,?)', (int(time.time()), decode(filename), decode(path),
decode(url), str(int(seek)), str(int(length)), str(ind), str(size)))
self.db.commit()
self._close()
def update(self, what, to, by, equal):
self._connect()
self.cur.execute('UPDATE history SET '+what+' = ' + to + ' where '+by+'=' + equal)
self.db.commit()
self._close()
def delete(self, addtime):
self._connect()
self.cur.execute('delete from history where addtime="' + addtime + '"')
self.db.commit()
self._close()
def clear(self):
self._connect()
self.cur.execute('delete from history')
self.db.commit()
self._close()
def _connect(self):
dirname = xbmc.translatePath('special://temp')
for subdir in ('xbmcup', 'plugin.video.torrenter'):
dirname = os.path.join(dirname, subdir)
if not xbmcvfs.exists(dirname):
xbmcvfs.mkdir(dirname)
self.filename = os.path.join(dirname, self.name)
first = False
if not xbmcvfs.exists(self.filename):
first = True
self.db = sqlite.connect(self.filename, check_same_thread=False)
if not first:
self.cur = self.db.cursor()
try:
self.cur.execute('select version from db_ver')
row = self.cur.fetchone()
if not row or float(row[0]) != self.version:
self.cur.execute('drop table history')
self.cur.execute('drop table if exists db_ver')
first = True
self.db.commit()
self.cur.close()
except:
self.cur.execute('drop table history')
first = True
self.db.commit()
self.cur.close()
if first:
cur = self.db.cursor()
cur.execute('pragma auto_vacuum=1')
cur.execute('create table db_ver(version real)')
cur.execute(
'create table history(addtime integer PRIMARY KEY, filename varchar(32), path varchar(32), url varchar(32), seek integer, length integer, ind integer, size integer)')
cur.execute('insert into db_ver(version) values(?)', (self.version,))
self.db.commit()
cur.close()
self.cur = self.db.cursor()
def _close(self):
self.cur.close()
self.db.close()
class Searchers():
def __init__(self):
pass
@ -1637,10 +1733,43 @@ def first_run_231():
xbmc.executebuiltin('Dialog.Close(all,true)')
xbmc.executebuiltin('XBMC.ActivateWindow(Addonbrowser,addons://search/%s)' % ('Torrenter Searcher'))
def first_run_241():
ok = xbmcgui.Dialog().ok('< %s >' % Localization.localize('Torrenter Update ') + '2.4.1',
Localization.localize('New player to Torrenter v2 - Torrent2HTTP! It can be enabled in settings.'),
Localization.localize('It should be faster, stable and better with Android, also seeking works in it.'))
def first_run_242():
if __settings__.getSetting('torrent_player')=='2':
__settings__.setSetting('first_run_242','True')
if not __settings__.getSetting('first_run_242')=='True':
__settings__.setSetting('first_run_242','True')
yes=xbmcgui.Dialog().yesno('< %s >' % (Localization.localize('Torrenter Update ') + '2.4.2'),
Localization.localize('New player to Torrenter v2 - Torrent2HTTP! It should be faster, '
'stable and better with Android, also seeking works in it.'),
Localization.localize('Would you like to try it?'),)
if yes:
__settings__.setSetting('torrent_player','2')
ok = xbmcgui.Dialog().ok('< %s >' % (Localization.localize('Torrenter Update ') + '2.4.2'),
Localization.localize('Torrent2HTTP enabled! Can be changed in Settings.'))
def seeking_warning(seek):
if __settings__.getSetting('torrent_player')=='2':
seek_point = '%02d:%02d:%02d' % ((seek / (60*60)), (seek / 60) % 60, seek % 60)
yes=xbmcgui.Dialog().yesno('< %s >' % (Localization.localize('Seeking')),
Localization.localize('Would you like to resume from %s?') % seek_point,)
if yes:
log('[seeking_warning]: yes, seek = '+str(seek))
return seek
else:
log('[seeking_warning]: no, seek = '+str(0))
return 0
else:
if not __settings__.getSetting('seeking_warning')=='True':
__settings__.setSetting('seeking_warning','True')
yes=xbmcgui.Dialog().yesno('< %s >' % (Localization.localize('Seeking')),
Localization.localize('Seeking is working only with player Torrent2HTTP.'),
Localization.localize('Would you like to try it?'))
if yes:
__settings__.setSetting('torrent_player','2')
ok = xbmcgui.Dialog().ok('< %s >' % (Localization.localize('Seeking')),
Localization.localize('Torrent2HTTP enabled! Can be changed in Settings.'))
return seek
def noActiveSerachers():
yes=xbmcgui.Dialog().yesno('< %s >' % Localization.localize('Torrenter v2'),