Auto update supported

This commit is contained in:
St.Huang 2018-07-31 15:46:03 +08:00
parent 7e4429446e
commit a1c470789d
14 changed files with 137 additions and 76 deletions

View File

@ -38,6 +38,8 @@ def start_here():
fastwq.config_menu() fastwq.config_menu()
fastwq.browser_menu() fastwq.browser_menu()
fastwq.customize_addcards() fastwq.customize_addcards()
if fastwq.config.auto_update:
fastwq.check_updates(True)
fastwq.window_shortcut(shortcut) fastwq.window_shortcut(shortcut)
addHook("profileLoaded", start_here) addHook("profileLoaded", start_here)

View File

@ -22,7 +22,7 @@ from aqt import mw
from anki.hooks import addHook, wrap from anki.hooks import addHook, wrap
from aqt.addcards import AddCards from aqt.addcards import AddCards
from aqt.utils import showInfo, shortcut from aqt.utils import showInfo, shortcut
from .gui import show_options, show_about_dialog from .gui import show_options, show_about_dialog, check_updates
from .query import query_from_browser, query_from_editor_all_fields from .query import query_from_browser, query_from_editor_all_fields
from .context import config, APP_ICON from .context import config, APP_ICON
from .lang import _ from .lang import _
@ -31,7 +31,7 @@ from .lang import _
__all__ = [ __all__ = [
'add_query_button', 'browser_menu', 'add_query_button', 'browser_menu',
'customize_addcards', 'config_menu', 'customize_addcards', 'config_menu',
'window_shortcut' 'window_shortcut', 'check_updates'
] ]
@ -122,4 +122,3 @@ def window_shortcut(key_sequence):
""" """
global my_shortcut global my_shortcut
my_shortcut = key_sequence my_shortcut = key_sequence

View File

@ -114,5 +114,10 @@ class Config(object):
'''ignore accents of field in querying''' '''ignore accents of field in querying'''
return self.data.get('ignore_accents', False) return self.data.get('ignore_accents', False)
@property
def auto_update(self):
'''auto check new version'''
return self.data.get('auto_update', True)
config = Config(mw) config = Config(mw)

View File

@ -33,16 +33,18 @@ from ..service import service_manager
__all__ = ['show_options', 'check_updates', 'show_fm_dialog', 'show_about_dialog'] __all__ = ['show_options', 'check_updates', 'show_fm_dialog', 'show_about_dialog']
def check_updates(): def check_updates(background=False):
'''check add-on last version''' '''check add-on last version'''
try: try:
state = ankihub.update([Endpoint.check_version], False, Endpoint.version) state = ankihub.update([Endpoint.check_version], Endpoint.version, background)
if state == 0: if not background:
showInfo(_('LATEST_VERSION')) if state == 0:
elif state == -1: showInfo(_('LATEST_VERSION'))
showInfo(_('CHECK_FAILURE')) elif state == -1:
showInfo(_('CHECK_FAILURE'))
except: except:
showInfo(_('CHECK_FAILURE')) if not background:
showInfo(_('CHECK_FAILURE'))
def show_fm_dialog(browser = None): def show_fm_dialog(browser = None):

View File

@ -35,6 +35,8 @@ class SettingDialog(Dialog):
super(SettingDialog, self).__init__(parent, title) super(SettingDialog, self).__init__(parent, title)
self.setFixedWidth(400) self.setFixedWidth(400)
self.check_force_update = None self.check_force_update = None
self.check_ignore_accents = None
self.check_auto_update = None
self.input_thread_number = None self.input_thread_number = None
self.build() self.build()
@ -51,6 +53,11 @@ class SettingDialog(Dialog):
layout.addWidget(check_ignore_accents) layout.addWidget(check_ignore_accents)
layout.addSpacing(10) layout.addSpacing(10)
check_auto_update = QCheckBox(_("AUTO_UPDATE"))
check_auto_update.setChecked(config.auto_update)
layout.addWidget(check_auto_update)
layout.addSpacing(10)
hbox = QHBoxLayout() hbox = QHBoxLayout()
input_thread_number = QSpinBox(parent=self) input_thread_number = QSpinBox(parent=self)
input_thread_number.setRange(1, 120) input_thread_number.setRange(1, 120)
@ -71,6 +78,7 @@ class SettingDialog(Dialog):
self.check_force_update = check_force_update self.check_force_update = check_force_update
self.check_ignore_accents = check_ignore_accents self.check_ignore_accents = check_ignore_accents
self.check_auto_update = check_auto_update
self.input_thread_number = input_thread_number self.input_thread_number = input_thread_number
layout.setAlignment(Qt.AlignTop|Qt.AlignLeft) layout.setAlignment(Qt.AlignTop|Qt.AlignLeft)
@ -84,7 +92,8 @@ class SettingDialog(Dialog):
data = { data = {
'force_update': self.check_force_update.isChecked(), 'force_update': self.check_force_update.isChecked(),
'ignore_accents': self.check_ignore_accents.isChecked(), 'ignore_accents': self.check_ignore_accents.isChecked(),
'thread_number': self.input_thread_number.value() 'auto_update': self.check_auto_update.isChecked(),
'thread_number': self.input_thread_number.value(),
} }
config.update(data) config.update(data)

View File

@ -18,7 +18,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from anki.lang import currentLang from anki.lang import currentLang
try:
basestring
except NameError:
basestring = str
__all__ = ['_', '_cl', '_sl'] __all__ = ['_', '_cl', '_sl']
@ -55,6 +58,7 @@ _arr = [
['CHECK_FAILURE', u'版本检查失败.', u'Version check failed.'], ['CHECK_FAILURE', u'版本检查失败.', u'Version check failed.'],
['NEW_VERSION', u'检查到新版本:', u'New version available:'], ['NEW_VERSION', u'检查到新版本:', u'New version available:'],
['UPDATE', u'更新', u'Update'], ['UPDATE', u'更新', u'Update'],
['AUTO_UPDATE', u'自动检测新版本', u'Auto check new version'],
['FORCE_UPDATE', u'强制更新字段', u'Forced Updates of all fields'], ['FORCE_UPDATE', u'强制更新字段', u'Forced Updates of all fields'],
['IGNORE_ACCENTS', u'忽略声调', u'Ignore Accents'], ['IGNORE_ACCENTS', u'忽略声调', u'Ignore Accents'],
['SKIP_VALUED', u'跳过有值项', u'Skip non-empty'], ['SKIP_VALUED', u'跳过有值项', u'Skip non-empty'],

View File

@ -22,6 +22,10 @@ from ..context import APP_ICON
from .AnkiHub.updates import Ui_DialogUpdates from .AnkiHub.updates import Ui_DialogUpdates
from .AnkiHub.markdown2 import markdown from .AnkiHub.markdown2 import markdown
__all__ = ['update']
# taken from Anki's aqt/profiles.py # taken from Anki's aqt/profiles.py
def defaultBase(): def defaultBase():
path = mw.pm.addonFolder() path = mw.pm.addonFolder()
@ -34,7 +38,8 @@ dataPath = os.path.join(defaultBase(),'.fastwq_2.0.x_ankihub.json')
class DialogUpdates(QDialog, Ui_DialogUpdates): class DialogUpdates(QDialog, Ui_DialogUpdates):
def __init__(self, parent, data, oldData, callback, install=False): def __init__(self, parent, data, oldData, callback):
parent = parent if parent else mw
QDialog.__init__(self,parent) QDialog.__init__(self,parent)
self.setModal(True) self.setModal(True)
self.setWindowFlags( self.setWindowFlags(
@ -46,7 +51,7 @@ class DialogUpdates(QDialog, Ui_DialogUpdates):
totalSize = sum(map(lambda x:x['size'],data['assets'])) totalSize = sum(map(lambda x:x['size'],data['assets']))
def answer(): def answer():
self.update.setEnabled(False) self.update.setEnabled(False)
callback(self.appendHtml, self.finish, install) callback(self.appendHtml, self.finish)
self.html = u'' self.html = u''
self.appendHtml(markdown(data['body'])) self.appendHtml(markdown(data['body']))
@ -105,7 +110,7 @@ def asset(a):
def updateSingle(repositories, path, data): def updateSingle(repositories, path, data):
def callback(appendHtml, onReady, install): def callback(appendHtml, onReady):
for asset in data['assets']: for asset in data['assets']:
code = asset['url'] code = asset['url']
p, fname = os.path.split(code) p, fname = os.path.split(code)
@ -147,19 +152,22 @@ def updateSingle(repositories, path, data):
return callback return callback
def update(add=[], install=False, VERSION='v0.0.0'): def update(add=[], VERSION='v0.0.0', background=False):
# progress win # progress win
progresswin = QProgressDialog('Update Checking...', '', 0, 0, mw) if not background:
progresswin.setWindowModality(Qt.ApplicationModal) progresswin = QProgressDialog('Update Checking...', '', 0, 0, mw)
progresswin.setCancelButton(None) progresswin.setWindowModality(Qt.ApplicationModal)
progresswin.setWindowFlags( progresswin.setCancelButton(None)
progresswin.windowFlags() & progresswin.setWindowFlags(
~Qt.WindowContextHelpButtonHint progresswin.windowFlags() &
) ~Qt.WindowContextHelpButtonHint
progresswin.setWindowIcon(APP_ICON) )
progresswin.setWindowTitle('FastWQ - Updater') progresswin.setWindowIcon(APP_ICON)
progresswin.resize(280, 60) progresswin.setWindowTitle('FastWQ - Updater')
progresswin.show() progresswin.resize(280, 60)
progresswin.show()
else:
progresswin = None
# #
conn = httplib.HTTPSConnection("api.github.com") conn = httplib.HTTPSConnection("api.github.com")
try: try:
@ -214,7 +222,7 @@ def update(add=[], install=False, VERSION='v0.0.0'):
if isMinor: if isMinor:
i = 1 i = 1
while i<newVersion[2]: while i<newVersion[2]:
if progresswin.wasCanceled(): if progresswin and progresswin.wasCanceled():
break break
try: try:
minorTagName = 'v{0}.{1}.{2}'.format(newVersion[0],oldVersion[1],i) minorTagName = 'v{0}.{1}.{2}'.format(newVersion[0],oldVersion[1],i)
@ -230,7 +238,7 @@ def update(add=[], install=False, VERSION='v0.0.0'):
if oldVersion[0]<newVersion[0] or oldVersion[1]<newVersion[1]: if oldVersion[0]<newVersion[0] or oldVersion[1]<newVersion[1]:
# new major release necessary! # new major release necessary!
# if the newest version is minor, fetch the additional assets from the major # if the newest version is minor, fetch the additional assets from the major
if isMinor and not progresswin.wasCanceled(): if isMinor and (background or not progresswin.wasCanceled()):
try: try:
majorTagName = 'v{0}.{1}'.format(newVersion[0],newVersion[1]) majorTagName = 'v{0}.{1}'.format(newVersion[0],newVersion[1])
urlthread = UrlThread( urlthread = UrlThread(
@ -245,22 +253,26 @@ def update(add=[], install=False, VERSION='v0.0.0'):
except: except:
pass pass
if not progresswin.wasCanceled(): if background or not progresswin.wasCanceled():
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
dialog = DialogUpdates(None, data, repository, updateSingle(repositories, path, data)) dialog = DialogUpdates(None, data, repository, updateSingle(repositories, path, data))
dialog.exec_() dialog.exec_()
dialog.destroy() dialog.destroy()
else: else:
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
return 1 return 1
else: else:
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
return 0 return 0
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
return -1 return -1

View File

@ -35,6 +35,8 @@ def start_here():
fastwq.config_menu() fastwq.config_menu()
fastwq.browser_menu() fastwq.browser_menu()
fastwq.customize_addcards() fastwq.customize_addcards()
if fastwq.config.auto_update:
fastwq.check_updates(True)
fastwq.window_shortcut(shortcut) fastwq.window_shortcut(shortcut)
addHook("profileLoaded", start_here) addHook("profileLoaded", start_here)

View File

@ -22,7 +22,7 @@ from aqt.qt import *
from anki.hooks import addHook, wrap from anki.hooks import addHook, wrap
from aqt.addcards import AddCards from aqt.addcards import AddCards
from aqt.utils import showInfo, shortcut from aqt.utils import showInfo, shortcut
from .gui import show_options, show_about_dialog from .gui import show_options, show_about_dialog, check_updates
from .query import query_from_browser, query_from_editor_all_fields from .query import query_from_browser, query_from_editor_all_fields
from .context import config, APP_ICON from .context import config, APP_ICON
from .lang import _ from .lang import _
@ -31,7 +31,7 @@ from .lang import _
__all__ = [ __all__ = [
'add_query_button', 'browser_menu', 'add_query_button', 'browser_menu',
'customize_addcards', 'config_menu', 'customize_addcards', 'config_menu',
'window_shortcut' 'window_shortcut', 'check_updates'
] ]

View File

@ -116,5 +116,9 @@ class Config(object):
'''ignore accents of field in querying''' '''ignore accents of field in querying'''
return self.data.get('ignore_accents', False) return self.data.get('ignore_accents', False)
@property
def auto_update(self):
'''auto check new version'''
return self.data.get('auto_update', True)
config = Config(mw) config = Config(mw)

View File

@ -33,16 +33,18 @@ from ..service import service_manager
__all__ = ['show_options', 'check_updates', 'show_fm_dialog', 'show_about_dialog'] __all__ = ['show_options', 'check_updates', 'show_fm_dialog', 'show_about_dialog']
def check_updates(): def check_updates(background=False):
'''check add-on last version''' '''check add-on last version'''
try: try:
state = ankihub.update([Endpoint.check_version], False, Endpoint.version) state = ankihub.update([Endpoint.check_version], Endpoint.version, background)
if state == 0: if not background:
showInfo(_('LATEST_VERSION')) if state == 0:
elif state == -1: showInfo(_('LATEST_VERSION'))
showInfo(_('CHECK_FAILURE')) elif state == -1:
showInfo(_('CHECK_FAILURE'))
except: except:
showInfo(_('CHECK_FAILURE')) if not background:
showInfo(_('CHECK_FAILURE'))
def show_fm_dialog(browser = None): def show_fm_dialog(browser = None):

View File

@ -35,6 +35,8 @@ class SettingDialog(Dialog):
super(SettingDialog, self).__init__(parent, title) super(SettingDialog, self).__init__(parent, title)
self.setFixedWidth(400) self.setFixedWidth(400)
self.check_force_update = None self.check_force_update = None
self.check_ignore_accents = None
self.check_auto_update = None
self.input_thread_number = None self.input_thread_number = None
self.build() self.build()
@ -51,6 +53,11 @@ class SettingDialog(Dialog):
layout.addWidget(check_ignore_accents) layout.addWidget(check_ignore_accents)
layout.addSpacing(10) layout.addSpacing(10)
check_auto_update = QCheckBox(_("AUTO_UPDATE"))
check_auto_update.setChecked(config.auto_update)
layout.addWidget(check_auto_update)
layout.addSpacing(10)
hbox = QHBoxLayout() hbox = QHBoxLayout()
input_thread_number = QSpinBox(parent=self) input_thread_number = QSpinBox(parent=self)
input_thread_number.setRange(1, 120) input_thread_number.setRange(1, 120)
@ -71,6 +78,7 @@ class SettingDialog(Dialog):
self.check_force_update = check_force_update self.check_force_update = check_force_update
self.check_ignore_accents = check_ignore_accents self.check_ignore_accents = check_ignore_accents
self.check_auto_update = check_auto_update
self.input_thread_number = input_thread_number self.input_thread_number = input_thread_number
layout.setAlignment(Qt.AlignTop|Qt.AlignLeft) layout.setAlignment(Qt.AlignTop|Qt.AlignLeft)
@ -84,7 +92,8 @@ class SettingDialog(Dialog):
data = { data = {
'force_update': self.check_force_update.isChecked(), 'force_update': self.check_force_update.isChecked(),
'ignore_accents': self.check_ignore_accents.isChecked(), 'ignore_accents': self.check_ignore_accents.isChecked(),
'thread_number': self.input_thread_number.value() 'auto_update': self.check_auto_update.isChecked(),
'thread_number': self.input_thread_number.value(),
} }
config.update(data) config.update(data)

View File

@ -23,7 +23,6 @@ try:
except NameError: except NameError:
basestring = str basestring = str
__all__ = ['_', '_cl', '_sl'] __all__ = ['_', '_cl', '_sl']
@ -59,6 +58,7 @@ _arr = [
['CHECK_FAILURE', u'版本检查失败.', u'Version check failed.'], ['CHECK_FAILURE', u'版本检查失败.', u'Version check failed.'],
['NEW_VERSION', u'检查到新版本:', u'New version available:'], ['NEW_VERSION', u'检查到新版本:', u'New version available:'],
['UPDATE', u'更新', u'Update'], ['UPDATE', u'更新', u'Update'],
['AUTO_UPDATE', u'自动检测新版本', u'Auto check new version'],
['FORCE_UPDATE', u'强制更新字段', u'Forced Updates of all fields'], ['FORCE_UPDATE', u'强制更新字段', u'Forced Updates of all fields'],
['IGNORE_ACCENTS', u'忽略声调', u'Ignore Accents'], ['IGNORE_ACCENTS', u'忽略声调', u'Ignore Accents'],
['SKIP_VALUED', u'跳过有值项', u'Skip non-empty'], ['SKIP_VALUED', u'跳过有值项', u'Skip non-empty'],

View File

@ -23,6 +23,9 @@ from .AnkiHub.updates import Ui_DialogUpdates
from .AnkiHub.markdown2 import markdown from .AnkiHub.markdown2 import markdown
__all__ = ['update']
# taken from Anki's aqt/profiles.py # taken from Anki's aqt/profiles.py
def defaultBase(): def defaultBase():
path = mw.pm.addonFolder() path = mw.pm.addonFolder()
@ -35,8 +38,9 @@ dataPath = os.path.join(defaultBase(),'.fastwq_2.1.x_ankihub.json')
class DialogUpdates(QDialog, Ui_DialogUpdates): class DialogUpdates(QDialog, Ui_DialogUpdates):
def __init__(self, parent, data, oldData, callback, install=False): def __init__(self, parent, data, oldData, callback):
QDialog.__init__(self,parent) parent = parent if parent else mw
QDialog.__init__(self, parent)
self.setModal(True) self.setModal(True)
self.setWindowFlags( self.setWindowFlags(
self.windowFlags() & self.windowFlags() &
@ -47,7 +51,7 @@ class DialogUpdates(QDialog, Ui_DialogUpdates):
totalSize = sum(map(lambda x:x['size'],data['assets'])) totalSize = sum(map(lambda x:x['size'],data['assets']))
def answer(): def answer():
self.update.setEnabled(False) self.update.setEnabled(False)
callback(self.appendHtml, self.finish, install) callback(self.appendHtml, self.finish)
self.html = u'' self.html = u''
self.appendHtml(markdown(data['body'])) self.appendHtml(markdown(data['body']))
@ -106,7 +110,7 @@ def asset(a):
def updateSingle(repositories, path, data): def updateSingle(repositories, path, data):
def callback(appendHtml, onReady, install): def callback(appendHtml, onReady):
for asset in data['assets']: for asset in data['assets']:
code = asset['url'] code = asset['url']
p, fname = os.path.split(code) p, fname = os.path.split(code)
@ -148,19 +152,22 @@ def updateSingle(repositories, path, data):
return callback return callback
def update(add=[], install=False, VERSION='v0.0.0'): def update(add=[], VERSION='v0.0.0', background=False):
# progress win # progress win
progresswin = QProgressDialog('Update Checking...', '', 0, 0, mw) if not background:
progresswin.setWindowModality(Qt.ApplicationModal) progresswin = QProgressDialog('Update Checking...', '', 0, 0, mw)
progresswin.setCancelButton(None) progresswin.setWindowModality(Qt.ApplicationModal)
progresswin.setWindowFlags( progresswin.setCancelButton(None)
progresswin.windowFlags() & progresswin.setWindowFlags(
~Qt.WindowContextHelpButtonHint progresswin.windowFlags() &
) ~Qt.WindowContextHelpButtonHint
progresswin.setWindowTitle('FastWQ - Updater') )
progresswin.setWindowIcon(APP_ICON) progresswin.setWindowTitle('FastWQ - Updater')
progresswin.resize(280, 60) progresswin.setWindowIcon(APP_ICON)
progresswin.show() progresswin.resize(280, 60)
progresswin.show()
else:
progresswin = None
# #
conn = httplib.HTTPSConnection("api.github.com") conn = httplib.HTTPSConnection("api.github.com")
try: try:
@ -215,7 +222,7 @@ def update(add=[], install=False, VERSION='v0.0.0'):
if isMinor: if isMinor:
i = 1 i = 1
while i<newVersion[2]: while i<newVersion[2]:
if progresswin.wasCanceled(): if progresswin and progresswin.wasCanceled():
break break
try: try:
minorTagName = 'v{0}.{1}.{2}'.format(newVersion[0],oldVersion[1],i) minorTagName = 'v{0}.{1}.{2}'.format(newVersion[0],oldVersion[1],i)
@ -231,7 +238,7 @@ def update(add=[], install=False, VERSION='v0.0.0'):
if oldVersion[0]<newVersion[0] or oldVersion[1]<newVersion[1]: if oldVersion[0]<newVersion[0] or oldVersion[1]<newVersion[1]:
# new major release necessary! # new major release necessary!
# if the newest version is minor, fetch the additional assets from the major # if the newest version is minor, fetch the additional assets from the major
if isMinor and not progresswin.wasCanceled(): if isMinor and (background or not progresswin.wasCanceled()):
try: try:
majorTagName = 'v{0}.{1}'.format(newVersion[0],newVersion[1]) majorTagName = 'v{0}.{1}'.format(newVersion[0],newVersion[1])
urlthread = UrlThread( urlthread = UrlThread(
@ -246,22 +253,26 @@ def update(add=[], install=False, VERSION='v0.0.0'):
except: except:
pass pass
if not progresswin.wasCanceled(): if background or not progresswin.wasCanceled():
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
dialog = DialogUpdates(None, data, repository, updateSingle(repositories, path, data)) dialog = DialogUpdates(None, data, repository, updateSingle(repositories, path, data))
dialog.exec_() dialog.exec_()
dialog.destroy() dialog.destroy()
else: else:
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
return 1 return 1
else: else:
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
return 0 return 0
progresswin.hide() if progresswin:
progresswin.destroy() progresswin.hide()
progresswin.destroy()
return -1 return -1