Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Issue #11 #36

Merged
merged 7 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@ frontend/.env
*.pyc
*.DS_Store
backend/support/.DS_Store
credentials.json
backend/credentials.json
.DS_Store
frontend/.DS_Store
backend/support/.DS_Store
frontend/.DS_Store
124 changes: 11 additions & 113 deletions backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,17 @@
import os
import threading
import time
import uuid

from dotenv import load_dotenv
from flask import Flask, abort, after_this_request, jsonify, request, send_from_directory
from flask_cors import CORS, cross_origin
from flask_apscheduler import APScheduler
import yaml

from blackboard_scraper import BlackboardSession
from file_management import clean_up_session_files, delete_session_files, list_files_in_drive_folder, update_drive_directory, clean_up_docs_files
from blackboard_session import BlackboardSession
from file_management import clean_up_session_files, delete_session_files, list_files_in_drive_folder, update_drive_directory, clean_up_docs_files, remove_file_safely, is_file_valid, authorize_drive, get_session_files_path
from blackboard_session_manager import BlackboardSessionManager
import config

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

app = Flask(__name__)
cors = CORS(app)
scheduler = APScheduler()
Expand All @@ -31,18 +27,6 @@
load_dotenv()


def is_file_valid(file_path):
return os.path.isfile(file_path) and not os.path.islink(file_path)


def remove_file_safely(file_path):
try:
if is_file_valid(file_path):
os.remove(file_path)
except OSError as error:
app.logger.error(f"Error removing file: {error}")


@scheduler.task('interval', id='clean_up', seconds=600)
def clean_up_and_upload_files_to_google_drive(file_path=None):

Expand All @@ -58,92 +42,17 @@ def clean_up_and_upload_files_to_google_drive(file_path=None):
app.logger.error(f"Error during post-download operations: {e}")


def authorize_drive():
current_directory = os.getcwd()

if 'backend' in current_directory:
settings_path = 'settings.yaml'
elif 'Archive-Me' in current_directory:
settings_path = 'backend/settings.yaml'
else:
raise Exception("Unable to locate settings file.")

with open(settings_path, 'r') as file:
settings = yaml.safe_load(file)

settings['client_config']['client_id'] = os.environ.get('GOOGLE_CLIENT_ID')
settings['client_config']['client_secret'] = os.environ.get(
'GOOGLE_CLIENT_SECRET')

gauth = GoogleAuth(settings=settings)

if os.path.isfile("credentials.json"):
gauth.LoadCredentialsFile("credentials.json")
else:
gauth.LocalWebserverAuth()
gauth.SaveCredentialsFile("credentials.json")

if gauth.access_token_expired:
gauth.Refresh()
gauth.SaveCredentialsFile("credentials.json")

drive = GoogleDrive(gauth)
return drive


bb_sessions = {}


def get_bb_session(username):
if 'bb_sessions' not in bb_sessions:
bb_sessions['bb_sessions'] = {}

if username not in bb_sessions['bb_sessions']:
session_id = str(uuid.uuid4()) # Generate a unique session ID
bb_sessions['bb_sessions'][username] = session_id
# Store the session object
bb_sessions[session_id] = BlackboardSession()

return bb_sessions[bb_sessions['bb_sessions'][username]]


def put_bb_session(username, bb_session):
session_id = bb_sessions['bb_sessions'].get(username)
if session_id:
bb_sessions[session_id] = bb_session


def retrieve_bb_session(username):
if 'bb_sessions' not in bb_sessions:
bb_sessions['bb_sessions'] = {}

session_id = bb_sessions['bb_sessions'].get(username)
if session_id:
return bb_sessions.get(session_id)

return None


def delete_bb_session(username):
session_id = bb_sessions['bb_sessions'].get(username)
if session_id:
session_to_delete = bb_sessions.pop(session_id, None)
if session_to_delete:
del bb_sessions['bb_sessions'][username]
bb_session_manager = BlackboardSessionManager()


@scheduler.task('interval', id='delete_sessions', seconds=60)
def delete_inactive_bb_sessions(inactivity_threshold_seconds=180):
current_time = time.time()

# Check if 'bb_sessions' key exists
if 'bb_sessions' not in bb_sessions:
return # No sessions exist yet

# Collect usernames with inactive sessions for deletion
usernames_to_delete = []
for username, session_id in bb_sessions['bb_sessions'].items():
session = bb_sessions.get(session_id)
for username, session_id in bb_session_manager.user_session_map.items():
session = bb_session_manager.bb_sessions.get(session_id)
if session:
last_activity_time = session.last_activity_time
inactive_duration = current_time - last_activity_time
Expand All @@ -152,13 +61,10 @@ def delete_inactive_bb_sessions(inactivity_threshold_seconds=180):

# Delete collected usernames' sessions
for username in usernames_to_delete:
delete_bb_session(username)
bb_session_manager.delete_bb_session(username)

print("Deleting inactive sessions at:", time.time())

session_id = bb_sessions['bb_sessions'].get(username)
return bb_sessions.get(session_id)


@app.route('/')
@cross_origin()
Expand All @@ -178,14 +84,14 @@ def login():

try:
# Retrieve or create a session for the user
bb_session = get_bb_session(username)
bb_session = bb_session_manager.get_bb_session(username)
bb_session.username = username
bb_session.password = password

bb_session.login()
response = bb_session.get_response()
if response == 'Login successful.':
put_bb_session(username, bb_session)
bb_session_manager.put_bb_session(username, bb_session)
return jsonify({'message': 'Logged in successfully'})
else:
return jsonify({'error': response}), 401
Expand All @@ -200,7 +106,7 @@ def scrape():
return jsonify({'error': 'Username is required'}), 400

try:
bb_session = retrieve_bb_session(username)
bb_session = bb_session_manager.retrieve_bb_session(username)

if not bb_session:
return jsonify({'error': 'Session not found'}), 400
Expand Down Expand Up @@ -255,7 +161,7 @@ def list_directory(path):

if len(items) == 1:
item = items[0]
item_type, file_name, file_id = item[3], item[0], item[2]
item_type, file_name, file_id = item[1], item[0], item[2]

if item_type == 'FILE':
return handle_single_file(file_id, file_name)
Expand Down Expand Up @@ -285,14 +191,6 @@ def trigger_post_download_operations(response):
return send_from_directory(session_files_path, file_name, as_attachment=True)


def get_session_files_path():
current_dir = os.path.dirname(os.path.abspath(__file__))
if os.path.basename(current_dir) != 'backend':
return os.path.join(current_dir, 'backend', 'Session Files')
else:
return os.path.join(current_dir, 'Session Files')


@app.route('/browse')
def list_root_directory():
return list_directory(None)
Expand Down
File renamed without changes.
35 changes: 35 additions & 0 deletions backend/blackboard_session_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import uuid
from blackboard_session import BlackboardSession

class BlackboardSessionManager:
def __init__(self):
self.bb_sessions = {}
self.user_session_map = {}

def get_bb_session(self, username):
if username not in self.user_session_map:
session_id = str(uuid.uuid4()) # Generate a unique session ID
self.user_session_map[username] = session_id
# Store the session object
self.bb_sessions[session_id] = BlackboardSession()

return self.bb_sessions[self.user_session_map[username]]

def put_bb_session(self, username, bb_session):
session_id = self.user_session_map.get(username)
if session_id:
self.bb_sessions[session_id] = bb_session

def retrieve_bb_session(self, username):
session_id = self.user_session_map.get(username)
if session_id:
return self.bb_sessions.get(session_id)

return None

def delete_bb_session(self, username):
session_id = self.user_session_map.get(username)
if session_id:
session_to_delete = self.bb_sessions.pop(session_id, None)
if session_to_delete:
del self.user_session_map[username]
2 changes: 1 addition & 1 deletion backend/features/steps/blackboard_session_steps.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from behave import given, when, then
from blackboard_scraper import BlackboardSession
from blackboard_session import BlackboardSession
import os
from unittest.mock import patch
from dotenv import load_dotenv
Expand Down
53 changes: 52 additions & 1 deletion backend/file_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import shutil
from flask import app
import yaml
from pdf_compressor import compress
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
Expand Down Expand Up @@ -228,4 +229,54 @@

except Exception as e:
logging.error(f"Error in list_files_in_drive_folder: {e}")
return []
return []

def is_file_valid(file_path):
normalized_path = os.path.normpath(file_path)
return os.path.isfile(normalized_path) and not os.path.islink(normalized_path)
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
Dismissed Show dismissed Hide dismissed
Dismissed Show dismissed Hide dismissed

def remove_file_safely(file_path):
try:
if is_file_valid(file_path):
os.remove(file_path)
except OSError as error:
app.logger.error(f"Error removing file: {error}")

def authorize_drive():
current_directory = os.getcwd()

if 'backend' in current_directory:
settings_path = 'settings.yaml'
elif 'Archive-Me' in current_directory:
settings_path = 'backend/settings.yaml'
else:
raise Exception("Unable to locate settings file.")

with open(settings_path, 'r') as file:
settings = yaml.safe_load(file)

settings['client_config']['client_id'] = os.environ.get('GOOGLE_CLIENT_ID')
settings['client_config']['client_secret'] = os.environ.get(
'GOOGLE_CLIENT_SECRET')

gauth = GoogleAuth(settings=settings)

if os.path.isfile("credentials.json"):
gauth.LoadCredentialsFile("credentials.json")
else:
gauth.LocalWebserverAuth()
gauth.SaveCredentialsFile("credentials.json")

if gauth.access_token_expired:
gauth.Refresh()
gauth.SaveCredentialsFile("credentials.json")

drive = GoogleDrive(gauth)
return drive

def get_session_files_path():
current_dir = os.path.dirname(os.path.abspath(__file__))
if os.path.basename(current_dir) != 'backend':
return os.path.join(current_dir, 'backend', 'Session Files')
else:
return os.path.join(current_dir, 'Session Files')
2 changes: 1 addition & 1 deletion backend/test_blackboard_scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import unittest

from dotenv import load_dotenv
from blackboard_scraper import BlackboardSession
from blackboard_session import BlackboardSession
from unittest.mock import patch
from usernames import usernames

Expand Down
15 changes: 8 additions & 7 deletions frontend/static/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ $(function () {
const app = (() => {
let fileKeyGlobal = null;
let currentPath = '';

const apiUrl = getApiUrl();

const showLoadingScreen = () => {
Expand All @@ -104,10 +104,12 @@ const app = (() => {

const updateDownloadButtonVisibility = () => {
const downloadButton = document.getElementById("downloadButton");
if (fileKeyGlobal) {
downloadButton.style.display = "block"; // Show button if file_key is present
} else {
downloadButton.style.display = "none"; // Hide button otherwise
if (downloadButton) {
if (fileKeyGlobal) {
downloadButton.style.display = "block"; // Show button if file_key is present
} else {
downloadButton.style.display = "none"; // Hide button otherwise
}
}
};

Expand Down Expand Up @@ -290,13 +292,12 @@ const app = (() => {
if (downloadButton) {
downloadButton.addEventListener("click", downloadFile);
}
if (document.getElementById('directoryList')) {
if (window.location.pathname === '/directory/') {
updateDirectoryList('');
}

hideLoadingScreen();
updateDownloadButtonVisibility();
updateDirectoryList('');
};

return { init };
Expand Down
Loading
Loading