Skip to content

Commit

Permalink
Merge pull request #83 from ai-naymul/refactor/refactor_google_drive_…
Browse files Browse the repository at this point in the history
…related_functions

Google drive related function is transferred into new file named gdrive_utils.py
  • Loading branch information
birm authored Nov 17, 2023
2 parents 57480b6 + d0bf292 commit a5c7745
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 29 deletions.
36 changes: 7 additions & 29 deletions SlideServer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import csv
import pathlib
import logging
from gDriveDownload import start, afterUrlAuth, callApi
from gdrive_utils import getFileFromGdrive, gDriveGetFile, checkDownloadStatus
from threading import Thread
from file_extensions import ALLOWED_EXTENSIONS
from time import sleep
Expand All @@ -48,8 +48,6 @@
app.config['SECRET_KEY'] = os.urandom(24)
app.config['ROI_FOLDER'] = "/images/roiDownload"



# should be used instead of secure_filename to create new files whose extensions are important.
# use secure_filename to access previous files.
# secure_filename ensures security but may result in invalid filenames.
Expand Down Expand Up @@ -656,39 +654,19 @@ def run(self):

# Route to start the OAuth Server(to listen if user is Authenticated) and start the file Download after Authentication
@app.route('/googleDriveUpload/getFile', methods=['POST'])
def gDriveGetFile():
def gDriveGetFileRoute():
body = flask.request.get_json()
if not body:
return flask.Response(json.dumps({"error": "Missing JSON body"}), status=400, mimetype='text/json')

token = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
token = secure_filename(token)
tmppath = os.path.join("/images/uploading/", token)
# regenerate if we happen to collide
while os.path.isfile(tmppath):
token = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
token = secure_filename(token)
tmppath = os.path.join("/images/uploading/", token)

try:
params = start(body['userId'])
except:
return flask.Response(json.dumps({'error': str(sys.exc_info()[0])}), status=400, mimetype='text/json')
thread_a = getFileFromGdrive(params, body['userId'], body['fileId'], token)
thread_a.start()
return flask.Response(json.dumps({"authURL": params["auth_url"], "token": token}), status=200, mimetype='text/json')
return flask.Response(json.dumps({"error": "Missing JSON body"}), status=400)
return gDriveGetFile(body)

# To check if a particular file is downloaded from Gdrive
@app.route('/googleDriveUpload/checkStatus', methods=['POST'])
def checkDownloadStatus():
def checkDownloadStatusRoute():
body = flask.request.get_json()
if not body:
return flask.Response(json.dumps({"error": "Missing JSON body"}), status=400, mimetype='text/json')
token = body['token']
path = app.config['TEMP_FOLDER']+'/'+token
if os.path.isfile(path):
return flask.Response(json.dumps({"downloadDone": True}), status=200, mimetype='text/json')
return flask.Response(json.dumps({"downloadDone": False}), status=200, mimetype='text/json')
return flask.Response(json.dumps({"error": "Missing JSON body"}), status=400)
return checkDownloadStatus(body)

# DICOM Explorer UI and DICOM server hostname and port
@app.route('/dicomsrv/location', methods=['GET'])
Expand Down
45 changes: 45 additions & 0 deletions gdrive_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from threading import Thread
from gDriveDownload import start, afterUrlAuth, callApi
import flask
import os
import random
import string
from werkzeug.utils import secure_filename
import sys

# A new Thread to call the Gdrive API after an Auth Response is returned to the user.
class getFileFromGdrive(Thread):
def __init__(self, params, userId, fileId, token):
Thread.__init__(self)
self.params, self.userId, self.fileId , self.token = params, userId, fileId, token

def run(self):
if(self.params["auth_url"] != None):
self.params["creds"] = afterUrlAuth(self.params["local_server"], self.params["flow"], self.params["wsgi_app"], self.userId)
call = callApi(self.params["creds"], self.fileId, self.token)
app.logger.info(call)

def gDriveGetFile(body):
token = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
token = secure_filename(token)
tmppath = os.path.join("/images/uploading/", token)
# regenerate if we happen to collide
while os.path.isfile(tmppath):
token = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
token = secure_filename(token)
tmppath = os.path.join("/images/uploading/", token)

try:
params = start(body['userId'])
except:
return flask.Response(json.dumps({'error': str(sys.exc_info()[0])}), status=400)
thread_a = getFileFromGdrive(params, body['userId'], body['fileId'], token)
thread_a.start()
return flask.Response(json.dumps({"authURL": params["auth_url"], "token": token}), status=200)

def checkDownloadStatus(body):
token = body['token']
path = app.config['TEMP_FOLDER']+'/'+token
if os.path.isfile(path):
return flask.Response(json.dumps({"downloadDone": True}), status=200)
return flask.Response(json.dumps({"downloadDone": False}), status=200)

0 comments on commit a5c7745

Please sign in to comment.