Files
littleprynter/src/web.py
T

132 lines
4.8 KiB
Python

"""
Manage all of the inputs from a web source
"""
import os
from werkzeug.utils import secure_filename
import uuid
from task import TextTask, ImageTask
class Web:
"""Web is the class that gets all of the information from web calls
( API and Web page ) and provides checks before sending stuff to printing"""
def __init__(self, app, print_queue):
super(Web).__init__()
self.print_queue = print_queue
self.app = app
def print_sms(self, texte, sign: str, do_cut: bool, many: int = 1) -> bool:
"""
Get text and a signature, prints the text and cuts after that.
"""
self.app.logger.debug("Printing : " + str(texte) + " from " + str(sign))
try:
# We create two new tasks and add them directly to the queue
# TODO: this might need to be improved because
# !! there is no garantee !! that both the SMS task and the Cut task
# are added back to back, another task could be
# inserted between the two.
for i in range(many):
sms = self.print_queue.enqueue(TextTask(content=texte, signature=sign, do_cut=do_cut))
self.app.logger.info("Added a SMS task at position %s, it should %scut", sms, "" if not do_cut else "not ")
self.app.logger.debug("%s", do_cut)
except Exception as e:
self.app.logger.error(e)
raise RuntimeError("Could not add SMS to queue, " + str(e)) from e
return True
def print_image(
self, image, sign: str, do_cut: bool, process_image: bool, many: int = 1
) -> bool:
"""
Get an image and a signature, prints the image and cuts after that.
"""
image_uuid = str(uuid.uuid4())
try:
file_uploaded = self.upload_file(image, image_uuid)
except Exception as e:
self.app.logger.error(e)
raise RuntimeError("Could not upload file : " + str(e)) from e
if file_uploaded:
self.app.logger.debug("File has been uploaded, printing...")
try:
for i in range(many):
img = self.print_queue.enqueue(
ImageTask(
os.path.join(
self.app.config["UPLOAD_FOLDER"],
secure_filename(str(file_uploaded.split("/").pop()))
),
signature=sign,
process=process_image,
task_id=str(uuid.uuid4()),
do_cut=do_cut
)
)
self.app.logger.info("Added a IMG task at position %s, it should %s cut", img, "not " if not do_cut else "")
except Exception as e:
raise RuntimeError("Could not add IMG to queue " + str(e)) from e
return True
# def login(self, username: str, password: str) -> bool:
# """Not implemented"""
# return
# def logout(self, username: str, password: str) -> bool:
# """Not implemented"""
# return
def allowed_file(self, filename) -> bool:
"""
Check if the file extension is allowed
"""
self.app.logger.debug("Checking if the file extension is allowed")
return (
"." in filename
and filename.rsplit(".", 1)[1].lower()
in self.app.config["ALLOWED_EXTENSIONS"]
)
def upload_file(self, image, image_uuid) -> bool:
"""
Save the file after executing checks on it
"""
self.app.logger.debug("Validating file")
if not image is None or not image == "":
if self.allowed_file(image.filename):
filename = secure_filename(image.filename)
extension = filename.split(".").pop()
self.app.logger.debug("File valid")
try:
image_uuid_path = os.path.join(self.app.config["UPLOAD_FOLDER"], image_uuid + "." + extension)
image.save(image_uuid_path)
except OSError as e:
self.app.logger.error("Could not save file %s", e)
raise RuntimeError(
"An OS error occured while uploading this file : " + str(e)
) from e
self.app.logger.debug("File saved to %s", image_uuid_path)
return image_uuid_path
self.app.logger.error("Could not save file because the filename is forbidden")
raise RuntimeError("This file type is forbidden.")
def get_queue_state(self):
"""Return current queue state"""
return self.print_queue.get_queue_state()
def get_queue_completed(self):
"""Return completed queue elements"""
return self.print_queue.get_queue_completed()