Dropper/src/dropper/routes/Routes.py

241 lines
7.6 KiB
Python

# Python imports
import os, hashlib, json, base64
from urllib.parse import unquote # For Python 2 use: from urlparse import unquote
# Flask imports
from flask import Flask, request, render_template, session, send_from_directory, url_for, redirect, escape
from flask_uploads import UploadSet, configure_uploads, ALL
from werkzeug.utils import secure_filename
# Application Imports
from .. import app, oidc, utils, ROOT_FILE_PTH
msgHandler = utils.MessageHandler()
isDebugging = app.config["DEBUG"]
SCRIPT_PTH = app.config["ROOT_FILE_PTH"]
HOME_PTH = app.config["HOME_PTH"]
NOTES_PTH = SCRIPT_PTH + '/static/' + "NOTES.txt"
UPLOADS_PTH = HOME_PTH + '/Downloads/'
files = UploadSet('files', ALL, default_dest=lambda x: UPLOADS_PTH)
list = [] # stores file name and hash
configure_uploads(app, files)
# Load notes...
notesListEncoded = []
notesListDecoded = []
with open(NOTES_PTH) as infile:
try:
notesJson = json.load(infile)
for entry in notesJson:
notesListEncoded.append(entry)
decodedStrPart = base64.urlsafe_b64decode(entry["string"].encode('utf-8')).decode('utf-8')
entryDecoded = unquote(decodedStrPart)
notesListDecoded.append({"id": entry["id"], "string": entryDecoded })
except Exception as e:
print(repr(e))
# Empty route used for url_for route
@app.route('/uploads', methods=['GET', 'POST'])
def uploads():
return ""
@app.route('/', methods=['GET', 'POST'])
def root():
# Get file list
del list[:]
files = os.listdir(UPLOADS_PTH)
for file in files:
fpth = UPLOADS_PTH + file
if not os.path.isdir(fpth): # ignore directories
hash = hash_file(fpth)
list.append([file, hash])
return render_template('index.html', files = list, notes = notesListDecoded)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and len(request.files) > 0:
for rFile in request.files:
try:
files.save(request.files[rFile])
except Exception as e:
msg = "[Error] Failed to Uploaded file(s)..."
return msgHandler.createMessageJSON("danger", msg)
msg = "[Success] Uploaded file(s)..."
return msgHandler.createMessageJSON("success", msg)
else:
msg = "Use POST request and send data...."
return msgHandler.createMessageJSON("danger", msg)
@app.route('/edit-file', methods=['GET', 'POST'])
def editFile():
hash = request.values['hash'].strip()
newName = request.values['newName'].strip()
if request.method == 'POST' and hash != '' and newName != '':
editedFile = False
fname = None
errorMsg = None
for file in list:
if file[1] == hash:
try:
oldPath = UPLOADS_PTH + file[0]
newPath = UPLOADS_PTH + newName
os.rename(oldPath, newPath)
editedFile = True
fname = file[0]
file[0] = newName
except Exception as e:
errorMsg = str(e)
print("Exception for editing action:")
print(repr(e))
if editedFile:
msg = "[Success] Renamed File!"
return msgHandler.createMessageJSON("success", msg)
else:
msg = "[Error] Failed to edit file name!"
return msgHandler.createMessageJSON("danger", msg)
else:
msg = "Use POST request and send data...."
return msgHandler.createMessageJSON("danger", msg)
@app.route('/delete-file', methods=['GET', 'POST'])
def deleteFile():
hash = request.values['hash'].strip()
if request.method == 'POST' and hash != '':
deletedFile = False
fname = None
errorMsg = None
for file in list:
if file[1] == hash:
try:
path = UPLOADS_PTH + file[0]
os.remove(path)
deletedFile = True
fname = file[0]
except Exception as e:
print("Exception for deletiong action:")
print(repr(e))
errorMsg = str(e)
if deletedFile:
msg = "[Success] Deleted file..."
return msgHandler.createMessageJSON("success", msg)
else:
msg = "[Error] Failed to delete file..."
return msgHandler.createMessageJSON("danger", msg)
else:
msg = "Use POST request and send data...."
return msgHandler.createMessageJSON("danger", msg)
@app.route('/delete-text', methods=['GET', 'POST'])
def deleteText():
if request.method == 'POST':
try:
noteIndex = int(request.values['noteIndex'].strip())
i = 0
for note in notesListDecoded:
if note["id"] == noteIndex:
notesListEncoded.pop(i)
notesListDecoded.pop(i)
i += 1
updateNotesFile()
msg = "[Success] Deleted entry..."
return msgHandler.createMessageJSON("success", msg)
except Exception as e:
print(repr(e))
msg = "[Error] Failed to delete entry!"
return msgHandler.createMessageJSON("danger", msg)
@app.route('/delete-all-text', methods=['GET', 'POST'])
def deleteAllText():
if request.method == 'POST':
try:
open(NOTES_PTH, 'w').close()
msg = "[Success] Deleted all enteries..."
return msgHandler.createMessageJSON("success", msg)
except Exception as e:
print(repr(e))
msg = "[Error] Failed to delete all enteries!"
return msgHandler.createMessageJSON("danger", msg)
@app.route('/add-note', methods=['GET', 'POST'])
def addNote():
text = request.values['entryText'].strip()
if request.method == 'POST' and text != '':
try:
encodedStr = text.strip()
decodedStrPart = base64.urlsafe_b64decode(encodedStr.encode('utf-8')).decode('utf-8')
decodedStr = unquote(decodedStrPart)
if isDebugging:
print("Encoded String:\n\t" + encodedStr)
print("Decoded String:\n\t" + decodedStr)
strIndex = len(notesListEncoded) + 1
notesListEncoded.append( {"id": strIndex, "string": encodedStr} )
notesListDecoded.append( {"id": strIndex, "string": decodedStr} )
updateNotesFile()
msg = "[Success] Added text entry!"
return msgHandler.createMessageJSON("success", msg)
except Exception as e:
print("Exception for file write action:")
print(repr(e))
msg = "[Error] A text entry write error occured!"
return msgHandler.createMessageJSON("danger", msg)
else:
msg = "Use POST request and send data...."
return msgHandler.createMessageJSON("danger", msg)
@app.route('/uploads/<id>')
def returnFile(id):
return send_from_directory(UPLOADS_PTH, id)
def updateNotesFile():
with open(NOTES_PTH, 'w') as file:
i = 1
objects = []
for note in notesListEncoded:
objects.append({"id": i, "string": note["string"] })
i += 1
file.write( json.dumps(objects, indent=4) )
file.close()
""""This function returns the SHA-1 hash of the file path/name passed into it"""
def hash_file(filename):
h = hashlib.sha1() # Make a sha1 hash object
h.update(filename.encode("utf-8")) # Encode string to byte string to update digest
return h.hexdigest() # Return digest string