Commit 4eeeb02b authored by OzzieIsaacs's avatar OzzieIsaacs

Merge remote-tracking branch 'update_check/master'

parents 36d26f20 e08eccba
...@@ -547,3 +547,23 @@ def check_unrar(unrarLocation): ...@@ -547,3 +547,23 @@ def check_unrar(unrarLocation):
error=True error=True
return (error, version) return (error, version)
def is_sha1(sha1):
if len(sha1) != 40:
return False
try:
int(sha1, 16)
except ValueError:
return False
return True
def get_current_version_info():
content = {}
# content[0] = '$Format: % H$'
# content[1] = '$Format: % cI$'
content[0] = 'bb7d2c6273ae4560e83950d36d64533343623a57'
content[1] = '2018-09-09T10:13:08+02:00'
if is_sha1(content[0]) and len(content[1]) > 0:
return {'hash': content[0], 'datetime': content[1]}
return False
...@@ -104,18 +104,39 @@ $(function() { ...@@ -104,18 +104,39 @@ $(function() {
var $this = $(this); var $this = $(this);
var buttonText = $this.html(); var buttonText = $this.html();
$this.html("..."); $this.html("...");
$("#update_error").addClass("hidden")
$.ajax({ $.ajax({
dataType: "json", dataType: "json",
url: window.location.pathname + "/../../get_update_status", url: window.location.pathname + "/../../get_update_status",
success: function success(data) { success: function success(data) {
$this.html(buttonText); $this.html(buttonText);
if (data.status === true) {
$("#check_for_update").addClass("hidden"); var cssClass = '';
$("#perform_update").removeClass("hidden"); var message = ''
$("#update_info")
.removeClass("hidden") if (data.success === true) {
.find("span").html(data.commit); if (data.update === true) {
$("#check_for_update").addClass("hidden");
$("#perform_update").removeClass("hidden");
$("#update_info")
.removeClass("hidden")
.find("span").html(data.commit);
data.history.reverse().forEach((entry, index) => {
$("<tr><td>" + entry[0] + "</td><td>" + entry[1] + "</td></tr>").appendTo($("#update_table"));
});
cssClass = 'alert-warning'
} else {
cssClass = 'alert-success'
}
} else {
cssClass = 'alert-danger'
} }
message = '<div class="alert ' + cssClass
+ ' fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>' + data.message + '</div>';
$(message).insertAfter($("#update_table"));
} }
}); });
}); });
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -1095,23 +1095,126 @@ def get_matching_tags(): ...@@ -1095,23 +1095,126 @@ def get_matching_tags():
@app.route("/get_update_status", methods=['GET']) @app.route("/get_update_status", methods=['GET'])
@login_required_if_no_ano @login_required_if_no_ano
def get_update_status(): def get_update_status():
status = {} status = {
'update': False,
'success': False,
'message': '',
'current_commit_hash': ''
}
parents = []
repository_url = 'https://api.github.com/repos/janeczku/calibre-web'
tz = datetime.timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone) tz = datetime.timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone)
if request.method == "GET": if request.method == "GET":
# should be automatically replaced by git with current commit hash version = helper.get_current_version_info()
commit_id = '$Format:%H$' if version is False:
# ToDo: Handle server not reachable -> ValueError: status['current_commit_hash'] = _(u'Unknown')
commit = requests.get('https://api.github.com/repos/janeczku/calibre-web/git/refs/heads/master').json()
if "object" in commit and commit['object']['sha'] != commit_id:
status['status'] = True
commitdate = requests.get('https://api.github.com/repos/janeczku/calibre-web/git/commits/'+commit['object']['sha']).json()
if "committer" in commitdate:
form_date=datetime.datetime.strptime(commitdate['committer']['date'],"%Y-%m-%dT%H:%M:%SZ") - tz
status['commit'] = format_datetime(form_date, format='short', locale=get_locale())
else:
status['commit'] = u'Unknown'
else: else:
status['status'] = False status['current_commit_hash'] = version['hash']
try:
r = requests.get(repository_url + '/git/refs/heads/master')
r.raise_for_status()
commit = r.json()
except requests.exceptions.HTTPError as ex:
status['message'] = _(u'HTTP Error') + ' ' + str(ex)
except requests.exceptions.ConnectionError:
status['message'] = _(u'Connection error')
except requests.exceptions.Timeout:
status['message'] = _(u'Timeout while establishing connection')
except requests.exceptions.RequestException:
status['message'] = _(u'General error')
if status['message'] != '':
return json.dumps(status)
if 'object' not in commit:
status['message'] = _(u'Unexpected data while reading update information')
return json.dumps(status)
if commit['object']['sha'] == status['current_commit_hash']:
status.update({
'update': False,
'success': True,
'message': _(u'No update available. You already have the latest version installed')
})
return json.dumps(status)
# a new update is available
status['update'] = True
try:
r = requests.get(repository_url + '/git/commits/' + commit['object']['sha'])
r.raise_for_status()
update_data = r.json()
except requests.exceptions.HTTPError as ex:
status['error'] = _(u'HTTP Error') + ' ' + str(ex)
except requests.exceptions.ConnectionError:
status['error'] = _(u'Connection error')
except requests.exceptions.Timeout:
status['error'] = _(u'Timeout while establishing connection')
except requests.exceptions.RequestException:
status['error'] = _(u'General error')
if status['message'] != '':
return json.dumps(status)
if 'committer' in update_data and 'message' in update_data:
status['success'] = True
status['message'] = _(u'A new update is available. Click on the button below to update to the latest version.')
new_commit_date = datetime.datetime.strptime(
update_data['committer']['date'], '%Y-%m-%dT%H:%M:%SZ') - tz
parents.append(
[
format_datetime(new_commit_date, format='short', locale=get_locale()),
update_data['message'],
update_data['sha']
]
)
# it only makes sense to analyze the parents if we know the current commit hash
if status['current_commit_hash'] != '':
try:
parent_commit = update_data['parents'][0]
# limit the maximum search depth
remaining_parents_cnt = 10
except IndexError:
remaining_parents_cnt = None
if remaining_parents_cnt is not None:
while True:
if remaining_parents_cnt == 0:
break
# check if we are more than one update behind if so, go up the tree
if parent_commit['sha'] != status['current_commit_hash']:
try:
r = requests.get(parent_commit['url'])
r.raise_for_status()
parent_data = r.json()
parent_commit_date = datetime.datetime.strptime(
parent_data['committer']['date'], '%Y-%m-%dT%H:%M:%SZ') - tz
parent_commit_date = format_datetime(
parent_commit_date, format='short', locale=get_locale())
parents.append([parent_commit_date, parent_data['message'], parent_data['sha']])
parent_commit = parent_data['parents'][0]
remaining_parents_cnt -= 1
except Exception:
# it isn't crucial if we can't get information about the parent
break
else:
# parent is our current version
break
else:
status['success'] = False
status['message'] = _(u'Could not fetch update information')
status['history'] = parents
return json.dumps(status) return json.dumps(status)
...@@ -2670,10 +2773,12 @@ def profile(): ...@@ -2670,10 +2773,12 @@ def profile():
@login_required @login_required
@admin_required @admin_required
def admin(): def admin():
commit = '$Format:%cI$' version = helper.get_current_version_info()
if commit.startswith("$"): if version is False:
commit = _(u'Unknown') commit = _(u'Unknown')
else: else:
commit = version['datetime']
tz = datetime.timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone) tz = datetime.timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone)
form_date = datetime.datetime.strptime(commit[:19], "%Y-%m-%dT%H:%M:%S") form_date = datetime.datetime.strptime(commit[:19], "%Y-%m-%dT%H:%M:%S")
if len(commit) > 19: # check if string has timezone if len(commit) > 19: # check if string has timezone
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment