From 2a018ab863ae22e4c91183e4d870d92c0850e967 Mon Sep 17 00:00:00 2001 From: crunk Date: Tue, 28 May 2024 23:02:17 +0200 Subject: [PATCH] I love trying different formatters --- pyproject.toml | 2 +- verse/adminpage.py | 126 ++++---- verse/admintool.py | 54 ++-- verse/app.py | 72 ++--- verse/deploydb.py | 30 +- verse/describer/describe_files.py | 103 ++++--- verse/describer/forms/describe_files_form.py | 60 ++-- verse/distribusikan/distribusikan.py | 18 +- verse/distribusikan/distribusiselector.py | 244 ++++++++-------- verse/distribusikan/distribusisinfo.py | 54 ++-- verse/distribusikan/distribusiworkflow.py | 176 ++++++------ verse/distribusikan/editor.py | 284 +++++++++---------- verse/distribusikan/themeselector.py | 90 +++--- verse/distribusikan/upload.py | 136 ++++----- verse/distribusikan/uploadpage.py | 64 ++--- verse/file_crawler.py | 96 +++---- verse/forms/admindistribusiform.py | 24 +- verse/forms/adminuserform.py | 24 +- verse/forms/distribusiform.py | 4 +- verse/forms/editorform.py | 46 +-- verse/forms/forgotpasswordform.py | 12 +- verse/forms/loginform.py | 18 +- verse/forms/publicthemeform.py | 10 +- verse/forms/registerform.py | 52 ++-- verse/forms/resetpasswordform.py | 28 +- verse/forms/selectorform.py | 10 +- verse/forms/themeform.py | 20 +- verse/forms/uploadform.py | 134 ++++----- verse/migrations/env.py | 86 +++--- verse/models/distribusi_file_model.py | 22 +- verse/models/distribusi_model.py | 24 +- verse/models/user_model.py | 24 +- verse/start.py | 108 +++---- verse/statuspengguna/forgotpassword.py | 78 ++--- verse/statuspengguna/helper.py | 126 ++++---- verse/statuspengguna/loginuser.py | 70 ++--- verse/statuspengguna/registeruser.py | 110 +++---- verse/statuspengguna/resetpassword.py | 126 ++++---- 38 files changed, 1379 insertions(+), 1386 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 17f3822..665a9ba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" [tool.ruff.format] quote-style = "double" -indent-style = "tab" +indent-style = "space" docstring-code-format = true line-ending = "auto" skip-magic-trailing-comma = false diff --git a/verse/adminpage.py b/verse/adminpage.py index 9763e3e..0bb1c39 100644 --- a/verse/adminpage.py +++ b/verse/adminpage.py @@ -3,10 +3,10 @@ import shutil from flask import render_template from sqlalchemy.exc import ( - DatabaseError, - DataError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + InterfaceError, + InvalidRequestError, ) from app import db @@ -18,88 +18,88 @@ from models.user_model import User def AdminPage(): - adminuserform = AddUsersToForm(AdminUserForm()) - admindistribusiform = AddDistribusisToForm(AdminDistribusiForm()) - if admindistribusiform.validate_on_submit(): - DeleteDistribusis(admindistribusiform) + adminuserform = AddUsersToForm(AdminUserForm()) + admindistribusiform = AddDistribusisToForm(AdminDistribusiForm()) + if admindistribusiform.validate_on_submit(): + DeleteDistribusis(admindistribusiform) - if adminuserform.validate_on_submit(): - if adminuserform.delete.data: - DeleteUsers(adminuserform) + if adminuserform.validate_on_submit(): + if adminuserform.delete.data: + DeleteUsers(adminuserform) - template = render_template( - "admin.html", - adminuserform=adminuserform, - admindistribusiform=admindistribusiform, - ) - return template + template = render_template( + "admin.html", + adminuserform=adminuserform, + admindistribusiform=admindistribusiform, + ) + return template def DeleteUsers(adminuserform): - for userform in adminuserform: - if "user" in userform.id: - if userform.data: - useremail = userform.label.text - user = User.query.filter_by(email=useremail).first() - DeleteUserDistribusis(user) - DeleteUserFromDb(user) - userform.errors.append(f"User {useremail} deleted!") + for userform in adminuserform: + if "user" in userform.id: + if userform.data: + useremail = userform.label.text + user = User.query.filter_by(email=useremail).first() + DeleteUserDistribusis(user) + DeleteUserFromDb(user) + userform.errors.append(f"User {useremail} deleted!") def DeleteUserFromDb(user): - try: - db.session.delete(user) - db.session.commit() - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() + try: + db.session.delete(user) + db.session.commit() + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() def DeleteUserDistribusis(user): - distribusis = DistribusisInfo.getuserdistribusis(user.email) - for distribusi in distribusis: - DeleteDistribusiFiles(distribusi.distribusiname) - DeleteDistribusiFromDb(distribusi) + distribusis = DistribusisInfo.getuserdistribusis(user.email) + for distribusi in distribusis: + DeleteDistribusiFiles(distribusi.distribusiname) + DeleteDistribusiFromDb(distribusi) def DeleteDistribusis(admindistribusiform): - for distribusiform in admindistribusiform: - if "distribusi" in distribusiform.id: - if distribusiform.data: - distribusiname = distribusiform.label.text - distribusi = Distribusis.query.filter_by( - distribusiname=distribusiname - ).first() - DeleteDistribusiFromDb(distribusi) - DeleteDistribusiFiles(distribusiname) - distribusiform.errors.append("Deleted distribusi") + for distribusiform in admindistribusiform: + if "distribusi" in distribusiform.id: + if distribusiform.data: + distribusiname = distribusiform.label.text + distribusi = Distribusis.query.filter_by( + distribusiname=distribusiname + ).first() + DeleteDistribusiFromDb(distribusi) + DeleteDistribusiFiles(distribusiname) + distribusiform.errors.append("Deleted distribusi") def DeleteDistribusiFromDb(distribusi): - try: - db.session.delete(distribusi) - db.session.commit() - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() + try: + db.session.delete(distribusi) + db.session.commit() + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() def DeleteDistribusiFiles(distribusiname): - userfolder = os.path.join("stash", distribusiname) - if os.path.exists(userfolder): - shutil.rmtree(userfolder) - cssfolder = os.path.join("themes/userthemes", distribusiname) - if os.path.exists(cssfolder): - shutil.rmtree(cssfolder) + userfolder = os.path.join("stash", distribusiname) + if os.path.exists(userfolder): + shutil.rmtree(userfolder) + cssfolder = os.path.join("themes/userthemes", distribusiname) + if os.path.exists(cssfolder): + shutil.rmtree(cssfolder) def AddDistribusisToForm(admindistribusiform): - distribusis = DistribusisInfo.visibledistribusis() - admindistribusiform = AdminDistribusiForm.distribusi_list_form_builder( - distribusis - ) - return admindistribusiform + distribusis = DistribusisInfo.visibledistribusis() + admindistribusiform = AdminDistribusiForm.distribusi_list_form_builder( + distribusis + ) + return admindistribusiform def AddUsersToForm(adminuserform): - users = User.query.all() - adminuserform = AdminUserForm.user_list_form_builder(users) - return adminuserform + users = User.query.all() + adminuserform = AdminUserForm.user_list_form_builder(users) + return adminuserform diff --git a/verse/admintool.py b/verse/admintool.py index def02bd..c8ddac3 100644 --- a/verse/admintool.py +++ b/verse/admintool.py @@ -1,10 +1,10 @@ import sys from sqlalchemy.exc import ( - DatabaseError, - DataError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + InterfaceError, + InvalidRequestError, ) from app import create_app, db @@ -13,32 +13,32 @@ from models.user_model import User # noqa: F401 def admintool(): - """Admin CLI tool. To elevate a user to admin""" - app = create_app() - app.app_context().push() - elevateusertoadmin() + """Admin CLI tool. To elevate a user to admin""" + app = create_app() + app.app_context().push() + elevateusertoadmin() def elevateusertoadmin(): - """To elevates user of first command line argument to admin""" - user = User.query.filter_by(email=sys.argv[1]).first() - print(f"user {user.username} found with email {user.email}") - try: - user.admin = True - db.session.commit() - print(f"Account {user.email} succesfully made into an admin") - except InvalidRequestError: - db.session.rollback() - print("Something went wrong!") - except InterfaceError: - db.session.rollback() - print("Error connecting to the database") - except DataError: - db.session.rollback() - print("Invalid Entry") - except DatabaseError: - db.session.rollback() - print("Error connecting to the database") + """To elevates user of first command line argument to admin""" + user = User.query.filter_by(email=sys.argv[1]).first() + print(f"user {user.username} found with email {user.email}") + try: + user.admin = True + db.session.commit() + print(f"Account {user.email} succesfully made into an admin") + except InvalidRequestError: + db.session.rollback() + print("Something went wrong!") + except InterfaceError: + db.session.rollback() + print("Error connecting to the database") + except DataError: + db.session.rollback() + print("Invalid Entry") + except DatabaseError: + db.session.rollback() + print("Error connecting to the database") admintool() diff --git a/verse/app.py b/verse/app.py index 9aff866..529db20 100644 --- a/verse/app.py +++ b/verse/app.py @@ -16,56 +16,56 @@ login_manager = LoginManager() def create_app(): - APP.secret_key = os.urandom(24) - APP.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///distribusiverse.db" - APP.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True + APP.secret_key = os.urandom(24) + APP.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///distribusiverse.db" + APP.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True - APP.config["MAX_CONTENT_LENGTH"] = 1024 * 1024 * 1024 - APP.config["MAIL_SERVER"] = "mail.autonomic.zone" - APP.config["MAIL_PORT"] = 587 - APP.config["MAIL_USE_SSL"] = False - APP.config["MAIL_USE_TLS"] = True - APP.config["MAIL_USERNAME"] = "noreply@vvvvvvaria.org" + APP.config["MAX_CONTENT_LENGTH"] = 1024 * 1024 * 1024 + APP.config["MAIL_SERVER"] = "mail.autonomic.zone" + APP.config["MAIL_PORT"] = 587 + APP.config["MAIL_USE_SSL"] = False + APP.config["MAIL_USE_TLS"] = True + APP.config["MAIL_USERNAME"] = "noreply@vvvvvvaria.org" - login_manager.session_protection = "strong" - login_manager.login_view = "index" - login_manager.login_message_category = "info" + login_manager.session_protection = "strong" + login_manager.login_view = "index" + login_manager.login_message_category = "info" - csrf = CSRFProtect() + csrf = CSRFProtect() - APP.config["SECRET_KEY"] = os.urandom(24) - APP.config["UPLOAD_FOLDER"] = "tmpupload" - APP.config["PUBLIC_THEMES"] = "themes/publicthemes" + APP.config["SECRET_KEY"] = os.urandom(24) + APP.config["UPLOAD_FOLDER"] = "tmpupload" + APP.config["PUBLIC_THEMES"] = "themes/publicthemes" - # user settings_file - settings() + # user settings_file + settings() - csrf.init_app(APP) - login_manager.init_app(APP) - db.init_app(APP) - migrate.init_app(APP, db, render_as_batch=True) - bcrypt.init_app(APP) + csrf.init_app(APP) + login_manager.init_app(APP) + db.init_app(APP) + migrate.init_app(APP, db, render_as_batch=True) + bcrypt.init_app(APP) - @APP.context_processor - def inject_title(): - return dict(title=APP.config["title"]) + @APP.context_processor + def inject_title(): + return dict(title=APP.config["title"]) - return APP + return APP def settings(): - settings = settings_from_file() - APP.config.update(settings) - return APP + settings = settings_from_file() + APP.config.update(settings) + return APP def get_app(): - return APP + return APP def settings_from_file(): - if os.path.isfile("settings_development.toml"): - with open("settings_development.toml", "rb") as settings_file: - return tomllib.load(settings_file) - with open("settings.toml", "rb") as settings_file: - return tomllib.load(settings_file) + if os.path.isfile("settings_development.toml"): + with open("settings_development.toml", "rb") as settings_file: + return tomllib.load(settings_file) + with open("settings.toml", "rb") as settings_file: + return tomllib.load(settings_file) diff --git a/verse/deploydb.py b/verse/deploydb.py index 51d8f13..30a8364 100644 --- a/verse/deploydb.py +++ b/verse/deploydb.py @@ -1,23 +1,23 @@ def deploy(): - """Run deployment of database.""" - from flask_migrate import init, migrate, stamp, upgrade + """Run deployment of database.""" + from flask_migrate import init, migrate, stamp, upgrade - from app import create_app, db - from models.distribusi_model import Distribusis # noqa: F401 - from models.distribusi_file_model import DistribusiFiles # noqa: F401 + from app import create_app, db + from models.distribusi_model import Distribusis # noqa: F401 + from models.distribusi_file_model import DistribusiFiles # noqa: F401 - # This model is required for flask_migrate to make the table - from models.user_model import User # noqa: F401 + # This model is required for flask_migrate to make the table + from models.user_model import User # noqa: F401 - app = create_app() - app.app_context().push() - db.create_all() + app = create_app() + app.app_context().push() + db.create_all() - # migrate database to latest revision - init() - stamp() - migrate() - upgrade() + # migrate database to latest revision + init() + stamp() + migrate() + upgrade() deploy() diff --git a/verse/describer/describe_files.py b/verse/describer/describe_files.py index 31a8e79..b2c40d0 100644 --- a/verse/describer/describe_files.py +++ b/verse/describer/describe_files.py @@ -1,9 +1,9 @@ from flask import ( - Blueprint, - render_template, - redirect, - url_for, - send_from_directory, + Blueprint, + render_template, + redirect, + url_for, + send_from_directory, ) from flask_login import current_user, login_required from models.distribusi_model import Distribusis @@ -11,70 +11,63 @@ from models.distribusi_file_model import DistribusiFiles from describer.forms.describe_files_form import DescribeFilesForm describer = Blueprint( - "describer", - __name__, - template_folder="templates/describe_files", - static_folder="static", + "describer", + __name__, + template_folder="templates/describe_files", + static_folder="static", ) @describer.route("/") @login_required def show_distribusi_files(distribusiname): - if not current_user.is_authenticated: - return redirect(url_for("index")) - distribusi = Distribusis.query.filter_by( - distribusiname=distribusiname - ).first() - distribusi_file_forms = get_distribusi_file_forms(distribusi.id) - return render_template( - "describe.html", - distribusi_file_forms=distribusi_file_forms, - ) + if not current_user.is_authenticated: + return redirect(url_for("index")) + distribusi = Distribusis.query.filter_by( + distribusiname=distribusiname + ).first() + distribusi_file_forms = get_distribusi_file_forms(distribusi.id) + return render_template( + "describe.html", + distribusi_file_forms=distribusi_file_forms, + ) @describer.route("/describe_file/", methods=["POST"]) @login_required def describe_file(file_id): - distribusi_file = DistribusiFiles.query.filter_by(id=file_id).first() - describe_form = DescribeFilesForm( - distribusi_file.id, distribusi_file.path, distribusi_file.type - ) - print( - f"file: {describe_form.file_path} description: {describe_form.description.data}" - ) - print( - f"file: {describe_form.file_path} searchtags: {describe_form.searchtags.data}" - ) - print( - f"file: {describe_form.file_path} alttext: {describe_form.alttext.data}" - ) - distribusi = Distribusis.query.filter_by( - id=distribusi_file.distribusi - ).first() - return redirect( - url_for( - "describer.show_distribusi_files", - distribusiname=distribusi.distribusiname, - ) - ) + distribusi_file = DistribusiFiles.query.filter_by(id=file_id).first() + describe_form = DescribeFilesForm( + distribusi_file.id, distribusi_file.path, distribusi_file.type + ) + + distribusi = Distribusis.query.filter_by( + id=distribusi_file.distribusi + ).first() + return redirect( + url_for( + "describer.show_distribusi_files", + distribusiname=distribusi.distribusiname, + ) + ) + @describer.route("/stash/") def send_stash_file(path): - return send_from_directory("stash", path) + return send_from_directory("stash", path) def get_distribusi_file_forms(distribusi_id): - distribusi_file_forms = {} - distribusi_files = DistribusiFiles.query.filter_by( - distribusi=distribusi_id - ).all() - for distribusi_file in distribusi_files: - describe_form = DescribeFilesForm( - distribusi_file.id, distribusi_file.path, distribusi_file.type - ) - describe_form.description.data = distribusi_file.description - describe_form.alttext.data = distribusi_file.alttext - describe_form.searchtags.data = distribusi_file.tags - distribusi_file_forms[distribusi_file.id] = describe_form - return distribusi_file_forms + distribusi_file_forms = {} + distribusi_files = DistribusiFiles.query.filter_by( + distribusi=distribusi_id + ).all() + for distribusi_file in distribusi_files: + describe_form = DescribeFilesForm( + distribusi_file.id, distribusi_file.path, distribusi_file.type + ) + describe_form.description.data = distribusi_file.description + describe_form.alttext.data = distribusi_file.alttext + describe_form.searchtags.data = distribusi_file.tags + distribusi_file_forms[distribusi_file.id] = describe_form + return distribusi_file_forms diff --git a/verse/describer/forms/describe_files_form.py b/verse/describer/forms/describe_files_form.py index 517b818..6155be4 100644 --- a/verse/describer/forms/describe_files_form.py +++ b/verse/describer/forms/describe_files_form.py @@ -7,38 +7,38 @@ from wtforms.widgets import TextArea class DescribeFilesForm(FlaskForm): - """DescribeFileForm selection form.""" + """DescribeFileForm selection form.""" - alttext = StringField( - "Alt-text for this file:", - validators=[ - Length(3, 255), - ], - ) - searchtags = StringField( - "Add search tags, seperated by commas. No need for the '#' sign:", - validators=[ - Length(3, 500), - ], - ) - description = StringField( - "Description of this file:", - validators=[ - Length(3, 4096), - ], - widget=TextArea(), - ) - save = SubmitField("Save") + alttext = StringField( + "Alt-text for this file:", + validators=[ + Length(3, 255), + ], + ) + searchtags = StringField( + "Add search tags, seperated by commas. No need for the '#' sign:", + validators=[ + Length(3, 500), + ], + ) + description = StringField( + "Description of this file:", + validators=[ + Length(3, 4096), + ], + widget=TextArea(), + ) + save = SubmitField("Save") - def __init__(self, id, file_path=None, type=None): - super(DescribeFilesForm, self).__init__() - self.id = id - self.file_path = file_path - self.type = type - self.alttext.id = f"alttext-{id}" - self.searchtags.id = f"searchtags-{id}" - self.description.id = f"description-{id}" - self.save.id = f"save-{id}" + def __init__(self, id, file_path=None, type=None): + super(DescribeFilesForm, self).__init__() + self.id = id + self.file_path = file_path + self.type = type + self.alttext.id = f"alttext-{id}" + self.searchtags.id = f"searchtags-{id}" + self.description.id = f"description-{id}" + self.save.id = f"save-{id}" # def StringFieldWithId(form_name, **kwargs): diff --git a/verse/distribusikan/distribusikan.py b/verse/distribusikan/distribusikan.py index 8b5308d..444cb96 100644 --- a/verse/distribusikan/distribusikan.py +++ b/verse/distribusikan/distribusikan.py @@ -10,38 +10,38 @@ from distribusikan.themeselector import ThemeSelector from distribusikan.uploadpage import UploadPage distribusikan = Blueprint( - "distribusikan", - __name__, - template_folder="templates/distribusikan", - static_folder="static", + "distribusikan", + __name__, + template_folder="templates/distribusikan", + static_folder="static", ) @distribusikan.route("/distribusi", methods=["GET", "POST"]) @login_required def distribusi(): - return DistribusiWorkflow() + return DistribusiWorkflow() @distribusikan.route("/upload", methods=["POST"]) @login_required def upload(): - return UploadPage() + return UploadPage() @distribusikan.route("/theme", methods=["GET", "POST"]) @login_required def theme(): - return ThemeSelector() + return ThemeSelector() @distribusikan.route("/editor", methods=["GET", "POST"]) @login_required def editor(): - return Editor() + return Editor() @distribusikan.route("/selector", methods=["GET", "POST"]) @login_required def selector(): - return DistribusiSelector() + return DistribusiSelector() diff --git a/verse/distribusikan/distribusiselector.py b/verse/distribusikan/distribusiselector.py index b035953..4201129 100644 --- a/verse/distribusikan/distribusiselector.py +++ b/verse/distribusikan/distribusiselector.py @@ -4,10 +4,10 @@ import shutil from flask import flash, render_template, redirect, url_for from flask_login import current_user from sqlalchemy.exc import ( - DatabaseError, - DataError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + InterfaceError, + InvalidRequestError, ) from app import db @@ -25,148 +25,148 @@ from statuspengguna.helper import UserHelper def DistribusiSelector(): - uploadform = UploadForm() - selectorform = SelectorForm() - selectorform.distribusis.choices = DistribusisInfo.userdistribusinames() - current_distribusi = UserHelper.current_distribusi() - if selectorform.validate_on_submit(): - if selectorform.new.data: - SelectNewDistribusi() - if selectorform.describe.data: - return SelectDescribeDistribusi(selectorform.distribusis.data) - if selectorform.delete.data: - selectorform = DeleteDistribusi(selectorform.distribusis.data) - selectorform.distribusis.choices = ( - DistribusisInfo.userdistribusinames() - ) - if selectorform.update.data: - SelectUpdateDistribusi(selectorform.distribusis.data) - current_distribusi = UserHelper.current_distribusi() - uploadform = AutoFillInUploadForm(uploadform, current_distribusi) - - return RenderDistribusiTemplate( - selectorform, uploadform, current_distribusi - ) + uploadform = UploadForm() + selectorform = SelectorForm() + selectorform.distribusis.choices = DistribusisInfo.userdistribusinames() + current_distribusi = UserHelper.current_distribusi() + if selectorform.validate_on_submit(): + if selectorform.new.data: + SelectNewDistribusi() + if selectorform.describe.data: + return SelectDescribeDistribusi(selectorform.distribusis.data) + if selectorform.delete.data: + selectorform = DeleteDistribusi(selectorform.distribusis.data) + selectorform.distribusis.choices = ( + DistribusisInfo.userdistribusinames() + ) + if selectorform.update.data: + SelectUpdateDistribusi(selectorform.distribusis.data) + current_distribusi = UserHelper.current_distribusi() + uploadform = AutoFillInUploadForm(uploadform, current_distribusi) + + return RenderDistribusiTemplate( + selectorform, uploadform, current_distribusi + ) def AutoFillInUploadForm(uploadform, current_distribusi): - distribusi = Distribusis.query.filter_by( - distribusiname=current_distribusi - ).first() - uploadform.sitename.data = distribusi.distribusiname - uploadform.sitename.render_kw = {"readonly": True} - uploadform.category.data = distribusi.category - uploadform.year.data = distribusi.year - uploadform.tags.data = distribusi.tags - return uploadform + distribusi = Distribusis.query.filter_by( + distribusiname=current_distribusi + ).first() + uploadform.sitename.data = distribusi.distribusiname + uploadform.sitename.render_kw = {"readonly": True} + uploadform.category.data = distribusi.category + uploadform.year.data = distribusi.year + uploadform.tags.data = distribusi.tags + return uploadform def SelectNewDistribusi(): - print("make a new distribusi") - SelectCurrentDistribusi("new") + print("make a new distribusi") + SelectCurrentDistribusi("new") def SelectDescribeDistribusi(distribusiname): - return redirect( - url_for( - "describer.show_distribusi_files", - distribusiname=distribusiname, - ) - ) + return redirect( + url_for( + "describer.show_distribusi_files", + distribusiname=distribusiname, + ) + ) def SelectUpdateDistribusi(distribusiname): - print(f"Update this distribusi {distribusiname}") - SelectCurrentDistribusi(distribusiname) + print(f"Update this distribusi {distribusiname}") + SelectCurrentDistribusi(distribusiname) def DeleteDistribusi(distribusiname): - print(f"delete this distribusi {distribusiname}") - selectorform = SelectorForm() - try: - user = User.query.filter_by(email=current_user.email).first() - distribusi = Distribusis.query.filter_by( - distribusiname=distribusiname - ).first() - if distribusi.userid is user.id: - db.session.delete(distribusi) - db.session.commit() - userfolder = os.path.join("stash", distribusi.distribusiname) - if os.path.exists(userfolder): - shutil.rmtree(userfolder) - cssfolder = os.path.join( - "themes/userthemes", distribusi.distribusiname - ) - if os.path.exists(cssfolder): - shutil.rmtree(cssfolder) - if distribusi.publictheme is not None: - publicthemefolder = os.path.join( - "themes/publicthemes", distribusi.distribusiname - ) - if os.path.exists(publicthemefolder): - shutil.rmtree(publicthemefolder) - # SelectField error is list is a tuple?? why?? - # selectorform.distribusis.errors.append("Distribusi deleted!") - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() - # selectorform.distribusis.errors.append("Unknown error occured!") - flash("An error occured !", "danger") - return selectorform + print(f"delete this distribusi {distribusiname}") + selectorform = SelectorForm() + try: + user = User.query.filter_by(email=current_user.email).first() + distribusi = Distribusis.query.filter_by( + distribusiname=distribusiname + ).first() + if distribusi.userid is user.id: + db.session.delete(distribusi) + db.session.commit() + userfolder = os.path.join("stash", distribusi.distribusiname) + if os.path.exists(userfolder): + shutil.rmtree(userfolder) + cssfolder = os.path.join( + "themes/userthemes", distribusi.distribusiname + ) + if os.path.exists(cssfolder): + shutil.rmtree(cssfolder) + if distribusi.publictheme is not None: + publicthemefolder = os.path.join( + "themes/publicthemes", distribusi.distribusiname + ) + if os.path.exists(publicthemefolder): + shutil.rmtree(publicthemefolder) + # SelectField error is list is a tuple?? why?? + # selectorform.distribusis.errors.append("Distribusi deleted!") + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() + # selectorform.distribusis.errors.append("Unknown error occured!") + flash("An error occured !", "danger") + return selectorform def SelectCurrentDistribusi(distribusiname): - if not current_user.is_authenticated: - return - user = User.query.filter_by(email=current_user.email).first() - try: - user.currentdistribusi = distribusiname - db.session.commit() - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() - flash("An error occured !", "danger") + if not current_user.is_authenticated: + return + user = User.query.filter_by(email=current_user.email).first() + try: + user.currentdistribusi = distribusiname + db.session.commit() + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() + flash("An error occured !", "danger") def DistribusiSelected(): - user = User.query.filter_by(email=current_user.email).first() - if user.currentdistribusi is None: - return False - return True + user = User.query.filter_by(email=current_user.email).first() + if user.currentdistribusi is None: + return False + return True def SelectorVisible(): - has_distribusi = UserHelper.has_distribusi() - distribusi_selected = DistribusiSelected() - if distribusi_selected: - return False - if not has_distribusi: - return False - return True + has_distribusi = UserHelper.has_distribusi() + distribusi_selected = DistribusiSelected() + if distribusi_selected: + return False + if not has_distribusi: + return False + return True def RenderDistribusiTemplate(selectorform, uploadform, current_distribusi): - distribusiform = DistribusiForm() - themeform = ThemeForm() - publicthemeform = PublicThemeForm() - publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() - files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) - distribusi_live = UserHelper.is_distribusi_live(current_distribusi) - - # because the user has chosen to update his distribusi, we assume - # no selected css. - css_selected = False - selectorvisible = SelectorVisible() - limit_reached = UserHelper.distribusi_limit_reached() - template = render_template( - "distribusi.html", - uploadform=uploadform, - distribusiform=distribusiform, - themeform=themeform, - publicthemeform=publicthemeform, - selectorform=selectorform, - files_uploaded=files_uploaded, - distribusi_live=distribusi_live, - css_selected=css_selected, - selectorvisible=selectorvisible, - limit_reached=limit_reached, - ) - return template + distribusiform = DistribusiForm() + themeform = ThemeForm() + publicthemeform = PublicThemeForm() + publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() + files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) + distribusi_live = UserHelper.is_distribusi_live(current_distribusi) + + # because the user has chosen to update his distribusi, we assume + # no selected css. + css_selected = False + selectorvisible = SelectorVisible() + limit_reached = UserHelper.distribusi_limit_reached() + template = render_template( + "distribusi.html", + uploadform=uploadform, + distribusiform=distribusiform, + themeform=themeform, + publicthemeform=publicthemeform, + selectorform=selectorform, + files_uploaded=files_uploaded, + distribusi_live=distribusi_live, + css_selected=css_selected, + selectorvisible=selectorvisible, + limit_reached=limit_reached, + ) + return template diff --git a/verse/distribusikan/distribusisinfo.py b/verse/distribusikan/distribusisinfo.py index 9021c3a..19ef284 100644 --- a/verse/distribusikan/distribusisinfo.py +++ b/verse/distribusikan/distribusisinfo.py @@ -5,34 +5,34 @@ from models.user_model import User class DistribusisInfo: - def userdistribusinames(): - distribusinames = [] - user = User.query.filter_by(email=current_user.email).first() - for distribusi in Distribusis.query.filter_by(userid=user.id).all(): - distribusinames.append(distribusi.distribusiname) - return distribusinames + def userdistribusinames(): + distribusinames = [] + user = User.query.filter_by(email=current_user.email).first() + for distribusi in Distribusis.query.filter_by(userid=user.id).all(): + distribusinames.append(distribusi.distribusiname) + return distribusinames - def publicthemes(): - publicthemes = [] - distribusis = Distribusis.query.filter( - Distribusis.publictheme.isnot(None) - ).all() - for distribusi in distribusis: - user = User.query.filter_by(id=distribusi.userid).first() - publictheme = ( - f"{distribusi.distribusiname}/{distribusi.publictheme}", - f"""{distribusi.publictheme} used in {distribusi.distribusiname} + def publicthemes(): + publicthemes = [] + distribusis = Distribusis.query.filter( + Distribusis.publictheme.isnot(None) + ).all() + for distribusi in distribusis: + user = User.query.filter_by(id=distribusi.userid).first() + publictheme = ( + f"{distribusi.distribusiname}/{distribusi.publictheme}", + f"""{distribusi.publictheme} used in {distribusi.distribusiname} made by {user.username}""", - ) - publicthemes.append(publictheme) - return publicthemes + ) + publicthemes.append(publictheme) + return publicthemes - def visibledistribusis(): - distribusis = Distribusis.query.filter( - Distribusis.visible.isnot(False) - ).all() - return distribusis + def visibledistribusis(): + distribusis = Distribusis.query.filter( + Distribusis.visible.isnot(False) + ).all() + return distribusis - def getuserdistribusis(useremail): - user = User.query.filter_by(email=useremail).first() - return Distribusis.query.filter_by(userid=user.id).all() + def getuserdistribusis(useremail): + user = User.query.filter_by(email=useremail).first() + return Distribusis.query.filter_by(userid=user.id).all() diff --git a/verse/distribusikan/distribusiworkflow.py b/verse/distribusikan/distribusiworkflow.py index 7b37a5e..4e3a376 100644 --- a/verse/distribusikan/distribusiworkflow.py +++ b/verse/distribusikan/distribusiworkflow.py @@ -8,10 +8,10 @@ from distribusi.distribusi import distribusify from flask import flash, redirect, render_template, url_for from flask_login import current_user from sqlalchemy.exc import ( - DatabaseError, - DataError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + InterfaceError, + InvalidRequestError, ) from app import db @@ -32,112 +32,112 @@ from statuspengguna.helper import UserHelper def DistribusiWorkflow(): - distribusiform = DistribusiForm() - current_distribusi = UserHelper.current_distribusi() - user = User.query.filter_by(email=current_user.email).first() - distribusi = Distribusis.query.filter_by( - distribusiname=current_distribusi - ).first() - - if distribusiform.validate_on_submit(): - userfolder = os.path.join("stash", distribusi.distribusiname) - cssfile = GetCssFile(distribusi) - UnzipDistribusiFiles(distribusi, userfolder) - CleanUpDistribusiFiles(userfolder) - RunDistribusi(userfolder, cssfile) - SetDistribusiToVisible(distribusi, user) - DeleteCssFile(cssfile) - return redirect(url_for("index")) - - return RenderDistribusiTemplate(distribusiform, current_distribusi) + distribusiform = DistribusiForm() + current_distribusi = UserHelper.current_distribusi() + user = User.query.filter_by(email=current_user.email).first() + distribusi = Distribusis.query.filter_by( + distribusiname=current_distribusi + ).first() + + if distribusiform.validate_on_submit(): + userfolder = os.path.join("stash", distribusi.distribusiname) + cssfile = GetCssFile(distribusi) + UnzipDistribusiFiles(distribusi, userfolder) + CleanUpDistribusiFiles(userfolder) + RunDistribusi(userfolder, cssfile) + SetDistribusiToVisible(distribusi, user) + DeleteCssFile(cssfile) + return redirect(url_for("index")) + + return RenderDistribusiTemplate(distribusiform, current_distribusi) def UnzipDistribusiFiles(distribusi, userfolder): - zipfilename = "{}.zip".format(distribusi.distribusiname) - unzipfile = os.path.join(userfolder, zipfilename) + zipfilename = "{}.zip".format(distribusi.distribusiname) + unzipfile = os.path.join(userfolder, zipfilename) - if os.path.exists(unzipfile): - with zipfile.ZipFile(unzipfile, "r") as zip_ref: - zip_ref.extractall(userfolder) - # after extracting all files remove zip file. - if os.path.exists(unzipfile): - os.remove(os.path.join(userfolder, zipfilename)) + if os.path.exists(unzipfile): + with zipfile.ZipFile(unzipfile, "r") as zip_ref: + zip_ref.extractall(userfolder) + # after extracting all files remove zip file. + if os.path.exists(unzipfile): + os.remove(os.path.join(userfolder, zipfilename)) def CleanUpDistribusiFiles(userfolder): - if os.path.exists(userfolder): - RemoveMacFolders(userfolder) + if os.path.exists(userfolder): + RemoveMacFolders(userfolder) def RemoveMacFolders(path): - for filename in os.listdir(path): - fullpath = os.path.join(path, filename) - if filename.startswith("."): - if os.path.isdir(fullpath): - shutil.rmtree(fullpath) - else: - os.remove(fullpath) - if filename == "__MACOSX": - shutil.rmtree(fullpath) - if os.path.isdir(fullpath): - RemoveMacFolders(fullpath) + for filename in os.listdir(path): + fullpath = os.path.join(path, filename) + if filename.startswith("."): + if os.path.isdir(fullpath): + shutil.rmtree(fullpath) + else: + os.remove(fullpath) + if filename == "__MACOSX": + shutil.rmtree(fullpath) + if os.path.isdir(fullpath): + RemoveMacFolders(fullpath) def GetCssFile(distribusi): - cssfile = "" - cssfolder = os.path.join("themes/userthemes", distribusi.distribusiname) - if os.path.exists(cssfolder): - for filename in os.listdir(cssfolder): - if filename.endswith(".css"): - cssfile = os.path.join(cssfolder, filename) - return cssfile + cssfile = "" + cssfolder = os.path.join("themes/userthemes", distribusi.distribusiname) + if os.path.exists(cssfolder): + for filename in os.listdir(cssfolder): + if filename.endswith(".css"): + cssfile = os.path.join(cssfolder, filename) + return cssfile def RunDistribusi(userfolder, cssfile): - parser = build_argparser() - args = parser.parse_args(["-t", "--menu-with-index", "-s", cssfile]) - distribusify(args, userfolder) + parser = build_argparser() + args = parser.parse_args(["-t", "--menu-with-index", "-s", cssfile]) + distribusify(args, userfolder) def SetDistribusiToVisible(distribusi, user): - try: - distribusi.visible = True - user.currentdistribusi = None - db.session.commit() - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() - flash("Unknown error occured!") + try: + distribusi.visible = True + user.currentdistribusi = None + db.session.commit() + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() + flash("Unknown error occured!") def DeleteCssFile(cssfile): - if os.path.exists(cssfile): - os.remove(cssfile) + if os.path.exists(cssfile): + os.remove(cssfile) def RenderDistribusiTemplate(distribusiform, current_distribusi): - uploadform = UploadForm() - themeform = ThemeForm() - publicthemeform = PublicThemeForm() - publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() - selectorform = SelectorForm() - selectorform.distribusis.choices = DistribusisInfo.userdistribusinames() - selectorvisible = SelectorVisible() - - files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) - distribusi_live = UserHelper.is_distribusi_live(current_distribusi) - css_selected = UserHelper.is_css_selected(current_distribusi) - limit_reached = UserHelper.distribusi_limit_reached() - template = render_template( - "distribusi.html", - uploadform=uploadform, - distribusiform=distribusiform, - themeform=themeform, - publicthemeform=publicthemeform, - selectorform=selectorform, - files_uploaded=files_uploaded, - distribusi_live=distribusi_live, - css_selected=css_selected, - selectorvisible=selectorvisible, - limit_reached=limit_reached, - ) - return template + uploadform = UploadForm() + themeform = ThemeForm() + publicthemeform = PublicThemeForm() + publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() + selectorform = SelectorForm() + selectorform.distribusis.choices = DistribusisInfo.userdistribusinames() + selectorvisible = SelectorVisible() + + files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) + distribusi_live = UserHelper.is_distribusi_live(current_distribusi) + css_selected = UserHelper.is_css_selected(current_distribusi) + limit_reached = UserHelper.distribusi_limit_reached() + template = render_template( + "distribusi.html", + uploadform=uploadform, + distribusiform=distribusiform, + themeform=themeform, + publicthemeform=publicthemeform, + selectorform=selectorform, + files_uploaded=files_uploaded, + distribusi_live=distribusi_live, + css_selected=css_selected, + selectorvisible=selectorvisible, + limit_reached=limit_reached, + ) + return template diff --git a/verse/distribusikan/editor.py b/verse/distribusikan/editor.py index 74e3a21..88e63c2 100644 --- a/verse/distribusikan/editor.py +++ b/verse/distribusikan/editor.py @@ -5,10 +5,10 @@ import bleach from bleach_allowlist import all_styles from flask import render_template from sqlalchemy.exc import ( - DatabaseError, - DataError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + InterfaceError, + InvalidRequestError, ) from werkzeug.utils import secure_filename @@ -25,175 +25,175 @@ from statuspengguna.helper import UserHelper def Editor(): - editorform = EditorForm() - current_distribusi = UserHelper.current_distribusi() - if editorform.validate_on_submit(): - ValidateEditCssForm(editorform, current_distribusi) - return RenderDistribusiTemplate(current_distribusi) + editorform = EditorForm() + current_distribusi = UserHelper.current_distribusi() + if editorform.validate_on_submit(): + ValidateEditCssForm(editorform, current_distribusi) + return RenderDistribusiTemplate(current_distribusi) - return RenderEditorTemplate(editorform, current_distribusi) + return RenderEditorTemplate(editorform, current_distribusi) def ValidateEditCssForm(editorform, current_distribusi): - newcssfolder = os.path.join("themes/userthemes", current_distribusi) - if os.path.exists(newcssfolder): - shutil.rmtree(newcssfolder) - - publicfolder = os.path.join("themes/publicthemes", current_distribusi) - if os.path.exists(publicfolder): - shutil.rmtree(publicfolder) - - if editorform.public.data: - MakePublicTheme(editorform, current_distribusi) - if editorform.cssfile.data: - SaveUploadCssFile(editorform, publicfolder) - CopyPublicToUserFolder(editorform, publicfolder, newcssfolder) - return - else: - WriteCssToFile(editorform, publicfolder) - - if editorform.cssfile.data: - SaveUploadCssFile(editorform, newcssfolder) - return - if editorform.cssname.data: - WriteCssToFile(editorform, newcssfolder) + newcssfolder = os.path.join("themes/userthemes", current_distribusi) + if os.path.exists(newcssfolder): + shutil.rmtree(newcssfolder) + + publicfolder = os.path.join("themes/publicthemes", current_distribusi) + if os.path.exists(publicfolder): + shutil.rmtree(publicfolder) + + if editorform.public.data: + MakePublicTheme(editorform, current_distribusi) + if editorform.cssfile.data: + SaveUploadCssFile(editorform, publicfolder) + CopyPublicToUserFolder(editorform, publicfolder, newcssfolder) + return + else: + WriteCssToFile(editorform, publicfolder) + + if editorform.cssfile.data: + SaveUploadCssFile(editorform, newcssfolder) + return + if editorform.cssname.data: + WriteCssToFile(editorform, newcssfolder) def SaveUploadCssFile(editorform, newcssfolder): - if not os.path.exists(newcssfolder): - os.mkdir(newcssfolder) - cssfile = editorform.cssfile.data - cssfilename = f"{secure_filename(editorform.cssname.data)}.css" - cssfile.save(os.path.join(newcssfolder, cssfilename)) - openfile = open(os.path.join(newcssfolder, cssfilename), "r") - cleancss = bleach.clean(openfile.read(), all_styles) - cleancss = cleancss.replace(">", ">") - openfile.close() - cleanfile = open(os.path.join(newcssfolder, cssfilename), "w") - cleanfile.write(cleancss) - cleanfile.close() + if not os.path.exists(newcssfolder): + os.mkdir(newcssfolder) + cssfile = editorform.cssfile.data + cssfilename = f"{secure_filename(editorform.cssname.data)}.css" + cssfile.save(os.path.join(newcssfolder, cssfilename)) + openfile = open(os.path.join(newcssfolder, cssfilename), "r") + cleancss = bleach.clean(openfile.read(), all_styles) + cleancss = cleancss.replace(">", ">") + openfile.close() + cleanfile = open(os.path.join(newcssfolder, cssfilename), "w") + cleanfile.write(cleancss) + cleanfile.close() def WriteCssToFile(editorform, newcssfolder): - if not os.path.exists(newcssfolder): - os.mkdir(newcssfolder) + if not os.path.exists(newcssfolder): + os.mkdir(newcssfolder) - cssfilename = f"{secure_filename(editorform.cssname.data)}.css" - cleancss = bleach.clean(editorform.css.data, all_styles) - cleancss = cleancss.replace(">", ">") - with open(os.path.join(newcssfolder, cssfilename), "w") as cssfile: - cssfile.write(cleancss) - cssfile.close + cssfilename = f"{secure_filename(editorform.cssname.data)}.css" + cleancss = bleach.clean(editorform.css.data, all_styles) + cleancss = cleancss.replace(">", ">") + with open(os.path.join(newcssfolder, cssfilename), "w") as cssfile: + cssfile.write(cleancss) + cssfile.close def CopyPublicToUserFolder(editorform, publicfolder, newcssfolder): - if not os.path.exists(newcssfolder): - os.mkdir(newcssfolder) - copycssfile = os.path.join( - publicfolder, f"{secure_filename(editorform.cssname.data)}.css" - ) - print(f"copying file: {copycssfile}") - print(f"to folder: {newcssfolder}") - shutil.copy(copycssfile, newcssfolder) + if not os.path.exists(newcssfolder): + os.mkdir(newcssfolder) + copycssfile = os.path.join( + publicfolder, f"{secure_filename(editorform.cssname.data)}.css" + ) + print(f"copying file: {copycssfile}") + print(f"to folder: {newcssfolder}") + shutil.copy(copycssfile, newcssfolder) def MakePublicTheme(editorform, current_distribusi): - try: - distribusi = Distribusis.query.filter_by( - distribusiname=current_distribusi - ).first() - distribusi.publictheme = secure_filename(editorform.cssname.data) - db.session.commit() - - except InvalidRequestError: - db.session.rollback() - editorform.public.errors.append("Something went wrong!") - except DataError: - db.session.rollback() - editorform.public.errors.append("Invalid Entry") - except InterfaceError: - db.session.rollback() - editorform.public.errors.append("Error connecting to the database") - except DatabaseError: - db.session.rollback() - editorform.public.errors.append("Error connecting to the database") + try: + distribusi = Distribusis.query.filter_by( + distribusiname=current_distribusi + ).first() + distribusi.publictheme = secure_filename(editorform.cssname.data) + db.session.commit() + + except InvalidRequestError: + db.session.rollback() + editorform.public.errors.append("Something went wrong!") + except DataError: + db.session.rollback() + editorform.public.errors.append("Invalid Entry") + except InterfaceError: + db.session.rollback() + editorform.public.errors.append("Error connecting to the database") + except DatabaseError: + db.session.rollback() + editorform.public.errors.append("Error connecting to the database") def RenderDistribusiTemplate(current_distribusi): - uploadform = UploadForm() - distribusiform = DistribusiForm() - themeform = ThemeForm() - publicthemeform = PublicThemeForm() - publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() - selectorform = SelectorForm() - - files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) - distribusi_live = UserHelper.is_distribusi_live(current_distribusi) - css_selected = True - selectorvisible = False - limit_reached = UserHelper.distribusi_limit_reached() - template = render_template( - "distribusi.html", - uploadform=uploadform, - distribusiform=distribusiform, - themeform=themeform, - publicthemeform=publicthemeform, - selectorform=selectorform, - files_uploaded=files_uploaded, - distribusi_live=distribusi_live, - css_selected=css_selected, - selectorvisible=selectorvisible, - limit_reached=limit_reached, - ) - return template + uploadform = UploadForm() + distribusiform = DistribusiForm() + themeform = ThemeForm() + publicthemeform = PublicThemeForm() + publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() + selectorform = SelectorForm() + + files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) + distribusi_live = UserHelper.is_distribusi_live(current_distribusi) + css_selected = True + selectorvisible = False + limit_reached = UserHelper.distribusi_limit_reached() + template = render_template( + "distribusi.html", + uploadform=uploadform, + distribusiform=distribusiform, + themeform=themeform, + publicthemeform=publicthemeform, + selectorform=selectorform, + files_uploaded=files_uploaded, + distribusi_live=distribusi_live, + css_selected=css_selected, + selectorvisible=selectorvisible, + limit_reached=limit_reached, + ) + return template def RenderEditorTemplate(editorform, current_distribusi): - htmlplaceholder = HtmlPlaceholder() + htmlplaceholder = HtmlPlaceholder() - cssplaceholder = CssPlaceholder(current_distribusi) - editorform.css.data = cssplaceholder + cssplaceholder = CssPlaceholder(current_distribusi) + editorform.css.data = cssplaceholder - files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) - distribusi_live = UserHelper.is_distribusi_live(current_distribusi) - template = render_template( - "editor.html", - files_uploaded=files_uploaded, - distribusi_live=distribusi_live, - editorform=editorform, - htmlplaceholder=htmlplaceholder, - ) - return template + files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) + distribusi_live = UserHelper.is_distribusi_live(current_distribusi) + template = render_template( + "editor.html", + files_uploaded=files_uploaded, + distribusi_live=distribusi_live, + editorform=editorform, + htmlplaceholder=htmlplaceholder, + ) + return template def CssPlaceholder(current_distribusi): - cssplaceholder = "Try out your CSS here" - distribusi = Distribusis.query.filter_by( - distribusiname=current_distribusi - ).first() - if distribusi is not None and distribusi.publictheme is not None: - cssplaceholder = GetPublicCssFile(distribusi) - else: - with open("themes/editor/placeholder.css") as f: - cssplaceholder = f.read() - return cssplaceholder + cssplaceholder = "Try out your CSS here" + distribusi = Distribusis.query.filter_by( + distribusiname=current_distribusi + ).first() + if distribusi is not None and distribusi.publictheme is not None: + cssplaceholder = GetPublicCssFile(distribusi) + else: + with open("themes/editor/placeholder.css") as f: + cssplaceholder = f.read() + return cssplaceholder def HtmlPlaceholder(): - htmlplaceholder = "Write some test HTML here" - with open("themes/editor/placeholder.html") as f: - htmlplaceholder = f.read() - return htmlplaceholder + htmlplaceholder = "Write some test HTML here" + with open("themes/editor/placeholder.html") as f: + htmlplaceholder = f.read() + return htmlplaceholder def GetPublicCssFile(distribusi): - cssplaceholder = "" - publicthemefolder = os.path.join( - "themes/publicthemes", distribusi.distribusiname - ) - for filename in os.listdir(publicthemefolder): - if filename.endswith(".css"): - cssfile = os.path.join(publicthemefolder, filename) - with open(cssfile) as f: - cssplaceholder = f.read() - return cssplaceholder + cssplaceholder = "" + publicthemefolder = os.path.join( + "themes/publicthemes", distribusi.distribusiname + ) + for filename in os.listdir(publicthemefolder): + if filename.endswith(".css"): + cssfile = os.path.join(publicthemefolder, filename) + with open(cssfile) as f: + cssplaceholder = f.read() + return cssplaceholder diff --git a/verse/distribusikan/themeselector.py b/verse/distribusikan/themeselector.py index 67237de..96b2d8a 100644 --- a/verse/distribusikan/themeselector.py +++ b/verse/distribusikan/themeselector.py @@ -13,55 +13,55 @@ from statuspengguna.helper import UserHelper def ThemeSelector(): - themeform = ThemeForm() - publicthemeform = PublicThemeForm() - publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() - current_distribusi = UserHelper.current_distribusi() - if themeform.validate_on_submit(): - copycssfile = os.path.join( - "themes", - f"{themeform.theme.data}.css", - ) - MoveCssToUserFolder(current_distribusi, copycssfile) - if publicthemeform.validate_on_submit(): - copycssfile = os.path.join( - "themes/publicthemes/", - f"{publicthemeform.publicthemes.data}.css", - ) - MoveCssToUserFolder(current_distribusi, copycssfile) - return RenderDistribusiTemplate( - themeform, publicthemeform, current_distribusi - ) + themeform = ThemeForm() + publicthemeform = PublicThemeForm() + publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() + current_distribusi = UserHelper.current_distribusi() + if themeform.validate_on_submit(): + copycssfile = os.path.join( + "themes", + f"{themeform.theme.data}.css", + ) + MoveCssToUserFolder(current_distribusi, copycssfile) + if publicthemeform.validate_on_submit(): + copycssfile = os.path.join( + "themes/publicthemes/", + f"{publicthemeform.publicthemes.data}.css", + ) + MoveCssToUserFolder(current_distribusi, copycssfile) + return RenderDistribusiTemplate( + themeform, publicthemeform, current_distribusi + ) def MoveCssToUserFolder(current_distribusi, copycssfile): - newcssfolder = os.path.join("themes/userthemes", current_distribusi) - if not os.path.exists(newcssfolder): - os.mkdir(newcssfolder) - shutil.copy(copycssfile, newcssfolder) + newcssfolder = os.path.join("themes/userthemes", current_distribusi) + if not os.path.exists(newcssfolder): + os.mkdir(newcssfolder) + shutil.copy(copycssfile, newcssfolder) def RenderDistribusiTemplate(themeform, publicthemeform, current_distribusi): - uploadform = UploadForm() - distribusiform = DistribusiForm() - selectorform = SelectorForm() + uploadform = UploadForm() + distribusiform = DistribusiForm() + selectorform = SelectorForm() - files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) - distribusi_live = UserHelper.is_distribusi_live(current_distribusi) - css_selected = UserHelper.is_css_selected(current_distribusi) - selectorvisible = False - limit_reached = UserHelper.distribusi_limit_reached() - template = render_template( - "distribusi.html", - uploadform=uploadform, - distribusiform=distribusiform, - themeform=themeform, - publicthemeform=publicthemeform, - selectorform=selectorform, - files_uploaded=files_uploaded, - distribusi_live=distribusi_live, - css_selected=css_selected, - selectorvisible=selectorvisible, - limit_reached=limit_reached, - ) - return template + files_uploaded = UserHelper.is_zip_uploaded(current_distribusi) + distribusi_live = UserHelper.is_distribusi_live(current_distribusi) + css_selected = UserHelper.is_css_selected(current_distribusi) + selectorvisible = False + limit_reached = UserHelper.distribusi_limit_reached() + template = render_template( + "distribusi.html", + uploadform=uploadform, + distribusiform=distribusiform, + themeform=themeform, + publicthemeform=publicthemeform, + selectorform=selectorform, + files_uploaded=files_uploaded, + distribusi_live=distribusi_live, + css_selected=css_selected, + selectorvisible=selectorvisible, + limit_reached=limit_reached, + ) + return template diff --git a/verse/distribusikan/upload.py b/verse/distribusikan/upload.py index 9ba4bae..83110b5 100644 --- a/verse/distribusikan/upload.py +++ b/verse/distribusikan/upload.py @@ -4,11 +4,11 @@ import shutil from flask import flash from flask_login import current_user from sqlalchemy.exc import ( - DatabaseError, - DataError, - IntegrityError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + IntegrityError, + InterfaceError, + InvalidRequestError, ) from app import db @@ -20,76 +20,76 @@ from statuspengguna.helper import UserHelper def UploadNewDistribusi(uploadfolder): - uploadform = UploadForm() - if uploadform.validate_on_submit(): - user = User.query.filter_by(email=current_user.email).first() - try: - newdistribusi = Distribusis( - distribusiname=uploadform.sitename.data, - userid=user.id, - category=uploadform.category.data, - year=uploadform.year.data, - tags=uploadform.tags.data, - ) - user.currentdistribusi = uploadform.sitename.data - db.session.add(newdistribusi) - db.session.commit() - except IntegrityError: - db.session.rollback() - uploadform.sitename.errors.append( - "distribusi name already exists!" - ) - flash("distribusi name already exists!", "warning") - return uploadform - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() - uploadform.sitename.errors.append("Something went wrong!") - flash("Something went wrong!", "danger") - return uploadform - SelectCurrentDistribusi(newdistribusi.distribusiname) - zipfilename = "{}.zip".format(newdistribusi.distribusiname) - zipfile = uploadform.zipfile.data - zipfile.save(os.path.join(uploadfolder, zipfilename)) + uploadform = UploadForm() + if uploadform.validate_on_submit(): + user = User.query.filter_by(email=current_user.email).first() + try: + newdistribusi = Distribusis( + distribusiname=uploadform.sitename.data, + userid=user.id, + category=uploadform.category.data, + year=uploadform.year.data, + tags=uploadform.tags.data, + ) + user.currentdistribusi = uploadform.sitename.data + db.session.add(newdistribusi) + db.session.commit() + except IntegrityError: + db.session.rollback() + uploadform.sitename.errors.append( + "distribusi name already exists!" + ) + flash("distribusi name already exists!", "warning") + return uploadform + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() + uploadform.sitename.errors.append("Something went wrong!") + flash("Something went wrong!", "danger") + return uploadform + SelectCurrentDistribusi(newdistribusi.distribusiname) + zipfilename = "{}.zip".format(newdistribusi.distribusiname) + zipfile = uploadform.zipfile.data + zipfile.save(os.path.join(uploadfolder, zipfilename)) - newuserfolder = os.path.join("stash", newdistribusi.distribusiname) - if not os.path.exists(newuserfolder): - os.mkdir(newuserfolder) + newuserfolder = os.path.join("stash", newdistribusi.distribusiname) + if not os.path.exists(newuserfolder): + os.mkdir(newuserfolder) - copyzipfile = os.path.join(uploadfolder, zipfilename) - shutil.copy(copyzipfile, newuserfolder) - os.remove(os.path.join(uploadfolder, zipfilename)) + copyzipfile = os.path.join(uploadfolder, zipfilename) + shutil.copy(copyzipfile, newuserfolder) + os.remove(os.path.join(uploadfolder, zipfilename)) - return uploadform + return uploadform def UploadUpdatedFiles(uploadfolder): - uploadform = UploadForm() - if uploadform.validate_on_submit(): - try: - current_distribusi = UserHelper.current_distribusi() - distribusi = Distribusis.query.filter_by( - distribusiname=current_distribusi - ).first() - distribusi.category = uploadform.category.data - distribusi.year = uploadform.year.data - distribusi.tags = uploadform.tags.data - distribusi.visible = False - db.session.commit() - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() - uploadform.sitename.errors.append("Something went wrong!") + uploadform = UploadForm() + if uploadform.validate_on_submit(): + try: + current_distribusi = UserHelper.current_distribusi() + distribusi = Distribusis.query.filter_by( + distribusiname=current_distribusi + ).first() + distribusi.category = uploadform.category.data + distribusi.year = uploadform.year.data + distribusi.tags = uploadform.tags.data + distribusi.visible = False + db.session.commit() + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() + uploadform.sitename.errors.append("Something went wrong!") - zipfilename = "{}.zip".format(distribusi.distribusiname) - zipfile = uploadform.zipfile.data - zipfile.save(os.path.join(uploadfolder, zipfilename)) + zipfilename = "{}.zip".format(distribusi.distribusiname) + zipfile = uploadform.zipfile.data + zipfile.save(os.path.join(uploadfolder, zipfilename)) - newuserfolder = os.path.join("stash", distribusi.distribusiname) - if os.path.exists(newuserfolder): - shutil.rmtree(newuserfolder) - os.mkdir(newuserfolder) + newuserfolder = os.path.join("stash", distribusi.distribusiname) + if os.path.exists(newuserfolder): + shutil.rmtree(newuserfolder) + os.mkdir(newuserfolder) - copyzipfile = os.path.join(uploadfolder, zipfilename) - shutil.copy(copyzipfile, newuserfolder) - os.remove(os.path.join(uploadfolder, zipfilename)) + copyzipfile = os.path.join(uploadfolder, zipfilename) + shutil.copy(copyzipfile, newuserfolder) + os.remove(os.path.join(uploadfolder, zipfilename)) - return uploadform + return uploadform diff --git a/verse/distribusikan/uploadpage.py b/verse/distribusikan/uploadpage.py index 347518c..a8f2510 100644 --- a/verse/distribusikan/uploadpage.py +++ b/verse/distribusikan/uploadpage.py @@ -14,37 +14,37 @@ from statuspengguna.helper import UserHelper def UploadPage(): - "render upload page section of distribusi workflow" - uploadfolder = APP.config["UPLOAD_FOLDER"] - distribusiform = DistribusiForm() - themeform = ThemeForm() - publicthemeform = PublicThemeForm() - publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() - selectorform = SelectorForm() - selectorform.distribusis.choices = DistribusisInfo.userdistribusinames() - selectorvisible = SelectorVisible() + "render upload page section of distribusi workflow" + uploadfolder = APP.config["UPLOAD_FOLDER"] + distribusiform = DistribusiForm() + themeform = ThemeForm() + publicthemeform = PublicThemeForm() + publicthemeform.publicthemes.choices = DistribusisInfo.publicthemes() + selectorform = SelectorForm() + selectorform.distribusis.choices = DistribusisInfo.userdistribusinames() + selectorvisible = SelectorVisible() - current_distribusi = UserHelper.current_distribusi() - if current_distribusi == "new" or UserHelper.has_distribusi() is False: - uploadform = UploadNewDistribusi(uploadfolder) - else: - uploadform = UploadUpdatedFiles(uploadfolder) + current_distribusi = UserHelper.current_distribusi() + if current_distribusi == "new" or UserHelper.has_distribusi() is False: + uploadform = UploadNewDistribusi(uploadfolder) + else: + uploadform = UploadUpdatedFiles(uploadfolder) - files_uploaded = UserHelper.is_zip_uploaded(uploadform.sitename.data) - distribusi_live = UserHelper.is_distribusi_live(current_distribusi) - css_selected = UserHelper.is_css_selected(current_distribusi) - limit_reached = UserHelper.distribusi_limit_reached() - template = render_template( - "distribusi.html", - uploadform=uploadform, - distribusiform=distribusiform, - themeform=themeform, - publicthemeform=publicthemeform, - selectorform=selectorform, - files_uploaded=files_uploaded, - distribusi_live=distribusi_live, - css_selected=css_selected, - selectorvisible=selectorvisible, - limit_reached=limit_reached, - ) - return template + files_uploaded = UserHelper.is_zip_uploaded(uploadform.sitename.data) + distribusi_live = UserHelper.is_distribusi_live(current_distribusi) + css_selected = UserHelper.is_css_selected(current_distribusi) + limit_reached = UserHelper.distribusi_limit_reached() + template = render_template( + "distribusi.html", + uploadform=uploadform, + distribusiform=distribusiform, + themeform=themeform, + publicthemeform=publicthemeform, + selectorform=selectorform, + files_uploaded=files_uploaded, + distribusi_live=distribusi_live, + css_selected=css_selected, + selectorvisible=selectorvisible, + limit_reached=limit_reached, + ) + return template diff --git a/verse/file_crawler.py b/verse/file_crawler.py index d378f85..ff57d14 100644 --- a/verse/file_crawler.py +++ b/verse/file_crawler.py @@ -6,68 +6,68 @@ from models.distribusi_model import Distribusis from models.distribusi_file_model import DistribusiFiles from app import create_app, get_app, db from sqlalchemy.exc import ( - DatabaseError, - DataError, - IntegrityError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + IntegrityError, + InterfaceError, + InvalidRequestError, ) MIME_TYPE = magic.Magic(mime=True) def _distribusi_file_with_type(distribusi, full_path): - mime = MIME_TYPE.from_file(full_path) - type_, subtype = mime.split("/") - if type_ in FILE_TYPES: - _add_distribusi_file_to_db(distribusi, full_path, type_) + mime = MIME_TYPE.from_file(full_path) + type_, subtype = mime.split("/") + if type_ in FILE_TYPES: + _add_distribusi_file_to_db(distribusi, full_path, type_) def _get_distribusi_from_path(path): - distribusi = Distribusis.query.filter_by(distribusiname=path).first() - return distribusi + distribusi = Distribusis.query.filter_by(distribusiname=path).first() + return distribusi def _add_distribusi_file_to_db(distribusi, full_path, type): - app = get_app() - print(f"adding file to database: {full_path} type: {type}") - try: - new_distribusi_file = DistribusiFiles( - path=full_path, - type=type, - distribusi=distribusi.id, - ) - db.session.add(new_distribusi_file) - db.session.commit() - return - except InvalidRequestError: - db.session.rollback() - app.logger.error("Something went wrong!") - except IntegrityError: - db.session.rollback() - app.logger.error("File %s already exists!", full_path) - except DataError: - db.session.rollback() - app.logger.error("%s Invalid Entry", full_path) - except InterfaceError: - db.session.rollback() - app.logger.error("Error connecting to the database") - except DatabaseError: - db.session.rollback() - app.logger.error("Error connecting to the database") + app = get_app() + print(f"adding file to database: {full_path} type: {type}") + try: + new_distribusi_file = DistribusiFiles( + path=full_path, + type=type, + distribusi=distribusi.id, + ) + db.session.add(new_distribusi_file) + db.session.commit() + return + except InvalidRequestError: + db.session.rollback() + app.logger.error("Something went wrong!") + except IntegrityError: + db.session.rollback() + app.logger.error("File %s already exists!", full_path) + except DataError: + db.session.rollback() + app.logger.error("%s Invalid Entry", full_path) + except InterfaceError: + db.session.rollback() + app.logger.error("Error connecting to the database") + except DatabaseError: + db.session.rollback() + app.logger.error("Error connecting to the database") def add_distribusi_files(path): - app = create_app() - with app.app_context(): - distribusi = _get_distribusi_from_path(path) - path = os.path.join("stash", path) - for root, dirs, files in os.walk(path, topdown=True): - files = list(filter(lambda f: not f.startswith("."), files)) - files = list(filter(lambda f: not f.endswith(".html"), files)) - for file in files: - full_path = os.path.join(root, file) - _distribusi_file_with_type(distribusi, full_path) + app = create_app() + with app.app_context(): + distribusi = _get_distribusi_from_path(path) + path = os.path.join("stash", path) + for root, dirs, files in os.walk(path, topdown=True): + files = list(filter(lambda f: not f.startswith("."), files)) + files = list(filter(lambda f: not f.endswith(".html"), files)) + for file in files: + full_path = os.path.join(root, file) + _distribusi_file_with_type(distribusi, full_path) -add_distribusi_files("2018-02-16-Extratonality") +add_distribusi_files("2018-12-WttF-Mastodon-and-the-Fediverse") diff --git a/verse/forms/admindistribusiform.py b/verse/forms/admindistribusiform.py index 38daf8f..f00f3db 100644 --- a/verse/forms/admindistribusiform.py +++ b/verse/forms/admindistribusiform.py @@ -5,19 +5,19 @@ from wtforms import BooleanField, SubmitField class AdminDistribusiForm(FlaskForm): - """Admin Distribusi form.""" + """Admin Distribusi form.""" - delete = SubmitField("Delete") + delete = SubmitField("Delete") - def distribusi_list_form_builder(distribusis): - class DistribusiListForm(AdminDistribusiForm): - pass + def distribusi_list_form_builder(distribusis): + class DistribusiListForm(AdminDistribusiForm): + pass - for i, distribusi in enumerate(distribusis): - setattr( - DistribusiListForm, - f"distribusi_{i}", - BooleanField(label=distribusi.distribusiname), - ) + for i, distribusi in enumerate(distribusis): + setattr( + DistribusiListForm, + f"distribusi_{i}", + BooleanField(label=distribusi.distribusiname), + ) - return DistribusiListForm() + return DistribusiListForm() diff --git a/verse/forms/adminuserform.py b/verse/forms/adminuserform.py index 93e2d25..aeda2e4 100644 --- a/verse/forms/adminuserform.py +++ b/verse/forms/adminuserform.py @@ -5,19 +5,19 @@ from wtforms import BooleanField, SubmitField class AdminUserForm(FlaskForm): - """Admin Userform form.""" + """Admin Userform form.""" - def user_list_form_builder(users): - class UserListForm(AdminUserForm): - pass + def user_list_form_builder(users): + class UserListForm(AdminUserForm): + pass - for i, user in enumerate(users): - setattr( - UserListForm, - f"user_{i}", - BooleanField(label=user.email), - ) + for i, user in enumerate(users): + setattr( + UserListForm, + f"user_{i}", + BooleanField(label=user.email), + ) - return UserListForm() + return UserListForm() - delete = SubmitField("Delete") + delete = SubmitField("Delete") diff --git a/verse/forms/distribusiform.py b/verse/forms/distribusiform.py index bd0fb71..6373162 100644 --- a/verse/forms/distribusiform.py +++ b/verse/forms/distribusiform.py @@ -3,6 +3,6 @@ from wtforms import SubmitField class DistribusiForm(FlaskForm): - """Distribusi class to launch your distribusi website""" + """Distribusi class to launch your distribusi website""" - submit = SubmitField("Distribusi!") + submit = SubmitField("Distribusi!") diff --git a/verse/forms/editorform.py b/verse/forms/editorform.py index 1db3e0d..284082d 100644 --- a/verse/forms/editorform.py +++ b/verse/forms/editorform.py @@ -3,33 +3,33 @@ from flask_wtf import FlaskForm from flask_wtf.file import FileAllowed, FileField, FileSize from wtforms import ( - BooleanField, - StringField, - SubmitField, - TextAreaField, - validators, + BooleanField, + StringField, + SubmitField, + TextAreaField, + validators, ) from wtforms.validators import Length class EditorForm(FlaskForm): - """Css editor form class.""" + """Css editor form class.""" - cssname = StringField( - "fill in a name for your css style:", - validators=[validators.InputRequired(), Length(5, 200)], - ) - cssfile = FileField( - "(Optional) upload your own css file:", - validators=[ - FileAllowed(["css"], "css files only!"), - FileSize( - max_size=10485760, - message="css file size must be smaller than 10MB", - ), - ], - ) - css = TextAreaField() - public = BooleanField("Make your CSS public so others can use it") + cssname = StringField( + "fill in a name for your css style:", + validators=[validators.InputRequired(), Length(5, 200)], + ) + cssfile = FileField( + "(Optional) upload your own css file:", + validators=[ + FileAllowed(["css"], "css files only!"), + FileSize( + max_size=10485760, + message="css file size must be smaller than 10MB", + ), + ], + ) + css = TextAreaField() + public = BooleanField("Make your CSS public so others can use it") - submit = SubmitField("Save") + submit = SubmitField("Save") diff --git a/verse/forms/forgotpasswordform.py b/verse/forms/forgotpasswordform.py index 9e416bb..385327d 100644 --- a/verse/forms/forgotpasswordform.py +++ b/verse/forms/forgotpasswordform.py @@ -6,10 +6,10 @@ from wtforms.validators import Email, Length class ForgotPasswordForm(FlaskForm): - """Forgotten password distribusiverse form class.""" + """Forgotten password distribusiverse form class.""" - email = StringField( - "Email address:", - validators=[validators.InputRequired(), Email(), Length(6, 64)], - ) - submit = SubmitField("Send email") + email = StringField( + "Email address:", + validators=[validators.InputRequired(), Email(), Length(6, 64)], + ) + submit = SubmitField("Send email") diff --git a/verse/forms/loginform.py b/verse/forms/loginform.py index 61830a2..b446850 100644 --- a/verse/forms/loginform.py +++ b/verse/forms/loginform.py @@ -6,13 +6,13 @@ from wtforms.validators import Email, Length class LoginForm(FlaskForm): - """Login distribusiverse form class.""" + """Login distribusiverse form class.""" - email = StringField( - "Email address:", - validators=[validators.InputRequired(), Email(), Length(6, 64)], - ) - password = PasswordField( - "Password:", validators=[validators.InputRequired()] - ) - submit = SubmitField("Sign In") + email = StringField( + "Email address:", + validators=[validators.InputRequired(), Email(), Length(6, 64)], + ) + password = PasswordField( + "Password:", validators=[validators.InputRequired()] + ) + submit = SubmitField("Sign In") diff --git a/verse/forms/publicthemeform.py b/verse/forms/publicthemeform.py index 46a2505..103fbeb 100644 --- a/verse/forms/publicthemeform.py +++ b/verse/forms/publicthemeform.py @@ -5,10 +5,10 @@ from wtforms import RadioField, SubmitField class PublicThemeForm(FlaskForm): - """PublicTheme selection form.""" + """PublicTheme selection form.""" - publicthemes = RadioField( - "Public themes from other distribusi-verse users:" - ) + publicthemes = RadioField( + "Public themes from other distribusi-verse users:" + ) - save = SubmitField("Save") + save = SubmitField("Save") diff --git a/verse/forms/registerform.py b/verse/forms/registerform.py index b300293..89c42d6 100644 --- a/verse/forms/registerform.py +++ b/verse/forms/registerform.py @@ -6,33 +6,33 @@ from wtforms.validators import Email, EqualTo, Length class RegisterForm(FlaskForm): - """Register for distribusi-verse form class""" + """Register for distribusi-verse form class""" - username = StringField( - "Username:", - validators=[validators.InputRequired(), Length(3, 150)], - ) + username = StringField( + "Username:", + validators=[validators.InputRequired(), Length(3, 150)], + ) - email = StringField( - "Email address:", - validators=[ - validators.InputRequired(), - Email(), - Length(6, 128), - ], - ) + email = StringField( + "Email address:", + validators=[ + validators.InputRequired(), + Email(), + Length(6, 128), + ], + ) - password = PasswordField( - "New password:", - validators=[validators.InputRequired(), Length(12, 72)], - ) + password = PasswordField( + "New password:", + validators=[validators.InputRequired(), Length(12, 72)], + ) - confirmpassword = PasswordField( - "Confirm your password:", - validators=[ - validators.InputRequired(), - Length(12, 72), - EqualTo("password", message="Passwords must match !"), - ], - ) - submit = SubmitField("Register to Distribusi-verse") + confirmpassword = PasswordField( + "Confirm your password:", + validators=[ + validators.InputRequired(), + Length(12, 72), + EqualTo("password", message="Passwords must match !"), + ], + ) + submit = SubmitField("Register to Distribusi-verse") diff --git a/verse/forms/resetpasswordform.py b/verse/forms/resetpasswordform.py index a3cbe34..481cb02 100644 --- a/verse/forms/resetpasswordform.py +++ b/verse/forms/resetpasswordform.py @@ -6,18 +6,18 @@ from wtforms.validators import EqualTo, Length class ResetPasswordForm(FlaskForm): - """ResetPassword for distribusi-verse form class""" + """ResetPassword for distribusi-verse form class""" - password = PasswordField( - "New password:", - validators=[validators.InputRequired(), Length(12, 72)], - ) - confirmpassword = PasswordField( - "Confirm your password:", - validators=[ - validators.InputRequired(), - Length(12, 72), - EqualTo("password", message="Passwords must match !"), - ], - ) - submit = SubmitField("Reset your password") + password = PasswordField( + "New password:", + validators=[validators.InputRequired(), Length(12, 72)], + ) + confirmpassword = PasswordField( + "Confirm your password:", + validators=[ + validators.InputRequired(), + Length(12, 72), + EqualTo("password", message="Passwords must match !"), + ], + ) + submit = SubmitField("Reset your password") diff --git a/verse/forms/selectorform.py b/verse/forms/selectorform.py index ecdba27..f2f9530 100644 --- a/verse/forms/selectorform.py +++ b/verse/forms/selectorform.py @@ -3,12 +3,12 @@ from wtforms import SelectField, SubmitField class SelectorForm(FlaskForm): - distribusis = SelectField("Your existing distribusi:") + distribusis = SelectField("Your existing distribusi:") - new = SubmitField("new") + new = SubmitField("new") - update = SubmitField("update") + update = SubmitField("update") - describe = SubmitField("describe") + describe = SubmitField("describe") - delete = SubmitField("delete") + delete = SubmitField("delete") diff --git a/verse/forms/themeform.py b/verse/forms/themeform.py index ca2b7bb..a1c3e02 100644 --- a/verse/forms/themeform.py +++ b/verse/forms/themeform.py @@ -5,15 +5,15 @@ from wtforms import RadioField, SubmitField class ThemeForm(FlaskForm): - """Basic theme selection form.""" + """Basic theme selection form.""" - theme = RadioField( - "Select your theme:", - choices=[ - ("hacking", "Hackers (black background, green text)"), - ("peachsunset", "Peach sunset (single column)"), - ("masonry", "Masonry (white background, grid layout)"), - ], - ) + theme = RadioField( + "Select your theme:", + choices=[ + ("hacking", "Hackers (black background, green text)"), + ("peachsunset", "Peach sunset (single column)"), + ("masonry", "Masonry (white background, grid layout)"), + ], + ) - save = SubmitField("Save") + save = SubmitField("Save") diff --git a/verse/forms/uploadform.py b/verse/forms/uploadform.py index 3f26824..90dcd70 100644 --- a/verse/forms/uploadform.py +++ b/verse/forms/uploadform.py @@ -1,85 +1,85 @@ from flask_wtf import FlaskForm from flask_wtf.file import FileAllowed, FileField, FileRequired, FileSize from wtforms import ( - SelectField, - StringField, - SubmitField, - validators, + SelectField, + StringField, + SubmitField, + validators, ) from wtforms.validators import ( - DataRequired, - Length, - ValidationError, + DataRequired, + Length, + ValidationError, ) from app import settings class UploadForm(FlaskForm): - """File upload class for a new site in distribusi-verse""" + """File upload class for a new site in distribusi-verse""" - def distribusiname(form, field): - if field.data.lower() == "new": - raise ValidationError("Name has to be unique and not just new.") + def distribusiname(form, field): + if field.data.lower() == "new": + raise ValidationError("Name has to be unique and not just new.") - def category_choices(): - APP = settings() - config_categories = APP.config["categories"] - categories = [] - for config_category in config_categories: - categories.append((config_category, config_category)) - return categories + def category_choices(): + APP = settings() + config_categories = APP.config["categories"] + categories = [] + for config_category in config_categories: + categories.append((config_category, config_category)) + return categories - def year_choices(): - APP = settings() - start_time = APP.config["start_time"] - end_time = APP.config["end_time"] - year_range = range(start_time.year, end_time.year, 1) - year_choices = [] - for year in year_range: - year_choices.append((str(year), str(year))) - return year_choices + def year_choices(): + APP = settings() + start_time = APP.config["start_time"] + end_time = APP.config["end_time"] + year_range = range(start_time.year, end_time.year, 1) + year_choices = [] + for year in year_range: + year_choices.append((str(year), str(year))) + return year_choices - sitename = StringField( - "Name of your archive section:", - validators=[ - validators.InputRequired(), - Length(2, 100), - distribusiname, - ], - ) - year = SelectField( - "Year:", - validate_choice=True, - coerce=str, - choices=year_choices, - option_widget=None, - validators=[DataRequired()], - ) - category = SelectField( - "Category:", - validate_choice=True, - coerce=str, - choices=category_choices, - option_widget=None, - validators=[DataRequired()], - ) + sitename = StringField( + "Name of your archive section:", + validators=[ + validators.InputRequired(), + Length(2, 100), + distribusiname, + ], + ) + year = SelectField( + "Year:", + validate_choice=True, + coerce=str, + choices=year_choices, + option_widget=None, + validators=[DataRequired()], + ) + category = SelectField( + "Category:", + validate_choice=True, + coerce=str, + choices=category_choices, + option_widget=None, + validators=[DataRequired()], + ) - tags = StringField( - "Add search tags, seperated by commas. No need for the '#' sign:", - validators=[validators.InputRequired(), Length(3, 500)], - ) + tags = StringField( + "Add search tags, seperated by commas. No need for the '#' sign:", + validators=[validators.InputRequired(), Length(3, 500)], + ) - zipfile = FileField( - "Upload your zip file with content here:", - validators=[ - FileAllowed(["zip"], "Zip archives only!"), - FileRequired(), - FileSize( - max_size=1073741824, - message="Zipfile size must be smaller than 100MB", - ), - ], - ) + zipfile = FileField( + "Upload your zip file with content here:", + validators=[ + FileAllowed(["zip"], "Zip archives only!"), + FileRequired(), + FileSize( + max_size=1073741824, + message="Zipfile size must be smaller than 100MB", + ), + ], + ) - submit = SubmitField("Upload") + submit = SubmitField("Upload") diff --git a/verse/migrations/env.py b/verse/migrations/env.py index 85debe8..68a0091 100644 --- a/verse/migrations/env.py +++ b/verse/migrations/env.py @@ -21,10 +21,10 @@ logger = logging.getLogger("alembic.env") # from myapp import mymodel # target_metadata = mymodel.Base.metadata config.set_main_option( - "sqlalchemy.url", - str(current_app.extensions["migrate"].db.get_engine().url).replace( - "%", "%%" - ), + "sqlalchemy.url", + str(current_app.extensions["migrate"].db.get_engine().url).replace( + "%", "%%" + ), ) target_metadata = current_app.extensions["migrate"].db.metadata @@ -35,59 +35,59 @@ target_metadata = current_app.extensions["migrate"].db.metadata def run_migrations_offline(): - """Run migrations in 'offline' mode. + """Run migrations in 'offline' mode. - This configures the context with just a URL - and not an Engine, though an Engine is acceptable - here as well. By skipping the Engine creation - we don't even need a DBAPI to be available. + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. - Calls to context.execute() here emit the given string to the - script output. + Calls to context.execute() here emit the given string to the + script output. - """ - url = config.get_main_option("sqlalchemy.url") - context.configure( - url=url, target_metadata=target_metadata, literal_binds=True - ) + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) - with context.begin_transaction(): - context.run_migrations() + with context.begin_transaction(): + context.run_migrations() def run_migrations_online(): - """Run migrations in 'online' mode. + """Run migrations in 'online' mode. - In this scenario we need to create an Engine - and associate a connection with the context. + In this scenario we need to create an Engine + and associate a connection with the context. - """ + """ - # this callback is used to prevent an auto-migration from being generated - # when there are no changes to the schema - # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html - def process_revision_directives(context, revision, directives): - if getattr(config.cmd_opts, "autogenerate", False): - script = directives[0] - if script.upgrade_ops.is_empty(): - directives[:] = [] - logger.info("No changes in schema detected.") + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, "autogenerate", False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info("No changes in schema detected.") - connectable = current_app.extensions["migrate"].db.get_engine() + connectable = current_app.extensions["migrate"].db.get_engine() - with connectable.connect() as connection: - context.configure( - connection=connection, - target_metadata=target_metadata, - process_revision_directives=process_revision_directives, - **current_app.extensions["migrate"].configure_args, - ) + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions["migrate"].configure_args, + ) - with context.begin_transaction(): - context.run_migrations() + with context.begin_transaction(): + context.run_migrations() if context.is_offline_mode(): - run_migrations_offline() + run_migrations_offline() else: - run_migrations_online() + run_migrations_online() diff --git a/verse/models/distribusi_file_model.py b/verse/models/distribusi_file_model.py index cfb6216..23003b1 100644 --- a/verse/models/distribusi_file_model.py +++ b/verse/models/distribusi_file_model.py @@ -2,17 +2,17 @@ from app import db class DistribusiFiles(db.Model): - """Distribusi file model class for a single file in a distribusi""" + """Distribusi file model class for a single file in a distribusi""" - __tablename__ = "distribusi_files" + __tablename__ = "distribusi_files" - id = db.Column(db.Integer, primary_key=True) - type = db.Column(db.String(100), nullable=True, unique=False) - distribusi = db.Column(db.Integer, db.ForeignKey("distribusis.id")) - path = db.Column(db.String(4096), nullable=True, unique=False) - alttext = db.Column(db.String(255), nullable=True, unique=False) - tags = db.Column(db.String(500), nullable=True, unique=False) - description = db.Column(db.String(4096), nullable=True, unique=False) + id = db.Column(db.Integer, primary_key=True) + type = db.Column(db.String(100), nullable=True, unique=False) + distribusi = db.Column(db.Integer, db.ForeignKey("distribusis.id")) + path = db.Column(db.String(4096), nullable=True, unique=False) + alttext = db.Column(db.String(255), nullable=True, unique=False) + tags = db.Column(db.String(500), nullable=True, unique=False) + description = db.Column(db.String(4096), nullable=True, unique=False) - def __repr__(self): - return "" % self.path + def __repr__(self): + return "" % self.path diff --git a/verse/models/distribusi_model.py b/verse/models/distribusi_model.py index 4d23545..d8f114e 100644 --- a/verse/models/distribusi_model.py +++ b/verse/models/distribusi_model.py @@ -2,18 +2,18 @@ from app import db class Distribusis(db.Model): - """distribusi model class for a single distribusi in distribusi-verse""" + """distribusi model class for a single distribusi in distribusi-verse""" - __tablename__ = "distribusis" + __tablename__ = "distribusis" - id = db.Column(db.Integer, primary_key=True) - distribusiname = db.Column(db.String(300), nullable=False, unique=True) - userid = db.Column(db.Integer, db.ForeignKey("users.id")) - category = db.Column(db.String(500), nullable=True, unique=False) - year = db.Column(db.String(9), nullable=True, unique=False) - tags = db.Column(db.String(500), nullable=True, unique=False) - publictheme = db.Column(db.String(300), unique=True, nullable=True) - visible = db.Column(db.Boolean, default=False) + id = db.Column(db.Integer, primary_key=True) + distribusiname = db.Column(db.String(300), nullable=False, unique=True) + userid = db.Column(db.Integer, db.ForeignKey("users.id")) + category = db.Column(db.String(500), nullable=True, unique=False) + year = db.Column(db.String(9), nullable=True, unique=False) + tags = db.Column(db.String(500), nullable=True, unique=False) + publictheme = db.Column(db.String(300), unique=True, nullable=True) + visible = db.Column(db.Boolean, default=False) - def __repr__(self): - return "" % self.distribusiname + def __repr__(self): + return "" % self.distribusiname diff --git a/verse/models/user_model.py b/verse/models/user_model.py index 0487d94..9522024 100644 --- a/verse/models/user_model.py +++ b/verse/models/user_model.py @@ -4,18 +4,18 @@ from app import db class User(UserMixin, db.Model): - """User model class for a user in distribusi-verse""" + """User model class for a user in distribusi-verse""" - __tablename__ = "users" + __tablename__ = "users" - id = db.Column(db.Integer, primary_key=True) - username = db.Column(db.String(150), unique=True, nullable=False) - email = db.Column(db.String(150), unique=True, nullable=False) - password = db.Column(db.String(300), nullable=False, unique=False) - currentdistribusi = db.Column(db.String(300), nullable=True, unique=False) - resethash = db.Column(db.String(300), nullable=True, unique=True) - resettime = db.Column(db.DateTime) - admin = db.Column(db.Boolean, default=False) + id = db.Column(db.Integer, primary_key=True) + username = db.Column(db.String(150), unique=True, nullable=False) + email = db.Column(db.String(150), unique=True, nullable=False) + password = db.Column(db.String(300), nullable=False, unique=False) + currentdistribusi = db.Column(db.String(300), nullable=True, unique=False) + resethash = db.Column(db.String(300), nullable=True, unique=True) + resettime = db.Column(db.DateTime) + admin = db.Column(db.Boolean, default=False) - def __repr__(self): - return "" % self.email + def __repr__(self): + return "" % self.email diff --git a/verse/start.py b/verse/start.py index 5e9530c..728fabc 100644 --- a/verse/start.py +++ b/verse/start.py @@ -3,18 +3,18 @@ from datetime import timedelta from flask import ( - Blueprint, - redirect, - render_template, - send_from_directory, - session, - url_for, + Blueprint, + redirect, + render_template, + send_from_directory, + session, + url_for, ) from flask_login import current_user, login_required, logout_user from flask_wtf.csrf import CSRFError from adminpage import AdminPage -from app import db, create_app, login_manager +from app import create_app, login_manager, db from describer.describe_files import describer from distribusikan.distribusikan import distribusikan from distribusikan.distribusisinfo import DistribusisInfo @@ -29,7 +29,6 @@ from statuspengguna.registeruser import register_user APP = create_app() stash_page = Blueprint("stash_page", __name__, static_folder="stash") APP.register_blueprint(stash_page) - APP.register_blueprint(describer, url_prefix="/describer") APP.register_blueprint(login_section, url_prefix="/login") APP.register_blueprint(register_user, url_prefix="/register") @@ -39,89 +38,90 @@ APP.register_blueprint(distribusikan) @APP.before_request def session_handler(): - session.permanent = True - APP.permanent_session_lifetime = timedelta(minutes=30) + session.permanent = True + APP.permanent_session_lifetime = timedelta(minutes=30) @APP.route("/") def index(): - UserHelper.reset_user_state() - uploadform = UploadForm() - distribusis = DistribusisInfo.visibledistribusis() - distribusisindex = {} - for distribusi in distribusis: - user = User.query.filter_by(id=distribusi.userid).first() - singledistribusi = { - "username": user.username, - "publictheme": distribusi.publictheme, - "category": distribusi.category, - "year": distribusi.year, - "tags": distribusi.tags.split(","), - } - distribusisindex[distribusi.distribusiname] = singledistribusi - years = uploadform.year.choices - categories = uploadform.category.choices - adminuser = is_adminuser() - template = render_template( - "base/index.html", - distribusisindex=distribusisindex, - years=years, - categories=categories, - adminuser=adminuser, - ) - return template + UserHelper.reset_user_state() + uploadform = UploadForm() + distribusis = DistribusisInfo.visibledistribusis() + distribusisindex = {} + for distribusi in distribusis: + user = User.query.filter_by(id=distribusi.userid).first() + singledistribusi = { + "username": user.username, + "publictheme": distribusi.publictheme, + "category": distribusi.category, + "year": distribusi.year, + "tags": distribusi.tags.split(","), + } + distribusisindex[distribusi.distribusiname] = singledistribusi + + years = uploadform.year.choices + categories = uploadform.category.choices + adminuser = is_adminuser() + template = render_template( + "base/index.html", + distribusisindex=distribusisindex, + years=years, + categories=categories, + adminuser=adminuser, + ) + return template @APP.route("/help") def help(): - return render_template("base/help.html") + return render_template("base/help.html") @APP.route("/publicthemes/") def publicthemes(path): - distribusi = Distribusis.query.filter_by(distribusiname=path).first() - publicthemefolder = f"publicthemes/{distribusi.distribusiname}/" - cssfile = f"{publicthemefolder}/{distribusi.publictheme}.css" - return send_from_directory("themes", cssfile, as_attachment=True) + distribusi = Distribusis.query.filter_by(distribusiname=path).first() + publicthemefolder = f"publicthemes/{distribusi.distribusiname}/" + cssfile = f"{publicthemefolder}/{distribusi.publictheme}.css" + return send_from_directory("themes", cssfile, as_attachment=True) @APP.route("/stash") def shortstashurl(): - return redirect(url_for("index")) + return redirect(url_for("index")) @APP.route("/admin", methods=["GET", "POST"]) @login_required def admin(): - if not is_adminuser(): - return redirect(url_for("index")) - return AdminPage() + if not is_adminuser(): + return redirect(url_for("index")) + return AdminPage() @APP.route("/logout") @login_required def logout(): - logout_user() - return redirect(url_for("index")) + logout_user() + return redirect(url_for("index")) @APP.errorhandler(CSRFError) def handle_csrf_error(e): - return render_template("csrf_error.html", reason=e.description), 400 + return render_template("csrf_error.html", reason=e.description), 400 @login_manager.user_loader def load_user(user_id): - return db.session.get(User, int(user_id)) + return db.session.get(User, int(user_id)) def is_adminuser(): - if not current_user.is_authenticated: - return False - user = User.query.filter_by(email=current_user.email).first() - return user.admin + if not current_user.is_authenticated: + return False + user = User.query.filter_by(email=current_user.email).first() + return user.admin if __name__ == "__main__": - APP.debug = True - APP.run(port=5000) + APP.debug = True + APP.run(port=5000) diff --git a/verse/statuspengguna/forgotpassword.py b/verse/statuspengguna/forgotpassword.py index 51b0ae0..dbb8049 100644 --- a/verse/statuspengguna/forgotpassword.py +++ b/verse/statuspengguna/forgotpassword.py @@ -4,10 +4,10 @@ from uuid import uuid1 from flask import Blueprint, render_template from flask_mail import Mail, Message from sqlalchemy.exc import ( - DatabaseError, - DataError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + InterfaceError, + InvalidRequestError, ) from app import db, get_app @@ -16,57 +16,57 @@ from models.user_model import User mail = Mail(get_app()) forgot_password = Blueprint( - "forgotpassword", - __name__, - template_folder="templates/statuspengguna", - static_folder="static", + "forgotpassword", + __name__, + template_folder="templates/statuspengguna", + static_folder="static", ) @forgot_password.route("/", methods=["GET", "POST"]) def forgotpassword(): - return ForgotPassword(mail) + return ForgotPassword(mail) def ForgotPassword(mail): - forgotpasswordform = ForgotPasswordForm() - if forgotpasswordform.validate_on_submit(): - user = User.query.filter_by( - email=forgotpasswordform.email.data - ).first() - if user is not None: - resethash = AddResetPasswordHash(user, forgotpasswordform) - ResetPassWordMessage(user, resethash, mail) - forgotpasswordform.email.errors.append( - f"""If {forgotpasswordform.email.data} exists, an email is send with + forgotpasswordform = ForgotPasswordForm() + if forgotpasswordform.validate_on_submit(): + user = User.query.filter_by( + email=forgotpasswordform.email.data + ).first() + if user is not None: + resethash = AddResetPasswordHash(user, forgotpasswordform) + ResetPassWordMessage(user, resethash, mail) + forgotpasswordform.email.errors.append( + f"""If {forgotpasswordform.email.data} exists, an email is send with a password reset link. (If your inbox doesn't contain any new mail, please check your spam folder.)""" - ) - return render_template( - "forgotpassword.html", forgotpasswordform=forgotpasswordform - ) + ) + return render_template( + "forgotpassword.html", forgotpasswordform=forgotpasswordform + ) def AddResetPasswordHash(user, forgotpasswordform): - resethash = uuid1().hex - try: - user.resettime = datetime.now() - user.resethash = resethash - db.session.commit() - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - forgotpasswordform.email.errors.append("Something went wrong!") - db.session.rollback() - return resethash + resethash = uuid1().hex + try: + user.resettime = datetime.now() + user.resethash = resethash + db.session.commit() + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + forgotpasswordform.email.errors.append("Something went wrong!") + db.session.rollback() + return resethash def ResetPassWordMessage(user, resethash, mail): - msg = Message( - "Distribusiverse Forgotten Password ", - sender=("Distribusiverse mailer", "test@this.com"), - recipients=[user.email], - ) - msg.html = f"""{user.username} has requested a password reset for + msg = Message( + "Distribusiverse Forgotten Password ", + sender=("Distribusiverse mailer", "test@this.com"), + recipients=[user.email], + ) + msg.html = f"""{user.username} has requested a password reset for Distribusiverse.

Click here to reset your password.""" - mail.send(msg) + mail.send(msg) diff --git a/verse/statuspengguna/helper.py b/verse/statuspengguna/helper.py index 9d01082..a8b26bd 100644 --- a/verse/statuspengguna/helper.py +++ b/verse/statuspengguna/helper.py @@ -3,10 +3,10 @@ import os from flask import flash from flask_login import current_user from sqlalchemy.exc import ( - DatabaseError, - DataError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + InterfaceError, + InvalidRequestError, ) from app import db @@ -16,68 +16,68 @@ from models.user_model import User class UserHelper: - def is_zip_uploaded(distribusiname): - userfolder = os.path.join("stash", distribusiname) - if os.path.exists(userfolder): - zipfilename = "{}.zip".format(distribusiname) - if os.path.exists(os.path.join(userfolder, zipfilename)): - print("folder with zipfile found, file uploaded") - return True - print("distribusi folder has no zipfile") - return False + def is_zip_uploaded(distribusiname): + userfolder = os.path.join("stash", distribusiname) + if os.path.exists(userfolder): + zipfilename = "{}.zip".format(distribusiname) + if os.path.exists(os.path.join(userfolder, zipfilename)): + print("folder with zipfile found, file uploaded") + return True + print("distribusi folder has no zipfile") + return False - def is_distribusi_live(distribusiname): - userfolder = os.path.join("stash", distribusiname) - if os.path.exists(userfolder): - zipfilename = "{}.zip".format(distribusiname) - if os.path.exists(os.path.join(userfolder, zipfilename)): - print("folder with zipfile found, file uploaded") - return False - if len(os.listdir(userfolder)) > 0: - return True - print("distribusi folder is empty") - return False + def is_distribusi_live(distribusiname): + userfolder = os.path.join("stash", distribusiname) + if os.path.exists(userfolder): + zipfilename = "{}.zip".format(distribusiname) + if os.path.exists(os.path.join(userfolder, zipfilename)): + print("folder with zipfile found, file uploaded") + return False + if len(os.listdir(userfolder)) > 0: + return True + print("distribusi folder is empty") + return False - def is_css_selected(distribusiname): - userfolder = os.path.join("themes/userthemes", distribusiname) - if os.path.exists(userfolder): - for file in os.listdir(userfolder): - if file.endswith(".css"): - return True - print("distribusi folder has no css file") - return False + def is_css_selected(distribusiname): + userfolder = os.path.join("themes/userthemes", distribusiname) + if os.path.exists(userfolder): + for file in os.listdir(userfolder): + if file.endswith(".css"): + return True + print("distribusi folder has no css file") + return False - def has_distribusi(): - user = User.query.filter_by(email=current_user.email).first() - distribusi = Distribusis.query.filter_by(userid=user.id).first() - if distribusi is None: - print("no distribusi found") - return False - return True + def has_distribusi(): + user = User.query.filter_by(email=current_user.email).first() + distribusi = Distribusis.query.filter_by(userid=user.id).first() + if distribusi is None: + print("no distribusi found") + return False + return True - def current_distribusi(): - user = User.query.filter_by(email=current_user.email).first() - if user.currentdistribusi is None: - return "None" - return user.currentdistribusi + def current_distribusi(): + user = User.query.filter_by(email=current_user.email).first() + if user.currentdistribusi is None: + return "None" + return user.currentdistribusi - def reset_user_state(): - """reset user state upon visiting index, so that distribusi workflow can - be done correctly""" - if not current_user.is_authenticated: - return - try: - user = User.query.filter_by(email=current_user.email).first() - user.currentdistribusi = None - db.session.commit() - except (InvalidRequestError, DataError, InterfaceError, DatabaseError): - db.session.rollback() - flash("An error occured !", "danger") + def reset_user_state(): + """reset user state upon visiting index, so that distribusi workflow can + be done correctly""" + if not current_user.is_authenticated: + return + try: + user = User.query.filter_by(email=current_user.email).first() + user.currentdistribusi = None + db.session.commit() + except (InvalidRequestError, DataError, InterfaceError, DatabaseError): + db.session.rollback() + flash("An error occured !", "danger") - def distribusi_limit_reached(): - user = User.query.filter_by(email=current_user.email).first() - distribusiamount = len(DistribusisInfo.getuserdistribusis(user.email)) - if distribusiamount > 19: - print("user already has 20 distribusis") - return True - return False + def distribusi_limit_reached(): + user = User.query.filter_by(email=current_user.email).first() + distribusiamount = len(DistribusisInfo.getuserdistribusis(user.email)) + if distribusiamount > 19: + print("user already has 20 distribusis") + return True + return False diff --git a/verse/statuspengguna/loginuser.py b/verse/statuspengguna/loginuser.py index 69bbbee..6f18cde 100644 --- a/verse/statuspengguna/loginuser.py +++ b/verse/statuspengguna/loginuser.py @@ -1,11 +1,11 @@ from flask import ( - Blueprint, - abort, - flash, - redirect, - render_template, - request, - url_for, + Blueprint, + abort, + flash, + redirect, + render_template, + request, + url_for, ) from flask_bcrypt import check_password_hash from flask_login import login_user @@ -14,39 +14,39 @@ from forms.loginform import LoginForm from models.user_model import User login_section = Blueprint( - "login", - __name__, - template_folder="templates/statuspengguna", - static_folder="static", + "login", + __name__, + template_folder="templates/statuspengguna", + static_folder="static", ) @login_section.route("/", methods=["GET", "POST"]) def login(): - return LoginUser() + return LoginUser() def LoginUser(): - loginform = LoginForm() - if loginform.validate_on_submit(): - try: - user = User.query.filter_by(email=loginform.email.data).first() - if user is None: - loginform.password.errors.append("Invalid email or password!") - return render_template("login.html", loginform=loginform) - if check_password_hash(user.password, loginform.password.data): - login_user(user) - flash("Logged in successfully.", "success") - next = request.args.get("next") - if next is not None and not is_safe_url(next): # noqa: F821 - print(next) - return abort(400) - print("index") - return redirect(next or url_for("index")) - else: - flash("Invalid email or password!", "danger") - loginform.password.errors.append("Invalid email or password!") - return render_template("login.html", loginform=loginform) - except Exception as e: - flash(e, "danger") - return render_template("login.html", loginform=loginform) + loginform = LoginForm() + if loginform.validate_on_submit(): + try: + user = User.query.filter_by(email=loginform.email.data).first() + if user is None: + loginform.password.errors.append("Invalid email or password!") + return render_template("login.html", loginform=loginform) + if check_password_hash(user.password, loginform.password.data): + login_user(user) + flash("Logged in successfully.", "success") + next = request.args.get("next") + if next is not None and not is_safe_url(next): # noqa: F821 + print(next) + return abort(400) + print("index") + return redirect(next or url_for("index")) + else: + flash("Invalid email or password!", "danger") + loginform.password.errors.append("Invalid email or password!") + return render_template("login.html", loginform=loginform) + except Exception as e: + flash(e, "danger") + return render_template("login.html", loginform=loginform) diff --git a/verse/statuspengguna/registeruser.py b/verse/statuspengguna/registeruser.py index ade624a..e97f1ee 100644 --- a/verse/statuspengguna/registeruser.py +++ b/verse/statuspengguna/registeruser.py @@ -2,11 +2,11 @@ from flask import Blueprint, flash, redirect, render_template, url_for from flask_bcrypt import generate_password_hash from flask_login import login_user from sqlalchemy.exc import ( - DatabaseError, - DataError, - IntegrityError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + IntegrityError, + InterfaceError, + InvalidRequestError, ) from werkzeug.routing import BuildError @@ -15,64 +15,64 @@ from forms.registerform import RegisterForm from models.user_model import User register_user = Blueprint( - "register", - __name__, - template_folder="templates/statuspengguna", - static_folder="static", + "register", + __name__, + template_folder="templates/statuspengguna", + static_folder="static", ) @register_user.route("/", methods=["GET", "POST"]) def register(): - return RegisterUser() + return RegisterUser() def RegisterUser(): - registerform = RegisterForm() - if registerform.validate_on_submit(): - try: - username = registerform.username.data - email = registerform.email.data - password = registerform.confirmpassword.data + registerform = RegisterForm() + if registerform.validate_on_submit(): + try: + username = registerform.username.data + email = registerform.email.data + password = registerform.confirmpassword.data - newuser = User( - username=username, - email=email, - password=generate_password_hash(password), - ) + newuser = User( + username=username, + email=email, + password=generate_password_hash(password), + ) - db.session.add(newuser) - db.session.commit() - flash("Account Succesfully created", "success") - login_user(newuser) - return redirect(url_for("index")) + db.session.add(newuser) + db.session.commit() + flash("Account Succesfully created", "success") + login_user(newuser) + return redirect(url_for("index")) - except InvalidRequestError: - db.session.rollback() - registerform.email.errors.append("Something went wrong!") - flash("Something went wrong!", "danger") - except IntegrityError: - db.session.rollback() - registerform.email.errors.append("User already exists!") - flash("User already exists!", "warning") - except DataError: - db.session.rollback() - registerform.email.errors.append("Invalid Entry") - flash("Invalid Entry", "warning") - except InterfaceError: - db.session.rollback() - registerform.email.errors.append( - "Error connecting to the database" - ) - flash("Error connecting to the database", "danger") - except DatabaseError: - db.session.rollback() - registerform.email.errors.append( - "Error connecting to the database" - ) - flash("Error connecting to the database", "danger") - except BuildError: - db.session.rollback() - registerform.email.errors.append("Unknown error occured!") - flash("An error occured !", "danger") - return render_template("register.html", registerform=registerform) + except InvalidRequestError: + db.session.rollback() + registerform.email.errors.append("Something went wrong!") + flash("Something went wrong!", "danger") + except IntegrityError: + db.session.rollback() + registerform.email.errors.append("User already exists!") + flash("User already exists!", "warning") + except DataError: + db.session.rollback() + registerform.email.errors.append("Invalid Entry") + flash("Invalid Entry", "warning") + except InterfaceError: + db.session.rollback() + registerform.email.errors.append( + "Error connecting to the database" + ) + flash("Error connecting to the database", "danger") + except DatabaseError: + db.session.rollback() + registerform.email.errors.append( + "Error connecting to the database" + ) + flash("Error connecting to the database", "danger") + except BuildError: + db.session.rollback() + registerform.email.errors.append("Unknown error occured!") + flash("An error occured !", "danger") + return render_template("register.html", registerform=registerform) diff --git a/verse/statuspengguna/resetpassword.py b/verse/statuspengguna/resetpassword.py index e0da583..c0288ae 100644 --- a/verse/statuspengguna/resetpassword.py +++ b/verse/statuspengguna/resetpassword.py @@ -4,11 +4,11 @@ from flask import Blueprint, flash, redirect, render_template, url_for from flask_bcrypt import generate_password_hash from flask_login import login_user from sqlalchemy.exc import ( - DatabaseError, - DataError, - IntegrityError, - InterfaceError, - InvalidRequestError, + DatabaseError, + DataError, + IntegrityError, + InterfaceError, + InvalidRequestError, ) from werkzeug.routing import BuildError @@ -17,74 +17,74 @@ from forms.resetpasswordform import ResetPasswordForm from models.user_model import User reset_password = Blueprint( - "reset_password", - __name__, - template_folder="templates/statuspengguna", - static_folder="static", + "reset_password", + __name__, + template_folder="templates/statuspengguna", + static_folder="static", ) @reset_password.route("/resetpassword/", methods=["GET", "POST"]) def resetpassword(path): - return ResetPassword(path) + return ResetPassword(path) def ResetPassword(path): - linkvalid = False - user = User.query.filter_by(resethash=path).first() - if user is None: - return redirect(url_for("index")) - timepassed = datetime.now() - user.resettime - if timepassed.days < 1: - linkvalid = True + linkvalid = False + user = User.query.filter_by(resethash=path).first() + if user is None: + return redirect(url_for("index")) + timepassed = datetime.now() - user.resettime + if timepassed.days < 1: + linkvalid = True - resetpasswordform = ResetPasswordForm() - if resetpasswordform.validate_on_submit(): - return ResetUserPasswordInDB(user, resetpasswordform) - return render_template( - "resetpassword.html", - resetpasswordform=resetpasswordform, - path=path, - linkvalid=linkvalid, - ) + resetpasswordform = ResetPasswordForm() + if resetpasswordform.validate_on_submit(): + return ResetUserPasswordInDB(user, resetpasswordform) + return render_template( + "resetpassword.html", + resetpasswordform=resetpasswordform, + path=path, + linkvalid=linkvalid, + ) def ResetUserPasswordInDB(user, resetpasswordform): - try: - newpassword = resetpasswordform.confirmpassword.data - user.password = generate_password_hash(newpassword) - user.resethash = None - user.resettime = None - db.session.commit() - flash("Password Succesfully updated", "success") - login_user(user) - return redirect(url_for("index")) + try: + newpassword = resetpasswordform.confirmpassword.data + user.password = generate_password_hash(newpassword) + user.resethash = None + user.resettime = None + db.session.commit() + flash("Password Succesfully updated", "success") + login_user(user) + return redirect(url_for("index")) - except InvalidRequestError: - db.session.rollback() - resetpasswordform.email.errors.append("Something went wrong!") - flash("Something went wrong!", "danger") - except IntegrityError: - db.session.rollback() - resetpasswordform.email.errors.append("User already exists!") - flash("User already exists!", "warning") - except DataError: - db.session.rollback() - resetpasswordform.email.errors.append("Invalid Entry") - flash("Invalid Entry", "warning") - except InterfaceError: - db.session.rollback() - resetpasswordform.email.errors.append( - "Error connecting to the database" - ) - flash("Error connecting to the database", "danger") - except DatabaseError: - db.session.rollback() - resetpasswordform.email.errors.append( - "Error connecting to the database" - ) - flash("Error connecting to the database", "danger") - except BuildError: - db.session.rollback() - resetpasswordform.email.errors.append("Unknown error occured!") - flash("An error occured !", "danger") + except InvalidRequestError: + db.session.rollback() + resetpasswordform.email.errors.append("Something went wrong!") + flash("Something went wrong!", "danger") + except IntegrityError: + db.session.rollback() + resetpasswordform.email.errors.append("User already exists!") + flash("User already exists!", "warning") + except DataError: + db.session.rollback() + resetpasswordform.email.errors.append("Invalid Entry") + flash("Invalid Entry", "warning") + except InterfaceError: + db.session.rollback() + resetpasswordform.email.errors.append( + "Error connecting to the database" + ) + flash("Error connecting to the database", "danger") + except DatabaseError: + db.session.rollback() + resetpasswordform.email.errors.append( + "Error connecting to the database" + ) + flash("Error connecting to the database", "danger") + except BuildError: + db.session.rollback() + resetpasswordform.email.errors.append("Unknown error occured!") + flash("An error occured !", "danger")