Skip to content

Commit

Permalink
run updates before Anki starts other addons
Browse files Browse the repository at this point in the history
  • Loading branch information
dayjaby committed Sep 10, 2016
1 parent e50cb8a commit 09615b9
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 22 deletions.
7 changes: 7 additions & 0 deletions AnkiHub/updates.ui
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="close">
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="always">
<property name="text">
Expand Down
108 changes: 86 additions & 22 deletions ankihub.py → ___ankihub.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,65 @@
import json
import os
import sys
import zipfile
import traceback
import io
from AnkiHub.updates import Ui_DialogUpdates
from AnkiHub.markdown2 import markdown
import aqt
from anki.hooks import addHook
from anki.utils import isMac, isWin

# taken from Anki's aqt/profiles.py
def defaultBase():
if isWin:
loc = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.DocumentsLocation)
return os.path.join(loc, "Anki")
elif isMac:
return os.path.expanduser("~/Documents/Anki")
else:
p = os.path.expanduser("~/Anki")
if os.path.exists(p):
return p
else:
loc = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.DocumentsLocation)
if loc[:-1] == QtGui.QDesktopServices.storageLocation(
QtGui.QDesktopServices.HomeLocation):
return os.path.expanduser("~/Documents/Anki")
else:
return os.path.join(loc, "Anki")

headers = {"User-Agent": "AnkiHub"}
dataPath = os.path.expanduser('~/.ankihub.json')
dataPath = os.path.join(defaultBase(),'.ankihub.json')


class DialogUpdates(QtGui.QDialog, Ui_DialogUpdates):
def __init__(self, parent, data, oldData, callback, automaticAnswer=None):
def __init__(self, parent, data, oldData, callback, automaticAnswer=None,install=False):
QtGui.QDialog.__init__(self,parent)
self.setupUi(self)
totalSize = sum(map(lambda x:x['size'],data['assets']))

def answer(doUpdate,answ,append):
callback(doUpdate,answ,append)
self.close()
def answer(doUpdate,answ):
callback(doUpdate,answ,self.appendHtml,self.close,install)

self.html = u''
self.appendHtml(markdown(data['body']))

if not automaticAnswer:
self.connect(self.update,QtCore.SIGNAL('clicked()'),
lambda:answer(True,'ask',self.appendHtml))
lambda:answer(True,'ask'))
self.connect(self.dont,QtCore.SIGNAL('clicked()'),
lambda:answer(False,'ask',self.appendHtml))
lambda:answer(False,'ask'))
self.connect(self.always,QtCore.SIGNAL('clicked()'),
lambda:answer(True,'always',self.appendHtml))
lambda:answer(True,'always'))
self.connect(self.never,QtCore.SIGNAL('clicked()'),
lambda:answer(False,'never',self.appendHtml))
lambda:answer(False,'never'))
else:
self.update.setEnabled(False)
self.dont.setEnabled(False)
self.always.setEnabled(False)
self.never.setEnabled(False)
answer(True,automaticAnswer,self.appendHtml)
answer(True,automaticAnswer)

fromVersion = ''
if 'tag_name' in oldData:
Expand All @@ -57,22 +79,41 @@ def appendHtml(self,html='',temp=''):
self.textBrowser.setHtml(u'<html><body>{0}{1}</body></html>'.format(self.html,temp))



def installZipFile(data, fname):
base = os.path.join(defaultBase(),'addons')
if fname.endswith(".py"):
path = os.path.join(base, fname)
open(path, "wb").write(data)
return True
# .zip file
try:
z = zipfile.ZipFile(io.BytesIO(data))
except zipfile.BadZipfile:
return False
for n in z.namelist():
if n.endswith("/"):
# folder; ignore
continue
# write
z.extract(n, base)
return True

def asset(a):
return {
'url': a['browser_download_url'],
'size': a['size']
}

profileLoaded = False
profileLoaded = True
def _profileLoaded():
profileLoaded = True

addHook("profileLoaded",_profileLoaded)

def updateSingle(repositories,path,data):
def callback(doUpdate,answer,appendHtml):
def callback(doUpdate,answer,appendHtml,onReady,install):
if doUpdate:
repositories[path] = data
for asset in data['assets']:
code = asset['url']
p, fname = os.path.split(code)
Expand All @@ -96,18 +137,41 @@ def callback(doUpdate,answer,appendHtml):
QtGui.QApplication.instance().processEvents()
appendHtml('<br />Downloading {1}: 100%<br/>'.format(int(dl*100/file_size),fname))
def installData():
aqt.mw.addonManager.install(d,fname)
repositories[path]['update'] = answer
with open(dataPath,'w') as file:
json.dump(repositories,file,indent=2)
if profileLoaded:
installData()
else:
addHook("profileLoaded",installData)
if install:
filesBefore = aqt.mw.addonManager.files()
#directoriesBefore = aqt.mw.addonManager.directories()
if not installZipFile(d,fname):
appendHtml('Corrupt file<br/>')
else:
repositories[path] = data
repositories[path]['update'] = answer
with open(dataPath,'w') as file:
json.dump(repositories,file,indent=2)
if install:
appendHtml('Executing new scripts...<br/>')
newFiles = set(aqt.mw.addonManager.files()) - set(filesBefore)
#newDirectories = set(aqt.mw.addonManager.directories()) - set(directoriesBefore)
onReady() # close the AnkiHub update window
for file in newFiles:
try:
__import__(file.replace(".py", ""))
except:
traceback.print_exc()
#for directory in newDirectories:
# try:
# __import__(directory)
# except:
# traceback.print_exc()
aqt.mw.addonManager.rebuildAddonsMenu()
else:
onReady() # close the AnkiHub update window

installData()
else:
repositories[path]['update'] = answer
with open(dataPath,'w') as file:
json.dump(repositories,file,indent=2)
onReady()
return callback

datas = []
Expand Down Expand Up @@ -154,7 +218,7 @@ def update(add=[],install=False):
if repository['update'] == 'always':
dialog = DialogUpdates(None,data,repository,updateSingle(repositories,path,data),'always')
elif install:
dialog = DialogUpdates(None,data,repository,updateSingle(repositories,path,data),'ask')
dialog = DialogUpdates(None,data,repository,updateSingle(repositories,path,data),'ask',install=True)
else:
dialog = DialogUpdates(None,data,repository,updateSingle(repositories,path,data))
dialog.exec_()
Expand Down

0 comments on commit 09615b9

Please sign in to comment.