Files
addon/platformcode/updater.py
greko 3eaf36d3e4 New scrape (#63)
* fix canale

* fix newest

* fix numero puntata

* experimental scrape as decorator

* prova su support.scrape e modifiche

* uso del decoratore support.scrape

Scritto guardaserieclick con supporto del decoratore
Modificato:
 - eurostreaming.py per piccoli fix
 - Support.py per fix oltre che a portarlo allo stato del master
 - zcrypt - bit.ly non funziona. DA FIXARE!!!

* migliorato codice

Tentativo vano di inserire autorenumber per gli anime

* New scrape (#55)

* fix canale

* fix newest

* fix numero puntata

* Fix Animeworld

* Nuovo Autorenumber

* initial background downloader support

* ops

* Update channels.json

* Update channels.json

* fix openload

* move json update to cohesist with updater

* disable json url updates

* prova su support.scrape e modifiche

* uso del decoratore support.scrape

Scritto guardaserieclick con supporto del decoratore
Modificato:
 - eurostreaming.py per piccoli fix
 - Support.py per fix oltre che a portarlo allo stato del master
 - zcrypt - bit.ly non funziona. DA FIXARE!!!

* migliorato codice

Tentativo vano di inserire autorenumber per gli anime

* fix autoplay in altadefinizioneLink

* camel case

* decoratore per i menu

* altadefinizione01 C

* Decoratore Menu e Altadefinizione01_C e _L

modifiche a support.menu per fix e scrittura dei canali:

	- Altadefinizione01_C
	- Altadefinizione01_L
per il supporto dei decoratori:
	- menu
	- scrape

* eliminato listGroup in favore dei nomi dei gruppi nelle regex

* cambio struttura in support.menu()

* cambio struttura in support.menu()

* supporto completo per i decoratori

Riscritti i canali per il supporto ai decoratori e alle sole regex:
	- Altadefinizione01_C
	- Altadefinizione01_L

* AltadefinizioneClick - altadefinizione01 e piccoli fix
	modified:   channels/altadefinizione01.py
	modified:   channels/altadefinizione01_club.py
	modified:   channels/altadefinizione01_link.py
	modified:   channels/altadefinizioneclick.py

* NewScrape  (#62)

* fix typo

* fix typo 2

* Add files via upload

* Add files via upload

* fix autoplay in community channels

* fix toonitalia

* Fix Toonitalia

* workaround serietvsubita

* Nuova Rinumerazione Automatica

* Fix per Rinumerazione Automatica

* workaround updater

* kod stable 0.3.1

* aggiunti nuovi file

* channel e custom json

* aggiunto bit.ly

* Fix on air

* ops

* Personalizzazione sezione "Oggi in TV"

* Aggiunto orario sezione Oggi in TV

* aggiunto bit.ly (#56)

* aggiunto bit.ly

* Aggiunta personalizzazione homepage

* Revert "initial background downloader support"

This reverts commit f676ab0f

* KoD 0.4

* KoD 0.4 (#57)

* fix next page

* testing new filmontv

* Wstream quick fix, no resolution displayed :(

* new filmontv

* now regex is ok

* fix .po files

* +netlovers

* working on filmontv

* fix debriders

* new updater

* updater

* fix crash

* fix updater and re-add dev mode

* new url eurostreaming

* Delete netlovers.py

* Delete netlovers.json

* -net from menù

* fix eurostreaming: numero stagione e newest (#50)

* fix canale

* fix newest

* fix numero puntata

* cleanup

* cleanup 2

* fix updater crash on windows

* Fix Animeworld

* Nuovo Autorenumber

* initial background downloader support

* ops

* Update channels.json

* Update channels.json

* fix openload

* move json update to cohesist with updater

* disable json url updates

* fix typo

* fix typo 2

* Add files via upload

* Add files via upload

* fix autoplay in community channels

* fix toonitalia

* Fix Toonitalia

* workaround serietvsubita

* Nuova Rinumerazione Automatica

* Fix per Rinumerazione Automatica

* workaround updater

* Fix on air

* ops

* Personalizzazione sezione "Oggi in TV"

* Aggiunto orario sezione Oggi in TV

* aggiunto bit.ly (#56)

* aggiunto bit.ly

* Aggiunta personalizzazione homepage

* Revert "initial background downloader support"

This reverts commit f676ab0f

* KoD 0.4

* stable

* Rimossa dipendenza inutile

* fix per i link bit.ly

sperando non ricambiano...

* Update updater.py

* update

* Fix Numerazione Automatica

* possible fix badZipFile on android

* possible fix crash if no internet connection

* try except unzipper -> workaround

* KoD 0.4.1

* Fix Numerazione Automatica

* Fix ricerca CB01

* pagination fix

* fix per bit.ly e fix di alcuni canali

* Cambio dominio per FilmPerTutti

* Fix per Wstream

* miglioramenti vari updater + fix definitivo android

* Fix Ricerca per Altadefinizione01

* Revert "Merge branch 'stable' of https://github.com/kodiondemand/addon into stable"

This reverts commit cf50d10a00, reversing
changes made to 4a695c096c.

* Revert "Revert "Merge branch 'stable' of https://github.com/kodiondemand/addon into stable""

This reverts commit cd19484c70.

* Rimosso canale non più funzionante

* Update addon.xml

* da master a newScrape (#38)

* Fix Numerazione Automatica

* possible fix badZipFile on android

* possible fix crash if no internet connection

* try except unzipper -> workaround

* KoD 0.4.1

* Fix Numerazione Automatica

* Fix CB01

* pagination fix

* Fix altadefinizione01_club e alcune mod a support

Il canale è stato riscritto per support, così è pronto per il decoratore.
Aggiunti dei fix a support altrimenti mi dava la lingua sub-ita a tutti i film successivi
di un film sub-ita

* fix di alcuni canali

	modified:   animesubita.py
	modified:   cinetecadibologna.py
	modified:   filmpertutti.json
	modified:   guardarefilm.py
	modified:   istitutoluce.py
	modified:   italiaserie.py

* fix per bit.ly (#58)

fix per bit.ly e fix di alcuni canali

* Cambio dominio per FilmPerTutti

* miglioramenti vari updater + fix definitivo android

* Fix per Wstream

* fix updater

* Fix Ricerca per Altadefinizione01

* Rimosso canale non più funzionante

* fix altadefinizione01 C

* fix altadefinizione01_C

* altadefinizione01 C fix regex
2019-07-17 21:36:14 +02:00

278 lines
10 KiB
Python

# -*- coding: utf-8 -*-
import hashlib
import io
import os
import shutil
import zipfile
from core import httptools, filetools, downloadtools
from core.ziptools import ziptools
from platformcode import logger, platformtools
import json
import xbmc
import re
import xbmcaddon
addon = xbmcaddon.Addon('plugin.video.kod')
_hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@.*")
branch = 'stable'
user = 'kodiondemand'
repo = 'addon'
addonDir = xbmc.translatePath("special://home/addons/") + "plugin.video.kod/"
maxPage = 5 # le api restituiscono 30 commit per volta, quindi se si è rimasti troppo indietro c'è bisogno di andare avanti con le pagine
trackingFile = "last_commit.txt"
def loadCommits(page=1):
apiLink = 'https://api.github.com/repos/' + user + '/' + repo + '/commits?sha=' + branch + "&page=" + str(page)
logger.info(apiLink)
# riprova ogni secondo finchè non riesce (ad esempio per mancanza di connessione)
while True:
try:
commitsLink = httptools.downloadpage(apiLink).data
ret = json.loads(commitsLink)
break
except:
xbmc.sleep(1000)
return ret
def check_addon_init():
if not addon.getSetting('addon_update_enabled'):
return False
logger.info('Cerco aggiornamenti..')
commits = loadCommits()
try:
localCommitFile = open(addonDir+trackingFile, 'r+')
except:
calcCurrHash()
localCommitFile = open(addonDir + trackingFile, 'r+')
localCommitSha = localCommitFile.read()
localCommitSha = localCommitSha.replace('\n', '') # da testare
logger.info('Commit locale: ' + localCommitSha)
updated = False
pos = None
for n, c in enumerate(commits):
if c['sha'] == localCommitSha:
pos = n
break
else:
# evitiamo che dia errore perchè il file è già in uso
localCommitFile.close()
calcCurrHash()
return True
if pos > 0:
changelog = ''
nCommitApplied = 0
for c in reversed(commits[:pos]):
commit = httptools.downloadpage(c['url']).data
commitJson = json.loads(commit)
logger.info('aggiornando a' + commitJson['sha'])
alreadyApplied = True
for file in commitJson['files']:
if file["filename"] == trackingFile: # il file di tracking non si modifica
continue
else:
logger.info(file["filename"])
if file['status'] == 'modified' or file['status'] == 'added':
if 'patch' in file:
text = ""
try:
localFile = open(addonDir + file["filename"], 'r+')
for line in localFile:
text += line
except IOError: # nuovo file
localFile = open(addonDir + file["filename"], 'w')
patched = apply_patch(text, (file['patch']+'\n').encode('utf-8'))
if patched != text: # non eseguo se già applicata (es. scaricato zip da github)
if getSha(patched) == file['sha']:
localFile.seek(0)
localFile.truncate()
localFile.writelines(patched)
localFile.close()
alreadyApplied = False
else: # nel caso ci siano stati problemi
logger.info('lo sha non corrisponde, scarico il file')
downloadtools.downloadfile(file['raw_url'], addonDir + file['filename'],
silent=True, continuar=True)
else: # è un file NON testuale, lo devo scaricare
# se non è già applicato
if not (filetools.isfile(addonDir + file['filename']) and getSha(
filetools.read(addonDir + file['filename']) == file['sha'])):
downloadtools.downloadfile(file['raw_url'], addonDir + file['filename'], silent=True, continuar=True)
alreadyApplied = False
elif file['status'] == 'removed':
try:
filetools.remove(addonDir+file["filename"])
alreadyApplied = False
except:
pass
elif file['status'] == 'renamed':
# se non è già applicato
if not (filetools.isfile(addonDir + file['filename']) and getSha(
filetools.read(addonDir + file['filename']) == file['sha'])):
dirs = file['filename'].split('/')
for d in dirs[:-1]:
if not filetools.isdir(addonDir + d):
filetools.mkdir(addonDir + d)
filetools.move(addonDir + file['previous_filename'], addonDir + file['filename'])
alreadyApplied = False
if not alreadyApplied: # non mando notifica se già applicata (es. scaricato zip da github)
changelog += commitJson['commit']['message'] + " | "
nCommitApplied += 1
if addon.getSetting("addon_update_message"):
time = nCommitApplied * 2000 if nCommitApplied < 10 else 20000
platformtools.dialog_notification('Kodi on Demand', changelog, time)
localCommitFile.seek(0)
localCommitFile.truncate()
localCommitFile.writelines(c['sha'])
localCommitFile.close()
else:
logger.info('Nessun nuovo aggiornamento')
return updated
def calcCurrHash():
from lib import githash
treeHash = githash.tree_hash(addonDir).hexdigest()
logger.info('tree hash: ' + treeHash)
commits = loadCommits()
lastCommitSha = commits[0]['sha']
page = 1
while commits and page <= maxPage:
found = False
for n, c in enumerate(commits):
if c['commit']['tree']['sha'] == treeHash:
localCommitFile = open(addonDir + trackingFile, 'w')
localCommitFile.write(c['sha'])
localCommitFile.close()
found = True
break
else:
page += 1
commits = loadCommits(page)
if found:
break
else:
logger.info('Non sono riuscito a trovare il commit attuale, scarico lo zip')
hash = updateFromZip()
# se ha scaricato lo zip si trova di sicuro all'ultimo commit
localCommitFile = open(addonDir + trackingFile, 'w')
localCommitFile.write(hash if hash else lastCommitSha)
localCommitFile.close()
# https://gist.github.com/noporpoise/16e731849eb1231e86d78f9dfeca3abc Grazie!
def apply_patch(s,patch,revert=False):
"""
Apply unified diff patch to string s to recover newer string.
If revert is True, treat s as the newer string, recover older string.
"""
s = s.splitlines(True)
p = patch.splitlines(True)
t = ''
i = sl = 0
(midx,sign) = (1,'+') if not revert else (3,'-')
while i < len(p) and p[i].startswith(("---","+++")): i += 1 # skip header lines
while i < len(p):
m = _hdr_pat.match(p[i])
if not m: raise Exception("Cannot process diff")
i += 1
l = int(m.group(midx))-1 + (m.group(midx+1) == '0')
t += ''.join(s[sl:l])
sl = l
while i < len(p) and p[i][0] != '@':
if i+1 < len(p) and p[i+1][0] == '\\': line = p[i][:-1]; i += 2
else: line = p[i]; i += 1
if len(line) > 0:
if line[0] == sign or line[0] == ' ': t += line[1:]
sl += (line[0] != sign)
t += ''.join(s[sl:])
return t
def getSha(fileText):
return hashlib.sha1("blob " + str(len(fileText)) + "\0" + fileText).hexdigest()
def updateFromZip():
dp = platformtools.dialog_progress_bg('Kodi on Demand', 'Aggiornamento in corso...')
dp.update(0)
remotefilename = 'https://github.com/' + user + "/" + repo + "/archive/" + branch + ".zip"
localfilename = xbmc.translatePath("special://home/addons/") + "plugin.video.kod.update.zip"
logger.info("remotefilename=%s" % remotefilename)
logger.info("localfilename=%s" % localfilename)
import urllib
urllib.urlretrieve(remotefilename, localfilename, lambda nb, bs, fs, url=remotefilename: _pbhook(nb, bs, fs, url, dp))
# Lo descomprime
logger.info("decompressione...")
destpathname = xbmc.translatePath("special://home/addons/")
logger.info("destpathname=%s" % destpathname)
try:
hash = fixZipGetHash(localfilename)
unzipper = ziptools()
unzipper.extract(localfilename, destpathname)
except Exception as e:
logger.info('Non sono riuscito ad estrarre il file zip')
logger.info(e)
return False
dp.update(95)
# puliamo tutto
shutil.rmtree(addonDir)
filetools.rename(destpathname + "addon-" + branch, addonDir)
logger.info("Cancellando il file zip...")
os.remove(localfilename)
dp.update(100)
return hash
# https://stackoverflow.com/questions/3083235/unzipping-file-results-in-badzipfile-file-is-not-a-zip-file
def fixZipGetHash(zipFile):
f = io.FileIO(zipFile, 'r+b')
data = f.read()
pos = data.find(b'\x50\x4b\x05\x06') # End of central directory signature
hash = ''
if pos > 0:
f.seek(pos + 20) # +20: see secion V.I in 'ZIP format' link above.
hash = f.read()[2:]
f.seek(pos + 20)
f.truncate()
f.write(
b'\x00\x00') # Zip file comment length: 0 byte length; tell zip applications to stop reading.
f.seek(0)
f.close()
return str(hash)
def _pbhook(numblocks, blocksize, filesize, url, dp):
try:
percent = min((numblocks*blocksize*90)/filesize, 100)
dp.update(percent)
except:
percent = 90
dp.update(percent)