diff --git a/.gitignore b/.gitignore
index bdac4f8..62f74a0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,22 +1,29 @@
-# application content
-media/
-**.sqlite
-database/
-site.conf
-site-*.conf
-run_8180.py
-.env
-alembic.ini
-venv/
-venv-*/
-.venv
-env
-
-# automatically generated garbage
-**/__pycache__/
+node_modules/
+__pycache__/
**.pyc
**~
-**/.\#*
-**/\#*\#
-ig_api_settings/
-node_modules/
+.*.swp
+\#*\#
+.\#*
+alembic.ini
+.env
+.env.*
+.venv
+env
+venv
+venv-*/
+config/
+conf/
+config.json
+data/
+site-*.conf
+site.conf
+.err
+.vscode
+/run.sh
+/target
+dist/
+build/
+**.egg-info
+ROADMAP.md
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4565eda..2f11a4b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,34 @@
# What’s New
+## 1.1.0
+
++ **Deprecated** several configuration values ~
++ **Schema changes**: several columns changed format. Update your schema.
++ Removed permanently the remains of extensions.
++ I18n improvements.
+
+## 1.0.0
+
++ **BREAKING CHANGES AHEAD**!
++ **SECURITY ADVISORY**: versions from `0.7` up to `0.9` are **VULNERABLE to XSS** due to `.jinja2` not getting autoescaped.
++ No more a monolith: `app.py` got split into several files into `salvi` package
++ Switched from peewee to **SQLAlchemy**; Schema as of 1.0 is the same as 0.9
++ Added dependency on [libsuou](https://github.com/yusurko/suou)
++ `site.conf` deprecated, but still supported for the time being
++ Switched to `pyproject.toml`. `requirements.txt` has been sunset.
++ Switched to the Apache License; the old license text is moved to `LICENSE.0_9`
++ Added color themes! This is a breaking (but trivial) aesthetic change. Default theme is 'Miku' (aquamarine green).
++ Extensions **have been removed**. They never had a clear, usable, public API in the first place.
+
+## 0.9
+
++ Removed `markdown_katex` dependency, and therefore support for math.
+ It is bloat; moreover, it ships executables with it, negatively impacting the lightweightness of the app.
++ Added support for `.env` (dotenv) file.
++ Now a database URL is required. For example, `[database]directory = /path/to/data/` becomes
+ `[database]url = sqlite:////path/to/data/data.sqlite` (site.conf) or
+ `DATABASE_URL=sqlite:////path/to/data/data.sqlite` (.env).
+
## 0.8
+ Schema changes:
diff --git a/LICENSE b/LICENSE
index a2d4b30..df8a219 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,19 +1,55 @@
-Copyright (C) 2020-2021 Sakuragasaki46
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
+Copyright (c) 2020-2025 Sakuragasaki46
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
diff --git a/LICENSE.0_9 b/LICENSE.0_9
new file mode 100644
index 0000000..a513535
--- /dev/null
+++ b/LICENSE.0_9
@@ -0,0 +1,20 @@
+
+Copyright (C) 2020-2021 Sakuragasaki46
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index 80617eb..56a8ff2 100644
--- a/README.md
+++ b/README.md
@@ -17,41 +17,47 @@ suitable as a community or team knowledge base.
+ Calendar
+ Works fine even with JavaScript disabled.
-## Requirements
+## Requirements & Dependencies
-+ **Python** 3.6+.
-+ **Flask** web framework (and Flask-Login / Flask-WTF extensions).
-+ **Peewee** ORM.
++ **Python** 3.10+.
++ **Flask** web framework (and Flask-Login / Flask-WTF / Flask-Arrest extensions).
++ **SQLAlchemy** ORM.
+ **Markdown** for page rendering.
-+ **Python-I18n**.
++ **[SUOU](https://github.com/yusurko/suou)**. (since 1.0)
+* **Python-Dotenv**.
+ The database drivers needed for the type of database.
-### Optional requirements
-
-* **Markdown-KaTeX** if you want to display math inside pages.
+To install the dependencies, run (virtualenv advised):
+> `pip install -e .`
## Usage
-+ Clone this repository: `git clone https://github.com/sakuragasaki46/salvi`
-+ Edit site.conf with the needed parameters. An example site.conf:
++ Clone this repository: `git clone https://github.com/yusurko/salvi`
++ Edit `.env` with the needed parameters. An example `.env` with MySQL:
```
-[site]
-name = Salvi
-
-[database]
-directory = /path/to/database/
+APP_NAME=Salvi
+DATABASE_URL=mysql://root:root@localhost/salvi
```
-+ Run `python3 -m app_init` to initialize the database and create the administrator user.
++ Run `python3 -m app_init` to initialize the database and create the administrator user. (The installer is unstable)
+ Run `flask run`.
+ You can now access Salvi in your browser at port 5000.
## Caveats
-+ The whole application is untested.
-+ If you forget the password, there is currently no way to reset it.
++ The whole application is free of unit tests. Ergo untested. No coverage.
++ If you forget the password, there is currently no way to reset it. E-mail is not supported as of 1.0.
++ This app comes with no content. It means, you have to write it yourself.
## License
-[MIT License](./LICENSE).
+Since 1.0, Salvi is licensed under the [Apache License, Version 2.0](LICENSE), a non-copyleft free and open source license.
+
+Salvi`<=0.9` is under **[MIT license](LICENSE.0_9)**, available at `LICENSE.0_9`.
+
+This is a hobby project, made available “AS IS”, with __no warranty__ express or implied.
+
+I (sakuragasaki46) may NOT be held accountable for Your use of my code.
+
+> It's pointless to file a lawsuit because you feel damaged, and it's only going to turn against you. What a waste of money you could have spent on a vacation or charity, or invested in stocks.
diff --git a/alembic/README b/alembic/README
new file mode 100644
index 0000000..98e4f9c
--- /dev/null
+++ b/alembic/README
@@ -0,0 +1 @@
+Generic single-database configuration.
\ No newline at end of file
diff --git a/alembic/env.py b/alembic/env.py
new file mode 100644
index 0000000..a283d9d
--- /dev/null
+++ b/alembic/env.py
@@ -0,0 +1,79 @@
+from logging.config import fileConfig
+
+from sqlalchemy import engine_from_config
+from sqlalchemy import pool
+
+from alembic import context
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+if config.config_file_name is not None:
+ fileConfig(config.config_file_name)
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+# from myapp import mymodel
+# target_metadata = mymodel.Base.metadata
+from salvi.models import Base
+target_metadata = Base.metadata
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def run_migrations_offline() -> None:
+ """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.
+
+ 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,
+ dialect_opts={"paramstyle": "named"},
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+def run_migrations_online() -> None:
+ """Run migrations in 'online' mode.
+
+ In this scenario we need to create an Engine
+ and associate a connection with the context.
+
+ """
+ connectable = engine_from_config(
+ config.get_section(config.config_ini_section, {}),
+ prefix="sqlalchemy.",
+ poolclass=pool.NullPool,
+ )
+
+ with connectable.connect() as connection:
+ context.configure(
+ connection=connection, target_metadata=target_metadata
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+if context.is_offline_mode():
+ run_migrations_offline()
+else:
+ run_migrations_online()
diff --git a/alembic/script.py.mako b/alembic/script.py.mako
new file mode 100644
index 0000000..fbc4b07
--- /dev/null
+++ b/alembic/script.py.mako
@@ -0,0 +1,26 @@
+"""${message}
+
+Revision ID: ${up_revision}
+Revises: ${down_revision | comma,n}
+Create Date: ${create_date}
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+${imports if imports else ""}
+
+# revision identifiers, used by Alembic.
+revision: str = ${repr(up_revision)}
+down_revision: Union[str, None] = ${repr(down_revision)}
+branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
+depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
+
+
+def upgrade() -> None:
+ ${upgrades if upgrades else "pass"}
+
+
+def downgrade() -> None:
+ ${downgrades if downgrades else "pass"}
diff --git a/alembic/versions/ae0587e14725_.py b/alembic/versions/ae0587e14725_.py
new file mode 100644
index 0000000..a9c6a70
--- /dev/null
+++ b/alembic/versions/ae0587e14725_.py
@@ -0,0 +1,86 @@
+"""empty message
+
+Sorry, due to unattended changes, upgrade from 1.0.0 is not reliable and untested. Sorry.
+
+Revision ID: ae0587e14725
+Revises:
+Create Date: 2025-10-04 09:43:41.158057
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import mysql
+
+# revision identifiers, used by Alembic.
+revision: str = 'ae0587e14725'
+down_revision: Union[str, None] = 'ebde30d24167'
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ # ### commands auto generated by Alembic - please adjust! ###
+ #op.drop_index('pagepolicykey_passphrase_sec_code', table_name='pagepolicykey')
+ #op.drop_index('page_owner', table_name='page')
+ op.create_index(op.f('ix_page_calendar'), 'page', ['calendar'], unique=False)
+ op.create_index('page_calendar', 'page', ['calendar'], unique=False)
+ op.drop_index('user_id', table_name='usergroupmembership')
+ op.drop_index('user_id_2', table_name='usergroupmembership')
+ #op.drop_index('usergroupmembership_group_id', table_name='usergroupmembership')
+ #op.drop_index('usergroupmembership_user_id', table_name='usergroupmembership')
+ # ### end Alembic commands ###
+
+
+def downgrade() -> None:
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.create_index('usergroupmembership_user_id', 'usergroupmembership', ['user_id'], unique=False)
+ op.create_index('usergroupmembership_group_id', 'usergroupmembership', ['group_id'], unique=False)
+ op.create_index('user_id_2', 'usergroupmembership', ['user_id', 'group_id'], unique=True)
+ op.create_index('user_id', 'usergroupmembership', ['user_id', 'group_id'], unique=True)
+ op.drop_index('page_calendar', table_name='page')
+ op.drop_index(op.f('ix_page_calendar'), table_name='page')
+ op.create_index('page_owner', 'page', ['owner_id'], unique=False)
+ op.create_table('upload',
+ sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
+ sa.Column('name', mysql.VARCHAR(length=256), nullable=False),
+ sa.Column('url_name', mysql.VARCHAR(length=256), nullable=True),
+ sa.Column('filetype', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('filesize', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('upload_date', mysql.DATETIME(), nullable=False),
+ sa.Column('md5', mysql.VARCHAR(length=32), nullable=False),
+ sa.PrimaryKeyConstraint('id'),
+ mariadb_collate='utf8mb4_general_ci',
+ mariadb_default_charset='utf8mb4',
+ mariadb_engine='InnoDB'
+ )
+ op.create_index('upload_upload_date', 'upload', ['upload_date'], unique=False)
+ op.create_index('upload_md5', 'upload', ['md5'], unique=False)
+ op.create_table('pagepolicy',
+ sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
+ sa.Column('page_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
+ sa.Column('type', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('key_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('sitewide', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.ForeignKeyConstraint(['key_id'], ['pagepolicykey.id'], name='pagepolicy_FK_0_0'),
+ sa.ForeignKeyConstraint(['page_id'], ['page.id'], name='pagepolicy_FK_1_0'),
+ sa.PrimaryKeyConstraint('id'),
+ mariadb_collate='utf8mb4_general_ci',
+ mariadb_default_charset='utf8mb4',
+ mariadb_engine='InnoDB'
+ )
+ op.create_index('pagepolicy_page_id_key_id', 'pagepolicy', ['page_id', 'key_id'], unique=True)
+ op.create_index('pagepolicy_page_id', 'pagepolicy', ['page_id'], unique=False)
+ op.create_index('pagepolicy_key_id', 'pagepolicy', ['key_id'], unique=False)
+ op.create_table('pagepolicykey',
+ sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
+ sa.Column('passphrase', mysql.VARCHAR(length=255), nullable=False),
+ sa.Column('sec_code', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.PrimaryKeyConstraint('id'),
+ mariadb_collate='utf8mb4_general_ci',
+ mariadb_default_charset='utf8mb4',
+ mariadb_engine='InnoDB'
+ )
+ op.create_index('pagepolicykey_passphrase_sec_code', 'pagepolicykey', ['passphrase', 'sec_code'], unique=True)
+ # ### end Alembic commands ###
diff --git a/alembic/versions/ebde30d24167_.py b/alembic/versions/ebde30d24167_.py
new file mode 100644
index 0000000..222417e
--- /dev/null
+++ b/alembic/versions/ebde30d24167_.py
@@ -0,0 +1,312 @@
+"""empty message
+
+Revision ID: ebde30d24167
+Revises: ae0587e14725
+Create Date: 2025-10-10 19:01:04.309127
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import mysql
+
+# revision identifiers, used by Alembic.
+revision: str = 'ebde30d24167'
+down_revision: Union[str, None] = None
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def downgrade() -> None:
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('pagepolicy',
+ sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
+ sa.Column('page_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
+ sa.Column('type', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('key_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('sitewide', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.ForeignKeyConstraint(['key_id'], ['pagepolicykey.id'], name='pagepolicy_FK_0_0'),
+ sa.ForeignKeyConstraint(['page_id'], ['page.id'], name='pagepolicy_FK_1_0'),
+ sa.PrimaryKeyConstraint('id'),
+ mariadb_collate='utf8mb4_general_ci',
+ mariadb_default_charset='utf8mb4',
+ mariadb_engine='InnoDB'
+ )
+ op.create_index('pagepolicy_page_id_key_id', 'pagepolicy', ['page_id', 'key_id'], unique=True)
+ op.create_index('pagepolicy_page_id', 'pagepolicy', ['page_id'], unique=False)
+ op.create_index('pagepolicy_key_id', 'pagepolicy', ['key_id'], unique=False)
+ op.create_table('pagepolicykey',
+ sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
+ sa.Column('passphrase', mysql.VARCHAR(length=255), nullable=False),
+ sa.Column('sec_code', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.PrimaryKeyConstraint('id'),
+ mariadb_collate='utf8mb4_general_ci',
+ mariadb_default_charset='utf8mb4',
+ mariadb_engine='InnoDB'
+ )
+ op.alter_column('page', 'title',
+ existing_type=mysql.VARCHAR(length=256),
+ nullable=True)
+ op.alter_column('page', 'touched',
+ existing_type=mysql.DATETIME(),
+ nullable=True)
+ op.alter_column('page', 'flags',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=True)
+ op.drop_index('page_calendar', table_name='page')
+ op.drop_index('page_owner', table_name='page')
+ op.drop_index('page_title', table_name='page')
+ op.drop_index('page_touched', table_name='page')
+ op.create_index(op.f('ix_page_title'), 'page', ['title'], unique=False)
+ op.create_index(op.f('ix_page_touched'), 'page', ['touched'], unique=False)
+ op.alter_column('pagelink', 'from_page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('pagelink', 'to_page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.drop_constraint('pagelink_ibfk_2', 'pagelink', type_='foreignkey')
+ op.drop_constraint('pagelink_ibfk_1', 'pagelink', type_='foreignkey')
+ op.create_foreign_key(None, 'pagelink', 'page', ['from_page_id'], ['id'])
+ op.create_foreign_key(None, 'pagelink', 'page', ['to_page_id'], ['id'])
+ op.alter_column('pagepermission', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('pagepermission', 'group_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('pagepermission', 'permissions',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=True)
+ op.drop_constraint('pagepermission_ibfk_4', 'pagepermission', type_='foreignkey')
+ op.drop_constraint('pagepermission_ibfk_5', 'pagepermission', type_='foreignkey')
+ op.create_foreign_key(None, 'pagepermission', 'usergroup', ['group_id'], ['id'])
+ op.create_foreign_key(None, 'pagepermission', 'page', ['page_id'], ['id'])
+ op.alter_column('pageproperty', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('pageproperty', 'key',
+ existing_type=mysql.VARCHAR(length=64),
+ nullable=True)
+ op.alter_column('pageproperty', 'value',
+ existing_type=mysql.VARCHAR(length=8000),
+ nullable=True)
+ op.alter_column('pagerevision', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('pagerevision', 'comment',
+ existing_type=mysql.VARCHAR(length=1024),
+ nullable=True)
+ op.alter_column('pagerevision', 'textref_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('pagerevision', 'pub_date',
+ existing_type=mysql.DATETIME(),
+ nullable=True)
+ op.alter_column('pagerevision', 'length',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.drop_constraint('pagerevision_ibfk_1', 'pagerevision', type_='foreignkey')
+ op.drop_constraint('pagerevision_ibfk_2', 'pagerevision', type_='foreignkey')
+ op.drop_constraint('pagerevision_ibfk_3', 'pagerevision', type_='foreignkey')
+ op.create_foreign_key(None, 'pagerevision', 'pagetext', ['textref_id'], ['id'])
+ op.create_foreign_key(None, 'pagerevision', 'page', ['page_id'], ['id'])
+ op.create_foreign_key(None, 'pagerevision', 'user', ['user_id'], ['id'])
+ op.alter_column('pagetag', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('pagetag', 'name',
+ existing_type=mysql.VARCHAR(length=64),
+ nullable=True)
+ op.drop_constraint('pagetag_ibfk_1', 'pagetag', type_='foreignkey')
+ op.create_foreign_key(None, 'pagetag', 'page', ['page_id'], ['id'])
+ op.alter_column('pagetext', 'content',
+ existing_type=sa.BLOB(),
+ nullable=True)
+ op.alter_column('pagetext', 'flags',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=True)
+ op.add_column('user', sa.Column('privileges', sa.BigInteger(), nullable=True))
+ op.add_column('user', sa.Column('restrictions', sa.BigInteger(), nullable=True))
+ op.alter_column('user', 'username',
+ existing_type=mysql.VARCHAR(length=32),
+ nullable=True)
+ op.alter_column('user', 'password',
+ existing_type=mysql.VARCHAR(length=255),
+ nullable=True)
+ op.alter_column('user', 'join_date',
+ existing_type=mysql.DATETIME(),
+ nullable=True)
+ op.alter_column('user', 'karma',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.drop_column('user', 'is_disabled')
+ op.drop_column('user', 'is_admin')
+ op.drop_column('user', 'color_theme')
+ op.alter_column('usergroup', 'name',
+ existing_type=mysql.VARCHAR(length=32),
+ nullable=True)
+ op.alter_column('usergroup', 'permissions',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=True)
+ op.alter_column('usergroupmembership', 'user_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('usergroupmembership', 'group_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=True)
+ op.alter_column('usergroupmembership', 'since',
+ existing_type=mysql.DATETIME(),
+ nullable=True)
+ op.drop_index('usergroupmembership_group_id', table_name='usergroupmembership')
+ op.drop_index('usergroupmembership_user_id', table_name='usergroupmembership')
+ # ### end Alembic commands ###
+
+
+def upgrade() -> None:
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.create_index('usergroupmembership_user_id', 'usergroupmembership', ['user_id'], unique=False)
+ op.create_index('usergroupmembership_group_id', 'usergroupmembership', ['group_id'], unique=False)
+ op.alter_column('usergroupmembership', 'since',
+ existing_type=mysql.DATETIME(),
+ nullable=False)
+ op.alter_column('usergroupmembership', 'group_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('usergroupmembership', 'user_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('usergroup', 'permissions',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=False)
+ op.alter_column('usergroup', 'name',
+ existing_type=mysql.VARCHAR(length=32),
+ nullable=False)
+ op.add_column('user', sa.Column('color_theme', mysql.SMALLINT(display_width=6), server_default=sa.text('0'), autoincrement=False, nullable=False))
+ op.add_column('user', sa.Column('is_admin', mysql.TINYINT(display_width=1), server_default=sa.text('0'), autoincrement=False, nullable=False))
+ op.add_column('user', sa.Column('is_disabled', mysql.TINYINT(display_width=1), server_default=sa.text('0'), autoincrement=False, nullable=False))
+ op.alter_column('user', 'karma',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('user', 'join_date',
+ existing_type=mysql.DATETIME(),
+ nullable=False)
+ op.alter_column('user', 'password',
+ existing_type=mysql.VARCHAR(length=255),
+ nullable=False)
+ op.alter_column('user', 'username',
+ existing_type=mysql.VARCHAR(length=32),
+ nullable=False)
+ op.drop_column('user', 'restrictions')
+ op.drop_column('user', 'privileges')
+ op.alter_column('pagetext', 'flags',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=False)
+ op.alter_column('pagetext', 'content',
+ existing_type=sa.BLOB(),
+ nullable=False)
+ op.drop_constraint(None, 'pagetag', type_='foreignkey')
+ op.create_foreign_key('pagetag_ibfk_1', 'pagetag', 'page', ['page_id'], ['id'], ondelete='CASCADE')
+ op.alter_column('pagetag', 'name',
+ existing_type=mysql.VARCHAR(length=64),
+ nullable=False)
+ op.alter_column('pagetag', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.drop_constraint(None, 'pagerevision', type_='foreignkey')
+ op.drop_constraint(None, 'pagerevision', type_='foreignkey')
+ op.drop_constraint(None, 'pagerevision', type_='foreignkey')
+ op.create_foreign_key('pagerevision_ibfk_3', 'pagerevision', 'user', ['user_id'], ['id'], ondelete='SET NULL')
+ op.create_foreign_key('pagerevision_ibfk_2', 'pagerevision', 'page', ['page_id'], ['id'], ondelete='CASCADE')
+ op.create_foreign_key('pagerevision_ibfk_1', 'pagerevision', 'pagetext', ['textref_id'], ['id'], ondelete='CASCADE')
+ op.alter_column('pagerevision', 'length',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('pagerevision', 'pub_date',
+ existing_type=mysql.DATETIME(),
+ nullable=False)
+ op.alter_column('pagerevision', 'textref_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('pagerevision', 'comment',
+ existing_type=mysql.VARCHAR(length=1024),
+ nullable=False)
+ op.alter_column('pagerevision', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('pageproperty', 'value',
+ existing_type=mysql.VARCHAR(length=8000),
+ nullable=False)
+ op.alter_column('pageproperty', 'key',
+ existing_type=mysql.VARCHAR(length=64),
+ nullable=False)
+ op.alter_column('pageproperty', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.drop_constraint(None, 'pagepermission', type_='foreignkey')
+ op.drop_constraint(None, 'pagepermission', type_='foreignkey')
+ op.create_foreign_key('pagepermission_ibfk_5', 'pagepermission', 'usergroup', ['group_id'], ['id'], ondelete='CASCADE')
+ op.create_foreign_key('pagepermission_ibfk_4', 'pagepermission', 'page', ['page_id'], ['id'], ondelete='CASCADE')
+ op.alter_column('pagepermission', 'permissions',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=False)
+ op.alter_column('pagepermission', 'group_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('pagepermission', 'page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.drop_constraint(None, 'pagelink', type_='foreignkey')
+ op.drop_constraint(None, 'pagelink', type_='foreignkey')
+ op.create_foreign_key('pagelink_ibfk_1', 'pagelink', 'page', ['to_page_id'], ['id'], ondelete='CASCADE')
+ op.create_foreign_key('pagelink_ibfk_2', 'pagelink', 'page', ['from_page_id'], ['id'], ondelete='CASCADE')
+ op.alter_column('pagelink', 'to_page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.alter_column('pagelink', 'from_page_id',
+ existing_type=mysql.INTEGER(display_width=11),
+ nullable=False)
+ op.drop_index(op.f('ix_page_touched'), table_name='page')
+ op.drop_index(op.f('ix_page_title'), table_name='page')
+ op.create_index('page_touched', 'page', ['touched'], unique=False)
+ op.create_index('page_title', 'page', ['title'], unique=False)
+ op.create_index('page_owner', 'page', ['owner_id'], unique=False)
+ op.create_index('page_calendar', 'page', ['calendar'], unique=False)
+ op.alter_column('page', 'flags',
+ existing_type=mysql.BIGINT(display_width=20),
+ nullable=False)
+ op.alter_column('page', 'touched',
+ existing_type=mysql.DATETIME(),
+ nullable=False)
+ op.alter_column('page', 'title',
+ existing_type=mysql.VARCHAR(length=256),
+ nullable=False)
+ op.create_table('upload',
+ sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
+ sa.Column('name', mysql.VARCHAR(length=256), nullable=False),
+ sa.Column('url_name', mysql.VARCHAR(length=256), nullable=True),
+ sa.Column('filetype', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('filesize', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),
+ sa.Column('upload_date', mysql.DATETIME(), nullable=False),
+ sa.Column('md5', mysql.VARCHAR(length=32), nullable=False),
+ sa.PrimaryKeyConstraint('id'),
+ mariadb_collate='utf8mb4_general_ci',
+ mariadb_default_charset='utf8mb4',
+ mariadb_engine='InnoDB'
+ )
+ op.create_index('upload_upload_date', 'upload', ['upload_date'], unique=False)
+ op.create_index('upload_md5', 'upload', ['md5'], unique=False)
+ try:
+ ## drop tables removed in 0.x
+ op.drop_table('pagepolicykey')
+ op.drop_index('pagepolicy_key_id', table_name='pagepolicy')
+ op.drop_index('pagepolicy_page_id', table_name='pagepolicy')
+ op.drop_index('pagepolicy_page_id_key_id', table_name='pagepolicy')
+ op.drop_table('pagepolicy')
+ op.drop_index('upload_md5', table_name='upload')
+ op.drop_index('upload_upload_date', table_name='upload')
+ op.drop_table('upload')
+ except Exception:
+ pass
+ # ### end Alembic commands ###
diff --git a/app.py b/app.py
deleted file mode 100644
index 4d89c54..0000000
--- a/app.py
+++ /dev/null
@@ -1,1397 +0,0 @@
-# (C) 2020-2021 Sakuragasaki46.
-# See LICENSE for copying info.
-
-'''
-A simple wiki-like note webapp.
-
-Pages are stored in SQLite/MySQL databases.
-Markdown is used for text formatting.
-
-Application is kept compact, with all its core in a single file.
-'''
-
-#### IMPORTS ####
-
-from flask import (
- Flask, Markup, abort, flash, g, jsonify, make_response, redirect, request,
- render_template, send_from_directory)
-from flask_login import LoginManager, login_user, logout_user, current_user, login_required
-from flask_wtf import CSRFProtect
-from werkzeug.security import generate_password_hash, check_password_hash
-from werkzeug.routing import BaseConverter
-from peewee import *
-from playhouse.db_url import connect as dbconnect
-import calendar, datetime, hashlib, html, importlib, json, markdown, os, random, \
- re, sys, warnings
-from functools import lru_cache, partial
-from urllib.parse import quote
-from configparser import ConfigParser
-import i18n
-import gzip
-from getpass import getpass
-
-__version__ = '0.8'
-
-#### CONSTANTS ####
-
-APP_BASE_DIR = os.path.dirname(__file__)
-
-FK = ForeignKeyField
-
-SLUG_RE = r'[a-z0-9]+(?:-[a-z0-9]+)*'
-ILINK_RE = r'\]\(/(p/\d+|' + SLUG_RE + ')/?\)'
-USERNAME_RE = r'[a-z0-9_-]{3,30}'
-PING_RE = r'(?' + match.group(1) + ''
-
-# XXX ugly monkeypatch to make spoilers prevail over blockquotes
-from markdown.blockprocessors import BlockQuoteProcessor
-BlockQuoteProcessor.RE = re.compile(r'(^|\n)[ ]{0,3}>(?!!)[ ]?(.*)')
-
-### XXX it currently only detects spoilers that are not at the beginning of the line. To be fixed.
-class SpoilerExtension(markdown.extensions.Extension):
- def extendMarkdown(self, md, md_globals=None):
- md.inlinePatterns.register(markdown.inlinepatterns.SimpleTagInlineProcessor(r'()>!(.*?)!<', 'span class="spoiler"'), 'spoiler', 14)
-
-
-#class PingExtension(markdown.extensions.Extension):
-# def extendMarkdown(self, md):
-# pass
-
-#### DATABASE SCHEMA ####
-
-database_url = _getconf('database', 'url')
-if database_url:
- database = dbconnect(database_url)
-else:
- database = SqliteDatabase(_getconf("database", "directory") + '/data.sqlite')
-
-class BaseModel(Model):
- class Meta:
- database = database
-
-# Used for PagePolicy
-def _passphrase_hash(pp):
- pp_bin = pp.encode('utf-8')
- h = str(len(pp_bin)) + ':' + hashlib.sha256(pp_bin).hexdigest()
- return h
-
-class User(BaseModel):
- username = CharField(32, unique=True)
- email = CharField(256, null=True)
- password = CharField()
- join_date = DateTimeField(default=datetime.datetime.now)
- karma = IntegerField(default=1)
- privileges = BitField()
- is_admin = privileges.flag(1)
- restrictions = BitField()
- is_disabled = restrictions.flag(1)
-
- # helpers for flask_login
- @property
- def is_anonymous(self):
- return False
- @property
- def is_active(self):
- return not self.is_disabled
- @property
- def is_authenticated(self):
- return True
-
- @property
- def groups(self):
- return (
- UserGroup.select().join(UserGroupMembership, on=UserGroupMembership.group)
- .where(UserGroupMembership.user == self)
- )
-
- def get_perms(self):
- if self.is_admin:
- return PERM_ALL
-
- perm = 0
-
- for gr in self.groups:
- perm |= gr.permissions
-
- return perm
-
-
-# page perms (used as bitmasks)
-PERM_READ = 1
-PERM_EDIT = 2
-PERM_CREATE = 4
-PERM_SET_URL = 8
-PERM_SET_TAGS = 16
-PERM_ALL = 31
-PERM_LOCK = ~(PERM_EDIT | PERM_CREATE | PERM_SET_URL | PERM_SET_TAGS)
-
-class UserGroup(BaseModel):
- name = CharField(32, unique=True)
- permissions = BitField()
- # Can read pages.
- can_read = permissions.flag(1)
- # Can edit all non-locked pages.
- can_edit = permissions.flag(2)
- # Can create and edit their own pages.
- can_create = permissions.flag(4)
- # Can set page URL.
- can_set_url = permissions.flag(8)
- # Can change page tags.
- can_set_tags = permissions.flag(16)
-
- @classmethod
- def get_default_group(cls):
- try:
- return cls[1]
- except cls.DoesNotExist:
- return cls.get(cls.name == 'default')
-
-class UserGroupMembership(BaseModel):
- user = ForeignKeyField(User, backref='group_memberships')
- group = ForeignKeyField(UserGroup, backref='user_memberships')
- since = DateTimeField(default=datetime.datetime.now)
-
- class Meta:
- indexes = (
- (('user', 'group'), True),
- )
-
-
-class Page(BaseModel):
- url = CharField(64, unique=True, null=True)
- title = CharField(256, index=True)
- touched = DateTimeField(index=True)
- calendar = DateTimeField(index=True, null=True)
- owner = ForeignKeyField(User, null=True)
- flags = BitField()
- is_redirect = flags.flag(1)
- is_sync = flags.flag(2)
- is_math_enabled = flags.flag(4)
- is_locked = flags.flag(8)
- is_cw = flags.flag(16)
- @property
- def latest(self):
- if self.revisions:
- return self.revisions.order_by(PageRevision.pub_date.desc())[0]
- def get_url(self):
- return '/' + self.url + '/' if self.url else '/p/{}/'.format(self.id)
- def short_desc(self):
- if self.is_cw:
- return '(Content Warning: we are not allowed to show a description.)'
- full_text = self.latest.text
- text = remove_tags(full_text, convert = not self.is_math_enabled and not _getconf('appearance', 'simple_remove_tags', False))
- return text[:200] + ('\u2026' if len(text) > 200 else '')
- def change_tags(self, new_tags):
- old_tags = set(x.name for x in self.tags)
- new_tags = set(new_tags)
- PageTag.delete().where((PageTag.page == self) &
- (PageTag.name << (old_tags - new_tags))).execute()
- for tag in (new_tags - old_tags):
- PageTag.create(page=self, name=tag)
- def js_info(self):
- latest = self.latest
- return dict(
- id=self.id,
- url=self.url,
- title=self.title,
- is_redirect=self.is_redirect,
- touched=self.touched.timestamp(),
- is_editable=self.is_editable(),
- latest=dict(
- id=latest.id if latest else None,
- length=latest.length,
- pub_date=latest.pub_date.timestamp() if latest and latest.pub_date else None
- ),
- tags=[x.name for x in self.tags]
- )
- @property
- def prop(self):
- return PagePropertyDict(self)
- def is_editable(self):
- return self.can_edit(current_user)
-
- def can_edit(self, user):
- perm = self.get_perms(user)
- return perm & PERM_EDIT or (self.owner == user and perm & PERM_CREATE)
- def is_owned_by(self, user):
- return user.id == self.owner.id
-
- def get_perms(self, user=None):
- if user is None:
- user = current_user
-
- if user.is_anonymous:
- return UserGroup.get_default_group().permissions & PERM_LOCK
-
- if user.is_admin:
- return PERM_ALL
-
- perm = 0
- # default groups
- for gr in user.groups:
- perm |= gr.permissions
-
- # page overrides
- for ov in self.permission_overrides:
- if ov.group in user.groups:
- perm |= ov.permissions
-
- if self.is_locked and self.owner.id != user.id:
- perm &= PERM_LOCK
- return perm
-
- def seo_keywords(self):
- kw = []
- for tag in self.tags:
- kw.append(tag.name.replace("-", " "))
- for bkl in self.back_links:
- try:
- kw.append(bkl.from_page.title.replace(",", ""))
- except Exception:
- pass
- return ", ".join(kw)
-
-
-class PageText(BaseModel):
- content = BlobField()
- flags = BitField()
- is_utf8 = flags.flag(1)
- is_gzipped = flags.flag(2)
- def get_content(self):
- c = self.content
- if self.is_gzipped:
- c = gzip.decompress(c)
- if self.is_utf8:
- return c.decode('utf-8')
- else:
- return c.decode('latin-1')
- @classmethod
- def create_content(cls, text, *, treshold=600, search_dup=True):
- c = text.encode('utf-8')
- use_gzip = len(c) > treshold
- if use_gzip and gzip:
- c = gzip.compress(c)
- if search_dup:
- item = cls.get_or_none((cls.content == c) & (cls.is_gzipped == use_gzip))
- if item:
- return item
- return cls.create(
- content=c,
- is_utf8=True,
- is_gzipped=use_gzip
- )
-
-class PageRevision(BaseModel):
- page = FK(Page, backref='revisions', index=True)
- user = ForeignKeyField(User, backref='contributions', null=True)
- comment = CharField(1024, default='')
- textref = FK(PageText)
- pub_date = DateTimeField(index=True)
- length = IntegerField()
- @property
- def text(self):
- return self.textref.get_content()
- def html(self, *, math=True):
- return md(self.text, math=self.page.is_math_enabled and math)
- def html_and_toc(self, *, math=True):
- return md_and_toc(self.text, math=self.page.is_math_enabled and math)
- def human_pub_date(self):
- delta = datetime.datetime.now() - self.pub_date
- T = partial(get_string, g.lang)
- if delta < datetime.timedelta(seconds=60):
- return T('just-now')
- elif delta < datetime.timedelta(seconds=3600):
- return T('n-minutes-ago').format(delta.seconds // 60)
-
- elif delta < datetime.timedelta(days=1):
- return T('n-hours-ago').format(delta.seconds // 3600)
- elif delta < datetime.timedelta(days=15):
- return T('n-days-ago').format(delta.days)
- else:
- return self.pub_date.strftime('%B %-d, %Y')
-
-class PageTag(BaseModel):
- page = FK(Page, backref='tags', index=True)
- name = CharField(64, index=True)
- class Meta:
- indexes = (
- (('page', 'name'), True),
- )
- def popularity(self):
- return PageTag.select().where(PageTag.name == self.name).count()
-
-class PageProperty(BaseModel):
- page = ForeignKeyField(Page, backref='page_meta', index=True)
- key = CharField(64)
- value = CharField(8000)
- class Meta:
- indexes = (
- (('page', 'key'), True),
- )
-
-# currently experimental
-class PagePropertyDict(object):
- def __init__(self, page):
- self._page = page
- def items(self):
- for kv in self._page.page_meta:
- yield kv.key, kv.value
- def __len__(self):
- return self._page.page_meta.count()
- def keys(self):
- for kv in self._page.page_meta:
- yield kv.key
- __iter__ = keys
- def __getitem__(self, key):
- try:
- return self._page.page_meta.get(PageProperty.key == key).value
- except PageProperty.DoesNotExist:
- raise KeyError(key)
- def get(self, key, default=None):
- try:
- return self._page.page_meta.get(PageProperty.key == key).value
- except PageProperty.DoesNotExist:
- return default
- def setdefault(self, key, default):
- try:
- return self._page.page_meta.get(PageProperty.key == key).value
- except PageProperty.DoesNotExist:
- self[key] = default
- return default
- def __setitem__(self, key, value):
- if key in self:
- pp = self._page.page_meta.get(PageProperty.key == key)
- pp.value = value
- pp.save()
- else:
- PageProperty.create(page=self._page, key=key, value=value)
- def __delitem__(self, key):
- PageProperty.delete().where((PageProperty.page == self._page) &
- (PageProperty.key == key)).execute()
- def __contains__(self, key):
- return PageProperty.select().where((PageProperty.page == self._page) &
- (PageProperty.key == key)).exists()
-
-
-# Link table for caching purposes.
-class PageLink(BaseModel):
- from_page = FK(Page, backref='forward_links')
- to_page = FK(Page, backref='back_links')
-
- class Meta:
- indexes = (
- (('from_page', 'to_page'), True),
- )
-
- @classmethod
- def parse_links(cls, from_page, text, erase=True):
- with database.atomic():
- old_links = list(cls.select().where(cls.from_page == from_page))
- for mo in re.finditer(ILINK_RE, text):
- try:
- pageurl = mo.group(1)
- if pageurl.startswith('p/'):
- to_page = Page[int(pageurl[2:])]
- else:
- to_page = Page.get(Page.url == pageurl)
-
- linkobj, created = PageLink.get_or_create(
- from_page = from_page,
- to_page = to_page)
- if linkobj in old_links:
- old_links.remove(linkobj)
- except Exception:
- continue
- if erase:
- for linkobj in old_links:
- linkobj.delete_instance()
-
- # The actual ULTIMATE method to refresh all links
- # To be called from a maintenance script only!
- @classmethod
- def refresh_all_links(cls):
- for p in Page.select():
- cls.parse_links(p, p.latest.text)
-
-class PagePermission(BaseModel):
- page = ForeignKeyField(Page, backref='permission_overrides')
- group = ForeignKeyField(UserGroup, backref='page_permissions')
- permissions = BitField()
- # Can read pages.
- can_read = permissions.flag(1)
- # Can edit all non-locked pages.
- can_edit = permissions.flag(2)
- # Can create and edit their own pages.
- can_create = permissions.flag(4)
- # Can set page URL.
- can_set_url = permissions.flag(8)
- # Can change page tags.
- can_set_tags = permissions.flag(16)
-
- class Meta:
- indexes = (
- (('page', 'group'), True),
- )
-
-def init_db():
- database.create_tables([
- User, UserGroup, UserGroupMembership,
- Page, PageText, PageRevision, PageTag, PageProperty, PageLink,
- PagePermission
- ])
-
-def init_db_and_create_first_user():
- try:
- User[1]
- UserGroup[1]
- except Exception:
- pass
- else:
- print('Looks like this site is already set up!')
- return
- username = input('Username: ')
- password = getpass('Password: ')
- confirm_password = getpass('Confirm password: ')
- email = input('Email: (optional)') or None
- if not is_username(username):
- print('Invalid username: usernames can contain only letters, numbers, underscores and hyphens.')
- return
- if password != confirm_password:
- print('Passwords do not match.')
- return
- default_permissions = PERM_ALL # all permissions
- if not input('Agree to the Terms of Use?')[0].lower() == 'y':
- print('You must accept Terms in order to register.')
- return
- with database.atomic():
- init_db()
- ua = User.create(
- username = username,
- email = email,
- password = generate_password_hash(password),
- join_date = datetime.datetime.now(),
- is_admin = True
- )
- ug = UserGroup.create(
- name = 'default',
- permissions = int(default_permissions)
- )
- UserGroupMembership.create(
- user = ua,
- group = ug
- )
- print('Installed successfully!')
-
-#### PERMS HELPERS ####
-
-def has_perms(user, flags, page=None):
- if page:
- perm = page.get_perms(user)
- else:
- perm = user.get_perms()
-
- if perm & flags:
- return True
- return False
-
-#### WIKI SYNTAX ####
-
-def md_and_toc(text, expand_magic=False, toc=True, math=True):
- if expand_magic:
- # DEPRECATED seeking for a better solution.
- warnings.warn('Magic words are no more supported.', DeprecationWarning)
- extensions = ['tables', 'footnotes', 'fenced_code', 'sane_lists']
- extension_configs = {}
- if not _getconf('markdown', 'disable_custom_extensions'):
- extensions.append(StrikethroughExtension())
- extensions.append(SpoilerExtension())
- if toc:
- extensions.append('toc')
- if math and markdown_katex and ('$`' in text or '```math' in text):
- extensions.append('markdown_katex')
- extension_configs['markdown_katex'] = {
- 'no_inline_svg': True,
- 'insert_fonts_css': not _getconf('site', 'katex_url')
- }
- try:
- converter = markdown.Markdown(extensions=extensions, extension_configs=extension_configs)
- if toc:
- return converter.convert(text), converter.toc
- else:
- return converter.convert(text), ''
- except Exception as e:
- return '
There was an error during rendering: {e.__class__.__name__}: {e}
+
+{% endblock %}
\ No newline at end of file
diff --git a/extensions/__init__.py b/salvi/templates/macros/icon.html
similarity index 100%
rename from extensions/__init__.py
rename to salvi/templates/macros/icon.html
diff --git a/salvi/templates/macros/nl.html b/salvi/templates/macros/nl.html
new file mode 100644
index 0000000..a4355fd
--- /dev/null
+++ b/salvi/templates/macros/nl.html
@@ -0,0 +1,70 @@
+
+
+
+{#
+ Recommendations: Always import this macro with context,
+ otherwise it fails. It depends on a couple context-defined functions.
+#}
+
+{# TODO rewrite to fit! #}
+{# TODO rewrite to fit! #}
+
+{% macro nl_list(l, hl_tags=(), hl_calendar=None, other_url='p/most_recent', is_main = False) %}
+{% set page_n = l.page %}
+{% set total_count = l.total %}
+
+{% if not is_main %}
+