2019-02-08 20:11:44 +01:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
|
|
|
# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11,
|
|
|
|
# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh,
|
|
|
|
# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe,
|
|
|
|
# ruben-herold, marblepebble, JackED42, SiphonSquirrel,
|
|
|
|
# apetresc, nanu-c, mutschler
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2019-06-06 17:10:22 +02:00
|
|
|
|
|
|
|
from __future__ import division, print_function, unicode_literals
|
2019-02-08 20:11:44 +01:00
|
|
|
import os
|
2019-06-06 17:10:22 +02:00
|
|
|
import hashlib
|
2019-02-08 20:11:44 +01:00
|
|
|
import json
|
2019-06-06 17:10:22 +02:00
|
|
|
import tempfile
|
2019-02-08 20:11:44 +01:00
|
|
|
from uuid import uuid4
|
|
|
|
from time import time
|
|
|
|
from shutil import move, copyfile
|
2019-06-06 17:10:22 +02:00
|
|
|
|
|
|
|
from flask import Blueprint, flash, request, redirect, url_for, abort
|
|
|
|
from flask_babel import gettext as _
|
|
|
|
from flask_login import login_required
|
2019-02-08 20:11:44 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
from googleapiclient.errors import HttpError
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
2019-06-06 17:10:22 +02:00
|
|
|
from . import logger, gdriveutils, config, ub, db
|
|
|
|
from .web import admin_required
|
|
|
|
|
|
|
|
|
2019-02-08 20:11:44 +01:00
|
|
|
gdrive = Blueprint('gdrive', __name__)
|
2019-06-11 18:35:20 +02:00
|
|
|
log = logger.create()
|
2019-02-08 20:11:44 +01:00
|
|
|
|
|
|
|
current_milli_time = lambda: int(round(time() * 1000))
|
|
|
|
|
|
|
|
gdrive_watch_callback_token = 'target=calibreweb-watch_files'
|
|
|
|
|
|
|
|
|
|
|
|
@gdrive.route("/gdrive/authenticate")
|
|
|
|
@login_required
|
|
|
|
@admin_required
|
|
|
|
def authenticate_google_drive():
|
|
|
|
try:
|
|
|
|
authUrl = gdriveutils.Gauth.Instance().auth.GetAuthUrl()
|
|
|
|
except gdriveutils.InvalidConfigError:
|
|
|
|
flash(_(u'Google Drive setup not completed, try to deactivate and activate Google Drive again'),
|
|
|
|
category="error")
|
|
|
|
return redirect(url_for('web.index'))
|
|
|
|
return redirect(authUrl)
|
|
|
|
|
|
|
|
|
|
|
|
@gdrive.route("/gdrive/callback")
|
|
|
|
def google_drive_callback():
|
|
|
|
auth_code = request.args.get('code')
|
|
|
|
if not auth_code:
|
|
|
|
abort(403)
|
|
|
|
try:
|
|
|
|
credentials = gdriveutils.Gauth.Instance().auth.flow.step2_exchange(auth_code)
|
2019-06-06 17:10:22 +02:00
|
|
|
with open(gdriveutils.CREDENTIALS, 'w') as f:
|
2019-02-08 20:11:44 +01:00
|
|
|
f.write(credentials.to_json())
|
|
|
|
except ValueError as error:
|
2019-06-11 18:35:20 +02:00
|
|
|
log.error(error)
|
2019-02-16 07:23:08 +01:00
|
|
|
return redirect(url_for('admin.configuration'))
|
2019-02-08 20:11:44 +01:00
|
|
|
|
|
|
|
|
|
|
|
@gdrive.route("/gdrive/watch/subscribe")
|
|
|
|
@login_required
|
|
|
|
@admin_required
|
|
|
|
def watch_gdrive():
|
|
|
|
if not config.config_google_drive_watch_changes_response:
|
2019-06-06 17:10:22 +02:00
|
|
|
with open(gdriveutils.CLIENT_SECRETS, 'r') as settings:
|
2019-02-08 20:11:44 +01:00
|
|
|
filedata = json.load(settings)
|
|
|
|
if filedata['web']['redirect_uris'][0].endswith('/'):
|
|
|
|
filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-((len('/gdrive/callback')+1))]
|
|
|
|
else:
|
|
|
|
filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-(len('/gdrive/callback'))]
|
|
|
|
address = '%s/gdrive/watch/callback' % filedata['web']['redirect_uris'][0]
|
|
|
|
notification_id = str(uuid4())
|
|
|
|
try:
|
|
|
|
result = gdriveutils.watchChange(gdriveutils.Gdrive.Instance().drive, notification_id,
|
|
|
|
'web_hook', address, gdrive_watch_callback_token, current_milli_time() + 604800*1000)
|
|
|
|
settings = ub.session.query(ub.Settings).first()
|
|
|
|
settings.config_google_drive_watch_changes_response = json.dumps(result)
|
|
|
|
ub.session.merge(settings)
|
|
|
|
ub.session.commit()
|
|
|
|
settings = ub.session.query(ub.Settings).first()
|
|
|
|
config.loadSettings()
|
|
|
|
except HttpError as e:
|
|
|
|
reason=json.loads(e.content)['error']['errors'][0]
|
|
|
|
if reason['reason'] == u'push.webhookUrlUnauthorized':
|
|
|
|
flash(_(u'Callback domain is not verified, please follow steps to verify domain in google developer console'), category="error")
|
|
|
|
else:
|
|
|
|
flash(reason['message'], category="error")
|
|
|
|
|
2019-02-16 07:23:08 +01:00
|
|
|
return redirect(url_for('admin.configuration'))
|
2019-02-08 20:11:44 +01:00
|
|
|
|
|
|
|
|
|
|
|
@gdrive.route("/gdrive/watch/revoke")
|
|
|
|
@login_required
|
|
|
|
@admin_required
|
|
|
|
def revoke_watch_gdrive():
|
|
|
|
last_watch_response = config.config_google_drive_watch_changes_response
|
|
|
|
if last_watch_response:
|
|
|
|
try:
|
|
|
|
gdriveutils.stopChannel(gdriveutils.Gdrive.Instance().drive, last_watch_response['id'],
|
|
|
|
last_watch_response['resourceId'])
|
|
|
|
except HttpError:
|
|
|
|
pass
|
|
|
|
settings = ub.session.query(ub.Settings).first()
|
|
|
|
settings.config_google_drive_watch_changes_response = None
|
|
|
|
ub.session.merge(settings)
|
|
|
|
ub.session.commit()
|
|
|
|
config.loadSettings()
|
2019-02-16 07:23:08 +01:00
|
|
|
return redirect(url_for('admin.configuration'))
|
2019-02-08 20:11:44 +01:00
|
|
|
|
|
|
|
|
|
|
|
@gdrive.route("/gdrive/watch/callback", methods=['GET', 'POST'])
|
|
|
|
def on_received_watch_confirmation():
|
2019-06-11 18:35:20 +02:00
|
|
|
log.debug('%r', request.headers)
|
2019-02-08 20:11:44 +01:00
|
|
|
if request.headers.get('X-Goog-Channel-Token') == gdrive_watch_callback_token \
|
|
|
|
and request.headers.get('X-Goog-Resource-State') == 'change' \
|
|
|
|
and request.data:
|
|
|
|
|
|
|
|
data = request.data
|
|
|
|
|
|
|
|
def updateMetaData():
|
2019-06-11 18:35:20 +02:00
|
|
|
log.info('Change received from gdrive')
|
|
|
|
log.debug('%r', data)
|
2019-02-08 20:11:44 +01:00
|
|
|
try:
|
|
|
|
j = json.loads(data)
|
2019-06-11 18:35:20 +02:00
|
|
|
log.info('Getting change details')
|
2019-02-08 20:11:44 +01:00
|
|
|
response = gdriveutils.getChangeById(gdriveutils.Gdrive.Instance().drive, j['id'])
|
2019-06-11 18:35:20 +02:00
|
|
|
log.debug('%r', response)
|
2019-02-08 20:11:44 +01:00
|
|
|
if response:
|
|
|
|
dbpath = os.path.join(config.config_calibre_dir, "metadata.db")
|
|
|
|
if not response['deleted'] and response['file']['title'] == 'metadata.db' and response['file']['md5Checksum'] != hashlib.md5(dbpath):
|
|
|
|
tmpDir = tempfile.gettempdir()
|
2019-06-11 18:35:20 +02:00
|
|
|
log.info('Database file updated')
|
2019-02-08 20:11:44 +01:00
|
|
|
copyfile(dbpath, os.path.join(tmpDir, "metadata.db_" + str(current_milli_time())))
|
2019-06-11 18:35:20 +02:00
|
|
|
log.info('Backing up existing and downloading updated metadata.db')
|
2019-02-08 20:11:44 +01:00
|
|
|
gdriveutils.downloadFile(None, "metadata.db", os.path.join(tmpDir, "tmp_metadata.db"))
|
2019-06-11 18:35:20 +02:00
|
|
|
log.info('Setting up new DB')
|
2019-02-08 20:11:44 +01:00
|
|
|
# prevent error on windows, as os.rename does on exisiting files
|
|
|
|
move(os.path.join(tmpDir, "tmp_metadata.db"), dbpath)
|
|
|
|
db.setup_db()
|
|
|
|
except Exception as e:
|
2019-06-11 18:35:20 +02:00
|
|
|
log.exception(e)
|
2019-02-08 20:11:44 +01:00
|
|
|
updateMetaData()
|
|
|
|
return ''
|