I love trying different formatters

This commit is contained in:
crunk 2024-05-28 23:02:17 +02:00
parent 7456eea083
commit 2a018ab863
38 changed files with 1369 additions and 1376 deletions

View File

@ -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

View File

@ -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

View File

@ -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()

View File

@ -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)

View File

@ -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()

View File

@ -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("/<string:distribusiname>")
@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/<int:file_id>", 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/<path:path>")
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

View File

@ -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):

View File

@ -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()

View File

@ -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)
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
)
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)
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
# 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

View File

@ -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()

View File

@ -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()
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"))
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)
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()
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
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

View File

@ -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)
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)
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.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)
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("&gt;", ">")
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("&gt;", ">")
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("&gt;", ">")
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("&gt;", ">")
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()
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")
except InvalidRequestError:
db.session.rollback()