main #12
@ -1,25 +1,49 @@
|
||||
[tool.black]
|
||||
[tool.ruff]
|
||||
line-length = 79
|
||||
target-version = ['py311']
|
||||
include = '\.pyi?$'
|
||||
exclude = '''
|
||||
/(
|
||||
\.eggs
|
||||
| \.git
|
||||
| \.hg
|
||||
| \.mypy_cache
|
||||
| \.tox
|
||||
| \.venv
|
||||
| _build
|
||||
| buck-out
|
||||
| build
|
||||
| dist
|
||||
|
||||
# The following are specific to Black, you probably don't want those.
|
||||
| blib2to3
|
||||
| tests/data
|
||||
| profiling
|
||||
)/
|
||||
'''
|
||||
target-version = "py311"
|
||||
#include = '\.pyi?$'
|
||||
exclude = [
|
||||
".bzr",
|
||||
".direnv",
|
||||
".eggs",
|
||||
".git",
|
||||
".git-rewrite",
|
||||
".hg",
|
||||
".ipynb_checkpoints",
|
||||
".mypy_cache",
|
||||
".nox",
|
||||
".pants.d",
|
||||
".pyenv",
|
||||
".pytest_cache",
|
||||
".pytype",
|
||||
".ruff_cache",
|
||||
".svn",
|
||||
".tox",
|
||||
".venv",
|
||||
".vscode",
|
||||
"__pypackages__",
|
||||
"_build",
|
||||
"buck-out",
|
||||
"build",
|
||||
"dist",
|
||||
"node_modules",
|
||||
"site-packages",
|
||||
"venv",
|
||||
]
|
||||
|
||||
[tool.ruff.lint]
|
||||
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
|
||||
select = ["E4", "E7", "E9", "F"]
|
||||
ignore = []
|
||||
# Allow fix for all enabled rules (when `--fix`) is provided.
|
||||
fixable = ["ALL"]
|
||||
unfixable = []
|
||||
# Allow unused variables when underscore-prefixed.
|
||||
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "double"
|
||||
indent-style = "tab"
|
||||
docstring-code-format = true
|
||||
line-ending = "auto"
|
||||
skip-magic-trailing-comma = false
|
||||
|
@ -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
|
||||
|
@ -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()
|
||||
|
72
verse/app.py
72
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)
|
||||
|
@ -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()
|
||||
|
@ -2,23 +2,31 @@ from flask import Blueprint, render_template, redirect, url_for
|
||||
from flask_login import current_user
|
||||
from models.distribusi_model import Distribusis
|
||||
from models.distribusi_file_model import DistribusiFiles
|
||||
from describer.forms.describe_file_form import DescribeFileForm
|
||||
|
||||
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>")
|
||||
def describe_distribusi_files(distribusiname):
|
||||
if not current_user.is_authenticated:
|
||||
return redirect(url_for("index"))
|
||||
distribusi = Distribusis.query.filter_by(
|
||||
distribusiname=distribusiname
|
||||
).first()
|
||||
distribusi_files = DistribusiFiles.query.filter_by(
|
||||
distribusi=distribusi.id
|
||||
).all()
|
||||
return render_template("describe.html", distribusi_files=distribusi_files)
|
||||
if not current_user.is_authenticated:
|
||||
return redirect(url_for("index"))
|
||||
distribusi = Distribusis.query.filter_by(
|
||||
distribusiname=distribusiname
|
||||
).first()
|
||||
distribusi_files = DistribusiFiles.query.filter_by(
|
||||
distribusi=distribusi.id
|
||||
).all()
|
||||
# distribusi_file_forms = {}
|
||||
# for distribusi_file in distribusi_files:
|
||||
describe_form = DescribeFileForm()
|
||||
return render_template(
|
||||
"describe.html",
|
||||
distribusi_files=distribusi_files,
|
||||
describe_form=describe_form,
|
||||
)
|
||||
|
@ -4,28 +4,29 @@ from flask_wtf import FlaskForm
|
||||
from wtforms import StringField, SubmitField, validators
|
||||
from wtforms.validators import Length
|
||||
|
||||
class DescribeFileForm(FlaskForm):
|
||||
"""DescribeFileForm selection form."""
|
||||
|
||||
alttext = StringField(
|
||||
"Alt-text for this file:",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
Length(3, 255),
|
||||
],
|
||||
)
|
||||
searchtags = StringField(
|
||||
"Add search tags, seperated by commas. No need for the '#' sign:",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
Length(3, 500),
|
||||
],
|
||||
)
|
||||
description = StringField(
|
||||
"Description of this file:",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
Length(3, 4096),
|
||||
],
|
||||
)
|
||||
save = SubmitField("Save")
|
||||
class DescribeFileForm(FlaskForm):
|
||||
"""DescribeFileForm selection form."""
|
||||
|
||||
alttext = StringField(
|
||||
"Alt-text for this file:",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
Length(3, 255),
|
||||
],
|
||||
)
|
||||
searchtags = StringField(
|
||||
"Add search tags, seperated by commas. No need for the '#' sign:",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
Length(3, 500),
|
||||
],
|
||||
)
|
||||
description = StringField(
|
||||
"Description of this file:",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
Length(3, 4096),
|
||||
],
|
||||
)
|
||||
save = SubmitField("Save")
|
||||
|
@ -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()
|
||||
|
@ -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.describe_distribusi_files",
|
||||
distribusiname=distribusiname,
|
||||
)
|
||||
)
|
||||
return redirect(
|
||||
url_for(
|
||||
"describer.describe_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
|
||||
|
@ -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()
|
||||
|
@ -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
|
||||
|
@ -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(">", ">")
|
||||
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()
|
||||
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()
|
||||
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()
|
||||
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
|
||||
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
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -6,70 +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-12-WttF-Mastodon-and-the-Fediverse")
|
||||
|
@ -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()
|
||||
|
@ -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")
|
||||
|
@ -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!")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -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")
|
||||
|
@ -14,17 +14,19 @@ config = context.config
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
logger = logging.getLogger('alembic.env')
|
||||
logger = logging.getLogger("alembic.env")
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# 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(
|
||||
'%', '%%'))
|
||||
target_metadata = current_app.extensions['migrate'].db.metadata
|
||||
"sqlalchemy.url",
|
||||
str(current_app.extensions["migrate"].db.get_engine().url).replace(
|
||||
"%", "%%"
|
||||
),
|
||||
)
|
||||
target_metadata = current_app.extensions["migrate"].db.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
@ -33,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()
|
||||
|
@ -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 "<Distribusi_File %r>" % self.path
|
||||
def __repr__(self):
|
||||
return "<Distribusi_File %r>" % self.path
|
||||
|
@ -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 "<Distribusi %r>" % self.distribusiname
|
||||
def __repr__(self):
|
||||
return "<Distribusi %r>" % self.distribusiname
|
||||
|
@ -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 "<User %r>" % self.email
|
||||
def __repr__(self):
|
||||
return "<User %r>" % self.email
|
||||
|
105
verse/start.py
105
verse/start.py
@ -2,8 +2,14 @@
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from flask import (Blueprint, redirect, render_template, send_from_directory,
|
||||
session, url_for)
|
||||
from flask import (
|
||||
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
|
||||
|
||||
@ -31,92 +37,91 @@ APP.register_blueprint(forgot_password, url_prefix="/login/forgotpassword")
|
||||
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 = isadminuser()
|
||||
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/<path>")
|
||||
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 isadminuser():
|
||||
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 User.query.get(int(user_id))
|
||||
return User.query.get(int(user_id))
|
||||
|
||||
|
||||
def isadminuser():
|
||||
if not current_user.is_authenticated:
|
||||
return False
|
||||
user = User.query.filter_by(email=current_user.email).first()
|
||||
return user.admin
|
||||
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 __name__ == "__main__":
|
||||
APP.debug = True
|
||||
APP.run(port=5000)
|
||||
APP.debug = True
|
||||
APP.run(port=5000)
|
||||
|
@ -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.<br><hr>
|
||||
<a href='http://localhost:5000/resetpassword/{resethash}'>Click here to
|
||||
reset your password.</a>"""
|
||||
mail.send(msg)
|
||||
mail.send(msg)
|
||||
|
@ -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
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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/<path>", 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")
|
||||
|
Loading…
Reference in New Issue
Block a user