KoD 0.9.1

- fix vari ed eventuali
This commit is contained in:
marco
2020-04-20 23:49:45 +02:00
parent dc3d2d4d2a
commit ca0b5a8c56
28 changed files with 1048 additions and 798 deletions
+2 -9
View File
@@ -1,4 +1,4 @@
<addon id="plugin.video.kod" name="Kodi on Demand" provider-name="KoD Team" version="0.9"> <addon id="plugin.video.kod" name="Kodi on Demand" provider-name="KoD Team" version="0.9.1">
<requires> <requires>
<import addon="script.module.libtorrent" optional="true"/> <import addon="script.module.libtorrent" optional="true"/>
<import addon="metadata.themoviedb.org"/> <import addon="metadata.themoviedb.org"/>
@@ -18,14 +18,7 @@
<screenshot>resources/media/themes/ss/2.png</screenshot> <screenshot>resources/media/themes/ss/2.png</screenshot>
<screenshot>resources/media/themes/ss/3.png</screenshot> <screenshot>resources/media/themes/ss/3.png</screenshot>
</assets> </assets>
<news>- Nuova sezione Musica <news>- fix vari ed eventuali</news>
- Download in Background
- Download dalla Videoteca e supporto file locali
- Backup e cancellazione della Videoteca
- Spostamento della Videoteca
- Migliorata integrazione con libreria di Kodi
- Gestione delle Viste Preferite
- Nuovo layout impostazioni</news>
<description lang="it">Naviga velocemente sul web e guarda i contenuti presenti</description> <description lang="it">Naviga velocemente sul web e guarda i contenuti presenti</description>
<disclaimer>[COLOR red]The owners and submitters to this addon do not host or distribute any of the content displayed by these addons nor do they have any affiliation with the content providers.[/COLOR] <disclaimer>[COLOR red]The owners and submitters to this addon do not host or distribute any of the content displayed by these addons nor do they have any affiliation with the content providers.[/COLOR]
[COLOR yellow]Kodi © is a registered trademark of the XBMC Foundation. We are not connected to or in any other way affiliated with Kodi, Team Kodi, or the XBMC Foundation. Furthermore, any software, addons, or products offered by us will receive no support in official Kodi channels, including the Kodi forums and various social networks.[/COLOR]</disclaimer> [COLOR yellow]Kodi © is a registered trademark of the XBMC Foundation. We are not connected to or in any other way affiliated with Kodi, Team Kodi, or the XBMC Foundation. Furthermore, any software, addons, or products offered by us will receive no support in official Kodi channels, including the Kodi forums and various social networks.[/COLOR]</disclaimer>
+1
View File
@@ -26,6 +26,7 @@
"guardaserie_stream": "https://guardaserie.store", "guardaserie_stream": "https://guardaserie.store",
"guardaserieclick": "https://www.guardaserie.productions", "guardaserieclick": "https://www.guardaserie.productions",
"hd4me": "https://hd4me.net", "hd4me": "https://hd4me.net",
"ilcorsaronero": "https://ilcorsaronero.pizza",
"ilgeniodellostreaming": "https://ilgeniodellostreaming.pl", "ilgeniodellostreaming": "https://ilgeniodellostreaming.pl",
"italiaserie": "https://italiaserie.org", "italiaserie": "https://italiaserie.org",
"mondoserietv": "https://mondoserietv.com", "mondoserietv": "https://mondoserietv.com",
+2 -2
View File
@@ -105,7 +105,7 @@ def peliculas(item):
'Aggiornamento Quotidiano Serie TV', 'OSCAR 2019 ▶ CB01.UNO: Vota il tuo film preferito! 🎬', 'Aggiornamento Quotidiano Serie TV', 'OSCAR 2019 ▶ CB01.UNO: Vota il tuo film preferito! 🎬',
'Openload: la situazione. Benvenuto Verystream', 'Openload: lo volete ancora?', 'Openload: la situazione. Benvenuto Verystream', 'Openload: lo volete ancora?',
'OSCAR 2020 &#x25b6; VOTA IL TUO FILM PREFERITO! &#x1f3ac;'] 'OSCAR 2020 &#x25b6; VOTA IL TUO FILM PREFERITO! &#x1f3ac;']
# debug= True
if 'newest' in item.args: if 'newest' in item.args:
if '/serietv/' not in item.url: if '/serietv/' not in item.url:
pagination = '' pagination = ''
@@ -118,7 +118,7 @@ def peliculas(item):
action = 'episodios' action = 'episodios'
elif '/serietv/' not in item.url: elif '/serietv/' not in item.url:
patron = r'<div class="card-image">\s<a[^>]+>\s*<img src="(?P<thumb>[^" ]+)" alt[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+><a href="?(?P<url>[^" >]+)(?:\/|"|\s+)>(?P<title>[^<[(]+)(?:\[(?P<quality>[A-Za-z0-9/-]+)])? (?:\((?P<year>[0-9]{4})\))?[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>(?P<genre>[^<>&–]+)(?:[^ ]+\s*DURATA\s*(?P<duration>[0-9]+)[^>]+>[^>]+>[^>]+>(?P<plot>[^<>]+))?' patron = r'<div class="card-image">\s*<a[^>]+>\s*<img src="(?P<thumb>[^" ]+)" alt[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+><a href="?(?P<url>[^" >]+)(?:\/|"|\s+)>(?P<title>[^<[(]+)(?:\[(?P<quality>[A-Za-z0-9/-]+)])? (?:\((?P<year>[0-9]{4})\))?[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>(?P<genre>[^<>&–]+)(?:[^ ]+\s*DURATA\s*(?P<duration>[0-9]+)[^>]+>[^>]+>[^>]+>(?P<plot>[^<>]+))?'
action = 'findvideos' action = 'findvideos'
else: else:
+1 -1
View File
@@ -155,6 +155,6 @@ def newest(categoria):
def findvideos(item): def findvideos(item):
if item.contentType == 'movie': if item.contentType == 'movie':
data = httptools.downloadpage(item.url).data data = httptools.downloadpage(item.url).data
return support.server(item, data=data) return support.server(item, data=data, patronTag='Versione: <[^>]+>([^<]+)')
else: else:
return support.server(item, item.url) return support.server(item, item.url)
+9 -2
View File
@@ -22,8 +22,11 @@ def mainlist(item):
@support.scrape @support.scrape
def peliculas(item): def peliculas(item):
# debug = True # debug = True
patron = r'<a href="(?P<url>[^"]+)" rel="[^"]+" title="(?P<title>[^\(]+)(?!\()\s*\((?P<year>\d+)\)\s\D+(?P<quality>\d+p) ... (?P<lang>[^ ]+).*?<img id="cov" src="(?P<thumb>[^"]+)"' if item.args == 'alternative':
patronNext = r'rel="next" href="([^"]+)"' patron = r'<a title="(?P<title>[^\(]+)\(\s*(?P<year>\d+)\)\s\D+(?P<quality>\d+p) ... (?P<lang>[^ ]+).*?[^"]+"\s*href="(?P<url>[^"]+)'
else:
patron = r'<a href="(?P<url>[^"]+)" rel="[^"]+" title="(?P<title>[^\(]+)(?!\()\s*\((?P<year>\d+)\)\s\D+(?P<quality>\d+p) ... (?P<lang>[^ ]+).*?<img id="cov" src="(?P<thumb>[^"]+)"'
patronNext = r'rel="next" href="([^"]+)"'
return locals() return locals()
@support.scrape @support.scrape
@@ -31,6 +34,10 @@ def genre(item):
action = 'peliculas' action = 'peliculas'
blacklist =['prova '] blacklist =['prova ']
patronMenu = r'<a href="(?P<url>[^"]+)" class="menu-link\s*sub-menu-link">(?P<title>[^<]+)<' patronMenu = r'<a href="(?P<url>[^"]+)" class="menu-link\s*sub-menu-link">(?P<title>[^<]+)<'
def itemHook(item):
if item.fulltitle in ['Classici Disney', 'Studio Ghibli', 'Pixar']:
item.args = 'alternative'
return item
return locals() return locals()
+12
View File
@@ -0,0 +1,12 @@
{
"id": "ilcorsaronero",
"name": "ilCorSaRoNeRo",
"active": false,
"adult": false,
"language": ["ita"],
"thumbnail": "ilcorsaronero.png",
"banner": "ilcorsaronero.png",
"categories": ["movie", "tvshow", "music", "torrent"],
"not_active": ["include_in_newest"],
"settings": []
}
+82
View File
@@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Canale per ilcorsaronero
# ------------------------------------------------------------
from core import support
host = support.config.get_channel_url()
# host = 'https://ilcorsaronero.xyz'
headers = [['Referer', host]]
list_servers = ['torrent']
list_quality = ['default']
@support.menu
def mainlist(item):
menu = [
('BDRiP {film}', ['/categoria.php?active=0&category=1&order=data&by=DESC&page=', 'peliculas', [0, 'movie']]),
('Cerca BDRiP... submenu {film}', ['/categoria.php?active=0&category=1&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('DVD {film}', ['/categoria.php?active=0&category=20&order=data&by=DESC&page=', 'peliculas', [0, 'movie']]),
('Cerca DVD... submenu {film}', ['/categoria.php?active=0&category=20&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('Screener {film}', ['/categoria.php?active=0&category=19&order=data&by=DESC&page=', 'peliculas', [0, 'movie']]),
('Cerca Screener.. submenu {film}', ['/categoria.php?active=0&category=19&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('Serie TV', ['/categoria.php?active=0&category=15&order=data&by=DES&page=', 'peliculas', [0 , 'tvshow']]),
('Cerca Serie TV.. submenu', ['/categoria.php?active=0&category=15&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('Anime', ['/categoria.php?active=0&category=5&order=data&by=DESC&page=', 'peliculas', [0, 'anime']]),
('Cerca Anime.. submenu', ['/categoria.php?active=0&category=5&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('Musica', ['/categoria.php?active=0&category=2&order=data&by=DESC&page=', 'peliculas', [0, 'music']]),
('Cerca Musica.. submenu', ['/categoria.php?active=0&category=2&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('Audiolibri {musica}', ['/categoria.php?active=0&category=18&order=data&by=DESC&page=', 'peliculas', [0, 'music']]),
('Cerca Audiolibri.. submenu', ['/categoria.php?active=0&category=18&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('Altro {film}', ['/categoria.php?active=0&category=4&order=data&by=DESC&page=', 'peliculas', [0, 'movie']]),
('Cerca altro.. submenu', ['/categoria.php?active=0&category=4&order=data&by=DESC&argh.php?search=', 'search', 'search']),
('Cerca Tutto... color kod bold', ['/argh.php?search=', 'search', 'search'])
]
return locals()
@support.scrape
def peliculas(item):
patron = r'>(?P<quality>[^"<]+)</td> <TD[^>]+><A class="tab" HREF="(?P<url>[^"]+)"\s*>(?P<title>[^<]+)<[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>(?P<size>[^<]+)<[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>(?P<seed>[^<]+)'
def itemHook(item):
item.title = item.title.replace('.',' ')
thumb = (item.args[1] if type(item.args) == list else item.args) + '.png'
item.thumbnail = support.thumb(thumb=thumb)
return item
if 'search' not in item.args:
support.log('OK')
item.url += str(item.args[0])
def itemlistHook(itemlist):
itemlist.append(
support.Item(channel=item.channel,
action = item.action,
contentType=item.contentType,
title=support.typo(support.config.get_localized_string(30992), 'color kod bold'),
url=item.url,
args=item.args[0] + 1,
thumbnail=support.thumb()))
return itemlist
return locals()
def search(item, text):
support.log(item, text)
itemlist = []
item.url += text
try:
return peliculas(item)
# Cattura la eccezione così non interrompe la ricerca globle se il canale si rompe!
except:
import sys
for line in sys.exc_info():
support.logger.error("search except: %s" % line)
return []
def findvideos(item):
video_library = True if 'movie' in item.args else False
return support.server(item, support.match(item.url, patron=r'"(magnet[^"]+)').match,down_load=False, video_library=video_library)
+1
View File
@@ -203,4 +203,5 @@ def findvideos(item):
log('URLS',urls) log('URLS',urls)
itemlist = support.server(item, urls) itemlist = support.server(item, urls)
support.addQualityTag(item, itemlist, data, 'Keywords:\s*(?:<span>)?([^<]+)')
return itemlist return itemlist
+2 -1
View File
@@ -100,7 +100,8 @@ def getchanneltypes(view="thumb_"):
logger.info() logger.info()
# Lista de categorias # Lista de categorias
channel_types = ["movie", "tvshow", "anime", "documentary", "vos", "direct", "live", "music"] # , "torrent" # channel_types = ["movie", "tvshow", "anime", "documentary", "vos", "direct", "live", "torrent", "music"]
channel_types = ["movie", "tvshow", "anime", "documentary", "vos", "direct", "live", "music"]
if config.get_setting("adult_mode") != 0: if config.get_setting("adult_mode") != 0:
channel_types.append("adult") channel_types.append("adult")
+1 -1
View File
@@ -120,7 +120,7 @@ def unescape(text):
pass pass
return text # leave as is return text # leave as is
return re.sub("&#?\w+;", str(fixup), str(text)) return re.sub("&#?\w+;", fixup, str(text))
# Convierte los codigos html "&ntilde;" y lo reemplaza por "ñ" caracter unicode utf-8 # Convierte los codigos html "&ntilde;" y lo reemplaza por "ñ" caracter unicode utf-8
+134 -122
View File
@@ -179,7 +179,7 @@ def scrapeBlock(item, args, block, patron, headers, action, pagination, debug, t
matches = scrapertools.find_multiple_matches_groups(block, patron) matches = scrapertools.find_multiple_matches_groups(block, patron)
log('MATCHES =', matches) log('MATCHES =', matches)
known_keys = ['url', 'title', 'title2', 'season', 'episode', 'thumb', 'quality', 'year', 'plot', 'duration', 'genere', 'rating', 'type', 'lang', 'other'] known_keys = ['url', 'title', 'title2', 'season', 'episode', 'thumb', 'quality', 'year', 'plot', 'duration', 'genere', 'rating', 'type', 'lang', 'other', 'size', 'seed']
# Legenda known_keys per i groups nei patron # Legenda known_keys per i groups nei patron
# known_keys = ['url', 'title', 'title2', 'season', 'episode', 'thumb', 'quality', # known_keys = ['url', 'title', 'title2', 'season', 'episode', 'thumb', 'quality',
# 'year', 'plot', 'duration', 'genere', 'rating', 'type', 'lang'] # 'year', 'plot', 'duration', 'genere', 'rating', 'type', 'lang']
@@ -246,6 +246,8 @@ def scrapeBlock(item, args, block, patron, headers, action, pagination, debug, t
longtitle = title + (s if title and title2 else '') + title2 longtitle = title + (s if title and title2 else '') + title2
longtitle = typo(longtitle, 'bold') longtitle = typo(longtitle, 'bold')
longtitle += typo(quality, '_ [] color kod') if quality else '' longtitle += typo(quality, '_ [] color kod') if quality else ''
longtitle += typo(scraped['size'], '_ [] color kod') if scraped['size'] else ''
longtitle += typo(scraped['seed']+ ' SEEDS', '_ [] color kod') if scraped['seed'] else ''
lang1, longtitle = scrapeLang(scraped, lang, longtitle) lang1, longtitle = scrapeLang(scraped, lang, longtitle)
@@ -457,7 +459,7 @@ def scrape(func):
if addVideolibrary and (item.infoLabels["title"] or item.fulltitle): if addVideolibrary and (item.infoLabels["title"] or item.fulltitle):
# item.fulltitle = item.infoLabels["title"] # item.fulltitle = item.infoLabels["title"]
videolibrary(itemlist, item, function=function) videolibrary(itemlist, item, function=function)
if config.get_setting('downloadenabled') and (function == 'episodios' or function == 'findvideos'): if function == 'episodios' or function == 'findvideos':
download(itemlist, item, function=function) download(itemlist, item, function=function)
if 'patronMenu' in args and itemlist: if 'patronMenu' in args and itemlist:
@@ -904,69 +906,70 @@ def match_dbg(data, patron):
def download(itemlist, item, typography='', function_level=1, function=''): def download(itemlist, item, typography='', function_level=1, function=''):
if not typography: typography = 'color kod bold' if config.get_setting('downloadenabled'):
if not typography: typography = 'color kod bold'
if item.contentType == 'movie': if item.contentType == 'movie':
from_action = 'findvideos' from_action = 'findvideos'
title = typo(config.get_localized_string(60354), typography) title = typo(config.get_localized_string(60354), typography)
elif item.contentType == 'episode': elif item.contentType == 'episode':
from_action = 'findvideos' from_action = 'findvideos'
title = typo(config.get_localized_string(60356), typography) + ' - ' + item.title title = typo(config.get_localized_string(60356), typography) + ' - ' + item.title
else: else:
from_action = 'episodios' from_action = 'episodios'
title = typo(config.get_localized_string(60355), typography) title = typo(config.get_localized_string(60355), typography)
function = function if function else inspect.stack()[function_level][3] function = function if function else inspect.stack()[function_level][3]
contentSerieName=item.contentSerieName if item.contentSerieName else '' contentSerieName=item.contentSerieName if item.contentSerieName else ''
contentTitle=item.contentTitle if item.contentTitle else '' contentTitle=item.contentTitle if item.contentTitle else ''
downloadItemlist = [i.tourl() for i in itemlist] downloadItemlist = [i.tourl() for i in itemlist]
if itemlist and item.contentChannel != 'videolibrary': if itemlist and item.contentChannel != 'videolibrary':
show = True show = True
# do not show if we are on findvideos and there are no valid servers # do not show if we are on findvideos and there are no valid servers
if from_action == 'findvideos': if from_action == 'findvideos':
for i in itemlist: for i in itemlist:
if i.action == 'play': if i.action == 'play':
break break
else: else:
show = False show = False
if show: if show:
itemlist.append( itemlist.append(
Item(channel='downloads', Item(channel='downloads',
from_channel=item.channel, from_channel=item.channel,
title=title, title=title,
fulltitle=item.fulltitle, fulltitle=item.fulltitle,
show=item.fulltitle, show=item.fulltitle,
contentType=item.contentType, contentType=item.contentType,
contentSerieName=contentSerieName, contentSerieName=contentSerieName,
url=item.url, url=item.url,
action='save_download', action='save_download',
from_action=from_action, from_action=from_action,
contentTitle=contentTitle, contentTitle=contentTitle,
path=item.path, path=item.path,
thumbnail=thumb(thumb='downloads.png'), thumbnail=thumb(thumb='downloads.png'),
downloadItemlist=downloadItemlist downloadItemlist=downloadItemlist
))
if from_action == 'episodios':
itemlist.append(
Item(channel='downloads',
from_channel=item.channel,
title=typo(config.get_localized_string(60357),typography),
fulltitle=item.fulltitle,
show=item.fulltitle,
contentType=item.contentType,
contentSerieName=contentSerieName,
url=item.url,
action='save_download',
from_action=from_action,
contentTitle=contentTitle,
download='season',
thumbnail=thumb(thumb='downloads.png'),
downloadItemlist=downloadItemlist
)) ))
if from_action == 'episodios':
itemlist.append(
Item(channel='downloads',
from_channel=item.channel,
title=typo(config.get_localized_string(60357),typography),
fulltitle=item.fulltitle,
show=item.fulltitle,
contentType=item.contentType,
contentSerieName=contentSerieName,
url=item.url,
action='save_download',
from_action=from_action,
contentTitle=contentTitle,
download='season',
thumbnail=thumb(thumb='downloads.png'),
downloadItemlist=downloadItemlist
))
return itemlist return itemlist
def videolibrary(itemlist, item, typography='', function_level=1, function=''): def videolibrary(itemlist, item, typography='', function_level=1, function=''):
@@ -1133,7 +1136,7 @@ def controls(itemlist, item, AutoPlay=True, CheckLinks=True, down_load=True, vid
autoplay.start(itemlist, item) autoplay.start(itemlist, item)
if item.contentChannel != 'videolibrary' and video_library: videolibrary(itemlist, item, function_level=3) if item.contentChannel != 'videolibrary' and video_library: videolibrary(itemlist, item, function_level=3)
if get_setting('downloadenabled') and down_load == True: download(itemlist, item, function_level=3) if down_load == True: download(itemlist, item, function_level=3)
VL = False VL = False
try: try:
@@ -1192,67 +1195,76 @@ def extract_wrapped(decorated):
return next((c for c in closure if isinstance(c, FunctionType)), None) return next((c for c in closure if isinstance(c, FunctionType)), None)
def addQualityTag(item, itemlist, data, patron): def addQualityTag(item, itemlist, data, patron):
defQualVideo = { if itemlist:
"CAM": "metodo di ripresa che indica video di bassa qualità", defQualVideo = {
"TS": "questo metodo di ripresa effettua la ripresa su un tre piedi. Qualità sufficiente.", "CAM": "metodo di ripresa che indica video di bassa qualità",
"TC": "abbreviazione di TeleCine. Il metodo di ripresa del film è basato su una macchina capace di riversare le Super-8, o 35mm. La qualità è superiore a quella offerta da CAM e TS.", "TS": "questo metodo di ripresa effettua la ripresa su un tre piedi. Qualità sufficiente.",
"R5": "la qualità video di un R5 è pari a quella di un dvd, può contenere anche sottotitoli. Se è presente la dicitura LINE.ITALIAN è in italiano, altrimenti sarà disponibile in una lingua asiatica o russa.", "TC": "abbreviazione di TeleCine. Il metodo di ripresa del film è basato su una macchina capace di riversare le Super-8, o 35mm. La qualità è superiore a quella offerta da CAM e TS.",
"R6": "video proveniente dallAsia.", "R5": "la qualità video di un R5 è pari a quella di un dvd, può contenere anche sottotitoli. Se è presente la dicitura LINE.ITALIAN è in italiano, altrimenti sarà disponibile in una lingua asiatica o russa.",
"FS": "video a schermo pieno, cioè FullScreen, quindi con un rapporto di 4:3.", "R6": "video proveniente dallAsia.",
"WS": "video WideScreen, cioè rapporto 16:9.", "FS": "video a schermo pieno, cioè FullScreen, quindi con un rapporto di 4:3.",
"VHSSCR": "video estratto da una videocassetta VHS.", "WS": "video WideScreen, cioè rapporto 16:9.",
"DVDRIP": "la fonte video proviene da un DVD, la qualità è buona.", "VHSSCR": "video estratto da una videocassetta VHS.",
"DVDSCR": "la fonte video proviene da un DVD. Tali filmati, di solito, appartengono a copie promozionali.", "DVDRIP": "la fonte video proviene da un DVD, la qualità è buona.",
"HDTVRIP": "video copiato e registrato da televisori in HD e che, per questo, restituiscono una qualità eccellente.", "DVDSCR": "la fonte video proviene da un DVD. Tali filmati, di solito, appartengono a copie promozionali.",
"PD": "video registrato da Tv satellitare, qualità accettabile.", "HDTVRIP": "video copiato e registrato da televisori in HD e che, per questo, restituiscono una qualità eccellente.",
"TV": "video registrato da Tv satellitare, qualità accettabile.", "PD": "video registrato da Tv satellitare, qualità accettabile.",
"SAT": "video registrato da Tv satellitare, qualità accettabile.", "TV": "video registrato da Tv satellitare, qualità accettabile.",
"DVBRIP": "video registrato da Tv satellitare, qualità accettabile.", "SAT": "video registrato da Tv satellitare, qualità accettabile.",
"TVRIP": "ripping simile al SAT RIP, solo che, in questo caso, la qualità del vide può variare a seconda dei casi.", "DVBRIP": "video registrato da Tv satellitare, qualità accettabile.",
"VHSRIP": "video registrato da videocassetta. Qualità variabile.", "TVRIP": "ripping simile al SAT RIP, solo che, in questo caso, la qualità del vide può variare a seconda dei casi.",
"BRRIP": "indica che il video è stato preso da una fonte BluRay. Nella maggior parte dei casi, avremo un video ad alta definizione.", "VHSRIP": "video registrato da videocassetta. Qualità variabile.",
"BDRIP": "indica che il video è stato preso da una fonte BluRay. Nella maggior parte dei casi, avremo un video ad alta definizione.", "BRRIP": "indica che il video è stato preso da una fonte BluRay. Nella maggior parte dei casi, avremo un video ad alta definizione.",
"DTTRIP": "video registrato da un canale digitale terreste. Qualità sufficiente.", "BDRIP": "indica che il video è stato preso da una fonte BluRay. Nella maggior parte dei casi, avremo un video ad alta definizione.",
"HQ": "video in alta qualità.", "DTTRIP": "video registrato da un canale digitale terreste. Qualità sufficiente.",
"WEBRIP": "in questo caso, i film sono estratti da portali relativi a canali televisivi o di video sharing come YouTube. La qualità varia dallSD al 1080p.", "HQ": "video in alta qualità.",
"WEB-DL": "si tratta di un 720p o 1080p reperiti dalla versione americana di iTunes americano. La qualità è paragonabile a quella di un BluRayRip e permette di fruire di episodi televisivi, senza il fastidioso bollo distintivo della rete che trasmette.", "WEBRIP": "in questo caso, i film sono estratti da portali relativi a canali televisivi o di video sharing come YouTube. La qualità varia dallSD al 1080p.",
"WEBDL": "si tratta di un 720p o 1080p reperiti dalla versione americana di iTunes americano. La qualità è paragonabile a quella di un BluRayRip e permette di fruire di episodi televisivi, senza il fastidioso bollo distintivo della rete che trasmette.", "WEB-DL": "si tratta di un 720p o 1080p reperiti dalla versione americana di iTunes americano. La qualità è paragonabile a quella di un BluRayRip e permette di fruire di episodi televisivi, senza il fastidioso bollo distintivo della rete che trasmette.",
"DLMux": "si tratta di un 720p o 1080p reperiti dalla versione americana di iTunes americano. La qualità è paragonabile a quella di un BluRayRip e permette di fruire di episodi televisivi, senza il fastidioso bollo distintivo della rete che trasmette.", "WEBDL": "si tratta di un 720p o 1080p reperiti dalla versione americana di iTunes americano. La qualità è paragonabile a quella di un BluRayRip e permette di fruire di episodi televisivi, senza il fastidioso bollo distintivo della rete che trasmette.",
"DVD5": "il film è in formato DVD Single Layer, nel quale vengono mantenute tutte le caratteristiche del DVD originale: tra queste il menu multilingue, i sottotitoli e i contenuti speciali, se presenti. Il video è codificato nel formato DVD originale MPEG-2.", "DLMux": "si tratta di un 720p o 1080p reperiti dalla versione americana di iTunes americano. La qualità è paragonabile a quella di un BluRayRip e permette di fruire di episodi televisivi, senza il fastidioso bollo distintivo della rete che trasmette.",
"DVD9": "ha le stesse caratteristiche del DVD5, ma le dimensioni del file sono di un DVD Dual Layer (8,5 GB).", "DVD5": "il film è in formato DVD Single Layer, nel quale vengono mantenute tutte le caratteristiche del DVD originale: tra queste il menu multilingue, i sottotitoli e i contenuti speciali, se presenti. Il video è codificato nel formato DVD originale MPEG-2.",
"HDTS": "viene utilizzata una videocamera professionale ad alta definizione posizionata in modo fisso. La qualità audio video è buona.", "DVD9": "ha le stesse caratteristiche del DVD5, ma le dimensioni del file sono di un DVD Dual Layer (8,5 GB).",
"DVDMUX": "indica una buona qualità video, laudio è stato aggiunto da una sorgente diversa per una migliore qualità.", "HDTS": "viene utilizzata una videocamera professionale ad alta definizione posizionata in modo fisso. La qualità audio video è buona.",
} "DVDMUX": "indica una buona qualità video, laudio è stato aggiunto da una sorgente diversa per una migliore qualità.",
}
defQualAudio = { defQualAudio = {
"MD": "laudio è stato registrato via microfono, quindi la qualità è scarsa.", "MD": "laudio è stato registrato via microfono, quindi la qualità è scarsa.",
"DTS": "audio ricavato dai dischi DTS2, quindi la qualità audio è elevata.", "DTS": "audio ricavato dai dischi DTS2, quindi la qualità audio è elevata.",
"LD": "laudio è stato registrato tramite jack collegato alla macchina da presa, pertanto di discreta qualità.", "LD": "laudio è stato registrato tramite jack collegato alla macchina da presa, pertanto di discreta qualità.",
"DD": "audio ricavato dai dischi DTS cinema. Laudio è di buona qualità, ma potreste riscontrare il fatto che non potrebbe essere più riproducibile.", "DD": "audio ricavato dai dischi DTS cinema. Laudio è di buona qualità, ma potreste riscontrare il fatto che non potrebbe essere più riproducibile.",
"AC3": "audio in Dolby Digital puo' variare da 2.0 a 5.1 canali in alta qualità.", "AC3": "audio in Dolby Digital puo' variare da 2.0 a 5.1 canali in alta qualità.",
"MP3": "codec per compressione audio utilizzato MP3.", "MP3": "codec per compressione audio utilizzato MP3.",
"RESYNC": "il film è stato lavorato e re sincronizzato con una traccia audio. A volte potresti riscontrare una mancata sincronizzazione tra audio e video.", "RESYNC": "il film è stato lavorato e re sincronizzato con una traccia audio. A volte potresti riscontrare una mancata sincronizzazione tra audio e video.",
} }
qualityStr = scrapertools.find_single_match(data, patron).strip() qualityStr = scrapertools.find_single_match(data, patron).strip().upper()
if PY3: if PY3:
qualityStr = qualityStr.encode('ascii', 'ignore') qualityStr = qualityStr.encode('ascii', 'ignore')
else: else:
qualityStr = qualityStr.decode('unicode_escape').encode('ascii', 'ignore') qualityStr = qualityStr.decode('unicode_escape').encode('ascii', 'ignore')
if qualityStr: if qualityStr:
try: try:
splitted = qualityStr.split('.') video, audio, descr = None, None, ''
video = splitted[-1] for tag in defQualVideo:
audio = splitted[-2] if tag in qualityStr:
descr = typo(video + ': ', 'color kod') + defQualVideo.get(video.upper(), '') + '\n' +\ video = tag
typo(audio + ': ', 'color kod') + defQualAudio.get(audio.upper(), '') break
except: for tag in defQualAudio:
descr = '' if tag in qualityStr:
itemlist.insert(0, audio = tag
Item(channel=item.channel, break
action="", if video:
title=typo(qualityStr, '[] color kod bold'), descr += typo(video + ': ', 'color kod') + defQualVideo.get(video, '') + '\n'
plot=descr, if audio:
folder=False)) descr += typo(audio + ': ', 'color kod') + defQualAudio.get(audio, '') + '\n'
else: except:
log('nessun tag qualità trovato') descr = ''
itemlist.insert(0,
Item(channel=item.channel,
action="",
title=typo(qualityStr, '[] color kod bold'),
plot=descr,
folder=False))
else:
log('nessun tag qualità trovato')
+30 -21
View File
@@ -75,7 +75,7 @@ def read_nfo(path_nfo, item=None):
return head_nfo, it return head_nfo, it
def save_movie(item): def save_movie(item, silent=False):
""" """
guarda en la libreria de peliculas el elemento item, con los valores que contiene. guarda en la libreria de peliculas el elemento item, con los valores que contiene.
@type item: item @type item: item
@@ -128,7 +128,8 @@ def save_movie(item):
_id = item.infoLabels['code'][0] _id = item.infoLabels['code'][0]
# progress dialog # progress dialog
p_dialog = platformtools.dialog_progress(config.get_localized_string(20000), config.get_localized_string(60062)) if not silent:
p_dialog = platformtools.dialog_progress(config.get_localized_string(20000), config.get_localized_string(60062))
if config.get_setting("original_title_folder", "videolibrary") and item.infoLabels['originaltitle']: if config.get_setting("original_title_folder", "videolibrary") and item.infoLabels['originaltitle']:
base_name = item.infoLabels['originaltitle'] base_name = item.infoLabels['originaltitle']
@@ -215,23 +216,24 @@ def save_movie(item):
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
if filetools.write(json_path, item.tojson()): if filetools.write(json_path, item.tojson()):
p_dialog.update(100, config.get_localized_string(60062), item.contentTitle) if not silent: p_dialog.update(100, config.get_localized_string(60062), item.contentTitle)
item_nfo.library_urls[item.channel] = item.url item_nfo.library_urls[item.channel] = item.url
if filetools.write(nfo_path, head_nfo + item_nfo.tojson()): if filetools.write(nfo_path, head_nfo + item_nfo.tojson()):
#logger.info("FOLDER_MOVIES : %s" % FOLDER_MOVIES) #logger.info("FOLDER_MOVIES : %s" % FOLDER_MOVIES)
# actualizamos la videoteca de Kodi con la pelicula # actualizamos la videoteca de Kodi con la pelicula
if config.is_xbmc() and config.get_setting("videolibrary_kodi"): if config.is_xbmc() and config.get_setting("videolibrary_kodi") and not silent:
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.update() xbmc_videolibrary.update()
p_dialog.close() if not silent: p_dialog.close()
return insertados, sobreescritos, fallidos return insertados, sobreescritos, fallidos
# Si llegamos a este punto es por q algo ha fallado # Si llegamos a este punto es por q algo ha fallado
logger.error("Could not save %s in the video library" % item.contentTitle) logger.error("Could not save %s in the video library" % item.contentTitle)
p_dialog.update(100, config.get_localized_string(60063), item.contentTitle) if not silent:
p_dialog.close() p_dialog.update(100, config.get_localized_string(60063), item.contentTitle)
p_dialog.close()
return 0, 0, -1 return 0, 0, -1
def update_renumber_options(item, head_nfo, path): def update_renumber_options(item, head_nfo, path):
@@ -419,7 +421,7 @@ def filter_list(episodelist, action=None, path=None):
return episodelist return episodelist
def save_tvshow(item, episodelist): def save_tvshow(item, episodelist, silent=False):
""" """
guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist
@type item: item @type item: item
@@ -549,7 +551,7 @@ def save_tvshow(item, episodelist):
# Guardar los episodios # Guardar los episodios
'''import time '''import time
start_time = time.time()''' start_time = time.time()'''
insertados, sobreescritos, fallidos = save_episodes(path, episodelist, item) insertados, sobreescritos, fallidos = save_episodes(path, episodelist, item, silent=silent)
'''msg = "Insertados: %d | Sobreescritos: %d | Fallidos: %d | Tiempo: %2.2f segundos" % \ '''msg = "Insertados: %d | Sobreescritos: %d | Fallidos: %d | Tiempo: %2.2f segundos" % \
(insertados, sobreescritos, fallidos, time.time() - start_time) (insertados, sobreescritos, fallidos, time.time() - start_time)
logger.debug(msg)''' logger.debug(msg)'''
@@ -588,20 +590,10 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
sobreescritos = 0 sobreescritos = 0
fallidos = 0 fallidos = 0
news_in_playcounts = {} news_in_playcounts = {}
# Listamos todos los ficheros de la serie, asi evitamos tener que comprobar si existe uno por uno # Listamos todos los ficheros de la serie, asi evitamos tener que comprobar si existe uno por uno
raiz, carpetas_series, ficheros = next(filetools.walk(path)) raiz, carpetas_series, ficheros = next(filetools.walk(path))
ficheros = [filetools.join(path, f) for f in ficheros] ficheros = [filetools.join(path, f) for f in ficheros]
nostrm_episodelist = []
for root, folders, files in filetools.walk(path):
for file in files:
season_episode = scrapertools.get_season_and_episode(file)
if season_episode == "" or filetools.exists(filetools.join(path, "%s.strm" % season_episode)):
continue
nostrm_episodelist.append(season_episode)
nostrm_episodelist = sorted(set(nostrm_episodelist))
# Silent es para no mostrar progreso (para service) # Silent es para no mostrar progreso (para service)
if not silent: if not silent:
# progress dialog # progress dialog
@@ -654,7 +646,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
e = emergency_urls(e, channel, json_path, headers=headers) #generamos las urls e = emergency_urls(e, channel, json_path, headers=headers) #generamos las urls
if e.emergency_urls: #Si ya tenemos urls... if e.emergency_urls: #Si ya tenemos urls...
emergency_urls_succ = True #... es un éxito y vamos a marcar el .nfo emergency_urls_succ = True #... es un éxito y vamos a marcar el .nfo
if not e.infoLabels["tmdb_id"] or (serie.infoLabels["tmdb_id"] and e.infoLabels["tmdb_id"] != serie.infoLabels["tmdb_id"]): #en series multicanal, prevalece el infolabels... if not e.infoLabels["tmdb_id"] or (serie.infoLabels["tmdb_id"] and e.infoLabels["tmdb_id"] != serie.infoLabels["tmdb_id"]): #en series multicanal, prevalece el infolabels...
e.infoLabels = serie.infoLabels #... del canal actual y no el del original e.infoLabels = serie.infoLabels #... del canal actual y no el del original
e.contentSeason, e.contentEpisodeNumber = season_episode.split("x") e.contentSeason, e.contentEpisodeNumber = season_episode.split("x")
@@ -679,6 +671,8 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
except: except:
t = 0 t = 0
local_episodelist = get_local_content(path)
last_season_episode = '' last_season_episode = ''
for i, e in enumerate(scraper.sort_episode_list(new_episodelist)): for i, e in enumerate(scraper.sort_episode_list(new_episodelist)):
if not silent: if not silent:
@@ -701,7 +695,7 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
nfo_path = filetools.join(path, "%s.nfo" % season_episode) nfo_path = filetools.join(path, "%s.nfo" % season_episode)
json_path = filetools.join(path, ("%s [%s].json" % (season_episode, e.channel)).lower()) json_path = filetools.join(path, ("%s [%s].json" % (season_episode, e.channel)).lower())
if season_episode in nostrm_episodelist: if season_episode in local_episodelist:
logger.info('Skipped: Serie ' + serie.contentSerieName + ' ' + season_episode + ' available as local content') logger.info('Skipped: Serie ' + serie.contentSerieName + ' ' + season_episode + ' available as local content')
continue continue
strm_exists = strm_path in ficheros strm_exists = strm_path in ficheros
@@ -844,6 +838,21 @@ def save_episodes(path, episodelist, serie, silent=False, overwrite=True):
return insertados, sobreescritos, fallidos return insertados, sobreescritos, fallidos
def get_local_content(path):
logger.info()
local_episodelist = []
for root, folders, files in filetools.walk(path):
for file in files:
season_episode = scrapertools.get_season_and_episode(file)
if season_episode == "" or filetools.exists(filetools.join(path, "%s.strm" % season_episode)):
continue
local_episodelist.append(season_episode)
local_episodelist = sorted(set(local_episodelist))
return local_episodelist
def add_movie(item): def add_movie(item):
""" """
guarda una pelicula en la libreria de cine. La pelicula puede ser un enlace dentro de un canal o un video guarda una pelicula en la libreria de cine. La pelicula puede ser un enlace dentro de un canal o un video
+3 -1
View File
@@ -245,7 +245,9 @@ def open_settings():
if not settings_pre.get("videolibrary_kodi", None) and settings_post.get("videolibrary_kodi", None): if not settings_pre.get("videolibrary_kodi", None) and settings_post.get("videolibrary_kodi", None):
xbmc_videolibrary.ask_set_content(silent=True) xbmc_videolibrary.ask_set_content(silent=True)
elif settings_pre.get("videolibrary_kodi", None) and not settings_post.get("videolibrary_kodi", None): elif settings_pre.get("videolibrary_kodi", None) and not settings_post.get("videolibrary_kodi", None):
xbmc_videolibrary.clean(get_setting('videolibrarypath')) strm_list = []
strm_list.append(get_setting('videolibrarypath'))
xbmc_videolibrary.clean(strm_list)
def get_setting(name, channel="", server="", default=None): def get_setting(name, channel="", server="", default=None):
+1 -1
View File
@@ -69,7 +69,7 @@ if DOWNLOAD_LIMIT:
else: else:
DOWNLOAD_LIMIT = 0 DOWNLOAD_LIMIT = 0
UPLOAD_LIMIT = 100 * 1024 UPLOAD_LIMIT = 100 * 1024
msg_header = 'KoD Client Torrent MCT' msg_header = 'MCT Client Torrent'
def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None): def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
+102 -132
View File
@@ -171,6 +171,7 @@ def render_items(itemlist, parent_item):
if not len(itemlist): if not len(itemlist):
itemlist.append(Item(title=config.get_localized_string(60347), thumbnail=get_thumb('nofolder.png'))) itemlist.append(Item(title=config.get_localized_string(60347), thumbnail=get_thumb('nofolder.png')))
dirItems = []
for item in itemlist: for item in itemlist:
item_url = item.tourl() item_url = item.tourl()
@@ -210,7 +211,8 @@ def render_items(itemlist, parent_item):
context_commands = def_context_commands context_commands = def_context_commands
listitem.addContextMenuItems(context_commands) listitem.addContextMenuItems(context_commands)
xbmcplugin.addDirectoryItem(_handle, '%s?%s' % (sys.argv[0], item_url), listitem, item.folder) dirItems.append(('%s?%s' % (sys.argv[0], item_url), listitem, item.folder))
xbmcplugin.addDirectoryItems(_handle, dirItems)
if parent_item.list_type == '': if parent_item.list_type == '':
breadcrumb = parent_item.category.capitalize() breadcrumb = parent_item.category.capitalize()
@@ -225,7 +227,7 @@ def render_items(itemlist, parent_item):
xbmcplugin.setPluginCategory(handle=_handle, category=breadcrumb) xbmcplugin.setPluginCategory(handle=_handle, category=breadcrumb)
set_view_mode(item, parent_item) set_view_mode(itemlist[0], parent_item)
xbmcplugin.endOfDirectory(_handle) xbmcplugin.endOfDirectory(_handle)
logger.info('END render_items') logger.info('END render_items')
@@ -248,32 +250,35 @@ def set_view_mode(item, parent_item):
config.set_setting('skin_name', xbmc.getSkinDir()) config.set_setting('skin_name', xbmc.getSkinDir())
config.set_setting('view_mode_%s' % mode, config.get_localized_string(70003) + ' , 0') config.set_setting('view_mode_%s' % mode, config.get_localized_string(70003) + ' , 0')
parent_actions = ['peliculas', 'novedades', 'search', 'get_from_temp', 'channel_search', 'newest', 'discover_list', 'new_search']
if xbmc.getSkinDir() != config.get_setting('skin_name') or not config.get_setting('skin_name'): if xbmc.getSkinDir() != config.get_setting('skin_name') or not config.get_setting('skin_name'):
reset_view_mode() reset_view_mode()
xbmcplugin.setContent(handle=int(sys.argv[1]), content='') xbmcplugin.setContent(handle=int(sys.argv[1]), content='')
xbmc.executebuiltin('Container.SetViewMode(%s)' % 55) xbmc.executebuiltin('Container.SetViewMode(%s)' % 55)
elif (item.contentType in ['movie'] and parent_item.action in ['peliculas']) \
or (item.channel in ['videolibrary'] and parent_item.action in ['list_movies']) \
or parent_item.action in ['now_on_tv', 'now_on_misc', 'now_on_misc_film']:
mode('movie', 'movies')
elif (item.contentType in ['tvshow'] and parent_item.action in ['peliculas']) \
or (item.channel in ['videolibrary'] and parent_item.action in ['list_tvshows']):
mode('tvshow', 'tvshows')
elif parent_item.action in ['get_seasons']:
mode('season', 'tvshows')
elif parent_item.action in ['episodios', 'get_episodes']:
mode('episode', 'tvshows')
elif parent_item.action == 'findvideos': elif parent_item.action == 'findvideos':
mode('server', '') mode('server', '')
elif parent_item.action == 'mainlist': elif parent_item.action == 'mainlist':
mode('channel', '') mode('channel', '')
elif (item.contentType in ['movie'] and parent_item.action in parent_actions ) \
or (item.channel in ['videolibrary'] and parent_item.action in ['list_movies']) \
or (parent_item.channel in ['favorites'] and parent_item.action in ['mainlist']) \
or parent_item.action in ['now_on_tv', 'now_on_misc', 'now_on_misc_film', 'mostrar_perfil']:
mode('movie', 'movies')
elif (item.contentType in ['tvshow'] and parent_item.action in parent_actions ) \
or (item.channel in ['videolibrary'] and parent_item.action in ['list_tvshows']):
mode('tvshow', 'tvshows')
elif parent_item.action in ['get_seasons']:
mode('season', 'tvshows')
elif parent_item.action in ['episodios', 'get_episodes'] or item.contentType == 'episode':
mode('episode', 'tvshows')
else: else:
mode('addon', '') mode('addon', '')
@@ -780,7 +785,7 @@ def set_context_commands(item, item_url, parent_item, **kwargs):
elif item.action in ["detail", "findvideos"] and item.contentType == 'movie' and item.contentTitle: elif item.action in ["detail", "findvideos"] and item.contentType == 'movie' and item.contentTitle:
context_commands.append((config.get_localized_string(60353), "XBMC.RunPlugin(%s?%s&%s)" % context_commands.append((config.get_localized_string(60353), "XBMC.RunPlugin(%s?%s&%s)" %
(sys.argv[0], item_url, 'action=add_pelicula_to_library&from_action=' + item.action))) (sys.argv[0], item_url, 'action=add_pelicula_to_library&from_action=' + item.action)))
if item.channel not in ["downloads"] and item.server != 'torrent' and parent_item.action != 'mainlist' and config.get_setting('downloadenabled'): if item.channel not in ["downloads"] and item.server != 'torrent' and parent_item.action != 'mainlist' and config.get_setting('downloadenabled'):
# Descargar pelicula # Descargar pelicula
if item.contentType == "movie": if item.contentType == "movie":
@@ -790,6 +795,10 @@ def set_context_commands(item, item_url, parent_item, **kwargs):
elif item.contentSerieName: elif item.contentSerieName:
# Descargar serie # Descargar serie
if item.contentType == "tvshow": if item.contentType == "tvshow":
if item.channel == 'videolibrary':
context_commands.append((config.get_localized_string(60003), "XBMC.RunPlugin(%s?%s&%s)" %
(sys.argv[0], item_url,
'channel=downloads&action=save_download&unseen=true&from_channel=' + item.channel + '&from_action=' + item.action)))
context_commands.append((config.get_localized_string(60355), "XBMC.RunPlugin(%s?%s&%s)" % context_commands.append((config.get_localized_string(60355), "XBMC.RunPlugin(%s?%s&%s)" %
(sys.argv[0], item_url, 'channel=downloads&action=save_download&from_channel=' + item.channel + '&from_action=' + item.action))) (sys.argv[0], item_url, 'channel=downloads&action=save_download&from_channel=' + item.channel + '&from_action=' + item.action)))
context_commands.append((config.get_localized_string(60357), "XBMC.RunPlugin(%s?%s&%s)" % context_commands.append((config.get_localized_string(60357), "XBMC.RunPlugin(%s?%s&%s)" %
@@ -1107,10 +1116,8 @@ def get_dialogo_opciones(item, default_action, strm, autoplay):
opciones.append(config.get_localized_string(30164)) opciones.append(config.get_localized_string(30164))
else: else:
# "Descargar" # "Descargar"
import xbmcaddon downloadenabled = config.get_setting('downloadenabled')
addon = xbmcaddon.Addon('plugin.video.kod') if downloadenabled != False and item.channel != 'videolibrary':
downloadenabled = addon.getSetting('downloadenabled')
if downloadenabled != "false":
opcion = config.get_localized_string(30153) opcion = config.get_localized_string(30153)
opciones.append(opcion) opciones.append(opcion)
@@ -1350,67 +1357,42 @@ def play_torrent(item, xlistitem, mediaurl):
# Opciones disponibles para Reproducir torrents # Opciones disponibles para Reproducir torrents
torrent_options = list() torrent_options = torrent_client_installed(show_tuple=True)
torrent_options.append([config.get_localized_string(30033)])
torrent_options.append([config.get_localized_string(30033) + ' MCT'])
torrent_options.extend(torrent_client_installed(show_tuple=True))
torrent_client = config.get_setting("torrent_client", server="torrent") torrent_client = config.get_setting("torrent_client", server="torrent")
# Si es Libtorrent y no está soportado, se ofrecen alternativas, si las hay... # Si es Libtorrent y no está soportado, se ofrecen alternativas, si las hay...
if not LIBTORRENT and len(torrent_options) < 3:
from specials import quasar_download
if dialog_yesno(config.get_localized_string(70784), config.get_localized_string(70782)):
quasar_download.download()
if torrent_client and torrent_client - 1 <= len(torrent_options): if len(torrent_options) > 1:
if torrent_client == 0: selection = dialog_select(config.get_localized_string(70193), [opcion[0] for opcion in torrent_options])
seleccion = dialog_select(config.get_localized_string(70193), [opcion[0] for opcion in torrent_options])
else:
seleccion = torrent_client - 1
else: else:
if len(torrent_options) > 1: selection = 0
seleccion = dialog_select(config.get_localized_string(70193), [opcion[0] for opcion in torrent_options])
else:
seleccion = 0
if seleccion < 2 and not LIBTORRENT:
dialog_ok(config.get_localized_string(30033), config.get_localized_string(70774), \
config.get_localized_string(70775) % config.get_setting("libtorrent_error", server="torrent", default=''), \
config.get_localized_string(70776))
if len(torrent_options) > 2:
seleccion = dialog_select(config.get_localized_string(70193), [opcion[0] for opcion in torrent_options])
if seleccion < 2:
return
else:
return
# Si es Torrenter o Elementum con opción de Memoria, se ofrece la posibilidad ee usar Libtorrent temporalemente # Si es Torrenter o Elementum con opción de Memoria, se ofrece la posibilidad ee usar Libtorrent temporalemente
elif seleccion > 1 and LIBTORRENT and UNRAR and 'RAR-' in item.torrent_info and ( if selection >= 0 and LIBTORRENT and UNRAR and 'RAR-' in item.torrent_info and (
"torrenter" in torrent_options[seleccion][0] \ "torrenter" in torrent_options[selection][0] \
or ("elementum" in torrent_options[seleccion][0] and xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ','')).getSetting('download_storage') == '1')): or ("elementum" in torrent_options[selection][0] and xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[selection][0].replace('Plugin externo: ','')).getSetting('download_storage') == '1')):
if dialog_yesno(torrent_options[seleccion][0], config.get_localized_string(70777), config.get_localized_string(70778), config.get_localized_string(70779) % size_rar): if dialog_yesno(torrent_options[selection][0], config.get_localized_string(70777), config.get_localized_string(70778), config.get_localized_string(70779) % size_rar):
seleccion = 1 selection = 1
else: else:
return return
# Si es Elementum pero con opción de Memoria, se muestras los Ajustes de Elementum y se pide al usuario que cambie a "Usar Archivos" # Si es Elementum pero con opción de Memoria, se muestras los Ajustes de Elementum y se pide al usuario que cambie a "Usar Archivos"
elif seleccion > 1 and not LIBTORRENT and UNRAR and 'RAR-' in item.torrent_info and "elementum" in \ elif selection >= 0 and not LIBTORRENT and UNRAR and 'RAR-' in item.torrent_info and "elementum" in \
torrent_options[seleccion][0] \ torrent_options[selection][0] \
and xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ', '')) \ and xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[selection][0].capitalize()) \
.getSetting('download_storage') == '1': .getSetting('download_storage') == '1':
if dialog_yesno(torrent_options[seleccion][0], config.get_localized_string(70780) % size_rar, config.get_localized_string(70781)): if dialog_yesno(torrent_options[selection][0], config.get_localized_string(70780) % size_rar, config.get_localized_string(70781)):
__settings__ = xbmcaddon.Addon( __settings__ = xbmcaddon.Addon(
id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ', '')) id="plugin.video.%s" % torrent_options[selection][0].capitalize())
__settings__.openSettings() # Se visulizan los Ajustes de Elementum __settings__.openSettings() # Se visulizan los Ajustes de Elementum
elementum_dl = xbmcaddon.Addon( elementum_dl = xbmcaddon.Addon(
id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ', '')) \ id="plugin.video.%s" % torrent_options[selection][0].capitalize()) \
.getSetting('download_storage') .getSetting('download_storage')
if elementum_dl != '1': if elementum_dl != '1':
config.set_setting("elementum_dl", "1", server="torrent") # Salvamos el cambio para restaurarlo luego config.set_setting("elementum_dl", "1", server="torrent") # Salvamos el cambio para restaurarlo luego
return # Se sale, porque habrá refresco y cancelaría Kodi si no return # Se sale, porque habrá refresco y cancelaría Kodi si no
# Descarga de torrents a local # Descarga de torrents a local
if seleccion >= 0: if selection >= 0:
#### Compatibilidad con Kodi 18: evita cuelgues/cancelaciones cuando el .torrent se lanza desde pantalla convencional #### Compatibilidad con Kodi 18: evita cuelgues/cancelaciones cuando el .torrent se lanza desde pantalla convencional
# if xbmc.getCondVisibility('Window.IsMedia'): # if xbmc.getCondVisibility('Window.IsMedia'):
@@ -1458,7 +1440,7 @@ def play_torrent(item, xlistitem, mediaurl):
if url: if url:
url_stat = True url_stat = True
item.url = url item.url = url
if "torrentin" in torrent_options[seleccion][0]: if "torrentin" in torrent_options[selection][0]:
item.url = 'file://' + item.url item.url = 'file://' + item.url
if not url and item.torrent_alt: # Si hay error, se busca un .torrent alternativo if not url and item.torrent_alt: # Si hay error, se busca un .torrent alternativo
@@ -1478,85 +1460,73 @@ def play_torrent(item, xlistitem, mediaurl):
item.url = filetools.join(config.get_videolibrary_path(), folder, item.url) # dirección del .torrent local en la Videoteca item.url = filetools.join(config.get_videolibrary_path(), folder, item.url) # dirección del .torrent local en la Videoteca
if filetools.copy(item.url, torrents_path, silent=True): # se copia a la carpeta generíca para evitar problemas de encode if filetools.copy(item.url, torrents_path, silent=True): # se copia a la carpeta generíca para evitar problemas de encode
item.url = torrents_path item.url = torrents_path
if "torrentin" in torrent_options[seleccion][0]: # Si es Torrentin, hay que añadir un prefijo if "torrentin" in torrent_options[selection][0]: # Si es Torrentin, hay que añadir un prefijo
item.url = 'file://' + item.url item.url = 'file://' + item.url
size, rar_files = generictools.get_torrent_size('', file_list=True, local_torr=torrents_path,short_pad=True) size, rar_files = generictools.get_torrent_size('', file_list=True, local_torr=torrents_path,short_pad=True)
mediaurl = item.url mediaurl = item.url
if seleccion >= 0: if selection >= 0:
# Reproductor propio BT (libtorrent) mediaurl = urllib.quote_plus(item.url)
if seleccion == 0: # Llamada con más parámetros para completar el título
torrent.bt_client(mediaurl, xlistitem, rar_files, subtitle=item.subtitle, password=password, item=item) if ("quasar" in torrent_options[selection][1] or "elementum" in torrent_options[selection][1]) and item.infoLabels['tmdb_id']:
if item.contentType == 'episode' and "elementum" not in torrent_options[selection][1]:
mediaurl += "&episode=%s&library=&season=%s&show=%s&tmdb=%s&type=episode" % (
item.infoLabels['episode'], item.infoLabels['season'], item.infoLabels['tmdb_id'],
item.infoLabels['tmdb_id'])
elif item.contentType == 'movie':
mediaurl += "&library=&tmdb=%s&type=movie" % (item.infoLabels['tmdb_id'])
# Reproductor propio MCT (libtorrent) xbmc.executebuiltin("PlayMedia(" + torrent_options[selection][1] % mediaurl + ")")
elif seleccion == 1:
from platformcode import mct
mct.play(mediaurl, xlistitem, subtitle=item.subtitle, password=password, item=item)
# Plugins externos # Si es un archivo RAR, monitorizamos el cliente Torrent hasta que haya descargado el archivo,
else: # y después lo extraemos, incluso con RAR's anidados y con contraseña
mediaurl = urllib.quote_plus(item.url) torr_client = torrent_options[selection][0].capitalize()
# Llamada con más parámetros para completar el título if 'RAR-' in size and torr_client in ['quasar', 'elementum'] and UNRAR:
if ("quasar" in torrent_options[seleccion][1] or "elementum" in torrent_options[seleccion][1]) and item.infoLabels['tmdb_id']: rar_file, save_path_videos, folder_torr = torrent.wait_for_download(item, mediaurl, rar_files, torr_client) # Esperamos mientras se descarga el RAR
if item.contentType == 'episode' and "elementum" not in torrent_options[seleccion][1]: if rar_file and save_path_videos: # Si se ha descargado el RAR...
mediaurl += "&episode=%s&library=&season=%s&show=%s&tmdb=%s&type=episode" % ( dp = dialog_progress_bg('KoD %s' % torr_client)
item.infoLabels['episode'], item.infoLabels['season'], item.infoLabels['tmdb_id'], video_file, rar, video_path, erase_file_path = torrent.extract_files(rar_file, save_path_videos, password, dp, item, torr_client) # ... extraemos el vídeo del RAR
item.infoLabels['tmdb_id']) dp.close()
elif item.contentType == 'movie':
mediaurl += "&library=&tmdb=%s&type=movie" % (item.infoLabels['tmdb_id'])
xbmc.executebuiltin("PlayMedia(" + torrent_options[seleccion][1] % mediaurl + ")") # Reproducimos el vídeo extraido, si no hay nada en reproducción
while is_playing() and rar and not xbmc.abortRequested:
time.sleep(3) # Repetimos cada intervalo
if rar and not xbmc.abortRequested:
time.sleep(1)
video_play = filetools.join(video_path, video_file)
log("##### video_play: %s" % video_play)
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
playlist.clear()
playlist.add(video_play, xlistitem)
xbmc_player.play(playlist)
# Si es un archivo RAR, monitorizamos el cliente Torrent hasta que haya descargado el archivo, # selectionamos que clientes torrent soportamos para el marcado de vídeos vistos: asumimos que todos funcionan
# y después lo extraemos, incluso con RAR's anidados y con contraseña torrent.mark_auto_as_watched(item)
torr_client = torrent_options[seleccion][0].replace('Plugin externo: ', '')
if 'RAR-' in size and torr_client in ['quasar', 'elementum'] and UNRAR:
rar_file, save_path_videos, folder_torr = torrent.wait_for_download(item, mediaurl, rar_files, torr_client) # Esperamos mientras se descarga el RAR
if rar_file and save_path_videos: # Si se ha descargado el RAR...
dp = dialog_progress_bg('KoD %s' % torr_client)
video_file, rar, video_path, erase_file_path = torrent.extract_files(rar_file, save_path_videos, password, dp, item, torr_client) # ... extraemos el vídeo del RAR
dp.close()
# Reproducimos el vídeo extraido, si no hay nada en reproducción # Si se ha extraido un RAR, se pregunta para borrar los archivos después de reproducir el vídeo (plugins externos)
while is_playing() and rar and not xbmc.abortRequested: while is_playing() and rar and not xbmc.abortRequested:
time.sleep(3) # Repetimos cada intervalo time.sleep(3) # Repetimos cada intervalo
if rar and not xbmc.abortRequested: if rar and not xbmc.abortRequested:
time.sleep(1) if dialog_yesno('KoD %s' % torr_client, config.get_localized_string(30031)):
video_play = filetools.join(video_path, video_file) log("##### erase_file_path: %s" % erase_file_path)
log("##### video_play: %s" % video_play) try:
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) torr_data, deamon_url, index = torrent.get_tclient_data(folder_torr, torr_client)
playlist.clear() if torr_data and deamon_url:
playlist.add(video_play, xlistitem) data = httptools.downloadpage('%sdelete/%s' % (deamon_url, index), timeout=5, alfa_s=True).data
xbmc_player.play(playlist) time.sleep(1)
if filetools.isdir(erase_file_path):
if seleccion > 1: filetools.rmdirtree(erase_file_path)
# Seleccionamos que clientes torrent soportamos para el marcado de vídeos vistos: asumimos que todos funcionan elif filetools.exists(erase_file_path) and filetools.isfile(erase_file_path):
torrent.mark_auto_as_watched(item) filetools.remove(erase_file_path)
except:
# Si se ha extraido un RAR, se pregunta para borrar los archivos después de reproducir el vídeo (plugins externos) logger.error(traceback.format_exc(1))
while is_playing() and rar and not xbmc.abortRequested: elementum_dl = config.get_setting("elementum_dl", server="torrent", default='') # Si salvamos el cambio de Elementum
time.sleep(3) # Repetimos cada intervalo if elementum_dl:
if rar and not xbmc.abortRequested: config.set_setting("elementum_dl", "", server="torrent") # lo reseteamos en Alfa
if dialog_yesno('KoD %s' % torr_client, config.get_localized_string(30031)): xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[selection][0].replace('Plugin externo: ', '')) \
log("##### erase_file_path: %s" % erase_file_path) .setSetting('download_storage', elementum_dl) # y lo reseteamos en Elementum
try:
torr_data, deamon_url, index = torrent.get_tclient_data(folder_torr, torr_client)
if torr_data and deamon_url:
data = httptools.downloadpage('%sdelete/%s' % (deamon_url, index), timeout=5, alfa_s=True).data
time.sleep(1)
if filetools.isdir(erase_file_path):
filetools.rmdirtree(erase_file_path)
elif filetools.exists(erase_file_path) and filetools.isfile(erase_file_path):
filetools.remove(erase_file_path)
except:
logger.error(traceback.format_exc(1))
elementum_dl = config.get_setting("elementum_dl", server="torrent", default='') # Si salvamos el cambio de Elementum
if elementum_dl:
config.set_setting("elementum_dl", "", server="torrent") # lo reseteamos en Alfa
xbmcaddon.Addon(id="plugin.video.%s" % torrent_options[seleccion][0].replace('Plugin externo: ', '')) \
.setSetting('download_storage', elementum_dl) # y lo reseteamos en Elementum
def log(texto): def log(texto):
+2 -1
View File
@@ -174,10 +174,11 @@ def check(background=False):
'w') # il file di tracking viene eliminato, lo ricreo 'w') # il file di tracking viene eliminato, lo ricreo
if addon.getSetting("addon_update_message"): if addon.getSetting("addon_update_message"):
if background: if background:
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80040) % commits[0]['sha'][:7], time=3000, sound=False)
with open(xbmc.translatePath(changelogFile), 'a+') as fileC: with open(xbmc.translatePath(changelogFile), 'a+') as fileC:
fileC.write(changelog) fileC.write(changelog)
elif changelog: elif changelog:
platformtools.dialog_ok('Kodi on Demand', 'Aggiornamenti applicati:\n' + changelog) platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(80041) + changelog)
localCommitFile.seek(0) localCommitFile.seek(0)
localCommitFile.truncate() localCommitFile.truncate()
+126 -129
View File
@@ -8,7 +8,7 @@ standard_library.install_aliases()
import sys import sys
PY3 = False PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import os import os
import threading import threading
import time import time
@@ -216,7 +216,6 @@ def sync_trakt_kodi(silent=True):
if notificacion: if notificacion:
platformtools.dialog_notification(config.get_localized_string(20000), platformtools.dialog_notification(config.get_localized_string(20000),
config.get_localized_string(60045), config.get_localized_string(60045),
icon=0,
time=2000) time=2000)
@@ -334,7 +333,7 @@ def mark_season_as_watched_on_kodi(item, value=1):
def mark_content_as_watched_on_alfa(path): def mark_content_as_watched_on_alfa(path):
from specials import videolibrary from specials import videolibrary
from core import videolibrarytools from core import videolibrarytools
""" """
marca toda la serie o película como vista o no vista en la Videoteca de Alfa basado en su estado en la Videoteca de Kodi marca toda la serie o película como vista o no vista en la Videoteca de Alfa basado en su estado en la Videoteca de Kodi
@type str: path @type str: path
@@ -342,7 +341,7 @@ def mark_content_as_watched_on_alfa(path):
""" """
logger.info() logger.info()
#logger.debug("path: " + path) #logger.debug("path: " + path)
FOLDER_MOVIES = config.get_setting("folder_movies") FOLDER_MOVIES = config.get_setting("folder_movies")
FOLDER_TVSHOWS = config.get_setting("folder_tvshows") FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
VIDEOLIBRARY_PATH = config.get_videolibrary_config_path() VIDEOLIBRARY_PATH = config.get_videolibrary_config_path()
@@ -353,7 +352,7 @@ def mark_content_as_watched_on_alfa(path):
# en caso de compartir BBDD esta funcionalidad no funcionara # en caso de compartir BBDD esta funcionalidad no funcionara
#if config.get_setting("db_mode", "videolibrary"): #if config.get_setting("db_mode", "videolibrary"):
# return # return
path2 = '' path2 = ''
if "special://" in VIDEOLIBRARY_PATH: if "special://" in VIDEOLIBRARY_PATH:
if FOLDER_TVSHOWS in path: if FOLDER_TVSHOWS in path:
@@ -376,7 +375,7 @@ def mark_content_as_watched_on_alfa(path):
path2 = path1.replace("\\", "/") #Formato no Windows path2 = path1.replace("\\", "/") #Formato no Windows
else: else:
path2 = path2.replace(nfo_name, '') path2 = path2.replace(nfo_name, '')
else: else:
contentType = "movie_view" #Marco la tabla de BBDD de Kodi Video contentType = "movie_view" #Marco la tabla de BBDD de Kodi Video
path1 = path.replace("\\\\", "\\") #Formato Windows path1 = path.replace("\\\\", "\\") #Formato Windows
@@ -386,7 +385,7 @@ def mark_content_as_watched_on_alfa(path):
path1 = path1.replace(nfo_name, '') #para la SQL solo necesito la carpeta path1 = path1.replace(nfo_name, '') #para la SQL solo necesito la carpeta
path2 = path2.replace(nfo_name, '') #para la SQL solo necesito la carpeta path2 = path2.replace(nfo_name, '') #para la SQL solo necesito la carpeta
path2 = filetools.remove_smb_credential(path2) #Si el archivo está en un servidor SMB, quitamos las credenciales path2 = filetools.remove_smb_credential(path2) #Si el archivo está en un servidor SMB, quitamos las credenciales
#Ejecutmos la sentencia SQL #Ejecutmos la sentencia SQL
sql = 'select strFileName, playCount from %s where (strPath like "%s" or strPath like "%s")' % (contentType, path1, path2) sql = 'select strFileName, playCount from %s where (strPath like "%s" or strPath like "%s")' % (contentType, path1, path2)
nun_records = 0 nun_records = 0
@@ -395,7 +394,7 @@ def mark_content_as_watched_on_alfa(path):
if nun_records == 0: #hay error? if nun_records == 0: #hay error?
logger.error("Error en la SQL: " + sql + ": 0 registros") logger.error("Error en la SQL: " + sql + ": 0 registros")
return #salimos: o no está catalogado en Kodi, o hay un error en la SQL return #salimos: o no está catalogado en Kodi, o hay un error en la SQL
for title, playCount in records: #Ahora recorremos todos los registros obtenidos for title, playCount in records: #Ahora recorremos todos los registros obtenidos
if contentType == "episode_view": if contentType == "episode_view":
title_plain = title.replace('.strm', '') #Si es Serie, quitamos el sufijo .strm title_plain = title.replace('.strm', '') #Si es Serie, quitamos el sufijo .strm
@@ -419,10 +418,10 @@ def mark_content_as_watched_on_alfa(path):
item = videolibrary.check_season_playcount(item, season_num) #llamamos al método que actualiza Temps. y Series item = videolibrary.check_season_playcount(item, season_num) #llamamos al método que actualiza Temps. y Series
filetools.write(path, head_nfo + item.tojson()) filetools.write(path, head_nfo + item.tojson())
#logger.debug(item) #logger.debug(item)
def get_data(payload): def get_data(payload):
""" """
obtiene la información de la llamada JSON-RPC con la información pasada en payload obtiene la información de la llamada JSON-RPC con la información pasada en payload
@@ -512,7 +511,7 @@ def update(folder_content=config.get_setting("folder_tvshows"), folder=""):
data = get_data(payload) data = get_data(payload)
xbmc.executebuiltin('XBMC.ReloadSkin()') #xbmc.executebuiltin('XBMC.ReloadSkin()')
def search_library_path(): def search_library_path():
@@ -701,7 +700,7 @@ def set_content(content_type, silent=False, custom=False):
if seleccion == -1 or seleccion == 0: if seleccion == -1 or seleccion == 0:
strScraper = 'metadata.themoviedb.org' strScraper = 'metadata.themoviedb.org'
path_settings = xbmc.translatePath("special://profile/addon_data/metadata.themoviedb.org/settings.xml") path_settings = xbmc.translatePath("special://profile/addon_data/metadata.themoviedb.org/settings.xml")
elif seleccion == 1: elif seleccion == 1:
strScraper = 'metadata.universal' strScraper = 'metadata.universal'
path_settings = xbmc.translatePath("special://profile/addon_data/metadata.universal/settings.xml") path_settings = xbmc.translatePath("special://profile/addon_data/metadata.universal/settings.xml")
if not os.path.exists(path_settings): if not os.path.exists(path_settings):
@@ -720,7 +719,7 @@ def set_content(content_type, silent=False, custom=False):
if seleccion == -1 or seleccion == 0: if seleccion == -1 or seleccion == 0:
strScraper = 'metadata.tvdb.com' strScraper = 'metadata.tvdb.com'
path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvdb.com/settings.xml") path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvdb.com/settings.xml")
elif seleccion == 1: elif seleccion == 1:
strScraper = 'metadata.tvshows.themoviedb.org' strScraper = 'metadata.tvshows.themoviedb.org'
path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml") path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml")
if not os.path.exists(path_settings): if not os.path.exists(path_settings):
@@ -878,7 +877,7 @@ def update_db(old_path, new_path, old_movies_folder, new_movies_folder, old_tvsh
xbmc.executebuiltin('XBMC.ReloadSkin()') xbmc.executebuiltin('XBMC.ReloadSkin()')
def clean(path=''): def clean(path_list=[]):
def sql_format(path): def sql_format(path):
if path.startswith("special://"): if path.startswith("special://"):
path = path.replace('/profile/', '/%/').replace('/home/userdata/', '/%/') path = path.replace('/profile/', '/%/').replace('/home/userdata/', '/%/')
@@ -894,127 +893,125 @@ def clean(path=''):
logger.info() logger.info()
idParentPath = 0
sql_path = ''
sql_movies_path = ''
sql_tvshows_path = ''
sql_episodes_path = ''
path, sep = sql_format(path)
movies_folder = config.get_setting("folder_movies")
tvshows_folder = config.get_setting("folder_tvshows")
# delete episode/movie (downloads.py move_to_libray)
if path.endswith(".strm"):
if movies_folder in path:
sql_movies_path = path
else:
sql_episodes_path = path
# delete movie
elif movies_folder in path:
if not path.endswith(sep): path += sep
sql_movies_path = path + '%'
# delete tvshow
elif tvshows_folder in path:
if not path.endswith(sep): path += sep
sql_tvshows_path = path + '%'
sql_episodes_path = sql_tvshows_path
# delete video library
else:
if not path.endswith(sep): path += sep
sql_path = path
sql_movies_path = sql_path + movies_folder
if not sql_movies_path.endswith(sep): sql_movies_path += sep
sql_movies_path += '%'
sql_tvshows_path = sql_path + tvshows_folder
if not sql_tvshows_path.endswith(sep): sql_tvshows_path += sep
sql_tvshows_path += '%'
sql_episodes_path = sql_tvshows_path
progress = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80025)) progress = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80025))
progress.update(0) progress.update(0)
if sql_path:
# search video library path in the DB
sql = 'SELECT idPath FROM path where strPath LIKE "%s"' % sql_path
nun_records, records = execute_sql_kodi(sql)
# delete video library path
if records:
idPath = records[0][0]
idParentPath = idPath
if not config.get_setting("videolibrary_kodi"):
sql = 'DELETE from path WHERE idPath=%s' % idPath
nun_records, records = execute_sql_kodi(sql)
progress.update(10) for path in path_list:
if sql_movies_path:
# search movies in the DB
sql = 'SELECT idMovie FROM movie where c22 LIKE "%s"' % sql_movies_path
nun_records, records = execute_sql_kodi(sql)
# delete movies
if records:
for record in records:
idMovie = record[0]
sql = 'DELETE from movie WHERE idMovie=%s' % idMovie
nun_records, records = execute_sql_kodi(sql)
progress.update(28) idParentPath = 0
if sql_movies_path: sql_path = ''
# search movies path and folders in the DB sql_movies_path = ''
sql = 'SELECT idPath, idParentPath FROM path where strPath LIKE "%s"' % sql_movies_path sql_tvshows_path = ''
nun_records, records = execute_sql_kodi(sql) sql_episodes_path = ''
# delete movies path and folders
if records:
for record in records:
if record[1] == idParentPath and config.get_setting("videolibrary_kodi"):
continue
idPath = record[0]
sql = 'DELETE from path WHERE idPath=%s' % idPath
nun_records, records = execute_sql_kodi(sql)
progress.update(46) path, sep = sql_format(path)
if sql_tvshows_path: movies_folder = config.get_setting("folder_movies")
# search TV shows in the DB tvshows_folder = config.get_setting("folder_tvshows")
sql = 'SELECT idShow FROM tvshow_view where strPath LIKE "%s"' % sql_tvshows_path
nun_records, records = execute_sql_kodi(sql)
# delete TV shows
if records:
for record in records:
idShow = record[0]
sql = 'DELETE from tvshow WHERE idShow=%s' % idShow
nun_records, records = execute_sql_kodi(sql)
progress.update(64) # delete episode/movie (downloads.py move_to_libray)
if sql_episodes_path: if path.endswith(".strm"):
# search episodes in the DB if movies_folder in path:
sql = 'SELECT idEpisode FROM episode where c18 LIKE "%s"' % sql_episodes_path sql_movies_path = path
nun_records, records = execute_sql_kodi(sql) else:
# delete episodes sql_episodes_path = path
if records: # delete movie
for record in records: elif movies_folder in path:
idEpisode = record[0] if not path.endswith(sep): path += sep
sql = 'DELETE from episode WHERE idEpisode=%s' % idEpisode
nun_records, records = execute_sql_kodi(sql)
progress.update(82) sql_movies_path = path + '%'
if sql_tvshows_path: # delete tvshow
# search TV shows path and folders in the DB elif tvshows_folder in path:
sql = 'SELECT idPath, idParentPath FROM path where strPath LIKE "%s"' % sql_tvshows_path if not path.endswith(sep): path += sep
nun_records, records = execute_sql_kodi(sql)
# delete tvshows path and folders sql_tvshows_path = path + '%'
if records:
for record in records: sql_episodes_path = sql_tvshows_path
if record[1] == idParentPath and config.get_setting("videolibrary_kodi"): # delete video library
continue else:
idPath = record[0] if not path.endswith(sep): path += sep
sql = 'DELETE from path WHERE idPath=%s' % idPath
nun_records, records = execute_sql_kodi(sql) sql_path = path
sql_movies_path = sql_path + movies_folder
if not sql_movies_path.endswith(sep): sql_movies_path += sep
sql_movies_path += '%'
sql_tvshows_path = sql_path + tvshows_folder
if not sql_tvshows_path.endswith(sep): sql_tvshows_path += sep
sql_tvshows_path += '%'
sql_episodes_path = sql_tvshows_path
if sql_path:
# search video library path in the DB
sql = 'SELECT idPath FROM path where strPath LIKE "%s"' % sql_path
nun_records, records = execute_sql_kodi(sql)
# delete video library path
if records:
idPath = records[0][0]
idParentPath = idPath
if not config.get_setting("videolibrary_kodi"):
sql = 'DELETE from path WHERE idPath=%s' % idPath
nun_records, records = execute_sql_kodi(sql)
if sql_movies_path:
# search movies in the DB
sql = 'SELECT idMovie FROM movie where c22 LIKE "%s"' % sql_movies_path
nun_records, records = execute_sql_kodi(sql)
# delete movies
if records:
for record in records:
idMovie = record[0]
sql = 'DELETE from movie WHERE idMovie=%s' % idMovie
nun_records, records = execute_sql_kodi(sql)
if sql_movies_path:
# search movies path and folders in the DB
sql = 'SELECT idPath, idParentPath FROM path where strPath LIKE "%s"' % sql_movies_path
nun_records, records = execute_sql_kodi(sql)
# delete movies path and folders
if records:
for record in records:
if record[1] == idParentPath and config.get_setting("videolibrary_kodi"):
continue
idPath = record[0]
sql = 'DELETE from path WHERE idPath=%s' % idPath
nun_records, records = execute_sql_kodi(sql)
if sql_tvshows_path:
# search TV shows in the DB
sql = 'SELECT idShow FROM tvshow_view where strPath LIKE "%s"' % sql_tvshows_path
nun_records, records = execute_sql_kodi(sql)
# delete TV shows
if records:
for record in records:
idShow = record[0]
sql = 'DELETE from tvshow WHERE idShow=%s' % idShow
nun_records, records = execute_sql_kodi(sql)
if sql_episodes_path:
# search episodes in the DB
sql = 'SELECT idEpisode FROM episode where c18 LIKE "%s"' % sql_episodes_path
nun_records, records = execute_sql_kodi(sql)
# delete episodes
if records:
for record in records:
idEpisode = record[0]
sql = 'DELETE from episode WHERE idEpisode=%s' % idEpisode
nun_records, records = execute_sql_kodi(sql)
if sql_tvshows_path:
# search TV shows path and folders in the DB
sql = 'SELECT idPath, idParentPath FROM path where strPath LIKE "%s"' % sql_tvshows_path
nun_records, records = execute_sql_kodi(sql)
# delete tvshows path and folders
if records:
for record in records:
if record[1] == idParentPath and config.get_setting("videolibrary_kodi"):
continue
idPath = record[0]
sql = 'DELETE from path WHERE idPath=%s' % idPath
nun_records, records = execute_sql_kodi(sql)
progress.update(100) progress.update(100)
xbmc.sleep(1000) xbmc.sleep(1000)
+79 -8
View File
@@ -697,7 +697,7 @@ msgid "Delete movie/channel"
msgstr "" msgstr ""
msgctxt "#60019" msgctxt "#60019"
msgid "Delete this movie" msgid "Delete movie"
msgstr "" msgstr ""
msgctxt "#60020" msgctxt "#60020"
@@ -789,7 +789,7 @@ msgid "Delete TV show"
msgstr "" msgstr ""
msgctxt "#60042" msgctxt "#60042"
msgid "Delete only the links of %s" msgid "Delete links of %s"
msgstr "" msgstr ""
msgctxt "#60043" msgctxt "#60043"
@@ -3121,7 +3121,11 @@ msgid "Show only links of "
msgstr "" msgstr ""
msgctxt "#70079" msgctxt "#70079"
msgid "Remove only links of " msgid "Delete ony the links of "
msgstr ""
msgctxt "#70081"
msgid "The folder also contains local or downloaded video files. Do you want to delete them?"
msgstr "" msgstr ""
msgctxt "#70082" msgctxt "#70082"
@@ -3141,7 +3145,7 @@ msgid "Delete TV show"
msgstr "" msgstr ""
msgctxt "#70086" msgctxt "#70086"
msgid "Remove only links of %s" msgid "Delete only the links of %s"
msgstr "" msgstr ""
msgctxt "#70087" msgctxt "#70087"
@@ -5892,19 +5896,19 @@ msgid "Do you want to call Elementum Settings to temporarily switch to Use Files
msgstr "" msgstr ""
msgctxt "#70782" msgctxt "#70782"
msgid "Your device is not compatible with the Internal Client, do you want to use Quasar for Torrents?" msgid "You must install an external Client to take advantage of the torrent support. Do you want to install Elementum?"
msgstr "" msgstr ""
msgctxt "#70783" msgctxt "#70783"
msgid "Quasar installed and configured, enjoy!" msgid "Elementum is installed on your device, but is not active. Do you want to activate it?"
msgstr "" msgstr ""
msgctxt "#70784" msgctxt "#70784"
msgid "Attention!!" msgid "Attention!"
msgstr "Attenzione!" msgstr "Attenzione!"
msgctxt "#70785" msgctxt "#70785"
msgid "Install Quasar" msgid "Install Elementum"
msgstr "" msgstr ""
msgctxt "#70786" msgctxt "#70786"
@@ -5923,6 +5927,65 @@ msgctxt "#70789"
msgid "* Change by opening the settings from KoD main menu" msgid "* Change by opening the settings from KoD main menu"
msgstr "" msgstr ""
msgctxt "#70790"
msgid "RAR download in progress"
msgstr ""
msgctxt "#70791"
msgid "A RAR file was detected in the download, but you have not installed the UnRAR extractor.\nDo you want to download it anyway?"
msgstr ""
msgctxt "#70792"
msgid "Delete downloaded files?"
msgstr ""
msgctxt "#70793"
msgid "Starting extraction..."
msgstr ""
msgctxt "#70794"
msgid "Enter the password (Look in %s)"
msgstr ""
msgctxt "#70795"
msgid "Extracted"
msgstr ""
msgctxt "#70796"
msgid "Error opening RAR File"
msgstr ""
msgctxt "#70797"
msgid "The RAR file is empty"
msgstr ""
msgctxt "#70798"
msgid "Or does not contain valid archives"
msgstr ""
msgctxt "#70799"
msgid "Extraction error"
msgstr ""
msgctxt "#70800"
msgid "Archive with errors"
msgstr ""
msgctxt "#70801"
msgid "Extract without playing"
msgstr ""
msgctxt "#70802"
msgid "Wait some minutes..."
msgstr ""
msgctxt "#70803"
msgid "Extracting files..."
msgstr ""
msgctxt "#70804"
msgid "Next extraction..."
msgstr ""
# DNS start [ settings and declaration ] # DNS start [ settings and declaration ]
msgctxt "#707401" msgctxt "#707401"
@@ -6219,4 +6282,12 @@ msgstr ""
msgctxt "#80039" msgctxt "#80039"
msgid "The video library has been deleted" msgid "The video library has been deleted"
msgstr ""
msgctxt "#80040"
msgid "Add-on updated to commit %s"
msgstr ""
msgctxt "#80041"
msgid "Latest updates:\n"
msgstr "" msgstr ""
+89 -18
View File
@@ -696,8 +696,8 @@ msgid "Delete movie/channel"
msgstr "Elimina film/canale" msgstr "Elimina film/canale"
msgctxt "#60019" msgctxt "#60019"
msgid "Delete this movie" msgid "Delete movie"
msgstr "Elimina questo film" msgstr "Elimina film"
msgctxt "#60020" msgctxt "#60020"
msgid "Mark TV show as not watched" msgid "Mark TV show as not watched"
@@ -781,15 +781,15 @@ msgstr "Errore nel canale %s"
msgctxt "#60040" msgctxt "#60040"
msgid "Delete movie" msgid "Delete movie"
msgstr "Rimuovere film" msgstr "Elimina film"
msgctxt "#60041" msgctxt "#60041"
msgid "Delete TV show" msgid "Delete TV show"
msgstr "Rimuovere serie TV" msgstr "Elimina serie TV"
msgctxt "#60042" msgctxt "#60042"
msgid "Delete only the links of %s" msgid "Delete links of %s"
msgstr "Rimuovere solo i link dei %s" msgstr "Elimina link di %s"
msgctxt "#60043" msgctxt "#60043"
msgid "Delete %s links of channel %s" msgid "Delete %s links of channel %s"
@@ -3120,8 +3120,12 @@ msgid "Show only links of "
msgstr "Mostra solo link di " msgstr "Mostra solo link di "
msgctxt "#70079" msgctxt "#70079"
msgid "Remove only links of " msgid "Delete only the links of "
msgstr "Rimuovere solo i collegamenti di " msgstr "Elimina solo i link di "
msgctxt "#70081"
msgid "The folder also contains local or downloaded video files. Do you want to delete them?"
msgstr "La cartella contiene anche file video locali o scaricati. Vuoi eliminarli?"
msgctxt "#70082" msgctxt "#70082"
msgid "Global Search" msgid "Global Search"
@@ -3140,12 +3144,12 @@ msgid "Delete TV show"
msgstr "Elimina serie TV" msgstr "Elimina serie TV"
msgctxt "#70086" msgctxt "#70086"
msgid "Remove only links of %s" msgid "Delete only the links of %s"
msgstr "Rimuovere solo i collegamenti di %s" msgstr "Elimina solo i link di %s"
msgctxt "#70087" msgctxt "#70087"
msgid "Deleted %s links from canal %s" msgid "Deleted %s links from canal %s"
msgstr "Eliminati %s links del canale %s" msgstr "Eliminati %s link del canale %s"
msgctxt "#70088" msgctxt "#70088"
msgid "Are you sure you want to delete '%s' from video library?" msgid "Are you sure you want to delete '%s' from video library?"
@@ -5892,20 +5896,20 @@ msgid "Do you want to call Elementum Settings to temporarily switch to Use Files
msgstr "Vuoi aprire i settaggi di Elementum per passare temporaneamente a usare i file?" msgstr "Vuoi aprire i settaggi di Elementum per passare temporaneamente a usare i file?"
msgctxt "#70782" msgctxt "#70782"
msgid "Your device is not compatible with the Internal Client, do you want to use Quasar for Torrents?" msgid "You must install an external Client to take advantage of the torrent support. Do you want to install Elementum?"
msgstr "Il tuo dispositivo non è compatibile con il Client Interno, Vuoi usare Quasar per i Torrent?" msgstr "Per poter usufruire del supporto torrent devi installare un Client esterno. Vuoi installare Elementum?"
msgctxt "#70783" msgctxt "#70783"
msgid "Quasar installed and configured, enjoy!" msgid "Elementum is installed on your device, but is not active. Do you want to activate it?"
msgstr "Quasar installato e configurato, buona Visione!" msgstr "Elementum è installato sul tuo dispositivo, ma non è attivo. Vuoi Attivarlo?"
msgctxt "#70784" msgctxt "#70784"
msgid "Attention!" msgid "Attention!"
msgstr "Attenzione!" msgstr "Attenzione!"
msgctxt "#70785" msgctxt "#70785"
msgid "Install Quasar" msgid "Install Elementum"
msgstr "Installa Quasar" msgstr "Installa Elementum"
msgctxt "#70786" msgctxt "#70786"
msgid "Autostart" msgid "Autostart"
@@ -5923,6 +5927,65 @@ msgctxt "#70789"
msgid "* Change by opening the settings from KoD main menu" msgid "* Change by opening the settings from KoD main menu"
msgstr "* Cambia aprendo le impostazioni dal menu principale di KoD" msgstr "* Cambia aprendo le impostazioni dal menu principale di KoD"
msgctxt "#70790"
msgid "RAR download in progress"
msgstr "Download RAR in corso"
msgctxt "#70791"
msgid "A RAR file was detected in the download, but you have not installed the UnRAR extractor.\nDo you want to download it anyway?"
msgstr "Un file RAR è stato rilevato nel download, ma non hai installato l'estrattore UnRAR.\nVuoi scaricarlo in ogni caso?"
msgctxt "#70792"
msgid "Delete downloaded files?"
msgstr "Cancellare i file scaricati?"
msgctxt "#70793"
msgid "Starting extraction..."
msgstr "Avvio dell'estrazione..."
msgctxt "#70794"
msgid "Enter the password (Look in %s)"
msgstr "Inserisci la password (Cerca in %s)"
msgctxt "#70795"
msgid "Extracted"
msgstr "Estratto"
msgctxt "#70796"
msgid "Error opening RAR File"
msgstr "Errore durante l'apertura del file RAR"
msgctxt "#70797"
msgid "The RAR file is empty"
msgstr "Il file RAR è vuoto"
msgctxt "#70798"
msgid "Or does not contain valid archives"
msgstr "O non contiene archivi validi"
msgctxt "#70799"
msgid "Extraction error"
msgstr "Errore di estrazione"
msgctxt "#70800"
msgid "Archive with errors"
msgstr "Archivio con errori"
msgctxt "#70801"
msgid "Extract without playing"
msgstr "Estrarre senza riprodurre"
msgctxt "#70802"
msgid "Wait some minutes..."
msgstr "Aspetta qualche minuto..."
msgctxt "#70803"
msgid "Extracting files..."
msgstr "Estrazione dei files..."
msgctxt "#70804"
msgid "Next extraction..."
msgstr "Estrazione successiva..."
# DNS start [ settings and declaration ] # DNS start [ settings and declaration ]
msgctxt "#707401" msgctxt "#707401"
@@ -6219,4 +6282,12 @@ msgstr "Eliminazione videoteca..."
msgctxt "#80039" msgctxt "#80039"
msgid "The video library has been deleted" msgid "The video library has been deleted"
msgstr "La videoteca è stata eliminata" msgstr "La videoteca è stata eliminata"
msgctxt "#80040"
msgid "Add-on updated to commit %s"
msgstr "Add-on aggiornato al commit %s"
msgctxt "#80041"
msgid "Latest updates:\n"
msgstr "Ultimi aggiornamenti:\n"
@@ -0,0 +1,5 @@
<settings version="2">
<setting id="skip_burst_search" default="true">true</setting>
<setting id="greeting_enabled">false</setting>
<setting id="do_not_disturb" default="true">true</setting>
</settings>
+136 -137
View File
@@ -61,8 +61,12 @@ trackers = [
# Returns an array of possible video url's from the page_url # Returns an array of possible video url's from the page_url
def get_video_url(page_url, premium=False, user="", password="", video_password=""): def get_video_url(page_url, premium=False, user="", password="", video_password=""):
logger.info("server=torrent, la url es la buena") torrent_options = platformtools.torrent_client_installed(show_tuple=True)
if len(torrent_options) == 0:
from specials import elementum_download
elementum_download.download()
logger.info("server=torrent, the url is the good")
if page_url.startswith("magnet:"): if page_url.startswith("magnet:"):
video_urls = [["magnet: [torrent]", page_url]] video_urls = [["magnet: [torrent]", page_url]]
else: else:
@@ -92,12 +96,12 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
t_hash = '' t_hash = ''
if referer: if referer:
headers.update({'Content-Type': 'application/x-www-form-urlencoded', 'Referer': referer}) #Necesario para el Post del .Torrent headers.update({'Content-Type': 'application/x-www-form-urlencoded', 'Referer': referer}) #Necesario para el Post del .Torrent
""" """
Descarga en el path recibido el .torrent de la url recibida, y pasa el decode Descarga en el path recibido el .torrent de la url recibida, y pasa el decode
Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito
""" """
videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca videolibrary_path = config.get_videolibrary_path() #Calculamos el path absoluto a partir de la Videoteca
if torrents_path == None: if torrents_path == None:
if not videolibrary_path: if not videolibrary_path:
@@ -110,7 +114,7 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
torrents_path += '.torrent' #path para dejar el .torrent torrents_path += '.torrent' #path para dejar el .torrent
#torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path #torrents_path_encode = filetools.encode(torrents_path) #encode utf-8 del path
torrents_path_encode = torrents_path torrents_path_encode = torrents_path
#if url.endswith(".rar") or url.startswith("magnet:"): #No es un archivo .torrent #if url.endswith(".rar") or url.startswith("magnet:"): #No es un archivo .torrent
if url.endswith(".rar"): #No es un archivo .torrent if url.endswith(".rar"): #No es un archivo .torrent
logger.error('No es un archivo Torrent: ' + url) logger.error('No es un archivo Torrent: ' + url)
@@ -118,7 +122,7 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
if data_torrent: if data_torrent:
return (torrents_path, torrent_file) return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío return torrents_path #Si hay un error, devolvemos el "path" vacío
try: try:
#Descargamos el .torrent #Descargamos el .torrent
if url.startswith("magnet:"): if url.startswith("magnet:"):
@@ -156,17 +160,17 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
#Si es un archivo .ZIP tratamos de extraer el contenido #Si es un archivo .ZIP tratamos de extraer el contenido
if torrent_file.startswith("PK"): if torrent_file.startswith("PK"):
logger.info('Es un archivo .ZIP: ' + url) logger.info("it's a zip archive: " + url)
torrents_path_zip = filetools.join(videolibrary_path, 'temp_torrents_zip') #Carpeta de trabajo torrents_path_zip = filetools.join(videolibrary_path, 'temp_torrents_zip') #Carpeta de trabajo
torrents_path_zip = filetools.encode(torrents_path_zip) torrents_path_zip = filetools.encode(torrents_path_zip)
torrents_path_zip_file = filetools.join(torrents_path_zip, 'temp_torrents_zip.zip') #Nombre del .zip torrents_path_zip_file = filetools.join(torrents_path_zip, 'temp_torrents_zip.zip') #Nombre del .zip
import time import time
filetools.rmdirtree(torrents_path_zip) #Borramos la carpeta temporal filetools.rmdirtree(torrents_path_zip) #Borramos la carpeta temporal
time.sleep(1) #Hay que esperar, porque si no da error time.sleep(1) #Hay que esperar, porque si no da error
filetools.mkdir(torrents_path_zip) #La creamos de nuevo filetools.mkdir(torrents_path_zip) #La creamos de nuevo
if filetools.write(torrents_path_zip_file, torrent_file_uncoded, vfs=VFS): #Salvamos el .zip if filetools.write(torrents_path_zip_file, torrent_file_uncoded, vfs=VFS): #Salvamos el .zip
torrent_file = '' #Borramos el contenido en memoria torrent_file = '' #Borramos el contenido en memoria
try: #Extraemos el .zip try: #Extraemos el .zip
@@ -177,7 +181,7 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
import xbmc import xbmc
xbmc.executebuiltin('XBMC.Extract("%s", "%s")' % (torrents_path_zip_file, torrents_path_zip)) xbmc.executebuiltin('XBMC.Extract("%s", "%s")' % (torrents_path_zip_file, torrents_path_zip))
time.sleep(1) time.sleep(1)
for root, folders, files in filetools.walk(torrents_path_zip): #Recorremos la carpeta para leer el .torrent for root, folders, files in filetools.walk(torrents_path_zip): #Recorremos la carpeta para leer el .torrent
for file in files: for file in files:
if file.endswith(".torrent"): if file.endswith(".torrent"):
@@ -196,20 +200,20 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
if data_torrent: if data_torrent:
return (torrents_path, torrent_file) return (torrents_path, torrent_file)
return torrents_path #Si hay un error, devolvemos el "path" vacío return torrents_path #Si hay un error, devolvemos el "path" vacío
#Calculamos el Hash del Torrent y modificamos el path #Calculamos el Hash del Torrent y modificamos el path
import bencode, hashlib import bencode, hashlib
decodedDict = bencode.bdecode(torrent_file_uncoded) decodedDict = bencode.bdecode(torrent_file_uncoded)
if not PY3: if not PY3:
t_hash = hashlib.sha1(bencode.bencode(decodedDict[b"info"])).hexdigest() t_hash = hashlib.sha1(bencode.bencode(decodedDict[b"info"])).hexdigest()
else: else:
t_hash = hashlib.sha1(bencode.bencode(decodedDict["info"])).hexdigest() t_hash = hashlib.sha1(bencode.bencode(decodedDict["info"])).hexdigest()
if t_hash: if t_hash:
torrents_path = filetools.join(filetools.dirname(torrents_path), t_hash + '.torrent') torrents_path = filetools.join(filetools.dirname(torrents_path), t_hash + '.torrent')
torrents_path_encode = filetools.join(filetools.dirname(torrents_path_encode), t_hash + '.torrent') torrents_path_encode = filetools.join(filetools.dirname(torrents_path_encode), t_hash + '.torrent')
#Salvamos el .torrent #Salvamos el .torrent
if not lookup: if not lookup:
if not filetools.write(torrents_path_encode, torrent_file_uncoded, vfs=VFS): if not filetools.write(torrents_path_encode, torrent_file_uncoded, vfs=VFS):
@@ -224,16 +228,16 @@ def caching_torrents(url, referer=None, post=None, torrents_path=None, timeout=1
torrent_file = '' #... y el buffer del .torrent torrent_file = '' #... y el buffer del .torrent
logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode) logger.error('Error en el proceso de descarga del .torrent: ' + url + ' / ' + torrents_path_encode)
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
#logger.debug(torrents_path) #logger.debug(torrents_path)
if data_torrent: if data_torrent:
return (torrents_path, torrent_file) return (torrents_path, torrent_file)
return torrents_path return torrents_path
def magnet2torrent(magnet, headers={}): def magnet2torrent(magnet, headers={}):
logger.info() logger.info()
torrent_file = '' torrent_file = ''
info = '' info = ''
post = '' post = ''
@@ -276,7 +280,7 @@ def magnet2torrent(magnet, headers={}):
'trackers': trackers, 'trackers': trackers,
'storage_mode': lt.storage_mode_t.storage_mode_allocate 'storage_mode': lt.storage_mode_t.storage_mode_allocate
} # Creamos los parámetros de la sesión } # Creamos los parámetros de la sesión
h = lt.add_magnet_uri(ses, magnet, params) # Abrimos la sesión h = lt.add_magnet_uri(ses, magnet, params) # Abrimos la sesión
i = 0 i = 0
while not h.has_metadata() and not xbmc.abortRequested: # Esperamos mientras Libtorrent abre la sesión while not h.has_metadata() and not xbmc.abortRequested: # Esperamos mientras Libtorrent abre la sesión
@@ -287,14 +291,14 @@ def magnet2torrent(magnet, headers={}):
if i > 5: if i > 5:
LIBTORRENT_PATH = '' # No puede convertir el magnet LIBTORRENT_PATH = '' # No puede convertir el magnet
break break
if LIBTORRENT_PATH: if LIBTORRENT_PATH:
info = h.get_torrent_info() # Obtiene la información del .torrent info = h.get_torrent_info() # Obtiene la información del .torrent
torrent_file = lt.bencode(lt.create_torrent(info).generate()) # Obtiene los datos del .torrent torrent_file = lt.bencode(lt.create_torrent(info).generate()) # Obtiene los datos del .torrent
ses.remove_torrent(h) # Desactiva Libtorrent ses.remove_torrent(h) # Desactiva Libtorrent
filetools.rmdirtree(LIBTORRENT_MAGNET_PATH) # Elimina la carpeta temporal filetools.rmdirtree(LIBTORRENT_MAGNET_PATH) # Elimina la carpeta temporal
return torrent_file return torrent_file
def verify_url_torrent(url, timeout=5): def verify_url_torrent(url, timeout=5):
@@ -316,7 +320,7 @@ def verify_url_torrent(url, timeout=5):
# Reproductor Cliente Torrent propio (libtorrent) # Reproductor Cliente Torrent propio (libtorrent)
def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item=None): def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item=None):
logger.info() logger.info()
# Importamos el cliente # Importamos el cliente
from btserver import Client from btserver import Client
@@ -334,7 +338,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if not save_path_videos: if not save_path_videos:
save_path_videos = filetools.join(config.get_data_path(), 'downloads', 'BT-torrents') save_path_videos = filetools.join(config.get_data_path(), 'downloads', 'BT-torrents')
config.set_setting("bt_download_path", filetools.join(config.get_data_path(), 'downloads'), server="torrent") config.set_setting("bt_download_path", filetools.join(config.get_data_path(), 'downloads'), server="torrent")
UNRAR = config.get_setting("unrar_path", server="torrent", default="") UNRAR = config.get_setting("unrar_path", server="torrent", default="")
BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True) BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True)
RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True) RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True)
@@ -351,7 +355,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
else: else:
DOWNLOAD_LIMIT = 0 DOWNLOAD_LIMIT = 0
UPLOAD_LIMIT = 100 UPLOAD_LIMIT = 100
torr_client = 'BT' torr_client = 'BT'
rar_file = '' rar_file = ''
rar_names = [] rar_names = []
@@ -366,7 +370,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg',
'.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg',
'.mpe', '.mp4', '.ogg', '.rar', '.wmv', '.zip'] '.mpe', '.mp4', '.ogg', '.rar', '.wmv', '.zip']
for entry in rar_files: for entry in rar_files:
for file, path in list(entry.items()): for file, path in list(entry.items()):
if file == 'path' and '.rar' in str(path): if file == 'path' and '.rar' in str(path):
@@ -389,16 +393,15 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if not video_file and mediaurl.startswith('magnet'): if not video_file and mediaurl.startswith('magnet'):
video_file = urllib.unquote_plus(scrapertools.find_single_match(mediaurl, '(?:\&|&amp;)dn=([^\&]+)\&')) video_file = urllib.unquote_plus(scrapertools.find_single_match(mediaurl, '(?:\&|&amp;)dn=([^\&]+)\&'))
erase_file_path = filetools.join(save_path_videos, video_file) erase_file_path = filetools.join(save_path_videos, video_file)
if rar and RAR and not UNRAR: if rar and RAR and not UNRAR:
if not platformtools.dialog_yesno(msg_header, 'Se ha detectado un archivo .RAR en la descarga', \ if not platformtools.dialog_yesno(msg_header, config.get_localized_string(70791)):
'No tiene instalado el extractor UnRAR', '¿Desea descargarlo en cualquier caso?'):
return return
# Iniciamos el cliente: # Iniciamos el cliente:
c = Client(url=mediaurl, is_playing_fnc=xbmc_player.isPlaying, wait_time=None, auto_shutdown=False, timeout=10, c = Client(url=mediaurl, is_playing_fnc=xbmc_player.isPlaying, wait_time=None, auto_shutdown=False, timeout=10,
temp_path=save_path_videos, print_status=debug, auto_delete=False) temp_path=save_path_videos, print_status=debug, auto_delete=False)
activo = True activo = True
finalizado = False finalizado = False
dp_cerrado = True dp_cerrado = True
@@ -406,10 +409,9 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
# Mostramos el progreso # Mostramos el progreso
if rar and RAR and BACKGROUND: # Si se descarga un RAR... if rar and RAR and BACKGROUND: # Si se descarga un RAR...
progreso = platformtools.dialog_progress_bg(msg_header) progreso = platformtools.dialog_progress_bg(msg_header)
platformtools.dialog_notification("Descarga de RAR en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \ platformtools.dialog_notification(config.get_localized_string(70790), config.get_localized_string(70769), time=10000)
"Te informaremos...", time=10000)
else: else:
progreso = platformtools.dialog_progress('Alfa %s Cliente Torrent' % torr_client, '') progreso = platformtools.dialog_progress('%s Torrent Client' % torr_client, '')
dp_cerrado = False dp_cerrado = False
# Mientras el progreso no sea cancelado ni el cliente cerrado # Mientras el progreso no sea cancelado ni el cliente cerrado
@@ -441,7 +443,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
time.sleep(1) time.sleep(1)
if (not bkg_user and progreso.iscanceled()) and (not (rar and RAR and BACKGROUND) and progreso.iscanceled()): if (not bkg_user and progreso.iscanceled()) and (not (rar and RAR and BACKGROUND) and progreso.iscanceled()):
if not dp_cerrado: if not dp_cerrado:
progreso.close() progreso.close()
dp_cerrado = True dp_cerrado = True
@@ -477,7 +479,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if ((s.pieces_sum >= BUFFER or 'Finalizado' in s.str_state or 'Seeding' in s.str_state) and not rar and not bkg_user) or \ if ((s.pieces_sum >= BUFFER or 'Finalizado' in s.str_state or 'Seeding' in s.str_state) and not rar and not bkg_user) or \
(s.pieces_sum >= s.pieces_len - 3 and s.pieces_len > 0 and ('Finalizado' in s.str_state or 'Seeding' \ (s.pieces_sum >= s.pieces_len - 3 and s.pieces_len > 0 and ('Finalizado' in s.str_state or 'Seeding' \
in s.str_state) and (rar or bkg_user)) and not played: in s.str_state) and (rar or bkg_user)) and not played:
if rar and RAR and UNRAR: if rar and RAR and UNRAR:
c.stop() c.stop()
activo = False activo = False
@@ -495,7 +497,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
elif bkg_user: elif bkg_user:
finalizado = True finalizado = True
break break
# Cerramos el progreso # Cerramos el progreso
if not dp_cerrado: if not dp_cerrado:
progreso.close() progreso.close()
@@ -506,8 +508,8 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT) # Bajamos la velocidad en background c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT) # Bajamos la velocidad en background
bkg_auto = True bkg_auto = True
while xbmc_player.isPlaying() and not xbmc.abortRequested: while xbmc_player.isPlaying() and not xbmc.abortRequested:
time.sleep(3) time.sleep(3)
# Obtenemos el playlist del torrent # Obtenemos el playlist del torrent
#videourl = c.get_play_list() #videourl = c.get_play_list()
if not rar_res: # Es un Magnet ? if not rar_res: # Es un Magnet ?
@@ -528,20 +530,20 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
# Marcamos como reproducido para que no se vuelva a iniciar # Marcamos como reproducido para que no se vuelva a iniciar
played = True played = True
mark_auto_as_watched(item) mark_auto_as_watched(item)
# Y esperamos a que el reproductor se cierre # Y esperamos a que el reproductor se cierre
bkg_auto = True bkg_auto = True
dp_cerrado = True dp_cerrado = True
while xbmc_player.isPlaying() and not xbmc.abortRequested: while xbmc_player.isPlaying() and not xbmc.abortRequested:
time.sleep(1) time.sleep(1)
if xbmc.getCondVisibility('Player.Playing'): if xbmc.getCondVisibility('Player.Playing'):
if not dp_cerrado: if not dp_cerrado:
dp_cerrado = True dp_cerrado = True
progreso.close() progreso.close()
if xbmc.getCondVisibility('Player.Paused') and not rar_res: if xbmc.getCondVisibility('Player.Paused') and not rar_res:
if not c.closed: s = c.status if not c.closed: s = c.status
txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \ txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
@@ -555,11 +557,11 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
progreso = xbmcgui.DialogProgressBG() progreso = xbmcgui.DialogProgressBG()
progreso.create(msg_header) progreso.create(msg_header)
progreso.update(s.buffer, msg_header, '[CR][CR]' + txt + '[CR]' + txt2) progreso.update(s.buffer, msg_header, '[CR][CR]' + txt + '[CR]' + txt2)
if not dp_cerrado: if not dp_cerrado:
dp_cerrado = True dp_cerrado = True
progreso.close() progreso.close()
# Miramos si se ha completado la descarga para borrar o no los archivos # Miramos si se ha completado la descarga para borrar o no los archivos
if activo: if activo:
s = c.status s = c.status
@@ -567,7 +569,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
finalizado = True finalizado = True
break break
if platformtools.dialog_yesno(msg_header, config.get_localized_string(30031), config.get_localized_string(30032)): if not platformtools.dialog_yesno(msg_header, config.get_localized_string(30031), config.get_localized_string(30032)):
progreso = platformtools.dialog_progress(msg_header, '') progreso = platformtools.dialog_progress(msg_header, '')
dp_cerrado = False dp_cerrado = False
break break
@@ -579,18 +581,18 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
progreso.update(s.buffer, txt, txt2) progreso.update(s.buffer, txt, txt2)
dp_cerrado = False dp_cerrado = False
continue continue
# Cuando este cerrado, Volvemos a mostrar el dialogo # Cuando este cerrado, Volvemos a mostrar el dialogo
if not (rar and bkg_user): if not (rar and bkg_user):
progreso = platformtools.dialog_progress(msg_header, '') progreso = platformtools.dialog_progress(msg_header, '')
progreso.update(s.buffer, txt, txt2, txt3) progreso.update(s.buffer, txt, txt2, txt3)
dp_cerrado = False dp_cerrado = False
break break
except: except:
logger.error(traceback.format_exc(1)) logger.error(traceback.format_exc(1))
return return
if not dp_cerrado: if not dp_cerrado:
if rar or bkg_user: if rar or bkg_user:
progreso.update(100, config.get_localized_string(70200), " ") progreso.update(100, config.get_localized_string(70200), " ")
@@ -606,11 +608,11 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
if not dp_cerrado: if not dp_cerrado:
progreso.close() progreso.close()
dp_cerrado = True dp_cerrado = True
# Y borramos los archivos de descarga restantes # Y borramos los archivos de descarga restantes
time.sleep(1) time.sleep(1)
if filetools.exists(erase_file_path) and not bkg_user: if filetools.exists(erase_file_path) and not bkg_user:
if finalizado and not platformtools.dialog_yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)'): if finalizado and not platformtools.dialog_yesno(msg_header, config.get_localized_string(70792)):
return return
log("##### erase_file_path: %s" % erase_file_path) log("##### erase_file_path: %s" % erase_file_path)
for x in range(10): for x in range(10):
@@ -629,7 +631,7 @@ def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item
def call_torrent_via_web(mediaurl, torr_client): def call_torrent_via_web(mediaurl, torr_client):
# Usado para llamar a los clientes externos de Torrents para automatizar la descarga de archivos que contienen .RAR # Usado para llamar a los clientes externos de Torrents para automatizar la descarga de archivos que contienen .RAR
logger.info() logger.info()
post = '' post = ''
ELEMENTUMD_HOST = "http://localhost:65220" ELEMENTUMD_HOST = "http://localhost:65220"
if torr_client == 'elementum': if torr_client == 'elementum':
@@ -642,7 +644,7 @@ def call_torrent_via_web(mediaurl, torr_client):
local_host = {"quasar": ["http://localhost:65251/torrents/", "add?uri"], \ local_host = {"quasar": ["http://localhost:65251/torrents/", "add?uri"], \
"elementum": ["%s/torrents/" % ELEMENTUMD_HOST, "add"]} "elementum": ["%s/torrents/" % ELEMENTUMD_HOST, "add"]}
if torr_client == "quasar": if torr_client == "quasar":
uri = '%s%s=%s' % (local_host[torr_client][0], local_host[torr_client][1], mediaurl) uri = '%s%s=%s' % (local_host[torr_client][0], local_host[torr_client][1], mediaurl)
elif torr_client == "elementum": elif torr_client == "elementum":
@@ -658,9 +660,9 @@ def call_torrent_via_web(mediaurl, torr_client):
def mark_auto_as_watched(item): def mark_auto_as_watched(item):
time_limit = time.time() + 150 #Marcamos el timepo máx. de buffering time_limit = time.time() + 150 #Marcamos el timepo máx. de buffering
while not platformtools.is_playing() and time.time() < time_limit: #Esperamos mientra buffera while not platformtools.is_playing() and time.time() < time_limit: #Esperamos mientra buffera
time.sleep(5) #Repetimos cada intervalo time.sleep(5) #Repetimos cada intervalo
#logger.debug(str(time_limit)) #logger.debug(str(time_limit))
if item.subtitle: if item.subtitle:
@@ -679,7 +681,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
logger.info() logger.info()
from subprocess import Popen, PIPE, STDOUT from subprocess import Popen, PIPE, STDOUT
# Analizamos los archivos dentro del .torrent # Analizamos los archivos dentro del .torrent
rar = False rar = False
rar_names = [] rar_names = []
@@ -700,10 +702,10 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
rar = True rar = True
elif file == '__name': elif file == '__name':
folder = path folder = path
if not folder: # Si no se detecta el folder... if not folder: # Si no se detecta el folder...
return ('', '', '') # ... no podemos hacer nada return ('', '', '') # ... no podemos hacer nada
if not rar_names: if not rar_names:
return ('', '', folder) return ('', '', folder)
rar_file = '%s/%s' % (folder, rar_names[0]) rar_file = '%s/%s' % (folder, rar_names[0])
@@ -726,7 +728,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
if not save_path_videos: # No hay path de descarga? if not save_path_videos: # No hay path de descarga?
return ('', '', folder) # Volvemos return ('', '', folder) # Volvemos
log("##### save_path_videos: %s" % save_path_videos) log("##### save_path_videos: %s" % save_path_videos)
# Si es nueva descarga, ponemos un archivo de control para reiniciar el UNRar si ha habido cancelación de Kodi # Si es nueva descarga, ponemos un archivo de control para reiniciar el UNRar si ha habido cancelación de Kodi
# Si ya existe el archivo (llamada), se reinicia el proceso de UNRar donde se quedó # Si ya existe el archivo (llamada), se reinicia el proceso de UNRar donde se quedó
if rar_control: if rar_control:
@@ -751,17 +753,17 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
if torr_client == 'quasar': # Quasar no copia en .torrent if torr_client == 'quasar': # Quasar no copia en .torrent
ret = filetools.copy(item.url, filetools.join(save_path_videos, 'torrents', \ ret = filetools.copy(item.url, filetools.join(save_path_videos, 'torrents', \
filetools.basename(item.url)), silent=True) filetools.basename(item.url)), silent=True)
# Esperamos mientras el .torrent se descarga. Verificamos si el .RAR está descargado al completo # Esperamos mientras el .torrent se descarga. Verificamos si el .RAR está descargado al completo
platformtools.dialog_notification("Automatizando la extracción", "Acepta descargar el archivo RAR y te iremos guiando...", time=10000) platformtools.dialog_notification(config.get_localized_string(70803), "", time=10000)
# Plan A: usar el monitor del cliente torrent para ver el status de la descarga # Plan A: usar el monitor del cliente torrent para ver el status de la descarga
loop = 3600 # Loop de 10 horas hasta crear archivo loop = 3600 # Loop de 10 horas hasta crear archivo
wait_time = 10 wait_time = 10
time.sleep(wait_time) time.sleep(wait_time)
fast = False fast = False
ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control)) ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control))
for x in range(loop): for x in range(loop):
if xbmc.abortRequested: if xbmc.abortRequested:
return ('', '', folder) return ('', '', folder)
@@ -773,27 +775,26 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
return ('', '', folder) # Volvemos return ('', '', folder) # Volvemos
if (torr_client in ['quasar'] or torr_client in ['elementum']) and not \ if (torr_client in ['quasar'] or torr_client in ['elementum']) and not \
torr_data['label'].startswith('0.00%') and not fast: torr_data['label'].startswith('0.00%') and not fast:
platformtools.dialog_notification("Descarga en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \ platformtools.dialog_notification(config.get_localized_string(60200), config.get_localized_string(70769), time=10000)
"Te informaremos...", time=10000)
fast = True fast = True
if not torr_data['label'].startswith('100.00%'): if not torr_data['label'].startswith('100.00%'):
log("##### Descargado: %s, ID: %s" % (scrapertools.find_single_match(torr_data['label'], '(^.*?\%)'), index)) log("##### Downloading: %s, ID: %s" % (scrapertools.find_single_match(torr_data['label'], '(^.*?\%)'), index))
time.sleep(wait_time) time.sleep(wait_time)
continue continue
update_rar_control(rar_control['download_path'], status='downloaded') update_rar_control(rar_control['download_path'], status='downloaded')
log("##### Torrent FINALIZADO: %s" % str(folder)) log("##### Torrent FINALIZED: %s" % str(folder))
return (rar_file, save_path_videos, folder) return (rar_file, save_path_videos, folder)
# Plan B: monitorizar con UnRAR si los archivos se han desacargado por completo # Plan B: monitorizar con UnRAR si los archivos se han desacargado por completo
unrar_path = config.get_setting("unrar_path", server="torrent", default="") unrar_path = config.get_setting("unrar_path", server="torrent", default="")
if not unrar_path: # Si Unrar no está instalado... if not unrar_path: # Si Unrar no está instalado...
return ('', '', folder) # ... no podemos hacer nada return ('', '', folder) # ... no podemos hacer nada
cmd = [] cmd = []
for rar_name in rar_names: # Preparamos por si es un archivo multiparte for rar_name in rar_names: # Preparamos por si es un archivo multiparte
cmd.append(['%s' % unrar_path, 'l', '%s' % filetools.join(save_path_videos, folder, rar_name)]) cmd.append(['%s' % unrar_path, 'l', '%s' % filetools.join(save_path_videos, folder, rar_name)])
creationflags = '' creationflags = ''
if xbmc.getCondVisibility("system.platform.Windows"): if xbmc.getCondVisibility("system.platform.Windows"):
creationflags = 0x08000000 creationflags = 0x08000000
@@ -834,7 +835,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
if returncode == '0': # Ya se ha descargado... parte ... if returncode == '0': # Ya se ha descargado... parte ...
dl_files += 1 dl_files += 1
part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)') part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)')
log("##### Torrent descargando: %s, %s" % (part_name, str(returncode))) log("##### Torrent downloading: %s, %s" % (part_name, str(returncode)))
if dl_files == len(cmd): # ... o todo if dl_files == len(cmd): # ... o todo
fast = True fast = True
rar = False rar = False
@@ -848,8 +849,7 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
#if loop == 30 and y == len(responses): # Si es la primera vez en proceso ... #if loop == 30 and y == len(responses): # Si es la primera vez en proceso ...
if loop == 30 and y == 1: # Si es la primera vez en proceso ... if loop == 30 and y == 1: # Si es la primera vez en proceso ...
if torr_client in ['quasar']: if torr_client in ['quasar']:
platformtools.dialog_notification("Descarga en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \ platformtools.dialog_notification(config.get_localized_string(60200), config.get_localized_string(70769), time=10000)
"Te informaremos...", time=10000)
loop_change = 3600 # ... pasamos a un loop de 10 horas loop_change = 3600 # ... pasamos a un loop de 10 horas
elif loop <= 6: # Recuerado el error desconocido elif loop <= 6: # Recuerado el error desconocido
loop_change = 3600 # ... pasamos a un loop de 10 horas loop_change = 3600 # ... pasamos a un loop de 10 horas
@@ -857,16 +857,16 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
break break
elif returncode == '1': # Ha alcanzado el fin de archivo ??? pasamos elif returncode == '1': # Ha alcanzado el fin de archivo ??? pasamos
part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)') part_name = scrapertools.find_single_match(str(out__), '(\.part\d+.rar)')
log("##### Torrent descargando: %s, %s" % (part_name, str(returncode))) log("##### Torrent downloading: %s, %s" % (part_name, str(returncode)))
else: # No entendemos el error else: # No entendemos el error
loop_change = loop_error # ... pasamos a un loop de 1 minutos para reintentar loop_change = loop_error # ... pasamos a un loop de 1 minutos para reintentar
loop_error += -1 loop_error += -1
break #... abortamos break #... abortamos
if str(returncode) in ['0', '6', '10']: if str(returncode) in ['0', '6', '10']:
log("##### Torrent descargando: %s" % str(returncode)) log("##### Torrent downloading: %s" % str(returncode))
else: else:
log("##### Torrent descargando: %s, %s" % (str(out__), str(returncode))) log("##### Torrent downloading: %s, %s" % (str(out__), str(returncode)))
if not rar or fast: if not rar or fast:
fast = False fast = False
break break
@@ -876,14 +876,14 @@ def wait_for_download(item, mediaurl, rar_files, torr_client, password='', size=
break break
if str(returncode) == '0': if str(returncode) == '0':
log("##### Torrent FINALIZADO: %s" % str(returncode)) log("##### Torrent FINALIZED: %s" % str(returncode))
else: else:
rar_file = '' rar_file = ''
logger.error('##### Torrent NO DESCARGADO: %s, %s' % (str(out__), str(returncode))) logger.error('##### Torrent NO DESCARGADO: %s, %s' % (str(out__), str(returncode)))
return (rar_file, save_path_videos, folder) return (rar_file, save_path_videos, folder)
def get_tclient_data(folder, torr_client): def get_tclient_data(folder, torr_client):
# Monitoriza el estado de descarga del torrent en Quasar y Elementum # Monitoriza el estado de descarga del torrent en Quasar y Elementum
@@ -901,7 +901,7 @@ def get_tclient_data(folder, torr_client):
torr_id = '' torr_id = ''
x = 0 x = 0
y = '' y = ''
try: try:
data = httptools.downloadpage(local_host[torr_client], timeout=5, alfa_s=True).data data = httptools.downloadpage(local_host[torr_client], timeout=5, alfa_s=True).data
if not data: if not data:
@@ -920,7 +920,7 @@ def get_tclient_data(folder, torr_client):
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
return '', local_host[torr_client], 0 return '', local_host[torr_client], 0
if torr_id: if torr_id:
y = torr_id y = torr_id
else: else:
@@ -931,9 +931,9 @@ def get_tclient_data(folder, torr_client):
def extract_files(rar_file, save_path_videos, password, dp, item=None, \ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
torr_client=None, rar_control={}, size='RAR', mediaurl=''): torr_client=None, rar_control={}, size='RAR', mediaurl=''):
logger.info() logger.info()
from platformcode import custom_code from platformcode import custom_code
if not rar_control: if not rar_control:
rar_control = { rar_control = {
'torr_client': torr_client, 'torr_client': torr_client,
@@ -949,12 +949,12 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
'mediaurl': mediaurl 'mediaurl': mediaurl
} }
ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control)) ret = filetools.write(filetools.join(rar_control['download_path'], '_rar_control.json'), jsontools.dump(rar_control))
#reload(sys) #reload(sys)
#sys.setdefaultencoding('utf-8') #sys.setdefaultencoding('utf-8')
sys.path.insert(0, config.get_setting("unrar_path", server="torrent", default="")\ sys.path.insert(0, config.get_setting("unrar_path", server="torrent", default="")\
.replace('/unrar', '').replace('\\unrar,exe', '')) .replace('/unrar', '').replace('\\unrar,exe', ''))
import rarfile import rarfile
# Verificamos si hay path para UnRAR # Verificamos si hay path para UnRAR
@@ -965,7 +965,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
return rar_file, False, '', '' return rar_file, False, '', ''
log("##### unrar_path: %s" % rarfile.UNRAR_TOOL) log("##### unrar_path: %s" % rarfile.UNRAR_TOOL)
rarfile.DEFAULT_CHARSET = 'utf-8' rarfile.DEFAULT_CHARSET = 'utf-8'
# Preparamos un path alternativo más corto para no sobrepasar la longitud máxima # Preparamos un path alternativo más corto para no sobrepasar la longitud máxima
video_path = '' video_path = ''
if item: if item:
@@ -978,7 +978,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
.replace("ú", "u").replace("ü", "u").replace("ñ", "n")\ .replace("ú", "u").replace("ü", "u").replace("ñ", "n")\
.replace("Á", "A").replace("É", "E").replace("Í", "I").replace("Ó", "O")\ .replace("Á", "A").replace("É", "E").replace("Í", "I").replace("Ó", "O")\
.replace("Ú", "U").replace("Ü", "U").replace("Ñ", "N") .replace("Ú", "U").replace("Ü", "U").replace("Ñ", "N")
# Renombramos el path dejado en la descarga a uno más corto # Renombramos el path dejado en la descarga a uno más corto
rename_status = False rename_status = False
org_rar_file = rar_file org_rar_file = rar_file
@@ -1007,11 +1007,11 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
save_path_videos = filetools.join(save_path_videos, 'Extracted') save_path_videos = filetools.join(save_path_videos, 'Extracted')
if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos)
log("##### save_path_videos: %s" % save_path_videos) log("##### save_path_videos: %s" % save_path_videos)
rar_control = update_rar_control(erase_file_path, status='UnRARing') rar_control = update_rar_control(erase_file_path, status='UnRARing')
# Permite hasta 5 pasadas de extracción de .RARs anidados # Permite hasta 5 pasadas de extracción de .RARs anidados
platformtools.dialog_notification("Empezando extracción...", rar_file, time=5000) platformtools.dialog_notification(config.get_localized_string(70793), rar_file, time=5000)
for x in range(5): for x in range(5):
try: try:
if not PY3: if not PY3:
@@ -1019,11 +1019,11 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
else: else:
archive = rarfile.RarFile(file_path) archive = rarfile.RarFile(file_path)
except: except:
log("##### ERROR en Archivo rar: %s" % rar_file) log("##### ERROR in rar archive: %s" % rar_file)
log("##### ERROR en Carpeta del rar: %s" % file_path) log("##### ERROR in rar folder: %s" % file_path)
log(traceback.format_exc()) log(traceback.format_exc())
error_msg = "Error al abrir el RAR" error_msg = config.get_localized_string(70796)
error_msg1 = "Comprueba el log para más detalles" error_msg1 = config.get_localized_string(60015)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
return rar_file, False, '', '' return rar_file, False, '', ''
@@ -1034,9 +1034,9 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
pass_path = filetools.split(file_path)[0] pass_path = filetools.split(file_path)[0]
password = last_password_search(pass_path, erase_file_path) password = last_password_search(pass_path, erase_file_path)
if not password : if not password :
password = platformtools.dialog_input(heading="Introduce la contraseña (Mira en %s)" % pass_path) password = platformtools.dialog_input(heading=config.get_localized_string(70794) % pass_path)
if not password: if not password:
error_msg = "No se ha introducido la contraseña" error_msg = config.get_localized_string(60309)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
@@ -1056,10 +1056,10 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
info.append("%s - %.2f MB" % (filename, i.file_size / 1048576.0)) info.append("%s - %.2f MB" % (filename, i.file_size / 1048576.0))
if info: if info:
info.append("Extraer todo sin reproducir") info.append(config.get_localized_string(70801))
else: else:
error_msg = "El RAR está vacío" error_msg = config.get_localized_string(70797)
error_msg1 = "O no contiene archivos válidos" error_msg1 = config.get_localized_string(70798)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
@@ -1069,7 +1069,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
#selection = xbmcgui.Dialog().select("Selecciona el fichero a extraer y reproducir", info) #selection = xbmcgui.Dialog().select("Selecciona el fichero a extraer y reproducir", info)
selection = len(info) - 1 selection = len(info) - 1
if selection < 0: if selection < 0:
error_msg = "El RAR está vacío" error_msg = config.get_localized_string(70797)
platformtools.dialog_notification(error_msg) platformtools.dialog_notification(error_msg)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
return rar_file, False, '', '' return rar_file, False, '', ''
@@ -1079,26 +1079,26 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
if selection == len(info) - 1: if selection == len(info) - 1:
log("##### rar_file 1: %s" % file_path) log("##### rar_file 1: %s" % file_path)
log("##### save_path_videos 1: %s" % save_path_videos) log("##### save_path_videos 1: %s" % save_path_videos)
dp.update(99, "Extrayendo archivos...", "Espera unos minutos....") dp.update(99, config.get_localized_string(70803), config.get_localized_string(70802))
archive.extractall(save_path_videos) archive.extractall(save_path_videos)
else: else:
log("##### rar_file 2: %s" % file_path) log("##### rar_file 2: %s" % file_path)
log("##### save_path_videos 2: %s" % save_path_videos) log("##### save_path_videos 2: %s" % save_path_videos)
dp.update(99, "Espera unos minutos....", "Extrayendo archivo... %s" % info[selection]) dp.update(99, config.get_localized_string(70802), config.get_localized_string(70803) + " %s" % info[selection])
archive.extract(files[selection], save_path_videos) archive.extract(files[selection], save_path_videos)
log("##### RAR Extract END #####") log("##### RAR Extract END #####")
except (rarfile.RarWrongPassword, rarfile.RarCRCError): except (rarfile.RarWrongPassword, rarfile.RarCRCError):
log(traceback.format_exc(1)) log(traceback.format_exc(1))
error_msg = "Error al extraer" error_msg = config.get_localized_string(70799)
error_msg1 = "Contraseña incorrecta" error_msg1 = config.get_localized_string(60309)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR')
dp.close() dp.close()
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
except rarfile.BadRarFile: except rarfile.BadRarFile:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
error_msg = "Error al extraer" error_msg = config.get_localized_string(70799)
error_msg1 = "Archivo rar con errores" error_msg1 = config.get_localized_string(60800)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg1, status='ERROR')
#return rar_file, False, '', erase_file_path #return rar_file, False, '', erase_file_path
@@ -1106,8 +1106,8 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
error_msg = "Error al extraer" error_msg = config.get_localized_string(70799)
error_msg1 = "Comprueba el log para más detalles" error_msg1 = config.get_localized_string(60015)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
@@ -1116,7 +1116,7 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg', extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg',
'.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg', '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg',
'.mpe', '.mp4', '.ogg', '.wmv'] '.mpe', '.mp4', '.ogg', '.wmv']
# Localizamos el path donde se ha dejado la extracción # Localizamos el path donde se ha dejado la extracción
folder = True folder = True
file_result = filetools.listdir(save_path_videos) file_result = filetools.listdir(save_path_videos)
@@ -1142,25 +1142,25 @@ def extract_files(rar_file, save_path_videos, password, dp, item=None, \
save_path_videos = filetools.join(save_path_videos, 'Extracted') save_path_videos = filetools.join(save_path_videos, 'Extracted')
rar_control = update_rar_control(erase_file_path, newextract=(rar_file)) rar_control = update_rar_control(erase_file_path, newextract=(rar_file))
if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos) if not filetools.exists(save_path_videos): filetools.mkdir(save_path_videos)
platformtools.dialog_notification("Siguiente extracción...", rar_file, time=5000) platformtools.dialog_notification(config.get_localized_string(70804), rar_file, time=5000)
# Si ya se ha extraido todo, preparamos el retorno # Si ya se ha extraido todo, preparamos el retorno
else: else:
video_list = [] video_list = []
for file_r in file_result: for file_r in file_result:
if os.path.splitext(file_r)[1] in extensions_list: if os.path.splitext(file_r)[1] in extensions_list:
video_list += [file_r] video_list += [file_r]
if len(video_list) == 0: if len(video_list) == 0:
error_msg = "El rar está vacío" error_msg = config.get_localized_string(70797)
error_msg1 = "O no contiene archivos válidos" error_msg1 = config.get_localized_string(70798)
platformtools.dialog_notification(error_msg, error_msg1) platformtools.dialog_notification(error_msg, error_msg1)
rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR') rar_control = update_rar_control(erase_file_path, error=True, error_msg=error_msg, status='ERROR')
dp.close() dp.close()
return custom_code.reactivate_unrar(init=False, mute=False) return custom_code.reactivate_unrar(init=False, mute=False)
else: else:
log("##### Archivo extraído: %s" % video_list[0]) log("##### Archive extracted: %s" % video_list[0])
platformtools.dialog_notification("Archivo extraído...", video_list[0], time=10000) platformtools.dialog_notification(config.get_localized_string(70795), video_list[0], time=10000)
log("##### Archivo remove: %s" % file_path) log("##### Archive removes: %s" % file_path)
#rar_control = update_rar_control(erase_file_path, status='DONE') #rar_control = update_rar_control(erase_file_path, status='DONE')
ret = filetools.remove(filetools.join(erase_file_path, '_rar_control.json'), silent=True) ret = filetools.remove(filetools.join(erase_file_path, '_rar_control.json'), silent=True)
return str(video_list[0]), True, save_path_videos, erase_file_path return str(video_list[0]), True, save_path_videos, erase_file_path
@@ -1180,12 +1180,12 @@ def rename_rar_dir(rar_file, save_path_videos, video_path, torr_client):
src = filetools.join(save_path_videos, folders[0]) src = filetools.join(save_path_videos, folders[0])
dst = filetools.join(save_path_videos, video_path) dst = filetools.join(save_path_videos, video_path)
dst_file = video_path dst_file = video_path
for x in range(20): for x in range(20):
if xbmc.abortRequested: if xbmc.abortRequested:
return rename_status, rar_file return rename_status, rar_file
xbmc.sleep(1000) xbmc.sleep(1000)
# Se para la actividad para que libere los archivos descargados # Se para la actividad para que libere los archivos descargados
if torr_client in ['quasar', 'elementum']: if torr_client in ['quasar', 'elementum']:
torr_data, deamon_url, index = get_tclient_data(folders[0], torr_client) torr_data, deamon_url, index = get_tclient_data(folders[0], torr_client)
@@ -1209,13 +1209,13 @@ def rename_rar_dir(rar_file, save_path_videos, video_path, torr_client):
rename_status = True rename_status = True
update_rar_control(dst, newpath=dst) update_rar_control(dst, newpath=dst)
break break
return rename_status, rar_file return rename_status, rar_file
def last_password_search(pass_path, erase_file_path=''): def last_password_search(pass_path, erase_file_path=''):
logger.info(pass_path) logger.info(pass_path)
if not erase_file_path: if not erase_file_path:
erase_file_path = pass_path erase_file_path = pass_path
@@ -1223,7 +1223,7 @@ def last_password_search(pass_path, erase_file_path=''):
password = '' password = ''
patron_url = '(http.*\:\/\/(?:www.)?\w+\.\w+\/.*?)[\n|\r|$]' patron_url = '(http.*\:\/\/(?:www.)?\w+\.\w+\/.*?)[\n|\r|$]'
patron_pass = '<input\s*type="text"\s*id="txt_password"\s*name="[^"]+"\s*onClick="[^"]+"\s*value="([^"]+)"' patron_pass = '<input\s*type="text"\s*id="txt_password"\s*name="[^"]+"\s*onClick="[^"]+"\s*value="([^"]+)"'
try: try:
pass_path_list = filetools.listdir(pass_path) pass_path_list = filetools.listdir(pass_path)
for file in pass_path_list: for file in pass_path_list:
@@ -1238,18 +1238,18 @@ def last_password_search(pass_path, erase_file_path=''):
break break
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
log("##### Contraseña extraída: %s" % password) log("##### Password Extracted: %s" % password)
return password return password
def update_rar_control(path, newpath='', newextract='', password='', error='', error_msg='', status=''): def update_rar_control(path, newpath='', newextract='', password='', error='', error_msg='', status=''):
try: try:
rar_control = {} rar_control = {}
rar_control = jsontools.load(filetools.read(filetools.join(path, '_rar_control.json'))) rar_control = jsontools.load(filetools.read(filetools.join(path, '_rar_control.json')))
if rar_control: if rar_control:
if newpath: if newpath:
rar_control['download_path'] = newpath rar_control['download_path'] = newpath
for x, entry in enumerate(rar_control['rar_files']): for x, entry in enumerate(rar_control['rar_files']):
if '__name' in entry: if '__name' in entry:
@@ -1273,7 +1273,7 @@ def update_rar_control(path, newpath='', newextract='', password='', error='', e
str(rar_control['error']), rar_control['error_msg'], rar_control['status'])) str(rar_control['error']), rar_control['error_msg'], rar_control['status']))
except: except:
log(traceback.format_exc(1)) log(traceback.format_exc(1))
return rar_control return rar_control
@@ -1300,21 +1300,21 @@ def import_libtorrent(LIBTORRENT_PATH):
from ctypes import CDLL from ctypes import CDLL
dll_path = os.path.join(LIBTORRENT_PATH, 'liblibtorrent.so') dll_path = os.path.join(LIBTORRENT_PATH, 'liblibtorrent.so')
liblibtorrent = CDLL(dll_path) liblibtorrent = CDLL(dll_path)
path_list = [LIBTORRENT_PATH, xbmc.translatePath('special://xbmc')] path_list = [LIBTORRENT_PATH, xbmc.translatePath('special://xbmc')]
fp, pathname, description = imp.find_module('libtorrent', path_list) fp, pathname, description = imp.find_module('libtorrent', path_list)
# Esta parte no funciona en Android. Por algún motivo da el error "dlopen failed: library "liblibtorrent.so" not found" # Esta parte no funciona en Android. Por algún motivo da el error "dlopen failed: library "liblibtorrent.so" not found"
# Hay que encontrar un hack para rodear el problema. Lo siguiente ha sido probado sin éxito: # Hay que encontrar un hack para rodear el problema. Lo siguiente ha sido probado sin éxito:
#if fp: fp.close() #if fp: fp.close()
#fp = filetools.file_open(filetools.join(LIBTORRENT_PATH, 'libtorrent.so'), mode='rb') # Usa XbmcVFS #fp = filetools.file_open(filetools.join(LIBTORRENT_PATH, 'libtorrent.so'), mode='rb') # Usa XbmcVFS
#fp = open(os.path.join(LIBTORRENT_PATH, 'libtorrent.so'), 'rb') #fp = open(os.path.join(LIBTORRENT_PATH, 'libtorrent.so'), 'rb')
try: try:
lt = imp.load_module('libtorrent', fp, pathname, description) lt = imp.load_module('libtorrent', fp, pathname, description)
finally: finally:
if fp: fp.close() if fp: fp.close()
except Exception as e1: except Exception as e1:
logger.error(traceback.format_exc(1)) logger.error(traceback.format_exc(1))
log('fp = ' + str(fp)) log('fp = ' + str(fp))
@@ -1332,7 +1332,7 @@ def import_libtorrent(LIBTORRENT_PATH):
ok = platformtools.dialog_ok(config.get_localized_string(30035), config.get_localized_string(30036), config.get_localized_string(60015), str(e2)) ok = platformtools.dialog_ok(config.get_localized_string(30035), config.get_localized_string(30036), config.get_localized_string(60015), str(e2))
except: except:
pass pass
try: try:
if not e1 and e2: e1 = e2 if not e1 and e2: e1 = e2
except: except:
@@ -1345,7 +1345,7 @@ def import_libtorrent(LIBTORRENT_PATH):
except: except:
e1 = '' e1 = ''
e2 = '' e2 = ''
return lt, e, e1, e2 return lt, e, e1, e2
@@ -1354,4 +1354,3 @@ def log(texto):
xbmc.log(texto, xbmc.LOGNOTICE) xbmc.log(texto, xbmc.LOGNOTICE)
except: except:
pass pass
+1 -2
View File
@@ -450,9 +450,8 @@ def init(channel, list_servers, list_quality, reset=False):
if not result: if not result:
heading = config.get_localized_string(60077) heading = config.get_localized_string(60077)
msj = config.get_localized_string(60078) msj = config.get_localized_string(60078)
icon = 1
platformtools.dialog_notification(heading, msj, icon, sound=False) platformtools.dialog_notification(heading, msj, sound=False)
return result return result
+5 -3
View File
@@ -46,7 +46,7 @@ def export_videolibrary(item):
p_dialog.update(100) p_dialog.update(100)
xbmc.sleep(1000) xbmc.sleep(1000)
p_dialog.close() p_dialog.close()
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80004), icon=0, time=5000, sound=False) platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80004), time=5000, sound=False)
def import_videolibrary(item): def import_videolibrary(item):
@@ -73,7 +73,9 @@ def import_videolibrary(item):
filetools.rmdirtree(videolibrarytools.TVSHOWS_PATH) filetools.rmdirtree(videolibrarytools.TVSHOWS_PATH)
p_dialog.update(50) p_dialog.update(50)
if config.is_xbmc() and config.get_setting("videolibrary_kodi"): if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
xbmc_videolibrary.clean(config.get_setting('videolibrarypath')) strm_list = []
strm_list.append(config.get_setting('videolibrarypath'))
xbmc_videolibrary.clean(strm_list)
config.verify_directories_created() config.verify_directories_created()
if filetools.exists(movies_path): if filetools.exists(movies_path):
@@ -87,7 +89,7 @@ def import_videolibrary(item):
p_dialog.update(100) p_dialog.update(100)
xbmc.sleep(1000) xbmc.sleep(1000)
p_dialog.close() p_dialog.close()
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80008), icon=0, time=5000, sound=False) platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80008), time=5000, sound=False)
if platformtools.dialog_yesno(config.get_localized_string(20000), config.get_localized_string(80009)): if platformtools.dialog_yesno(config.get_localized_string(20000), config.get_localized_string(80009)):
import service import service
+1 -1
View File
@@ -9,6 +9,7 @@ from core.item import Item
from platformcode import config, platformtools from platformcode import config, platformtools
from specials import autoplay from specials import autoplay
from channelselector import get_thumb from channelselector import get_thumb
from collections import OrderedDict
info_language = ["de", "en", "es", "fr", "it", "pt"] # from videolibrary.json info_language = ["de", "en", "es", "fr", "it", "pt"] # from videolibrary.json
try: lang = info_language[config.get_setting("info_language", "videolibrary")] try: lang = info_language[config.get_setting("info_language", "videolibrary")]
@@ -588,7 +589,6 @@ def filter_thread(filter, key, item, description):
# for load json from item or url # for load json from item or url
def load_json(item): def load_json(item):
support.log() support.log()
from collections import OrderedDict
url = item.url if type(item) == Item else item url = item.url if type(item) == Item else item
try: try:
+39 -85
View File
@@ -61,8 +61,7 @@ def mainlist(item):
# Comprobamos que la serie no este ya en el itemlist # Comprobamos que la serie no este ya en el itemlist
if not [x for x in itemlist if x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel]: if not [x for x in itemlist if x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel]:
title = TITLE_TVSHOW % ( title = TITLE_TVSHOW % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel)
STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel)
itemlist.append(Item(title=title, channel="downloads", action="mainlist", contentType="tvshow", itemlist.append(Item(title=title, channel="downloads", action="mainlist", contentType="tvshow",
contentSerieName=i.contentSerieName, contentChannel=i.contentChannel, contentSerieName=i.contentSerieName, contentChannel=i.contentChannel,
@@ -78,8 +77,7 @@ def mainlist(item):
STATUS_CODES.completed, STATUS_CODES.stoped]: STATUS_CODES.completed, STATUS_CODES.stoped]:
s.downloadStatus = i.downloadStatus s.downloadStatus = i.downloadStatus
s.title = TITLE_TVSHOW % ( s.title = TITLE_TVSHOW % (STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel)
STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel)
# Peliculas # Peliculas
elif i.contentType == "movie" or i.contentType == "video": elif i.contentType == "movie" or i.contentType == "video":
@@ -89,8 +87,7 @@ def mainlist(item):
# Listado dentro de una serie # Listado dentro de una serie
else: else:
if i.contentType == "episode" and i.contentSerieName == item.contentSerieName and i.contentChannel == item.contentChannel: if i.contentType == "episode" and i.contentSerieName == item.contentSerieName and i.contentChannel == item.contentChannel:
i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.title = TITLE_FILE % (STATUS_COLORS[i.downloadStatus], i.downloadProgress, "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle))
"%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle))
itemlist.append(i) itemlist.append(i)
estados = [i.downloadStatus for i in itemlist] estados = [i.downloadStatus for i in itemlist]
@@ -186,11 +183,13 @@ def clean_all(item):
for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
if fichero.endswith(".json"): if fichero.endswith(".json"):
download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero))) download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or ( if not item.contentType == "tvshow" or ( item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
filetools.remove(filetools.join(DOWNLOAD_LIST_PATH, fichero)) filetools.remove(filetools.join(DOWNLOAD_LIST_PATH, fichero))
if removeFiles: if removeFiles:
filetools.remove(filetools.join(DOWNLOAD_PATH, download_item.downloadFilename)) filetools.remove(filetools.join(DOWNLOAD_PATH, download_item.downloadFilename))
dirName = filetools.join(DOWNLOAD_PATH, filetools.dirname(download_item.downloadFilename))
if len(filetools.listdir(dirName)) == 0:
filetools.rmdir(dirName)
xbmc.sleep(100) xbmc.sleep(100)
platformtools.itemlist_refresh() platformtools.itemlist_refresh()
@@ -208,7 +207,7 @@ def stop_all(item=None):
download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero))) download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero)))
if download_item.downloadStatus == 4: if download_item.downloadStatus == 4:
update_json(filetools.join(DOWNLOAD_LIST_PATH, fichero), {"downloadStatus": STATUS_CODES.stoped}) update_json(filetools.join(DOWNLOAD_LIST_PATH, fichero), {"downloadStatus": STATUS_CODES.stoped})
xbmc.sleep(100) xbmc.sleep(300)
if item: if item:
platformtools.itemlist_refresh() platformtools.itemlist_refresh()
@@ -218,8 +217,7 @@ def clean_ready(item):
for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)): for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
if fichero.endswith(".json"): if fichero.endswith(".json"):
download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero))) download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or ( if not item.contentType == "tvshow" or ( item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
if download_item.downloadStatus == STATUS_CODES.completed: if download_item.downloadStatus == STATUS_CODES.completed:
filetools.remove(filetools.join(DOWNLOAD_LIST_PATH, fichero)) filetools.remove(filetools.join(DOWNLOAD_LIST_PATH, fichero))
@@ -232,8 +230,7 @@ def restart_error(item):
if fichero.endswith(".json"): if fichero.endswith(".json"):
download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero))) download_item = Item().fromjson(filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or ( if not item.contentType == "tvshow" or ( item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
if download_item.downloadStatus == STATUS_CODES.error: if download_item.downloadStatus == STATUS_CODES.error:
if filetools.isfile( if filetools.isfile(
filetools.join(DOWNLOAD_PATH, download_item.downloadFilename)): filetools.join(DOWNLOAD_PATH, download_item.downloadFilename)):
@@ -259,8 +256,7 @@ def download_all_background(item):
download_item = Item(path=filetools.join(DOWNLOAD_LIST_PATH, fichero)).fromjson( download_item = Item(path=filetools.join(DOWNLOAD_LIST_PATH, fichero)).fromjson(
filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero))) filetools.read(filetools.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or ( if not item.contentType == "tvshow" or ( item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
if download_item.downloadStatus in [STATUS_CODES.stoped, STATUS_CODES.canceled]: if download_item.downloadStatus in [STATUS_CODES.stoped, STATUS_CODES.canceled]:
res = start_download(download_item) res = start_download(download_item)
# platformtools.itemlist_refresh() # platformtools.itemlist_refresh()
@@ -361,14 +357,14 @@ def move_to_libray(item):
move_path = filetools.join(config.get_videolibrary_path(), FOLDER) move_path = filetools.join(config.get_videolibrary_path(), FOLDER)
download_path = filetools.join(DOWNLOAD_PATH, item.downloadFilename) download_path = filetools.join(DOWNLOAD_PATH, item.downloadFilename)
library_path = filetools.join(move_path, *filetools.split(item.downloadFilename)) library_path = filetools.join(move_path, *filetools.split(item.downloadFilename))
final_path = download_path final_path = download_path
if item.contentType == "movie" and item.infoLabels["tmdb_id"]: if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
contentTitle = item.contentTitle if item.contentTitle else item.fulltitle contentTitle = item.contentTitle if item.contentTitle else item.fulltitle
library_item = Item(title= filetools.split(item.downloadFilename)[-1], channel="downloads", contentTitle = contentTitle, library_item = Item(title= filetools.split(item.downloadFilename)[-1], channel="downloads", contentTitle = contentTitle,
fulltitle = item.fulltitle,action="findvideos", infoLabels=item.infoLabels, url=library_path) fulltitle = item.fulltitle,action="findvideos", infoLabels=item.infoLabels, url=library_path)
videolibrarytools.save_movie(library_item) videolibrarytools.save_movie(library_item, silent=True)
elif item.contentType == "episode" and item.infoLabels["tmdb_id"]: elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
contentSerieName = item.contentSerieName if item.contentSerieName else item.fulltitle contentSerieName = item.contentSerieName if item.contentSerieName else item.fulltitle
@@ -376,7 +372,7 @@ def move_to_libray(item):
fulltitle = item.fulltitle, action="findvideos", infoLabels=item.infoLabels, url=library_path) fulltitle = item.fulltitle, action="findvideos", infoLabels=item.infoLabels, url=library_path)
tvshow = Item(channel="downloads", contentType="tvshow", contentSerieName = contentSerieName, tvshow = Item(channel="downloads", contentType="tvshow", contentSerieName = contentSerieName,
fulltitle = item.fulltitle, infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]}) fulltitle = item.fulltitle, infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]})
videolibrarytools.save_tvshow(tvshow, [library_item]) videolibrarytools.save_tvshow(tvshow, [library_item], silent=True)
if not filetools.isdir(filetools.dirname(library_path)): if not filetools.isdir(filetools.dirname(library_path)):
filetools.mkdir(filetools.dirname(library_path)) filetools.mkdir(filetools.dirname(library_path))
@@ -410,61 +406,11 @@ def move_to_libray(item):
if config.is_xbmc() and config.get_setting("videolibrary_kodi"): if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
if clean == True: if clean == True:
xbmc_videolibrary.clean(file_strm_path) strm_list = []
strm_list.append(file_strm_path)
xbmc_videolibrary.clean(strm_list)
xbmc_videolibrary.update(FOLDER, path_title) xbmc_videolibrary.update(FOLDER, path_title)
"""if config.get_setting("library_add") == True and config.get_setting("library_move") == True:
if not filetools.isdir(filetools.dirname(library_path)):
filetools.mkdir(filetools.dirname(library_path))
if filetools.isfile(library_path) and filetools.isfile(download_path):
filetools.remove(library_path)
if filetools.isfile(download_path):
if filetools.move(download_path, library_path):
final_path = library_path
if len(filetools.listdir(filetools.dirname(download_path))) == 0:
filetools.rmdir(filetools.dirname(download_path))
logger.info('ITEM = ' + str(item))
name = item.contentTitle if item.contentType == 'movie' else str(item.infoLabels['season']) + 'x' + str(item.infoLabels['episode']).zfill(2)
list_item = filetools.listdir(filetools.join(config.get_videolibrary_path(), FOLDER, path_title))
clean = False
for File in list_item:
filename = File.lower()
name = name.lower()
if filename.startswith(name) and (filename.endswith('.strm') or filename.endswith('.json') or filename.endswith('.nfo')):
clean = True
logger.info('Delete File: ' + str(filetools.join(config.get_videolibrary_path(), FOLDER, path_title, File)))
filetools.remove(filetools.join(config.get_videolibrary_path(), FOLDER, path_title, File))
if config.get_setting("videolibrary_kodi"):
from platformcode import xbmc_videolibrary
xbmc_videolibrary.update(FOLDER)
if clean == True:
import xbmc
while xbmc.getCondVisibility('Library.IsScanningVideo()'):
xbmc.sleep(500)
xbmc_videolibrary.clean()
if config.get_setting("library_add") == True and config.get_setting("library_move") == False:
if filetools.isfile(final_path):
if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
library_item = Item(title=config.get_localized_string(70228) % item.downloadFilename, channel="downloads",
action="findvideos", infoLabels=item.infoLabels, url=final_path)
videolibrarytools.save_movie(library_item)
elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
library_item = Item(title=config.get_localized_string(70228) % item.downloadFilename, channel="downloads",
action="findvideos", infoLabels=item.infoLabels, url=final_path)
tvshow = Item(channel="downloads", contentType="tvshow",
infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]})
videolibrarytools.save_tvshow(tvshow, [library_item])"""
def update_json(path, params): def update_json(path, params):
item = Item().fromjson(filetools.read(path)) item = Item().fromjson(filetools.read(path))
@@ -550,8 +496,7 @@ def get_match_list(data, match_list, order_list=None, only_ascii=False, ignoreca
# Si ascii = True, eliminamos todos los accentos y Ñ # Si ascii = True, eliminamos todos los accentos y Ñ
if only_ascii: if only_ascii:
data = ''.join((c for c in unicodedata.normalize('NFD', data) if unicodedata.category(c) != 'Mn')) data = ''.join((c for c in unicodedata.normalize('NFD', data) if unicodedata.category(c) != 'Mn'))
match_dict = dict((''.join((c for c in unicodedata.normalize('NFD', key) if unicodedata.category(c) != 'Mn')), match_dict = dict((''.join((c for c in unicodedata.normalize('NFD', key) if unicodedata.category(c) != 'Mn')), match_dict[key]) for key in match_dict)
match_dict[key]) for key in match_dict)
# Ordenamos el listado de mayor tamaño a menor y buscamos. # Ordenamos el listado de mayor tamaño a menor y buscamos.
for match in sorted(match_dict, key=lambda x: len(x), reverse=True): for match in sorted(match_dict, key=lambda x: len(x), reverse=True):
@@ -836,7 +781,13 @@ def select_server(item):
if not i.server and hasattr(channel, "play"): if not i.server and hasattr(channel, "play"):
play_items[x] = getattr(channel, "play")(i) play_items[x] = getattr(channel, "play")(i)
seleccion = platformtools.dialog_select(config.get_localized_string(70192), ["Auto"] + [s.title for s in play_items]) if len(play_items) == 1:
# if there is only one server select it
seleccion = 1
else:
# altrimenti mostra la finestra di selezione
seleccion = platformtools.dialog_select(config.get_localized_string(70192), ["Auto"] + [s.title for s in play_items])
if seleccion >= 1: if seleccion >= 1:
update_json(item.path, { update_json(item.path, {
"downloadServer": {"url": play_items[seleccion - 1].url, "server": play_items[seleccion - 1].server}}) "downloadServer": {"url": play_items[seleccion - 1].url, "server": play_items[seleccion - 1].server}})
@@ -959,8 +910,7 @@ def write_json(item):
if not item.contentThumbnail: if not item.contentThumbnail:
item.contentThumbnail = item.thumbnail item.contentThumbnail = item.thumbnail
for name in ["text_bold", "text_color", "text_italic", "context", "totalItems", "viewmode", "title", "contentTitle", for name in ["text_bold", "text_color", "text_italic", "context", "totalItems", "viewmode", "title", "contentTitle", "thumbnail"]:
"thumbnail"]:
if name in item.__dict__: if name in item.__dict__:
item.__dict__.pop(name) item.__dict__.pop(name)
@@ -996,7 +946,10 @@ def save_download_background(item):
if item.channel == 'videolibrary': if item.channel == 'videolibrary':
from specials import videolibrary from specials import videolibrary
parent = Item().fromurl(item.parent) if not item.parent:
parent = item
else:
parent = Item().fromurl(item.parent)
parent.contentChannel = 'videolibrary' parent.contentChannel = 'videolibrary'
if item.downloadItemlist: # episode if item.downloadItemlist: # episode
parent.downloadItemlist = item.downloadItemlist parent.downloadItemlist = item.downloadItemlist
@@ -1047,15 +1000,13 @@ def save_download_video(item):
write_json(item) write_json(item)
if not platformtools.dialog_yesno(config.get_localized_string(30101), config.get_localized_string(70189)): if not platformtools.dialog_yesno(config.get_localized_string(30101), config.get_localized_string(70189)):
platformtools.dialog_ok(config.get_localized_string(30101), item.contentTitle, platformtools.dialog_ok(config.get_localized_string(30101), item.contentTitle, config.get_localized_string(30109))
config.get_localized_string(30109))
else: else:
start_download(item) start_download(item)
def save_download_movie(item): def save_download_movie(item):
logger.info("contentAction: %s | contentChannel: %s | contentTitle: %s" % ( logger.info("contentAction: %s | contentChannel: %s | contentTitle: %s" % ( item.contentAction, item.contentChannel, item.contentTitle))
item.contentAction, item.contentChannel, item.contentTitle))
progreso = platformtools.dialog_progress_bg(config.get_localized_string(30101), config.get_localized_string(70191)) progreso = platformtools.dialog_progress_bg(config.get_localized_string(30101), config.get_localized_string(70191))
@@ -1068,7 +1019,7 @@ def save_download_movie(item):
progreso.update(0, config.get_localized_string(60062)) progreso.update(0, config.get_localized_string(60062))
item.downloadFilename = filetools.validate_path("%s [%s] [%s]" % (item.contentTitle.strip(), item.contentChannel, item.infoLabels['IMDBNumber'])) item.downloadFilename = filetools.validate_path("%s [%s]" % (item.contentTitle.strip(), item.infoLabels['IMDBNumber']))
write_json(item) write_json(item)
@@ -1096,11 +1047,15 @@ def save_download_tvshow(item):
try: try:
item.show = item.fulltitle item.show = item.fulltitle
scraper.find_and_set_infoLabels(item) scraper.find_and_set_infoLabels(item)
if not item.contentSerieName: item.contentSerieName = item.fulltitle if not item.contentSerieName: item.contentSerieName = item.fulltitle
item.downloadFilename = filetools.validate_path("%s [%s]" % (item.contentSerieName, item.infoLabels['IMDBNumber'])) if item.strm_path: item.downloadFilename = filetools.validate_path(item.strm_path.split(os.sep)[-2])
else: item.downloadFilename = filetools.validate_path("%s [%s]" % (item.contentSerieName, item.infoLabels['IMDBNumber']))
if config.get_setting("lowerize_title", "videolibrary"): if config.get_setting("lowerize_title", "videolibrary"):
item.downloadFilename = item.downloadFilename.lower() item.downloadFilename = item.downloadFilename.lower()
progreso.update(0, config.get_localized_string(70186), config.get_localized_string(70180) % item.contentChannel) progreso.update(0, config.get_localized_string(70186), config.get_localized_string(70180) % item.contentChannel)
episodes = get_episodes(item) episodes = get_episodes(item)
@@ -1108,8 +1063,7 @@ def save_download_tvshow(item):
progreso.update(0, config.get_localized_string(70190), " ") progreso.update(0, config.get_localized_string(70190), " ")
for x, i in enumerate(episodes): for x, i in enumerate(episodes):
progreso.update(old_div(x * 100, len(episodes)), progreso.update(old_div(x * 100, len(episodes)), "%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle))
"%dx%0.2d: %s" % (i.contentSeason, i.contentEpisodeNumber, i.contentTitle))
write_json(i) write_json(i)
finally: finally:
progreso.close() progreso.close()
@@ -1,51 +1,76 @@
from core import filetools, downloadtools, support from core import filetools, downloadtools, support
from platformcode import config, platformtools, updater from platformcode import config, platformtools, updater
from time import sleep import xbmc, xbmcaddon, sys, platform
import xbmc, xbmcaddon, os, sys, platform
host = 'https://github.com' host = 'https://github.com'
quasar_url = host + '/scakemyer/plugin.video.quasar/releases' elementum_url = host + '/elgatito/plugin.video.elementum/releases'
filename = filetools.join(config.get_data_path(),'quasar.zip') filename = filetools.join(config.get_data_path(),'elementum.zip')
addon_path = xbmc.translatePath("special://home/addons/") addon_path = xbmc.translatePath('special://home/addons/')
quasar_path = filetools.join(addon_path,'plugin.video.quasar') setting_path = xbmc.translatePath('special://profile/addon_data/')
elementum_path = filetools.join(addon_path,'plugin.video.elementum')
elementum_setting = filetools.join(setting_path,'plugin.video.elementum')
elementum_setting_file = filetools.join(elementum_setting,'settings.xml')
kod_setting_file = filetools.join(addon_path,'plugin.video.kod', 'resources', 'settings', 'elementum', 'settings.xml')
def download(item=None): def download(item=None):
if filetools.exists(quasar_path):
xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.quasar", "enabled": false }}')
sleep(1)
filetools.rmdirtree(quasar_path)
if filetools.exists(filename): if filetools.exists(elementum_path):
filetools.remove(filename) if platformtools.dialog_yesno(config.get_localized_string(70784), config.get_localized_string(70783)):
return download() setting()
platformtools.dialog_ok('Elementum', config.get_localized_string(70783))
else: else:
platform = get_platform() if platformtools.dialog_yesno(config.get_localized_string(70784), config.get_localized_string(70782)):
support.log('OS:', platform) pform = get_platform()
support.log('Extract IN:', quasar_path) url = support.match(elementum_url, patronBlock=r'<div class="release-entry">(.*?)<!-- /.release-body -->', patron=r'<a href="([a-zA-Z0-9/\.-]+%s.zip)' % pform).match
url = support.match(quasar_url, patronBlock=r'<div class="release-entry">(.*?)<!-- /.release-body -->', patron=r'<a href="([a-zA-Z0-9/\.-]+%s.zip)' % platform).match support.log('OS:', pform)
support.log('URL:', url) support.log('Extract IN:', elementum_path)
if url: support.log('URL:', url)
downloadtools.downloadfile(host + url, filename) if url:
extract() downloadtools.downloadfile(host + url, filename)
extract()
xbmc.sleep(1000)
setting()
def extract(): def extract():
import zipfile import zipfile
support.log('Estraggo Quasar in:', quasar_path) support.log('Estraggo Elementum in:', elementum_path)
with zipfile.ZipFile(filename, 'r') as zip_ref: with zipfile.ZipFile(filename, 'r') as zip_ref:
zip_ref.extractall(xbmc.translatePath("special://home/addons/")) zip_ref.extractall(xbmc.translatePath(addon_path))
def setting():
# support.dbg()
xbmc.executebuiltin('UpdateLocalAddons') xbmc.executebuiltin('UpdateLocalAddons')
if platformtools.dialog_ok('Quasar', config.get_localized_string(70783)): xbmc.sleep(1000)
if filetools.exists(filename): if filetools.isfile(elementum_setting_file):
filetools.remove(filename) xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.elementum", "enabled": true }}')
xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.quasar", "enabled": true }}') Continue = True
updater.refreshLang() while Continue:
xbmcaddon.Addon(id="plugin.video.quasar").setSetting('download_path', config.get_setting('downloadpath')) try:
xbmc.executebuiltin('UpdateLocalAddons') __settings__ = xbmcaddon.Addon(id="plugin.video.elementum")
sleep(2) __settings__.setSetting('skip_burst_search', 'true')
__settings__.setSetting('greeting_enabled', 'false')
__settings__.setSetting('do_not_disturb', 'true')
Continue = False
except:
support.log('RIPROVO')
xbmc.sleep(100)
else:
if not filetools.exists(elementum_path):
filetools.mkdir(elementum_path)
filetools.copy(kod_setting_file, elementum_setting_file)
xbmc.sleep(1000)
xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.elementum", "enabled": true }}')
updater.refreshLang()
if filetools.exists(filename):
filetools.remove(filename)
def get_platform(): def get_platform():
@@ -64,8 +89,7 @@ def get_platform():
if "arm" in platform.machine() or "aarch" in platform.machine(): if "arm" in platform.machine() or "aarch" in platform.machine():
ret["arch"] = "arm" ret["arch"] = "arm"
if "64" in platform.machine() and ret["auto_arch"] == "64-bit": if "64" in platform.machine() and ret["auto_arch"] == "64-bit":
ret["arch"] = "arm" ret["arch"] = "arm64"
#ret["arch"] = "x64" #The binary is corrupted in install package
elif xbmc.getCondVisibility("system.platform.linux"): elif xbmc.getCondVisibility("system.platform.linux"):
ret["os"] = "linux" ret["os"] = "linux"
if "aarch" in platform.machine() or "arm64" in platform.machine(): if "aarch" in platform.machine() or "arm64" in platform.machine():
+2 -1
View File
@@ -156,6 +156,7 @@ def new_search(item):
thumbnail=thumbnail, thumbnail=thumbnail,
fanart=fanart, fanart=fanart,
mode=item.mode, mode=item.mode,
contentType=item.mode,
infoLabels=result) infoLabels=result)
if item.mode == 'movie': if item.mode == 'movie':
@@ -629,7 +630,7 @@ def discover_list(item):
new_item = Item(channel='search', title=typo(title, 'bold'), infoLabels=elem, new_item = Item(channel='search', title=typo(title, 'bold'), infoLabels=elem,
action='channel_search', text=title, action='channel_search', text=title,
thumbnail=thumbnail, fanart=fanart, thumbnail=thumbnail, fanart=fanart,
context='', mode=mode, context='', mode=mode, contentType=mode,
release_date=year) release_date=year)
if tvshow: if tvshow:
+122 -86
View File
@@ -363,7 +363,7 @@ def get_seasons(item):
# Creamos un item por cada temporada # Creamos un item por cada temporada
for season, title in list(dict_temp.items()): for season, title in list(dict_temp.items()):
new_item = item.clone(action="get_episodes", title=title, contentSeason=season, new_item = item.clone(action="get_episodes", title=title, contentSeason=season,
filtrar_season=True) filtrar_season=True, channel='videolibrary')
# Menu contextual: Marcar la temporada como vista o no # Menu contextual: Marcar la temporada como vista o no
visto = item_nfo.library_playcounts.get("season %s" % season, 0) visto = item_nfo.library_playcounts.get("season %s" % season, 0)
@@ -407,7 +407,7 @@ def get_episodes(item):
# Crear un item en la lista para cada strm encontrado # Crear un item en la lista para cada strm encontrado
for i in ficheros: for i in ficheros:
if i.split('.')[-1] not in ['json','nfo']: #i.endswith('.strm'): if i.split('.')[-1] not in ['json','nfo']: #i.endswith('.strm'):
season_episode = scrapertools.get_season_and_episode(i) season_episode = scrapertools.get_season_and_episode(i)
if not season_episode: if not season_episode:
# El fichero no incluye el numero de temporada y episodio # El fichero no incluye el numero de temporada y episodio
@@ -419,38 +419,39 @@ def get_episodes(item):
# Obtener los datos del season_episode.nfo # Obtener los datos del season_episode.nfo
nfo_path = filetools.join(raiz, '%sx%s.nfo' % (season, episode))#.replace('.strm', '.nfo') nfo_path = filetools.join(raiz, '%sx%s.nfo' % (season, episode))#.replace('.strm', '.nfo')
head_nfo, epi = videolibrarytools.read_nfo(nfo_path) if filetools.isfile(nfo_path):
head_nfo, epi = videolibrarytools.read_nfo(nfo_path)
# Fijar el titulo del capitulo si es posible # Fijar el titulo del capitulo si es posible
if epi.contentTitle: if epi.contentTitle:
title_episodie = epi.contentTitle.strip() title_episodie = epi.contentTitle.strip()
else: else:
title_episodie = config.get_localized_string(60031) % \ title_episodie = config.get_localized_string(60031) % \
(epi.contentSeason, str(epi.contentEpisodeNumber).zfill(2)) (epi.contentSeason, str(epi.contentEpisodeNumber).zfill(2))
epi.contentTitle = "%sx%s" % (epi.contentSeason, str(epi.contentEpisodeNumber).zfill(2)) epi.contentTitle = "%sx%s" % (epi.contentSeason, str(epi.contentEpisodeNumber).zfill(2))
epi.title = "%sx%s - %s" % (epi.contentSeason, str(epi.contentEpisodeNumber).zfill(2), title_episodie) epi.title = "%sx%s - %s" % (epi.contentSeason, str(epi.contentEpisodeNumber).zfill(2), title_episodie)
if item_nfo.library_filter_show: if item_nfo.library_filter_show:
epi.library_filter_show = item_nfo.library_filter_show epi.library_filter_show = item_nfo.library_filter_show
# Menu contextual: Marcar episodio como visto o no # Menu contextual: Marcar episodio como visto o no
visto = item_nfo.library_playcounts.get(season_episode, 0) visto = item_nfo.library_playcounts.get(season_episode, 0)
epi.infoLabels["playcount"] = visto epi.infoLabels["playcount"] = visto
if visto > 0: if visto > 0:
texto = config.get_localized_string(60032) texto = config.get_localized_string(60032)
value = 0 value = 0
else: else:
texto = config.get_localized_string(60033) texto = config.get_localized_string(60033)
value = 1 value = 1
epi.context = [{"title": texto, epi.context = [{"title": texto,
"action": "mark_content_as_watched", "action": "mark_content_as_watched",
"channel": "videolibrary", "channel": "videolibrary",
"playcount": value, "playcount": value,
"nfo": item.nfo}] "nfo": item.nfo}]
# logger.debug("epi:\n" + epi.tostring('\n')) # logger.debug("epi:\n" + epi.tostring('\n'))
itemlist.append(epi) itemlist.append(epi)
itemlist = sorted(itemlist, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber))) itemlist = sorted(itemlist, key=lambda it: (int(it.contentSeason), int(it.contentEpisodeNumber)))
add_download_items(item, itemlist) add_download_items(item, itemlist)
@@ -754,7 +755,7 @@ def move_videolibrary(current_path, new_path, current_movies_folder, new_movies_
xbmc.sleep(1000) xbmc.sleep(1000)
progress.close() progress.close()
if notify: if notify:
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80014), icon=0, time=5000, sound=False) platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80014), time=5000, sound=False)
def delete_videolibrary(item): def delete_videolibrary(item):
@@ -772,14 +773,16 @@ def delete_videolibrary(item):
p_dialog.update(80) p_dialog.update(80)
if config.is_xbmc() and config.get_setting("videolibrary_kodi"): if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.clean(config.get_setting('videolibrarypath')) strm_list = []
strm_list.append(config.get_setting('videolibrarypath'))
xbmc_videolibrary.clean(strm_list)
p_dialog.update(90) p_dialog.update(90)
config.verify_directories_created() config.verify_directories_created()
p_dialog.update(100) p_dialog.update(100)
xbmc.sleep(1000) xbmc.sleep(1000)
p_dialog.close() p_dialog.close()
platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80039), icon=0, time=5000, sound=False) platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80039), time=5000, sound=False)
# metodos de menu contextual # metodos de menu contextual
@@ -1024,12 +1027,22 @@ def delete(item):
raiz, carpeta_serie, ficheros = next(filetools.walk(_item.path)) raiz, carpeta_serie, ficheros = next(filetools.walk(_item.path))
if ficheros == []: if ficheros == []:
filetools.rmdir(_item.path) filetools.rmdir(_item.path)
else:
if _item.contentType == 'movie':
heading = config.get_localized_string(70084)
else:
heading = config.get_localized_string(70085)
if platformtools.dialog_yesno(heading, config.get_localized_string(70081)):
filetools.rmdirtree(_item.path)
if config.is_xbmc() and config.get_setting("videolibrary_kodi"): if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
from platformcode import xbmc_videolibrary from platformcode import xbmc_videolibrary
xbmc_videolibrary.clean(_item.extra) strm_list = []
strm_list.append(_item.extra)
xbmc_videolibrary.clean(strm_list)
logger.info("All links removed") logger.info("All links removed")
xbmc.sleep(1000)
platformtools.itemlist_refresh() platformtools.itemlist_refresh()
# logger.info(item.contentTitle) # logger.info(item.contentTitle)
@@ -1042,46 +1055,68 @@ def delete(item):
if item.multicanal: if item.multicanal:
# Obtener listado de canales # Obtener listado de canales
if item.dead == '': if item.dead == '':
opciones = [config.get_localized_string(70086) % k.capitalize() for k in list(item.library_urls.keys()) if opciones = []
k != "downloads"] channels = []
for k in list(item.library_urls.keys()):
if k != "downloads":
opciones.append(config.get_localized_string(70086) % k.capitalize())
channels.append(k)
opciones.insert(0, heading) opciones.insert(0, heading)
index = platformtools.dialog_select(config.get_localized_string(30163), opciones) index = platformtools.dialog_select(config.get_localized_string(30163), opciones)
if index == 0: if index == 0:
# Seleccionado Eliminar pelicula/serie # Seleccionado Eliminar pelicula/serie
canal = None
delete_all(item) delete_all(item)
elif index > 0: elif index > 0:
# Seleccionado Eliminar canal X # Seleccionado Eliminar canal X
canal = opciones[index].replace(config.get_localized_string(70079), "").lower() canal = opciones[index].replace(config.get_localized_string(70079), "").lower()
channels.remove(canal)
else: else:
return return
else: else:
canal = item.dead canal = item.dead
num_enlaces = 0 if canal:
for fd in filetools.listdir(item.path): num_enlaces = 0
if fd.endswith(canal + '].json') or scrapertools.find_single_match(fd, '%s]_\d+.torrent' % canal): strm_list = []
if filetools.remove(filetools.join(item.path, fd)): for fd in filetools.listdir(item.path):
num_enlaces += 1 if fd.endswith(canal + '].json') or scrapertools.find_single_match(fd, '%s]_\d+.torrent' % canal):
if filetools.remove(filetools.join(item.path, fd)):
num_enlaces += 1
# Remove strm and nfo if no other channel
episode = fd.replace(' [' + canal + '].json', '')
found_ch = False
for ch in channels:
if filetools.exists(filetools.join(item.path, episode + ' [' + ch + '].json')):
found_ch = True
break
if found_ch == False:
filetools.remove(filetools.join(item.path, episode + '.nfo'))
filetools.remove(filetools.join(item.path, episode + '.strm'))
strm_list.append(filetools.join(item.extra, episode + '.strm'))
if num_enlaces > 0: if config.is_xbmc() and config.get_setting("videolibrary_kodi") and strm_list:
# Actualizar .nfo from platformcode import xbmc_videolibrary
head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo) xbmc_videolibrary.clean(strm_list)
del item_nfo.library_urls[canal]
if item_nfo.emergency_urls and item_nfo.emergency_urls.get(canal, False):
del item_nfo.emergency_urls[canal]
filetools.write(item.nfo, head_nfo + item_nfo.tojson())
msg_txt = config.get_localized_string(70087) % (num_enlaces, canal) if num_enlaces > 0:
logger.info(msg_txt) # Actualizar .nfo
platformtools.dialog_notification(heading, msg_txt) head_nfo, item_nfo = videolibrarytools.read_nfo(item.nfo)
platformtools.itemlist_refresh() del item_nfo.library_urls[canal]
if item_nfo.emergency_urls and item_nfo.emergency_urls.get(canal, False):
del item_nfo.emergency_urls[canal]
filetools.write(item.nfo, head_nfo + item_nfo.tojson())
msg_txt = config.get_localized_string(70087) % (num_enlaces, canal)
logger.info(msg_txt)
platformtools.dialog_notification(heading, msg_txt)
platformtools.itemlist_refresh()
else: else:
if platformtools.dialog_yesno(heading, if platformtools.dialog_yesno(heading, config.get_localized_string(70088) % item.infoLabels['title']):
config.get_localized_string(70088) % item.infoLabels['title']):
delete_all(item) delete_all(item)
@@ -1133,37 +1168,38 @@ def check_tvshow_playcount(item, season):
def add_download_items(item, itemlist): def add_download_items(item, itemlist):
localOnly = True if config.get_setting('downloadenabled'):
for i in itemlist: localOnly = True
if i.contentChannel != 'local': for i in itemlist:
localOnly = False if i.contentChannel != 'local':
break localOnly = False
if not item.fromLibrary and not localOnly: break
downloadItem = Item(channel='downloads', if not item.fromLibrary and not localOnly:
from_channel=item.channel, downloadItem = Item(channel='downloads',
title=typo(config.get_localized_string(60355), "color kod bold"), from_channel=item.channel,
fulltitle=item.fulltitle, title=typo(config.get_localized_string(60355), "color kod bold"),
show=item.fulltitle, fulltitle=item.fulltitle,
contentType=item.contentType, show=item.fulltitle,
contentSerieName=item.contentSerieName, contentType=item.contentType,
url=item.url, contentSerieName=item.contentSerieName,
action='save_download', url=item.url,
from_action="findvideos", action='save_download',
contentTitle=item.contentTitle, from_action="findvideos",
path=item.path, contentTitle=item.contentTitle,
thumbnail=thumb(thumb='downloads.png'), path=item.path,
parent=item.tourl()) thumbnail=thumb(thumb='downloads.png'),
if item.action == 'findvideos': parent=item.tourl())
if item.contentType == 'episode': if item.action == 'findvideos':
downloadItem.title = typo(config.get_localized_string(60356), "color kod bold") if item.contentType == 'episode':
else: # film downloadItem.title = typo(config.get_localized_string(60356), "color kod bold")
downloadItem.title = typo(config.get_localized_string(60354), "color kod bold") else: # film
downloadItem.downloadItemlist = [i.tourl() for i in itemlist] downloadItem.title = typo(config.get_localized_string(60354), "color kod bold")
itemlist.append(downloadItem) downloadItem.downloadItemlist = [i.tourl() for i in itemlist]
else:
if item.contentSeason: # season
downloadItem.title = typo(config.get_localized_string(60357), "color kod bold")
itemlist.append(downloadItem) itemlist.append(downloadItem)
else: # tvshow + not seen else:
itemlist.append(downloadItem) if item.contentSeason: # season
itemlist.append(downloadItem.clone(title=typo(config.get_localized_string(60003), "color kod bold"), unseen=True)) downloadItem.title = typo(config.get_localized_string(60357), "color kod bold")
itemlist.append(downloadItem)
else: # tvshow + not seen
itemlist.append(downloadItem)
itemlist.append(downloadItem.clone(title=typo(config.get_localized_string(60003), "color kod bold"), unseen=True))