Compare commits
No commits in common. "master" and "v0.4" have entirely different histories.
104 changed files with 2785 additions and 4339 deletions
39
.gitignore
vendored
39
.gitignore
vendored
|
|
@ -1,29 +1,14 @@
|
||||||
node_modules/
|
# application content
|
||||||
__pycache__/
|
media/
|
||||||
|
**.sqlite
|
||||||
|
database/
|
||||||
|
site.conf
|
||||||
|
run_8180.py
|
||||||
|
|
||||||
|
# automatically generated garbage
|
||||||
|
**/__pycache__/
|
||||||
**.pyc
|
**.pyc
|
||||||
**~
|
**~
|
||||||
.*.swp
|
**/.\#*
|
||||||
\#*\#
|
**/\#*\#
|
||||||
.\#*
|
ig_api_settings/
|
||||||
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
|
|
||||||
|
|
||||||
|
|
|
||||||
104
CHANGELOG.md
104
CHANGELOG.md
|
|
@ -1,109 +1,5 @@
|
||||||
# What’s New
|
# 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:
|
|
||||||
+ New tables `UserGroup`, `UserGroupMembership` and `PagePermission`.
|
|
||||||
+ Added flag `is_cw` to `Page`.
|
|
||||||
+ Added `restrictions` field to `User`.
|
|
||||||
+ Pages now can have a Content Warning. It prevents them to show up in previews, and adds a
|
|
||||||
caution message when viewing them.
|
|
||||||
+ SEO improvement: added `keywords` and `description` meta tags to viewing pages.
|
|
||||||
+ Added Terms, Privacy Policy and Rules.
|
|
||||||
+ Changed user page URLs (contributions page) from `/u/user` to `/@user`.
|
|
||||||
+ `/manage/` is now a list of all managing options, including export/import and the brand new
|
|
||||||
`/manage/accounts`.
|
|
||||||
+ Users can now be disabled (and re-enabled) by administrator.
|
|
||||||
+ TOC is now shown in pages when screen width is greater than 960 pixels.
|
|
||||||
+ Style changes: added a top bar with the site title. It replaces the floating menu on the top right.
|
|
||||||
+ Now logged-in users have an “Edit” button below the first heading. All users can access page history
|
|
||||||
by clicking the last modified time.
|
|
||||||
+ Added a built-in installer (`app_init.py`). You still need to manually create `site.conf`.
|
|
||||||
|
|
||||||
## 0.7.1
|
|
||||||
|
|
||||||
+ Improved calendar view. Now `/calendar` shows a list of years and months.
|
|
||||||
|
|
||||||
## 0.7
|
|
||||||
|
|
||||||
+ Schema changes:
|
|
||||||
+ Removed `PagePolicy` and `PagePolicyKey` tables altogether. They were never useful.
|
|
||||||
+ Added `calendar` field to `Page`.
|
|
||||||
+ Added `User` table.
|
|
||||||
+ Added `Flask-Login` and `Flask-WTF` dependencies in order to implement user logins.
|
|
||||||
+ Added `python-i18n` as a dependency. Therefore, i18n changed format, using JSON files now.
|
|
||||||
+ Login is now required for creating and editing.
|
|
||||||
+ Now you can leave a comment while changing a page’s text. Moreover, a new revision is created now
|
|
||||||
only in case of an effective text change.
|
|
||||||
+ Now a page can be dated in the calendar.
|
|
||||||
+ Now you can export and import pages in a JSON format. Importing can be done by admin users only.
|
|
||||||
+ Improved page history view, and added user contributions page.
|
|
||||||
+ Updated Markdown extensions to work under latest version.
|
|
||||||
+ Like it or not, now gzip library is required.
|
|
||||||
+ Added CSS variables in the site style.
|
|
||||||
+ Templates are now with `.jinja2` extension.
|
|
||||||
|
|
||||||
## 0.6
|
|
||||||
|
|
||||||
+ Added support for database URLs: you can now specify the URL of the database
|
|
||||||
in `site.conf` by setting `[database]url`, be it MySQL, PostgreSQL or SQLite.
|
|
||||||
+ Added experimental math support, with `markdown_katex` library. The math
|
|
||||||
parsing can be opted out in many ways.
|
|
||||||
+ Backlinks can now be accessed for each page.
|
|
||||||
+ Spoiler tags at beginning of line now work. Just for now.
|
|
||||||
+ Removed `Upload` table.
|
|
||||||
+ Added `PageLink` table.
|
|
||||||
|
|
||||||
## 0.5
|
|
||||||
|
|
||||||
+ Removed support for uploads. The `/upload/` endpoint now points to an info
|
|
||||||
page, and the “Upload image” button and gallery from home page are now gone.
|
|
||||||
+ `markdown_strikethrough` extension is no more needed. Now there are two new
|
|
||||||
built-in extensions: `StrikethroughExtension` and `SpoilerExtension` (the
|
|
||||||
last one is buggy tho).
|
|
||||||
+ Removed support for magic words (the commands between `{{` `}}`). These
|
|
||||||
features are now lost: `backto`, `media` and `gallery` (easily replaceable
|
|
||||||
with simple Markdown).
|
|
||||||
+ Added app version to site footer.
|
|
||||||
+ Added client-side drafts (they require JS enabled).
|
|
||||||
|
|
||||||
## 0.4
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## 0.3
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## 0.2
|
## 0.2
|
||||||
|
|
||||||
+ Some code refactoring.
|
+ Some code refactoring.
|
||||||
|
|
|
||||||
68
LICENSE
68
LICENSE
|
|
@ -1,55 +1,19 @@
|
||||||
|
Copyright (C) 2020-2021 Sakuragasaki46
|
||||||
|
|
||||||
Copyright (c) 2020-2025 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:
|
||||||
|
|
||||||
Apache License
|
The above copyright notice and this permission notice shall be included
|
||||||
Version 2.0, January 2004
|
in all copies or substantial portions of the Software.
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
1. Definitions.
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
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
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
SOFTWARE.
|
||||||
|
|
||||||
"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
|
|
||||||
|
|
|
||||||
20
LICENSE.0_9
20
LICENSE.0_9
|
|
@ -1,20 +0,0 @@
|
||||||
|
|
||||||
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.
|
|
||||||
47
README.md
47
README.md
|
|
@ -11,53 +11,22 @@ suitable as a community or team knowledge base.
|
||||||
+ Write notes on the go, using Markdown syntax
|
+ Write notes on the go, using Markdown syntax
|
||||||
+ Any note can have its own URL
|
+ Any note can have its own URL
|
||||||
+ Revision history
|
+ Revision history
|
||||||
+ Stored in SQLite/MySQL databases
|
+ Stored in SQLite databases
|
||||||
+ Material Icons
|
+ Material Icons
|
||||||
+ Light/dark theme
|
+ Light/dark theme
|
||||||
+ Calendar
|
|
||||||
+ Works fine even with JavaScript disabled.
|
+ Works fine even with JavaScript disabled.
|
||||||
|
|
||||||
## Requirements & Dependencies
|
## Requirements
|
||||||
|
|
||||||
+ **Python** <mark>3.10+</mark>.
|
+ **Python** 3.6+.
|
||||||
+ **Flask** web framework (and Flask-Login / Flask-WTF / Flask-Arrest extensions).
|
+ **Flask** web framework.
|
||||||
+ **SQLAlchemy** ORM.
|
+ **Peewee** ORM.
|
||||||
+ **Markdown** for page rendering.
|
|
||||||
+ **[SUOU](https://github.com/yusurko/suou)**. <mark>(since 1.0)</mark>
|
|
||||||
* **Python-Dotenv**.
|
|
||||||
+ The database drivers needed for the type of database.
|
|
||||||
|
|
||||||
To install the dependencies, run (virtualenv advised):
|
|
||||||
> `pip install -e .`
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
+ Clone this repository: `git clone https://github.com/yusurko/salvi`
|
|
||||||
+ Edit `.env` with the needed parameters. An example `.env` with MySQL:
|
|
||||||
|
|
||||||
```
|
|
||||||
APP_NAME=Salvi
|
|
||||||
DATABASE_URL=mysql://root:root@localhost/salvi
|
|
||||||
```
|
|
||||||
|
|
||||||
+ 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
|
## Caveats
|
||||||
|
|
||||||
+ The whole application is free of unit tests. Ergo untested. No coverage.
|
+ All pages created are, as of now, viewable and editable by anyone, with no
|
||||||
+ If you forget the password, there is currently no way to reset it. E-mail is not supported as of 1.0.
|
trace of users and/or passwords.
|
||||||
+ This app comes with no content. It means, you have to write it yourself.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Since 1.0, Salvi is licensed under the [Apache License, Version 2.0](LICENSE), a non-copyleft free and open source license.
|
[MIT License](./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.
|
|
||||||
|
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
Generic single-database configuration.
|
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
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()
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
"""${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"}
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
"""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 ###
|
|
||||||
|
|
@ -1,312 +0,0 @@
|
||||||
"""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 ###
|
|
||||||
893
app.py
Normal file
893
app.py
Normal file
|
|
@ -0,0 +1,893 @@
|
||||||
|
# (C) 2020-2021 Sakuragasaki46.
|
||||||
|
# See LICENSE for copying info.
|
||||||
|
|
||||||
|
'''
|
||||||
|
A simple wiki-like note webapp.
|
||||||
|
|
||||||
|
Pages are stored in SQLite databases.
|
||||||
|
Markdown is used for text formatting.
|
||||||
|
|
||||||
|
Application is kept compact, with all its core in a single file.
|
||||||
|
Extensions are supported (?), kept in extensions/ folder.
|
||||||
|
'''
|
||||||
|
|
||||||
|
#### IMPORTS ####
|
||||||
|
|
||||||
|
from flask import (
|
||||||
|
Flask, Markup, abort, flash, g, jsonify, make_response, redirect, request,
|
||||||
|
render_template, send_from_directory)
|
||||||
|
from werkzeug.routing import BaseConverter
|
||||||
|
from peewee import *
|
||||||
|
import csv, datetime, hashlib, html, importlib, json, markdown, os, random, \
|
||||||
|
re, sys, uuid, warnings
|
||||||
|
from functools import lru_cache, partial
|
||||||
|
from urllib.parse import quote
|
||||||
|
from configparser import ConfigParser
|
||||||
|
try:
|
||||||
|
import gzip
|
||||||
|
except ImportError:
|
||||||
|
gzip = None
|
||||||
|
try:
|
||||||
|
from slugify import slugify
|
||||||
|
except ImportError:
|
||||||
|
slugify = None
|
||||||
|
try:
|
||||||
|
import markdown_strikethrough
|
||||||
|
except Exception:
|
||||||
|
markdown_strikethrough = None
|
||||||
|
|
||||||
|
__version__ = '0.4'
|
||||||
|
|
||||||
|
#### CONSTANTS ####
|
||||||
|
|
||||||
|
APP_BASE_DIR = os.path.dirname(__file__)
|
||||||
|
|
||||||
|
FK = ForeignKeyField
|
||||||
|
|
||||||
|
SLUG_RE = r'[a-z0-9]+(?:-[a-z0-9]+)*'
|
||||||
|
MAGIC_RE = r'\{\{\s*(' + SLUG_RE + ')\s*:\s*(.*?)\s*\}\}'
|
||||||
|
REDIRECT_RE = r'\{\{\s*redirect\s*:\s*(\d+)\s*\}\}'
|
||||||
|
|
||||||
|
upload_types = {'jpeg': 1, 'jpg': 1, 'png': 2}
|
||||||
|
upload_types_rev = {1: 'jpg', 2: 'png'}
|
||||||
|
|
||||||
|
UPLOAD_DIR = APP_BASE_DIR + '/media'
|
||||||
|
DATABASE_DIR = APP_BASE_DIR + "/database"
|
||||||
|
|
||||||
|
#### GENERAL CONFIG ####
|
||||||
|
|
||||||
|
DEFAULT_CONF = {
|
||||||
|
('site', 'title'): 'Salvi',
|
||||||
|
('config', 'media_dir'): APP_BASE_DIR + '/media',
|
||||||
|
('config', 'database_dir'): APP_BASE_DIR + "/database",
|
||||||
|
}
|
||||||
|
|
||||||
|
_cfp = ConfigParser()
|
||||||
|
if _cfp.read([APP_BASE_DIR + '/site.conf']):
|
||||||
|
@lru_cache(maxsize=50)
|
||||||
|
def _getconf(k1, k2, fallback=None, cast=None):
|
||||||
|
if fallback is None:
|
||||||
|
fallback = DEFAULT_CONF.get((k1, k2))
|
||||||
|
v = _cfp.get(k1, k2, fallback=fallback)
|
||||||
|
if cast in (int, float, str):
|
||||||
|
try:
|
||||||
|
v = cast(v)
|
||||||
|
except ValueError:
|
||||||
|
v = fallback
|
||||||
|
return v
|
||||||
|
else:
|
||||||
|
def _getconf(k1, k2, fallback=None, cast=None):
|
||||||
|
if fallback is None:
|
||||||
|
fallback = DEFAULT_CONF.get((k1, k2))
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
#### misc. helpers ####
|
||||||
|
|
||||||
|
def _makelist(l):
|
||||||
|
if isinstance(l, (str, bytes, bytearray)):
|
||||||
|
return [l]
|
||||||
|
elif hasattr(l, '__iter__'):
|
||||||
|
return list(l)
|
||||||
|
elif l:
|
||||||
|
return [l]
|
||||||
|
else:
|
||||||
|
return []
|
||||||
|
|
||||||
|
#### DATABASE SCHEMA ####
|
||||||
|
|
||||||
|
database = SqliteDatabase(_getconf("config", "database_dir") + '/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 Page(BaseModel):
|
||||||
|
url = CharField(64, unique=True, null=True)
|
||||||
|
title = CharField(256, index=True)
|
||||||
|
touched = DateTimeField(index=True)
|
||||||
|
flags = BitField()
|
||||||
|
is_redirect = flags.flag(1)
|
||||||
|
is_sync = flags.flag(2)
|
||||||
|
@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):
|
||||||
|
text = remove_tags(self.latest.text)
|
||||||
|
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 unlock(self, perm, pp, sec):
|
||||||
|
## XX complete later!
|
||||||
|
policies = self.policies.where(PagePolicy.type << _makelist(perm))
|
||||||
|
if not policies.exists():
|
||||||
|
return True
|
||||||
|
for policy in policies:
|
||||||
|
if policy.verify(pp, sec):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
def is_locked(self, perm):
|
||||||
|
policies = self.policies.where(PagePolicy.type << _makelist(perm))
|
||||||
|
return policies.exists()
|
||||||
|
def is_classified(self):
|
||||||
|
return self.is_locked(POLICY_CLASSIFY)
|
||||||
|
def is_editable(self):
|
||||||
|
return not self.is_locked(POLICY_EDIT)
|
||||||
|
|
||||||
|
|
||||||
|
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_id = IntegerField(default=0)
|
||||||
|
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):
|
||||||
|
return md(self.text)
|
||||||
|
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()
|
||||||
|
|
||||||
|
# Store keys for PagePolicy.
|
||||||
|
# Experimental.
|
||||||
|
class PagePolicyKey(BaseModel):
|
||||||
|
passphrase = CharField()
|
||||||
|
sec_code = IntegerField()
|
||||||
|
class Meta:
|
||||||
|
indexes = (
|
||||||
|
(('passphrase','sec_code'), True),
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create_from_plain(cls, pp, sec):
|
||||||
|
PagePolicyKey.create(passphrase=_passphrase_hash(pp), sec_code=sec)
|
||||||
|
def verify(self, pp, sec):
|
||||||
|
h = _passphrase_hash(pp)
|
||||||
|
return self.passphrase == h and self.sec_code == sec
|
||||||
|
|
||||||
|
POLICY_ADMIN = 1
|
||||||
|
POLICY_READ = 2
|
||||||
|
POLICY_EDIT = 3
|
||||||
|
POLICY_META = 4
|
||||||
|
POLICY_CLASSIFY = 5
|
||||||
|
|
||||||
|
# Manage policies for pages (e.g., reading or editing).
|
||||||
|
# Experimental.
|
||||||
|
class PagePolicy(BaseModel):
|
||||||
|
page = FK(Page, backref='policies', index=True, null=True)
|
||||||
|
type = IntegerField()
|
||||||
|
key = FK(PagePolicyKey, backref='applied_to')
|
||||||
|
sitewide = IntegerField(default=0)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
indexes = (
|
||||||
|
(('page', 'key'), True),
|
||||||
|
)
|
||||||
|
|
||||||
|
class Upload(BaseModel):
|
||||||
|
name = CharField(256)
|
||||||
|
url_name = CharField(256, null=True)
|
||||||
|
filetype = SmallIntegerField()
|
||||||
|
filesize = IntegerField()
|
||||||
|
upload_date = DateTimeField(index=True)
|
||||||
|
md5 = CharField(32, index=True)
|
||||||
|
@property
|
||||||
|
def filepath(self):
|
||||||
|
return '{0}/{1}/{2}{3}.{4}'.format(self.md5[:1], self.md5[:2], self.id,
|
||||||
|
'-' + self.url_name if self.url_name else '', upload_types_rev[self.filetype])
|
||||||
|
@property
|
||||||
|
def url(self):
|
||||||
|
return '/media/' + self.filepath
|
||||||
|
def get_content(self, check=True):
|
||||||
|
with open(os.path.join(UPLOAD_DIR, self.filepath)) as f:
|
||||||
|
content = f.read()
|
||||||
|
if check:
|
||||||
|
if len(content) != self.filesize:
|
||||||
|
raise AssertionError('file is corrupted')
|
||||||
|
if hashlib.md5(content).hexdigest() != self.md5:
|
||||||
|
raise AssertionError('file is corrupted')
|
||||||
|
return content
|
||||||
|
@classmethod
|
||||||
|
def create_content(cls, name, ext, content):
|
||||||
|
ext = ext.lstrip('.')
|
||||||
|
if ext not in upload_types:
|
||||||
|
raise ValueError('invalid file type')
|
||||||
|
filetype = upload_types[ext]
|
||||||
|
name = name[:256]
|
||||||
|
if slugify:
|
||||||
|
url_name = slugify(name)[:256]
|
||||||
|
else:
|
||||||
|
url_name = None
|
||||||
|
filemd5 = hashlib.md5(content).hexdigest()
|
||||||
|
basepath = os.path.join(UPLOAD_DIR, filemd5[:1], filemd5[:2])
|
||||||
|
if not os.path.exists(basepath):
|
||||||
|
os.makedirs(basepath)
|
||||||
|
obj = cls.create(
|
||||||
|
name=name,
|
||||||
|
url_name=url_name,
|
||||||
|
filetype=filetype,
|
||||||
|
filesize=len(content),
|
||||||
|
upload_date=datetime.datetime.now(),
|
||||||
|
md5=filemd5
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with open(os.path.join(basepath, '{0}{1}.{2}'.format(obj.id,
|
||||||
|
'-' + url_name if url_name else '', upload_types_rev[filetype]
|
||||||
|
)), 'wb') as f:
|
||||||
|
f.write(content)
|
||||||
|
except OSError:
|
||||||
|
cls.delete_by_id(obj.id)
|
||||||
|
raise
|
||||||
|
return obj
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
database.create_tables([Page, PageText, PageRevision, PageTag, PageProperty, PagePolicyKey, PagePolicy, Upload])
|
||||||
|
|
||||||
|
#### WIKI SYNTAX ####
|
||||||
|
|
||||||
|
magic_word_filters = {}
|
||||||
|
|
||||||
|
def _replace_magic_word(match):
|
||||||
|
name = match.group(1)
|
||||||
|
if name not in magic_word_filters:
|
||||||
|
return match.group()
|
||||||
|
f = magic_word_filters[name]
|
||||||
|
try:
|
||||||
|
return f(*(x.strip() for x in match.group(2).split('|')))
|
||||||
|
except Exception:
|
||||||
|
return ''
|
||||||
|
|
||||||
|
def expand_magic_words(text):
|
||||||
|
'''
|
||||||
|
Replace the special markups in double curly brackets.
|
||||||
|
|
||||||
|
Unknown keywords are not replaced. Valid keywords with invalid arguments are replaced with nothing.
|
||||||
|
'''
|
||||||
|
return re.sub(MAGIC_RE, _replace_magic_word, text)
|
||||||
|
|
||||||
|
def md(text, expand_magic=False, toc=True):
|
||||||
|
if expand_magic:
|
||||||
|
# DEPRECATED seeking for a better solution.
|
||||||
|
warnings.warn('Magic words are no more supported.', DeprecationWarning)
|
||||||
|
text = expand_magic_words(text)
|
||||||
|
extensions = ['tables', 'footnotes', 'fenced_code', 'sane_lists']
|
||||||
|
if markdown_strikethrough:
|
||||||
|
extensions.append("markdown_strikethrough.extension")
|
||||||
|
if toc:
|
||||||
|
extensions.append('toc')
|
||||||
|
return markdown.Markdown(extensions=extensions).convert(text)
|
||||||
|
|
||||||
|
def remove_tags(text, convert=True, headings=True):
|
||||||
|
if headings:
|
||||||
|
text = re.sub(r'\#[^\n]*', '', text)
|
||||||
|
if convert:
|
||||||
|
text = md(text, expand_magic=False, toc=False)
|
||||||
|
return re.sub(r'<.*?>|\{\{.*?\}\}', '', text)
|
||||||
|
|
||||||
|
|
||||||
|
### Magic words (deprecated!) ###
|
||||||
|
|
||||||
|
def expand_backto(pageid):
|
||||||
|
p = Page[pageid]
|
||||||
|
return '*« Main article: [{}]({}).*'.format(html.escape(p.title), p.get_url())
|
||||||
|
|
||||||
|
magic_word_filters['backto'] = expand_backto
|
||||||
|
|
||||||
|
def expand_upload(id, *opt):
|
||||||
|
try:
|
||||||
|
upload = Upload[id]
|
||||||
|
except Upload.DoesNotExist:
|
||||||
|
return ''
|
||||||
|
if opt:
|
||||||
|
desc = opt[-1]
|
||||||
|
else:
|
||||||
|
desc = None
|
||||||
|
classname = 'fig-right'
|
||||||
|
return '<figure class="{0}"><a href="/upload-info/{4}"><img alt="{1}" src="{2}" title="{1}"></a>{3}</figure>'.format(
|
||||||
|
classname, html.escape(upload.name), upload.url,
|
||||||
|
'<figcaption>{0}</figcaption>'.format(md(desc, expand_magic=False)) if desc else '',
|
||||||
|
upload.id)
|
||||||
|
|
||||||
|
magic_word_filters['media'] = expand_upload
|
||||||
|
|
||||||
|
def make_gallery(items):
|
||||||
|
result = []
|
||||||
|
for upload, desc in items:
|
||||||
|
result.append('<figure class="fig-gallery"><a href="/upload-info/{0}"><img alt="{1}" src="{2}" title="{1}"></a>{3}</figure>'.format(
|
||||||
|
upload.id, html.escape(upload.name), upload.url,
|
||||||
|
'<figcaption>{0}</figcaption>'.format(md(desc, expand_magic=False)) if desc else ''))
|
||||||
|
return '<div class="gallery">' + ''.join(result) + '</div>'
|
||||||
|
|
||||||
|
def expand_gallery(*ids):
|
||||||
|
items = []
|
||||||
|
for i in ids:
|
||||||
|
if ' ' in i:
|
||||||
|
id, desc = i.split(' ', 1)
|
||||||
|
else:
|
||||||
|
id, desc = i, ''
|
||||||
|
try:
|
||||||
|
upload = Upload[id]
|
||||||
|
except Upload.DoesNotExist:
|
||||||
|
continue
|
||||||
|
items.append((upload, desc))
|
||||||
|
return make_gallery(items)
|
||||||
|
|
||||||
|
magic_word_filters['gallery'] = expand_gallery
|
||||||
|
|
||||||
|
#### I18N ####
|
||||||
|
|
||||||
|
lang_poses = {'en': 1, 'en-US': 1, 'it': 2, 'it-IT': 2}
|
||||||
|
|
||||||
|
def read_strings():
|
||||||
|
with open(APP_BASE_DIR + '/strings.csv', encoding='utf-8') as f:
|
||||||
|
return csv.reader(f)
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1000)
|
||||||
|
def get_string(lang, name):
|
||||||
|
with open(APP_BASE_DIR + '/strings.csv', encoding='utf-8') as f:
|
||||||
|
for line in csv.reader(f):
|
||||||
|
if not line[0] or line[0].startswith('#'):
|
||||||
|
continue
|
||||||
|
if line[0] == name:
|
||||||
|
ln = lang_poses[lang]
|
||||||
|
if len(line) > ln and line[ln]:
|
||||||
|
return line[ln]
|
||||||
|
elif len(line) > 1:
|
||||||
|
return line[1]
|
||||||
|
return '(' + name + ')'
|
||||||
|
|
||||||
|
|
||||||
|
#### APPLICATION CONFIG ####
|
||||||
|
|
||||||
|
class SlugConverter(BaseConverter):
|
||||||
|
regex = SLUG_RE
|
||||||
|
|
||||||
|
def is_valid_url(url):
|
||||||
|
return re.fullmatch(SLUG_RE, url)
|
||||||
|
|
||||||
|
def is_url_available(url):
|
||||||
|
return url not in forbidden_urls and not Page.select().where(Page.url == url).exists()
|
||||||
|
|
||||||
|
forbidden_urls = [
|
||||||
|
'create', 'edit', 'p', 'ajax', 'history', 'manage', 'static', 'media',
|
||||||
|
'accounts', 'tags', 'init-config', 'upload', 'upload-info', 'about',
|
||||||
|
'stats', 'terms', 'privacy', 'easter', 'search', 'help', 'circles',
|
||||||
|
'protect', 'kt', 'embed'
|
||||||
|
]
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.secret_key = 'qrdldCcvamtdcnidmtasegasdsedrdqvtautar'
|
||||||
|
app.url_map.converters['slug'] = SlugConverter
|
||||||
|
|
||||||
|
|
||||||
|
#### ROUTES ####
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def _before_request():
|
||||||
|
for l in request.headers.get('accept-language', 'it,en').split(','):
|
||||||
|
if ';' in l:
|
||||||
|
l, _ = l.split(';')
|
||||||
|
if l in lang_poses:
|
||||||
|
lang = l
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
lang = 'en'
|
||||||
|
g.lang = lang
|
||||||
|
|
||||||
|
@app.context_processor
|
||||||
|
def _inject_variables():
|
||||||
|
return {
|
||||||
|
'T': partial(get_string, g.lang),
|
||||||
|
'app_name': _getconf('site', 'title'),
|
||||||
|
'strong': lambda x:Markup('<strong>{0}</strong>').format(x),
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.template_filter()
|
||||||
|
def linebreaks(text):
|
||||||
|
text = html.escape(text)
|
||||||
|
text = text.replace("\n\n", '</p><p>').replace('\n', '<br />')
|
||||||
|
return Markup(text)
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def homepage():
|
||||||
|
page_limit = _getconf("appearance","items_per_page",20,cast=int)
|
||||||
|
return render_template('home.html', new_notes=Page.select()
|
||||||
|
.order_by(Page.touched.desc()).limit(page_limit),
|
||||||
|
gallery=make_gallery((x, '') for x in Upload.select().order_by(Upload.upload_date.desc()).limit(3)))
|
||||||
|
|
||||||
|
@app.route('/robots.txt')
|
||||||
|
def robots():
|
||||||
|
return send_from_directory(APP_BASE_DIR, 'robots.txt')
|
||||||
|
|
||||||
|
@app.route('/favicon.ico')
|
||||||
|
def favicon():
|
||||||
|
return send_from_directory(APP_BASE_DIR, 'favicon.ico')
|
||||||
|
|
||||||
|
## error handlers ##
|
||||||
|
|
||||||
|
@app.errorhandler(404)
|
||||||
|
def error_404(body):
|
||||||
|
return render_template('notfound.html'), 404
|
||||||
|
|
||||||
|
@app.errorhandler(403)
|
||||||
|
def error_403(body):
|
||||||
|
return render_template('forbidden.html'), 403
|
||||||
|
|
||||||
|
@app.errorhandler(500)
|
||||||
|
def error_400(body):
|
||||||
|
return render_template('badrequest.html'), 400
|
||||||
|
|
||||||
|
# Middle point during page editing.
|
||||||
|
def savepoint(form, is_preview=False):
|
||||||
|
if is_preview:
|
||||||
|
preview = md(form['text'])
|
||||||
|
else:
|
||||||
|
preview = None
|
||||||
|
pl_js_info = dict()
|
||||||
|
pl_js_info['editing'] = dict(
|
||||||
|
original_text = None, # TODO
|
||||||
|
preview_text = form['text'],
|
||||||
|
)
|
||||||
|
return render_template('edit.html', pl_url=form['url'], pl_title=form['title'], pl_text=form['text'], pl_tags=form['tags'], preview=preview, pl_js_info=pl_js_info)
|
||||||
|
|
||||||
|
@app.route('/create/', methods=['GET', 'POST'])
|
||||||
|
def create():
|
||||||
|
if request.method == 'POST':
|
||||||
|
if request.form.get('preview'):
|
||||||
|
return savepoint(request.form, is_preview=True)
|
||||||
|
p_url = request.form['url'] or None
|
||||||
|
if p_url:
|
||||||
|
if not is_valid_url(p_url):
|
||||||
|
flash('Invalid URL. Valid URLs contain only letters, numbers and hyphens.')
|
||||||
|
return savepoint(request.form)
|
||||||
|
elif not is_url_available(p_url):
|
||||||
|
flash('This URL is not available.')
|
||||||
|
return savepoint(request.form)
|
||||||
|
p_tags = [x.strip().lower().replace(' ', '-').replace('_', '-').lstrip('#')
|
||||||
|
for x in request.form.get('tags', '').split(',') if x]
|
||||||
|
if any(not re.fullmatch(SLUG_RE, x) for x in p_tags):
|
||||||
|
flash('Invalid tags text. Tags contain only letters, numbers and hyphens, and are separated by comma.')
|
||||||
|
return savepoint(request.form)
|
||||||
|
try:
|
||||||
|
p = Page.create(
|
||||||
|
url=p_url,
|
||||||
|
title=request.form['title'],
|
||||||
|
is_redirect=False,
|
||||||
|
touched=datetime.datetime.now(),
|
||||||
|
)
|
||||||
|
p.change_tags(p_tags)
|
||||||
|
except IntegrityError as e:
|
||||||
|
flash('An error occurred while saving this revision: {e}'.format(e=e))
|
||||||
|
return savepoint(request.form)
|
||||||
|
pr = PageRevision.create(
|
||||||
|
page=p,
|
||||||
|
user_id=0,
|
||||||
|
comment='',
|
||||||
|
textref=PageText.create_content(request.form['text']),
|
||||||
|
pub_date=datetime.datetime.now(),
|
||||||
|
length=len(request.form['text'])
|
||||||
|
)
|
||||||
|
return redirect(p.get_url())
|
||||||
|
return render_template('edit.html', pl_url=request.args.get('url'))
|
||||||
|
|
||||||
|
@app.route('/edit/<int:id>/', methods=['GET', 'POST'])
|
||||||
|
def edit(id):
|
||||||
|
p = Page[id]
|
||||||
|
if request.method == 'POST':
|
||||||
|
if request.form.get('preview'):
|
||||||
|
return savepoint(request.form, is_preview=True)
|
||||||
|
p_url = request.form['url'] or None
|
||||||
|
if p_url:
|
||||||
|
if not is_valid_url(p_url):
|
||||||
|
flash('Invalid URL. Valid URLs contain only letters, numbers and hyphens.')
|
||||||
|
return savepoint(request.form)
|
||||||
|
elif not is_url_available(p_url) and p_url != p.url:
|
||||||
|
flash('This URL is not available.')
|
||||||
|
return savepoint(request.form)
|
||||||
|
p_tags = [x.strip().lower().replace(' ', '-').replace('_', '-').lstrip('#')
|
||||||
|
for x in request.form.get('tags', '').split(',')]
|
||||||
|
p_tags = [x for x in p_tags if x]
|
||||||
|
if any(not re.fullmatch(SLUG_RE, x) for x in p_tags):
|
||||||
|
flash('Invalid tags text. Tags contain only letters, numbers and hyphens, and are separated by comma.')
|
||||||
|
return savepoint(request.form)
|
||||||
|
p.url = p_url
|
||||||
|
p.title = request.form['title']
|
||||||
|
p.touched = datetime.datetime.now()
|
||||||
|
p.save()
|
||||||
|
p.change_tags(p_tags)
|
||||||
|
pr = PageRevision.create(
|
||||||
|
page=p,
|
||||||
|
user_id=0,
|
||||||
|
comment='',
|
||||||
|
textref=PageText.create_content(request.form['text']),
|
||||||
|
pub_date=datetime.datetime.now(),
|
||||||
|
length=len(request.form['text'])
|
||||||
|
)
|
||||||
|
return redirect(p.get_url())
|
||||||
|
return render_template('edit.html', pl_url=p.url, pl_title=p.title, pl_text=p.latest.text, pl_tags=','.join(x.name for x in p.tags))
|
||||||
|
|
||||||
|
@app.route("/__sync_start")
|
||||||
|
def __sync_start():
|
||||||
|
if _getconf("sync", "master", "this") == "this":
|
||||||
|
abort(403)
|
||||||
|
from app_sync import main
|
||||||
|
main()
|
||||||
|
flash("Successfully synced messages.")
|
||||||
|
return redirect("/")
|
||||||
|
|
||||||
|
@app.route('/_jsoninfo/<int:id>', methods=['GET', 'POST'])
|
||||||
|
def page_jsoninfo(id):
|
||||||
|
try:
|
||||||
|
p = Page[id]
|
||||||
|
except Page.DoesNotExist:
|
||||||
|
return jsonify({'status':'fail'}), 404
|
||||||
|
j = p.js_info()
|
||||||
|
j["status"] = "ok"
|
||||||
|
if request.method == "POST":
|
||||||
|
j["text"] = p.latest.text
|
||||||
|
return jsonify(j)
|
||||||
|
|
||||||
|
@app.route("/_jsoninfo/changed/<float:ts>")
|
||||||
|
def jsoninfo_changed(ts):
|
||||||
|
tse = str(datetime.datetime.fromtimestamp(ts).isoformat(" "))
|
||||||
|
ps = Page.select().where(Page.touched >= tse)
|
||||||
|
return jsonify({
|
||||||
|
"ids": [i.id for i in ps],
|
||||||
|
"status": "ok"
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/p/<int:id>/')
|
||||||
|
def view_unnamed(id):
|
||||||
|
try:
|
||||||
|
p = Page[id]
|
||||||
|
except Page.DoesNotExist:
|
||||||
|
abort(404)
|
||||||
|
if p.url:
|
||||||
|
if p.url not in forbidden_urls:
|
||||||
|
return redirect(p.get_url())
|
||||||
|
else:
|
||||||
|
flash('The URL of this page is a reserved URL. Please change it.')
|
||||||
|
return render_template('view.html', p=p, rev=p.latest)
|
||||||
|
|
||||||
|
@app.route('/embed/<int:id>/')
|
||||||
|
def embed_view(id):
|
||||||
|
try:
|
||||||
|
p = Page[id]
|
||||||
|
except Page.DoesNotExist:
|
||||||
|
return "", 404
|
||||||
|
rev = p.latest
|
||||||
|
return "<h1>{0}</h1><div class=\"inner-content\">{1}</div>".format(
|
||||||
|
html.escape(p.title), rev.html())
|
||||||
|
|
||||||
|
@app.route('/p/most_recent/')
|
||||||
|
@app.route('/p/most_recent/<int:page>/')
|
||||||
|
def view_most_recent(page=1):
|
||||||
|
general_query = Page.select().order_by(Page.touched.desc())
|
||||||
|
return render_template('listrecent.html', notes=general_query.paginate(page),
|
||||||
|
page_n=page, total_count=general_query.count(), min=min)
|
||||||
|
|
||||||
|
@app.route('/p/random/')
|
||||||
|
def view_random():
|
||||||
|
page = None
|
||||||
|
if Page.select().count() < 2:
|
||||||
|
flash('Too few pages in this site.')
|
||||||
|
abort(404)
|
||||||
|
while not page:
|
||||||
|
try:
|
||||||
|
page = Page[random.randint(1, Page.select().count())]
|
||||||
|
except Page.DoesNotExist:
|
||||||
|
continue
|
||||||
|
return redirect(page.get_url())
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/<slug:name>/')
|
||||||
|
def view_named(name):
|
||||||
|
try:
|
||||||
|
p = Page.get(Page.url == name)
|
||||||
|
except Page.DoesNotExist:
|
||||||
|
abort(404)
|
||||||
|
return render_template('view.html', p=p, rev=p.latest)
|
||||||
|
|
||||||
|
@app.route('/init-config/tables/')
|
||||||
|
def init_config_tables():
|
||||||
|
init_db()
|
||||||
|
flash('Tables successfully created.')
|
||||||
|
return redirect('/')
|
||||||
|
|
||||||
|
@app.route('/history/<int:id>/')
|
||||||
|
def history(id):
|
||||||
|
try:
|
||||||
|
p = Page[id]
|
||||||
|
except Page.DoesNotExist:
|
||||||
|
abort(404)
|
||||||
|
return render_template('history.html', p=p, history=p.revisions.order_by(PageRevision.pub_date.desc()))
|
||||||
|
|
||||||
|
@app.route('/history/revision/<int:revisionid>/')
|
||||||
|
def view_old(revisionid):
|
||||||
|
try:
|
||||||
|
rev = PageRevision[revisionid]
|
||||||
|
except PageRevision.DoesNotExist:
|
||||||
|
abort(404)
|
||||||
|
p = rev.page
|
||||||
|
return render_template('viewold.html', p=p, rev=rev)
|
||||||
|
|
||||||
|
@app.route('/search/', methods=['GET', 'POST'])
|
||||||
|
def search():
|
||||||
|
if request.method == 'POST':
|
||||||
|
q = request.form['q']
|
||||||
|
include_tags = bool(request.form.get('include-tags'))
|
||||||
|
query = Page.select().where(Page.title ** ('%' + q + '%'))
|
||||||
|
if include_tags:
|
||||||
|
query |= Page.select().join(PageTag, on=PageTag.page
|
||||||
|
).where(PageTag.name ** ('%' + q + '%'))
|
||||||
|
query = query.order_by(Page.touched.desc())
|
||||||
|
return render_template('search.html', q=q, pl_include_tags=include_tags,
|
||||||
|
results=query.paginate(1))
|
||||||
|
return render_template('search.html', pl_include_tags=True)
|
||||||
|
|
||||||
|
@app.route('/tags/<slug:tag>/')
|
||||||
|
@app.route('/tags/<slug:tag>/<int:page>/')
|
||||||
|
def listtag(tag, page=1):
|
||||||
|
general_query = Page.select().join(PageTag, on=PageTag.page).where(PageTag.name == tag).order_by(Page.touched.desc())
|
||||||
|
page_query = general_query.paginate(page)
|
||||||
|
return render_template('listtag.html', tagname=tag, tagged_notes=page_query,
|
||||||
|
page_n=page, total_count=general_query.count(), min=min)
|
||||||
|
|
||||||
|
@app.route('/media/<path:fp>')
|
||||||
|
def media(fp):
|
||||||
|
return send_from_directory(UPLOAD_DIR, fp)
|
||||||
|
|
||||||
|
@app.route('/upload/', methods=['GET', 'POST'])
|
||||||
|
def upload():
|
||||||
|
if request.method == 'POST':
|
||||||
|
name = request.form['name']
|
||||||
|
file = request.files['file']
|
||||||
|
filename = file.filename
|
||||||
|
ext = os.path.splitext(filename)[1]
|
||||||
|
content = file.read()
|
||||||
|
try:
|
||||||
|
upl = Upload.create_content(name, ext, content)
|
||||||
|
flash('File uploaded successfully')
|
||||||
|
return redirect('/upload-info/{}/'.format(upl.id))
|
||||||
|
except Exception:
|
||||||
|
sys.excepthook(*sys.exc_info())
|
||||||
|
flash('Unable to upload file. Try again later.')
|
||||||
|
return render_template('upload.html')
|
||||||
|
|
||||||
|
@app.route('/upload-info/<int:id>/')
|
||||||
|
def upload_info(id):
|
||||||
|
upl = Upload[id]
|
||||||
|
return render_template('uploadinfo.html', upl=upl, type_list=upload_types_rev)
|
||||||
|
|
||||||
|
@app.route('/stats/')
|
||||||
|
def stats():
|
||||||
|
return render_template('stats.html',
|
||||||
|
notes_count=Page.select().count(),
|
||||||
|
notes_with_url=Page.select().where(Page.url != None).count(),
|
||||||
|
upload_count=Upload.select().count(),
|
||||||
|
revision_count=PageRevision.select().count()
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.route('/accounts/theme-switch')
|
||||||
|
def theme_switch():
|
||||||
|
cook = request.cookies.get('dark')
|
||||||
|
resp = make_response(redirect(request.args.get('next', '/')))
|
||||||
|
resp.set_cookie('dark', '0' if cook == '1' else '1', max_age=31556952, path='/')
|
||||||
|
return resp
|
||||||
|
|
||||||
|
## easter egg (lol) ##
|
||||||
|
|
||||||
|
MNeaster = {
|
||||||
|
15: (22, 2), 16: (22, 2), 17: (23, 3), 18: (23, 4), 19: (24, 5), 20: (24, 5),
|
||||||
|
21: (24, 6), 22: (25, 0), 23: (26, 1), 24: (25, 1)}
|
||||||
|
|
||||||
|
def calculate_easter(y):
|
||||||
|
a, b, c = y % 19, y % 4, y % 7
|
||||||
|
M, N = (15, 6) if y < 1583 else MNeaster[y // 100]
|
||||||
|
d = (19 * a + M) % 30
|
||||||
|
e = (2 * b + 4 * c + 6 * d + N) % 7
|
||||||
|
if d + e < 10:
|
||||||
|
return datetime.date(y, 3, d + e + 22)
|
||||||
|
else:
|
||||||
|
day = d + e - 9
|
||||||
|
if day == 26:
|
||||||
|
day = 19
|
||||||
|
elif day == 25 and d == 28 and e == 6 and a > 10:
|
||||||
|
day = 18
|
||||||
|
return datetime.date(y, 4, day)
|
||||||
|
|
||||||
|
def stash_easter(y):
|
||||||
|
easter = calculate_easter(y)
|
||||||
|
natale = datetime.date(y, 12, 25)
|
||||||
|
avvento1 = natale - datetime.timedelta(days=22 + natale.weekday())
|
||||||
|
return dict(
|
||||||
|
easter = easter,
|
||||||
|
ceneri = easter - datetime.timedelta(days=47),
|
||||||
|
ascensione = easter + datetime.timedelta(days=42),
|
||||||
|
pentecoste = easter + datetime.timedelta(days=49),
|
||||||
|
avvento1 = avvento1
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.route('/easter/')
|
||||||
|
@app.route('/easter/<int:y>/')
|
||||||
|
def easter_y(y=None):
|
||||||
|
if 'y' in request.args:
|
||||||
|
return redirect('/easter/' + request.args['y'] + '/')
|
||||||
|
if y:
|
||||||
|
if y > 2499:
|
||||||
|
flash('Years above 2500 A.D. are currently not supported.')
|
||||||
|
return render_template('easter.html')
|
||||||
|
return render_template('easter.html', y=y, easter_dates=stash_easter(y))
|
||||||
|
else:
|
||||||
|
return render_template('easter.html')
|
||||||
|
|
||||||
|
#### EXTENSIONS ####
|
||||||
|
|
||||||
|
active_extensions = ['contactnova']
|
||||||
|
|
||||||
|
for ext in active_extensions:
|
||||||
|
try:
|
||||||
|
bp = importlib.import_module('extensions.' + ext).bp
|
||||||
|
app.register_blueprint(bp)
|
||||||
|
except Exception:
|
||||||
|
sys.stderr.write('Extension not loaded: ' + ext + '\n')
|
||||||
|
sys.excepthook(*sys.exc_info())
|
||||||
|
|
||||||
175
app_sync.py
Normal file
175
app_sync.py
Normal file
|
|
@ -0,0 +1,175 @@
|
||||||
|
"""
|
||||||
|
Helper module for sync.
|
||||||
|
|
||||||
|
Remember to set sync:master variable in site.conf!
|
||||||
|
|
||||||
|
(c) 2021 Sakuragasaki46.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import datetime, time
|
||||||
|
import requests
|
||||||
|
import sys, os
|
||||||
|
from configparser import ConfigParser
|
||||||
|
from app import Page, PageRevision, PageText
|
||||||
|
from peewee import IntegrityError
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
## CONSTANTS ##
|
||||||
|
|
||||||
|
APP_BASE_DIR = os.path.dirname(__file__)
|
||||||
|
|
||||||
|
UPLOAD_DIR = APP_BASE_DIR + '/media'
|
||||||
|
DATABASE_DIR = APP_BASE_DIR + "/database"
|
||||||
|
|
||||||
|
#### GENERAL CONFIG ####
|
||||||
|
|
||||||
|
DEFAULT_CONF = {
|
||||||
|
('site', 'title'): 'Salvi',
|
||||||
|
('config', 'media_dir'): APP_BASE_DIR + '/media',
|
||||||
|
('config', 'database_dir'): APP_BASE_DIR + "/database",
|
||||||
|
}
|
||||||
|
|
||||||
|
_cfp = ConfigParser()
|
||||||
|
if _cfp.read([APP_BASE_DIR + '/site.conf']):
|
||||||
|
@lru_cache(maxsize=50)
|
||||||
|
def _getconf(k1, k2, fallback=None):
|
||||||
|
if fallback is None:
|
||||||
|
fallback = DEFAULT_CONF.get((k1, k2))
|
||||||
|
v = _cfp.get(k1, k2, fallback=fallback)
|
||||||
|
return v
|
||||||
|
else:
|
||||||
|
def _getconf(k1, k2, fallback=None):
|
||||||
|
if fallback is None:
|
||||||
|
fallback = DEFAULT_CONF.get((k1, k2))
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
#### misc. helpers ####
|
||||||
|
|
||||||
|
def _makelist(l):
|
||||||
|
if isinstance(l, (str, bytes, bytearray)):
|
||||||
|
return [l]
|
||||||
|
elif hasattr(l, '__iter__'):
|
||||||
|
return list(l)
|
||||||
|
elif l:
|
||||||
|
return [l]
|
||||||
|
else:
|
||||||
|
return []
|
||||||
|
|
||||||
|
#### REQUESTS ####
|
||||||
|
|
||||||
|
def fetch_updated_ids(baseurl):
|
||||||
|
try:
|
||||||
|
with open(_getconf("config", "database_dir") + "/latest_sync") as f:
|
||||||
|
last_sync = float(f.read().rstrip("\n"))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
last_sync = 946681200.0 # Jan 1, 2000
|
||||||
|
r = requests.get(baseurl + "/_jsoninfo/changed/{ts}".format(ts=last_sync))
|
||||||
|
if r.status_code >= 400:
|
||||||
|
raise RuntimeError("sync unavailable")
|
||||||
|
return r.json()["ids"]
|
||||||
|
|
||||||
|
def update_contacts(baseurl):
|
||||||
|
from extensions.contactnova import Contact
|
||||||
|
try:
|
||||||
|
with open(_getconf("config", "database_dir") + "/latest_sync") as f:
|
||||||
|
last_sync = float(f.read().rstrip("\n"))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
last_sync = 946681200.0 # Jan 1, 2000
|
||||||
|
r = requests.get(baseurl + "/kt/_jsoninfo/{ts}".format(ts=last_sync))
|
||||||
|
if r.status_code >= 400:
|
||||||
|
raise RuntimeError("sync unavailable")
|
||||||
|
# update contacts
|
||||||
|
updated = 0
|
||||||
|
for pinfo in r.json()['data']:
|
||||||
|
p = Contact.get_or_none(Contact.code == pinfo['code'])
|
||||||
|
if p is None:
|
||||||
|
p = Contact.create(
|
||||||
|
code = pinfo['code'],
|
||||||
|
display_name = pinfo['display_name'],
|
||||||
|
issues = pinfo['issues'],
|
||||||
|
status = pinfo['status'],
|
||||||
|
description = pinfo['description'],
|
||||||
|
due = datetime.date.fromtimestamp(pinfo['due'])
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
p.display_name = pinfo['display_name']
|
||||||
|
p.issues = pinfo['issues']
|
||||||
|
p.status = pinfo['status']
|
||||||
|
p.description = pinfo['description']
|
||||||
|
p.due = datetime.date.fromtimestamp(pinfo['due'])
|
||||||
|
p.touched = datetime.datetime.now()
|
||||||
|
p.save()
|
||||||
|
updated += 1
|
||||||
|
print('\x1b[32m{0} contacts updated :)\x1b[0m'.format(updated))
|
||||||
|
|
||||||
|
|
||||||
|
def update_page(p, pageinfo):
|
||||||
|
p.touched = datetime.datetime.fromtimestamp(pageinfo["touched"])
|
||||||
|
p.url = pageinfo["url"]
|
||||||
|
p.title = pageinfo["title"]
|
||||||
|
p.save()
|
||||||
|
p.change_tags(pageinfo["tags"])
|
||||||
|
assert len(pageinfo["text"]) == pageinfo["latest"]["length"]
|
||||||
|
pr = PageRevision.create(
|
||||||
|
page=p,
|
||||||
|
user_id=0,
|
||||||
|
comment='',
|
||||||
|
textref=PageText.create_content(pageinfo['text']),
|
||||||
|
pub_date=datetime.datetime.fromtimestamp(pageinfo["latest"]["pub_date"]),
|
||||||
|
length=pageinfo["latest"]["length"]
|
||||||
|
)
|
||||||
|
|
||||||
|
#### MAIN ####
|
||||||
|
|
||||||
|
def main():
|
||||||
|
baseurl = _getconf("sync", "master", "this")
|
||||||
|
if baseurl == "this":
|
||||||
|
print("unsyncable: master", file=sys.stderr)
|
||||||
|
return
|
||||||
|
if not baseurl.startswith(("http:", "https:")):
|
||||||
|
print("unsyncable: invalid url", repr(baseurl), file=sys.stderr)
|
||||||
|
return
|
||||||
|
passed, failed = 0, 0
|
||||||
|
for i in fetch_updated_ids(baseurl):
|
||||||
|
pageinfo_r = requests.post(baseurl + "/_jsoninfo/{i}".format(i=i))
|
||||||
|
if pageinfo_r.status_code >= 400:
|
||||||
|
print("\x1b[31mSkipping {i}: HTTP {s}\x1b[0m".format(i=i, s=pageinfo_r.status_code))
|
||||||
|
failed += 1
|
||||||
|
continue
|
||||||
|
pageinfo = pageinfo_r.json()
|
||||||
|
try:
|
||||||
|
p = Page[i]
|
||||||
|
except Page.DoesNotExist:
|
||||||
|
try:
|
||||||
|
p = Page.create(
|
||||||
|
id=i,
|
||||||
|
url=pageinfo['url'],
|
||||||
|
title=pageinfo['title'],
|
||||||
|
is_redirect=pageinfo['is_redirect'],
|
||||||
|
touched=datetime.datetime.fromtimestamp(pageinfo["touched"]),
|
||||||
|
is_sync = True
|
||||||
|
)
|
||||||
|
update_page(p, pageinfo)
|
||||||
|
except IntegrityError:
|
||||||
|
print("\x1b[31mSkipping {i}: Integrity error\x1b[0m".format(i=i))
|
||||||
|
failed += 1
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
if pageinfo["touched"] > p.touched.timestamp():
|
||||||
|
update_page(p, pageinfo)
|
||||||
|
passed += 1
|
||||||
|
try:
|
||||||
|
if _getconf("sync", "contacts", None) is not None:
|
||||||
|
update_contacts(baseurl)
|
||||||
|
except Exception as e:
|
||||||
|
print("\x1b[33mContacts not updated - {e} :(\x1b[0m".format(e=e))
|
||||||
|
with open(DATABASE_DIR + "/last_sync", "w") as fw:
|
||||||
|
fw.write(str(time.time()))
|
||||||
|
if passed > 0 and failed == 0:
|
||||||
|
print("\x1b[32mSuccessfully updated {p} pages :)\x1b[0m".format(p=passed))
|
||||||
|
else:
|
||||||
|
print("\x1b[33m{p} pages successfully updated, {f} errors.\x1b[0m".format(p=passed, f=failed))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
241
extensions/circles.py
Normal file
241
extensions/circles.py
Normal file
|
|
@ -0,0 +1,241 @@
|
||||||
|
# (C) 2020-2021 Sakuragasaki46.
|
||||||
|
# See LICENSE for copying info.
|
||||||
|
|
||||||
|
'''
|
||||||
|
Circles (people) extension for Salvi.
|
||||||
|
'''
|
||||||
|
|
||||||
|
from peewee import *
|
||||||
|
import datetime
|
||||||
|
from app import _getconf
|
||||||
|
from flask import Blueprint, request, redirect, render_template
|
||||||
|
from werkzeug.routing import BaseConverter
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import itertools
|
||||||
|
|
||||||
|
#### HELPERS ####
|
||||||
|
|
||||||
|
def _getmbt(s):
|
||||||
|
s = s.upper()
|
||||||
|
try:
|
||||||
|
return 16 + (
|
||||||
|
dict(I=0, E=8)[s[0]] |
|
||||||
|
dict(N=0, S=4)[s[1]] |
|
||||||
|
dict(T=0, F=2)[s[2]] |
|
||||||
|
dict(J=0, P=1)[s[3]]
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
return 2
|
||||||
|
|
||||||
|
|
||||||
|
def _putmbt(s):
|
||||||
|
if s & 16 == 0:
|
||||||
|
return "1x38B"
|
||||||
|
return ''.join((
|
||||||
|
'IE'[(s & 8) >> 3],
|
||||||
|
'NS'[(s & 4) >> 2],
|
||||||
|
'TF'[(s & 2) >> 1],
|
||||||
|
'JP'[s & 1]
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### DATABASE SCHEMA ####
|
||||||
|
|
||||||
|
database = SqliteDatabase(_getconf("config", "database_dir") + '/circles.sqlite')
|
||||||
|
|
||||||
|
class BaseModel(Model):
|
||||||
|
class Meta:
|
||||||
|
database = database
|
||||||
|
|
||||||
|
class MbTypeField(Field):
|
||||||
|
field_type = 'integer'
|
||||||
|
|
||||||
|
def db_value(self, value):
|
||||||
|
if isinstance(value, int):
|
||||||
|
return value
|
||||||
|
return _getmbt(value)
|
||||||
|
def python_value(self, value):
|
||||||
|
return _putmbt(value)
|
||||||
|
|
||||||
|
ST_ORANGE = 0
|
||||||
|
ST_YELLOW = 1
|
||||||
|
ST_GREEN = 2
|
||||||
|
ST_RED = -1
|
||||||
|
|
||||||
|
class Person(BaseModel):
|
||||||
|
code = IntegerField(primary_key=True)
|
||||||
|
display_name = CharField(256)
|
||||||
|
first_name = CharField(128, null=True)
|
||||||
|
last_name = CharField(128, null=True)
|
||||||
|
circle = IntegerField(default=7, index=True)
|
||||||
|
status = IntegerField(default=ST_ORANGE, index=True)
|
||||||
|
type = MbTypeField(default=0, index=True)
|
||||||
|
area = IntegerField(default=0, index=True)
|
||||||
|
touched = DateTimeField(default=datetime.datetime.now)
|
||||||
|
class Meta:
|
||||||
|
indexes = (
|
||||||
|
(('last_name', 'first_name'), False),
|
||||||
|
)
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
database.create_tables([Person])
|
||||||
|
|
||||||
|
def add_from_csv(s):
|
||||||
|
f = io.StringIO()
|
||||||
|
f.write(s)
|
||||||
|
f.seek(0)
|
||||||
|
rd = csv.reader(f)
|
||||||
|
for line in rd:
|
||||||
|
code = line[0]
|
||||||
|
if not code.isdigit():
|
||||||
|
continue
|
||||||
|
names = line[1:4]
|
||||||
|
while len(names) < 3:
|
||||||
|
names.append('')
|
||||||
|
if not names[2]:
|
||||||
|
names[2] = names[0] + " " + names[1]
|
||||||
|
type_ = line[4] if len(line) > 4 else 0
|
||||||
|
try:
|
||||||
|
p = Person[code]
|
||||||
|
except Person.DoesNotExist:
|
||||||
|
p = Person.create(
|
||||||
|
code = code,
|
||||||
|
display_name = names[2],
|
||||||
|
first_name = names[0],
|
||||||
|
last_name = names[1],
|
||||||
|
type = type_
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
p.touched = datetime.datetime.now()
|
||||||
|
p.first_name, p.last_name, p.display_name = names
|
||||||
|
p.type = type_ or p.type
|
||||||
|
p.save()
|
||||||
|
|
||||||
|
#### ROUTING ####
|
||||||
|
|
||||||
|
class MbTypeConverter(BaseConverter):
|
||||||
|
regex = '[IE][NS][TF][JP]|[ie][ns][tf][jp]'
|
||||||
|
def to_python(self, value):
|
||||||
|
return value.upper()
|
||||||
|
def to_url(self, value):
|
||||||
|
return value.lower()
|
||||||
|
|
||||||
|
class StatusColorConverter(BaseConverter):
|
||||||
|
regex = 'red|yellow|green|orange'
|
||||||
|
def to_python(self, value):
|
||||||
|
if value == 'red':
|
||||||
|
return -1
|
||||||
|
return ['orange', 'yellow', 'green'].index(value)
|
||||||
|
def to_url(self, value):
|
||||||
|
return ['orange', 'yellow', 'green', ..., 'red'][value]
|
||||||
|
|
||||||
|
def _register_converters(state):
|
||||||
|
state.app.url_map.converters['mbtype'] = MbTypeConverter
|
||||||
|
state.app.url_map.converters['statuscolor'] = StatusColorConverter
|
||||||
|
|
||||||
|
bp = Blueprint('circles', __name__,
|
||||||
|
url_prefix='/circles')
|
||||||
|
bp.record_once(_register_converters)
|
||||||
|
|
||||||
|
@bp.route('/init-config')
|
||||||
|
def _init_config():
|
||||||
|
init_db()
|
||||||
|
return redirect('/circles')
|
||||||
|
|
||||||
|
@bp.route('/new', methods=['GET', 'POST'])
|
||||||
|
def add_new():
|
||||||
|
if request.method == 'POST':
|
||||||
|
p = Person.create(
|
||||||
|
code = request.form["code"],
|
||||||
|
display_name = request.form["display_name"],
|
||||||
|
first_name = request.form["first_name"],
|
||||||
|
last_name = request.form["last_name"],
|
||||||
|
type = request.form["type"],
|
||||||
|
status = int(request.form.get('status', 0))
|
||||||
|
)
|
||||||
|
return redirect("/circles")
|
||||||
|
return render_template("circles/add.html")
|
||||||
|
|
||||||
|
@bp.route('/edit/<int:id>', methods=['GET', 'POST'])
|
||||||
|
def edit_detail(id):
|
||||||
|
p = Person[id]
|
||||||
|
if request.method == 'POST':
|
||||||
|
p.touched = datetime.datetime.now()
|
||||||
|
p.first_name = request.form['first_name']
|
||||||
|
p.last_name = request.form['last_name']
|
||||||
|
p.display_name = request.form['display_name']
|
||||||
|
p.status = int(request.form.get('status', 0))
|
||||||
|
p.type = request.form["type"]
|
||||||
|
p.area = request.form['area']
|
||||||
|
p.save()
|
||||||
|
return redirect(request.form['returnto'])
|
||||||
|
return render_template("circles/add.html", pl=p, returnto=request.headers.get('Referer', '/circles'))
|
||||||
|
|
||||||
|
@bp.route('/csv', methods=['GET', 'POST'])
|
||||||
|
def add_csv():
|
||||||
|
if request.method == 'POST' and request.form.get('consent') == 'y':
|
||||||
|
add_from_csv(request.form['text'])
|
||||||
|
return redirect('/circles')
|
||||||
|
return render_template("circles/csv.html")
|
||||||
|
|
||||||
|
# Helper for pagination.
|
||||||
|
def paginate_list(cat, q):
|
||||||
|
pageno = int(request.args.get('page', 1))
|
||||||
|
return render_template(
|
||||||
|
"circles/list.html",
|
||||||
|
cat=cat,
|
||||||
|
count=q.count(),
|
||||||
|
people=q.offset(50 * (pageno - 1)).limit(50),
|
||||||
|
pageno=pageno
|
||||||
|
)
|
||||||
|
|
||||||
|
@bp.route('/')
|
||||||
|
def homepage():
|
||||||
|
q = Person.select().order_by(Person.touched.desc())
|
||||||
|
return paginate_list('all', q)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route('/<mbtype:typ>')
|
||||||
|
def typelist(typ):
|
||||||
|
q = Person.select().where(Person.type == typ).order_by(Person.touched.desc())
|
||||||
|
return paginate_list(typ, q)
|
||||||
|
|
||||||
|
@bp.route('/<statuscolor:typ>')
|
||||||
|
def statuslist(typ):
|
||||||
|
q = Person.select().where(Person.status == typ).order_by(Person.touched.desc())
|
||||||
|
return paginate_list(['Orange', 'Yellow', 'Green', ..., 'Red'][typ], q)
|
||||||
|
|
||||||
|
@bp.route('/area-<int:a>')
|
||||||
|
def arealist(a):
|
||||||
|
q = Person.select().where(Person.area == a).order_by(Person.status.desc(), Person.touched.desc())
|
||||||
|
return paginate_list('Area {}'.format(a), q)
|
||||||
|
|
||||||
|
@bp.route('/no-area')
|
||||||
|
def noarealist():
|
||||||
|
q = Person.select().where(Person.area == 0).order_by(Person.touched.desc())
|
||||||
|
return paginate_list('Unassigned area', q)
|
||||||
|
|
||||||
|
@bp.route("/stats")
|
||||||
|
def stats():
|
||||||
|
bq = Person.select()
|
||||||
|
return render_template(
|
||||||
|
"circles/stats.html",
|
||||||
|
count=bq.count(),
|
||||||
|
typed_count={
|
||||||
|
''.join(x) : bq.where(Person.type == ''.join(x)).count()
|
||||||
|
for x in itertools.product('IE', 'NS', 'TF', 'JP')
|
||||||
|
},
|
||||||
|
status_count={
|
||||||
|
'Red': bq.where(Person.status == -1).count(),
|
||||||
|
'Orange': bq.where(Person.status == 0).count(),
|
||||||
|
'Yellow': bq.where(Person.status == 1).count(),
|
||||||
|
'Green': bq.where(Person.status == 2).count()
|
||||||
|
},
|
||||||
|
area_count={
|
||||||
|
k: bq.where(Person.area == k).count()
|
||||||
|
for k in range(1, 13)
|
||||||
|
},
|
||||||
|
no_area_count=bq.where(Person.area == None).count()
|
||||||
|
)
|
||||||
214
extensions/contactnova.py
Normal file
214
extensions/contactnova.py
Normal file
|
|
@ -0,0 +1,214 @@
|
||||||
|
# (c) 2021 Sakuragasaki46
|
||||||
|
# See LICENSE for copying info.
|
||||||
|
|
||||||
|
'''
|
||||||
|
Contact Nova extension for Salvi.
|
||||||
|
'''
|
||||||
|
|
||||||
|
from peewee import *
|
||||||
|
import datetime
|
||||||
|
from app import _getconf
|
||||||
|
from flask import Blueprint, request, redirect, render_template, jsonify, abort
|
||||||
|
from werkzeug.routing import BaseConverter
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import itertools
|
||||||
|
|
||||||
|
#### HELPERS ####
|
||||||
|
|
||||||
|
class RegExpField(CharField):
|
||||||
|
def __init__(self, regex, max_length=255, *args, **kw):
|
||||||
|
super().__init__(max_length, *args, **kw)
|
||||||
|
self.regex = regex
|
||||||
|
def db_value(self, value):
|
||||||
|
value = value.strip()
|
||||||
|
# XXX %: bug fix for LIKE, but it’s not something regular!
|
||||||
|
if not '%' in value and not re.fullmatch(self.regex, value):
|
||||||
|
raise IntegrityError("regexp mismatch: {!r}".format(self.regex))
|
||||||
|
return value
|
||||||
|
|
||||||
|
def now7days():
|
||||||
|
return datetime.datetime.now() + datetime.timedelta(days=7)
|
||||||
|
|
||||||
|
#### DATABASE SCHEMA ####
|
||||||
|
|
||||||
|
database = SqliteDatabase(_getconf("config", "database_dir") + '/contactnova.sqlite')
|
||||||
|
|
||||||
|
class BaseModel(Model):
|
||||||
|
class Meta:
|
||||||
|
database = database
|
||||||
|
|
||||||
|
ST_UNKNOWN = 0
|
||||||
|
ST_OK = 1
|
||||||
|
ST_ISSUES = 2
|
||||||
|
|
||||||
|
class Contact(BaseModel):
|
||||||
|
code = RegExpField(r'[A-Z]\.\d+', 30, unique=True)
|
||||||
|
display_name = RegExpField('[A-Za-z0-9_. ]+', 50, index=True)
|
||||||
|
status = IntegerField(default=ST_UNKNOWN, index=True)
|
||||||
|
issues = CharField(500, default='')
|
||||||
|
description = CharField(5000, default='')
|
||||||
|
due = DateField(index=True, default=now7days)
|
||||||
|
touched = DateTimeField(index=True, default=datetime.datetime.now)
|
||||||
|
def status_str(self):
|
||||||
|
return {
|
||||||
|
1: "task_alt",
|
||||||
|
2: "error_outline",
|
||||||
|
}.get(self.status, "")
|
||||||
|
def __repr__(self):
|
||||||
|
return '<{0.__class__.__name__}: {0.code}>'.format(self)
|
||||||
|
@classmethod
|
||||||
|
def next_code(cls, letter):
|
||||||
|
try:
|
||||||
|
last_code = Contact.select().where(Contact.code ** (letter + '%')).order_by(Contact.id.desc()).first().code.split('.')
|
||||||
|
except (Contact.DoesNotExist, AttributeError):
|
||||||
|
last_code = letter, '0'
|
||||||
|
code = letter + '.' + str(int(last_code[1]) + 1)
|
||||||
|
return code
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
database.create_tables([Contact])
|
||||||
|
|
||||||
|
def create_cli():
|
||||||
|
code = Contact.next_code(input('Code letter:'))
|
||||||
|
|
||||||
|
return Contact.create(
|
||||||
|
code=code,
|
||||||
|
display_name=input('Display name:'),
|
||||||
|
due=datetime.datetime.fromisoformat(input('Due date (ISO):')),
|
||||||
|
description=input('Description (optional):')
|
||||||
|
)
|
||||||
|
|
||||||
|
# Helper for command line.
|
||||||
|
class _CCClass:
|
||||||
|
def __init__(self, cb=lambda x:x):
|
||||||
|
self.callback = cb
|
||||||
|
def __neg__(self):
|
||||||
|
return create_cli()
|
||||||
|
def __getattr__(self, value):
|
||||||
|
code = value[0] + '.' + value[1:]
|
||||||
|
try:
|
||||||
|
return self.callback(Contact.get(Contact.code == code))
|
||||||
|
except Contact.DoesNotExist:
|
||||||
|
raise AttributeError(value) from None
|
||||||
|
def ok(self):
|
||||||
|
def cb(a):
|
||||||
|
a.status = 1
|
||||||
|
a.save()
|
||||||
|
return a
|
||||||
|
return self.__class__(cb)
|
||||||
|
CC = _CCClass()
|
||||||
|
del _CCClass
|
||||||
|
|
||||||
|
#### ROUTE HELPERS ####
|
||||||
|
|
||||||
|
class ContactCodeConverter(BaseConverter):
|
||||||
|
regex = r'[A-Z]\.\d+'
|
||||||
|
|
||||||
|
class ContactMockConverter(BaseConverter):
|
||||||
|
regex = r'[A-Z]'
|
||||||
|
|
||||||
|
def _register_converters(state):
|
||||||
|
state.app.url_map.converters['contactcode'] = ContactCodeConverter
|
||||||
|
state.app.url_map.converters['singleletter'] = ContactMockConverter
|
||||||
|
|
||||||
|
# Helper for pagination.
|
||||||
|
def paginate_list(cat, q):
|
||||||
|
pageno = int(request.args.get('page', 1))
|
||||||
|
return render_template(
|
||||||
|
"contactnova/list.html",
|
||||||
|
cat=cat,
|
||||||
|
count=q.count(),
|
||||||
|
people=q.offset(50 * (pageno - 1)).limit(50),
|
||||||
|
pageno=pageno
|
||||||
|
)
|
||||||
|
|
||||||
|
bp = Blueprint('contactnova', __name__,
|
||||||
|
url_prefix='/kt')
|
||||||
|
bp.record_once(_register_converters)
|
||||||
|
|
||||||
|
@bp.route('/init-config')
|
||||||
|
def _init_config():
|
||||||
|
init_db()
|
||||||
|
return redirect('/kt')
|
||||||
|
|
||||||
|
@bp.route('/')
|
||||||
|
def homepage():
|
||||||
|
q = Contact.select().where(Contact.due > datetime.datetime.now()).order_by(Contact.due.desc())
|
||||||
|
return paginate_list('All', q)
|
||||||
|
|
||||||
|
@bp.route('/expired')
|
||||||
|
def expired():
|
||||||
|
q = Contact.select().where(Contact.due <= datetime.datetime.now()).order_by(Contact.due)
|
||||||
|
return paginate_list('Expired', q)
|
||||||
|
|
||||||
|
@bp.route('/ok')
|
||||||
|
def sanecontacts():
|
||||||
|
q = Contact.select().where((Contact.due > datetime.datetime.now()) &
|
||||||
|
(Contact.status == ST_OK)).order_by(Contact.due)
|
||||||
|
return paginate_list('Sane', q)
|
||||||
|
|
||||||
|
@bp.route('/<singleletter:l>')
|
||||||
|
def singleletter(l):
|
||||||
|
q = Contact.select().where(Contact.code ** (l + '%')).order_by(Contact.id)
|
||||||
|
return paginate_list('Series {}'.format(l), q)
|
||||||
|
|
||||||
|
@bp.route('/<contactcode:code>')
|
||||||
|
def singlecontact(code):
|
||||||
|
try:
|
||||||
|
p = Contact.get(Contact.code == code)
|
||||||
|
except IntegrityError:
|
||||||
|
abort(404)
|
||||||
|
return render_template('contactnova/single.html', p=p)
|
||||||
|
|
||||||
|
@bp.route('/_newcode/<singleletter:l>')
|
||||||
|
def newcode(l):
|
||||||
|
return Contact.next_code(l), {"Content-Type": "text/plain"}
|
||||||
|
|
||||||
|
@bp.route('/new', methods=['GET', 'POST'])
|
||||||
|
def newcontact():
|
||||||
|
if request.method == 'POST':
|
||||||
|
Contact.create(
|
||||||
|
code = Contact.next_code(request.form['letter']),
|
||||||
|
display_name = request.form['display_name'],
|
||||||
|
status = request.form['status'],
|
||||||
|
issues = request.form['issues'],
|
||||||
|
description = request.form['description'],
|
||||||
|
due = datetime.date.fromisoformat(request.form['due'])
|
||||||
|
)
|
||||||
|
return redirect(request.form.get('returnto','/kt/'+request.form['letter']))
|
||||||
|
return render_template('contactnova/new.html', pl_date = now7days())
|
||||||
|
|
||||||
|
@bp.route('/edit/<contactcode:code>', methods=['GET', 'POST'])
|
||||||
|
def editcontact(code):
|
||||||
|
pl = Contact.get(Contact.code == code)
|
||||||
|
if request.method == 'POST':
|
||||||
|
pl.display_name = request.form['display_name']
|
||||||
|
pl.issues = request.form['issues']
|
||||||
|
pl.status = request.form['status']
|
||||||
|
pl.description = request.form['description']
|
||||||
|
pl.due = datetime.date.fromisoformat(request.form['due'])
|
||||||
|
pl.touched = datetime.datetime.now()
|
||||||
|
pl.save()
|
||||||
|
return redirect(request.form.get('returnto','/kt/'+pl.code[0]))
|
||||||
|
return render_template('contactnova/new.html', pl = pl)
|
||||||
|
|
||||||
|
@bp.route('/_jsoninfo/<float:ts>')
|
||||||
|
def contact_jsoninfo(ts):
|
||||||
|
tse = str(datetime.datetime.fromtimestamp(ts).isoformat(" "))
|
||||||
|
ps = Contact.select().where(Contact.touched >= tse)
|
||||||
|
return jsonify({
|
||||||
|
"ids": [i.code for i in ps],
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
'code': i.code,
|
||||||
|
'display_name': i.display_name,
|
||||||
|
'due': datetime.datetime.fromisoformat(i.due.isoformat()).timestamp(),
|
||||||
|
'issues': i.issues,
|
||||||
|
'description': i.description,
|
||||||
|
'status': i.status
|
||||||
|
} for i in ps
|
||||||
|
],
|
||||||
|
"status": "ok"
|
||||||
|
})
|
||||||
70
extensions/importexport.py
Normal file
70
extensions/importexport.py
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
from flask import Blueprint, render_template, request
|
||||||
|
import json, datetime
|
||||||
|
|
||||||
|
from app import Page, PageTag
|
||||||
|
|
||||||
|
bp = Blueprint('importexport', __name__)
|
||||||
|
|
||||||
|
class Exporter(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.root = {'pages': [], 'users': {}}
|
||||||
|
def add_page(self, p, include_history=True, include_users=False):
|
||||||
|
pobj = {}
|
||||||
|
pobj['title'] = p.title
|
||||||
|
pobj['url'] = p.url
|
||||||
|
pobj['tags'] = [tag.name for tag in p.tags]
|
||||||
|
hist = []
|
||||||
|
for rev in (p.revisions if include_history else [p.latest]):
|
||||||
|
revobj = {}
|
||||||
|
revobj['text'] = rev.text
|
||||||
|
revobj['timestamp'] = rev.pub_date.timestamp()
|
||||||
|
if include_users:
|
||||||
|
revobj['user'] = rev.user_id
|
||||||
|
if rev.user_id not in self.root['users']:
|
||||||
|
self.root['users'][rev.user_id] = rev.user_info()
|
||||||
|
else:
|
||||||
|
revobj['user'] = None
|
||||||
|
revobj['comment'] = rev.comment
|
||||||
|
revobj['length'] = rev.length
|
||||||
|
hist.append(revobj)
|
||||||
|
pobj['history'] = hist
|
||||||
|
self.root['pages'].append(pobj)
|
||||||
|
def add_page_list(self, pl, include_history=True, include_users=False):
|
||||||
|
for p in pl:
|
||||||
|
self.add_page(p, include_history=include_history, include_users=include_users)
|
||||||
|
def export(self):
|
||||||
|
return json.dumps(self.root)
|
||||||
|
|
||||||
|
@bp.route('/manage/export/', methods=['GET', 'POST'])
|
||||||
|
def exportpages():
|
||||||
|
if request.method == 'POST':
|
||||||
|
raw_list = request.form['export-list']
|
||||||
|
q_list = []
|
||||||
|
for item in raw_list.split('\n'):
|
||||||
|
item = item.strip()
|
||||||
|
if len(item) < 2:
|
||||||
|
continue
|
||||||
|
if item.startswith('+'):
|
||||||
|
q_list.append(Page.select().where(Page.id == item[1:]))
|
||||||
|
elif item.startswith('#'):
|
||||||
|
q_list.append(Page.select().join(PageTag, on=PageTag.page).where(PageTag.name == item[1:]))
|
||||||
|
elif item.startswith('/'):
|
||||||
|
q_list.append(Page.select().where(Page.url == item[1:].rstrip('/')))
|
||||||
|
else:
|
||||||
|
q_list.append(Page.select().where(Page.title == item))
|
||||||
|
if not q_list:
|
||||||
|
flash('Failed to export pages: The list is empty!')
|
||||||
|
return render_template('exportpages.html')
|
||||||
|
query = q_list.pop(0)
|
||||||
|
while q_list:
|
||||||
|
query |= q_list.pop(0)
|
||||||
|
e = Exporter()
|
||||||
|
e.add_page_list(query)
|
||||||
|
return e.export(), {'Content-Type': 'application/json', 'Content-Disposition': 'attachment; ' +
|
||||||
|
'filename=export-{}.json'.format(datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))}
|
||||||
|
return render_template('exportpages.html')
|
||||||
|
|
||||||
|
@bp.route('/manage/import/', methods=['GET', 'POST'])
|
||||||
|
def importpages():
|
||||||
|
return render_template('importpages.html')
|
||||||
|
|
||||||
173
extensions/instagram.py
Normal file
173
extensions/instagram.py
Normal file
|
|
@ -0,0 +1,173 @@
|
||||||
|
from flask import Blueprint, render_template
|
||||||
|
from peewee import *
|
||||||
|
import instagram_private_api, json, os, sys, random, codecs
|
||||||
|
|
||||||
|
database = SqliteDatabase('instagram.sqlite')
|
||||||
|
|
||||||
|
class BaseModel(Model):
|
||||||
|
class Meta:
|
||||||
|
database = database
|
||||||
|
|
||||||
|
class InstagramProfile(BaseModel):
|
||||||
|
p_id = IntegerField()
|
||||||
|
p_username = CharField(30)
|
||||||
|
p_full_name = CharField(30)
|
||||||
|
p_biography = CharField(150)
|
||||||
|
posts_count = IntegerField()
|
||||||
|
followers_count = IntegerField()
|
||||||
|
following_count = IntegerField()
|
||||||
|
flags = BitField()
|
||||||
|
pub_date = DateTimeField()
|
||||||
|
is_verified = flags.flag(1)
|
||||||
|
is_private = flags.flag(2)
|
||||||
|
|
||||||
|
class InstagramMedia(BaseModel):
|
||||||
|
user = IntegerField()
|
||||||
|
pub_date = DateTimeField()
|
||||||
|
media_url = TextField()
|
||||||
|
description = CharField(2200)
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
database.create_tables([InstagramProfile, InstagramMedia])
|
||||||
|
|
||||||
|
def bytes_to_json(python_object):
|
||||||
|
if isinstance(python_object, bytes):
|
||||||
|
return {'__class__': 'bytes',
|
||||||
|
'__value__': codecs.encode(python_object, 'base64').decode()}
|
||||||
|
raise TypeError(repr(python_object) + ' is not JSON serializable')
|
||||||
|
|
||||||
|
def bytes_from_json(json_object):
|
||||||
|
if '__class__' in json_object and json_object['__class__'] == 'bytes':
|
||||||
|
return codecs.decode(json_object['__value__'].encode(), 'base64')
|
||||||
|
return json_object
|
||||||
|
|
||||||
|
SETTINGS_PATH = 'ig_api_settings'
|
||||||
|
|
||||||
|
def load_settings(username):
|
||||||
|
with open(os.path.join(SETTINGS_PATH, username + '.json')) as f:
|
||||||
|
settings = json.load(f, object_hook=bytes_from_json)
|
||||||
|
return settings
|
||||||
|
|
||||||
|
def save_settings(username, settings):
|
||||||
|
with open(os.path.join(SETTINGS_PATH, username + '.json'), 'w') as f:
|
||||||
|
json.dump(settings, f, default=bytes_to_json)
|
||||||
|
|
||||||
|
CLIENTS = []
|
||||||
|
|
||||||
|
def load_clients():
|
||||||
|
try:
|
||||||
|
with open(os.path.join(SETTINGS_PATH, 'config.txt')) as f:
|
||||||
|
conf = f.read()
|
||||||
|
except OSError:
|
||||||
|
print('Config file not found.')
|
||||||
|
return
|
||||||
|
for up in conf.split('\n'):
|
||||||
|
try:
|
||||||
|
up = up.split('#')[0].strip()
|
||||||
|
if not up:
|
||||||
|
continue
|
||||||
|
username, password = up.split(':')
|
||||||
|
try:
|
||||||
|
settings = load_settings(username)
|
||||||
|
except Exception:
|
||||||
|
settings = None
|
||||||
|
try:
|
||||||
|
if settings:
|
||||||
|
device_id = settings.get('device_id')
|
||||||
|
api = instagram_private_api.Client(
|
||||||
|
username, password,
|
||||||
|
settings=settings
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
api = instagram_private_api.Client(
|
||||||
|
username, password,
|
||||||
|
on_login=lambda x: save_settings(username, x.settings)
|
||||||
|
)
|
||||||
|
except (instagram_private_api.ClientCookieExpiredError,
|
||||||
|
instagram_private_api.ClientLoginRequiredError) as e:
|
||||||
|
api = instagram_private_api.Client(
|
||||||
|
username, password,
|
||||||
|
device_id=device_id,
|
||||||
|
on_login=lambda x: save_settings(username, x.settings)
|
||||||
|
)
|
||||||
|
CLIENTS.append(api)
|
||||||
|
except Exception:
|
||||||
|
sys.excepthook(*sys.exc_info())
|
||||||
|
continue
|
||||||
|
|
||||||
|
def make_request(method_name, *args, **kwargs):
|
||||||
|
exc = None
|
||||||
|
usable_clients = list(range(len(CLIENTS)))
|
||||||
|
while usable_clients:
|
||||||
|
ci = random.choice(usable_clients)
|
||||||
|
client = CLIENTS[ci]
|
||||||
|
usable_clients.remove(ci)
|
||||||
|
try:
|
||||||
|
method = getattr(client, method_name)
|
||||||
|
except AttributeError:
|
||||||
|
raise ValueError('client has no method called {!r}'.format(method_name))
|
||||||
|
if not callable(method):
|
||||||
|
raise ValueError('client has no method called {!r}'.format(method_name))
|
||||||
|
try:
|
||||||
|
return method(*args, **kwargs)
|
||||||
|
except Exception as e:
|
||||||
|
exc = e
|
||||||
|
if exc:
|
||||||
|
raise exc
|
||||||
|
else:
|
||||||
|
raise RuntimeError('no active clients')
|
||||||
|
|
||||||
|
N_FORCE = 0
|
||||||
|
N_FALLBACK_CACHE = 1
|
||||||
|
N_PREFER_CACHE = 2
|
||||||
|
N_OFFLINE = 3
|
||||||
|
|
||||||
|
def choose_method(online, offline, network):
|
||||||
|
if network == N_FORCE:
|
||||||
|
return online()
|
||||||
|
elif network == N_FALLBACK_CACHE:
|
||||||
|
try:
|
||||||
|
return online()
|
||||||
|
except Exception:
|
||||||
|
return offline()
|
||||||
|
elif network == N_PREFER_CACHE:
|
||||||
|
try:
|
||||||
|
return offline()
|
||||||
|
except Exception:
|
||||||
|
return online()
|
||||||
|
elif network == N_OFFLINE:
|
||||||
|
return offline()
|
||||||
|
|
||||||
|
def get_profile_info(username_or_id, network=N_FALLBACK_CACHE):
|
||||||
|
if isinstance(username_or_id, str):
|
||||||
|
username, userid = username_or_id, None
|
||||||
|
elif isinstance(username_or_id, int):
|
||||||
|
username, userid = None, username_or_id
|
||||||
|
else:
|
||||||
|
raise TypeError('invalid username or id')
|
||||||
|
def online():
|
||||||
|
if userid:
|
||||||
|
data = make_request('user_info', userid)
|
||||||
|
else:
|
||||||
|
data = make_request('username_info', username)
|
||||||
|
return InstagramProfile.create(
|
||||||
|
p_id = data['user']['pk'],
|
||||||
|
p_username = data['user']['username'],
|
||||||
|
p_full_name = data['user']['full_name'],
|
||||||
|
p_biography = data['user']['biography'],
|
||||||
|
posts_count = data['user']['media_count'],
|
||||||
|
followers_count = data['user']['follower_count'],
|
||||||
|
following_count = data['user']['following_count'],
|
||||||
|
is_verified = data['user']['is_verified'],
|
||||||
|
is_private = data['user']['is_private'],
|
||||||
|
pub_date = datetime.datetime.now()
|
||||||
|
)
|
||||||
|
def offline():
|
||||||
|
if userid:
|
||||||
|
q = InstagramProfile.select().where(InstagramProfile.p_id == userid)
|
||||||
|
else:
|
||||||
|
q = InstagramProfile.select().where(InstagramProfile.p_username == username)
|
||||||
|
return q.order_by(InstagramProfile.pub_date.desc())[0]
|
||||||
|
return choose_method(online, offline, network)
|
||||||
|
|
||||||
|
load_clients()
|
||||||
BIN
favicon.ico
BIN
favicon.ico
Binary file not shown.
|
Before Width: | Height: | Size: 318 B After Width: | Height: | Size: 198 B |
|
|
@ -1,83 +0,0 @@
|
||||||
{
|
|
||||||
"en": {
|
|
||||||
"access-denied": "Access Denied",
|
|
||||||
"access-denied-text": "You have no permission to access this resource",
|
|
||||||
"action-edit": "Edit",
|
|
||||||
"action-history": "History",
|
|
||||||
"action-view-source": "View source",
|
|
||||||
"already-have-account": "Already have an account?",
|
|
||||||
"back-to": "Back to",
|
|
||||||
"backlinks": "Backlinks",
|
|
||||||
"backlinks-empty": "No other pages linking here. Is this page orphan?",
|
|
||||||
"bad-request": "Bad request",
|
|
||||||
"calculate": "Calculate",
|
|
||||||
"calendar": "Calendar",
|
|
||||||
"confirm-password": "Confirm password",
|
|
||||||
"easter": "Easter",
|
|
||||||
"easter-date-calc": "Easter date calculation",
|
|
||||||
"email": "E-mail",
|
|
||||||
"groups-count": "User group count",
|
|
||||||
"have-read-terms": "I have read {0} and {1}",
|
|
||||||
"homepage": "Homepage",
|
|
||||||
"in-the-future": "in the future",
|
|
||||||
"in-the-past": "in the past",
|
|
||||||
"include-tags": "Include tags",
|
|
||||||
"input-tags": "Tags (comma separated)",
|
|
||||||
"jump-to-actions": "Jump to actions",
|
|
||||||
"just-now": "just now",
|
|
||||||
"last-changed": "Last changed",
|
|
||||||
"latest-notes": "Most recent pages",
|
|
||||||
"latest-uploads": "Latest uploads",
|
|
||||||
"logged-in-as": "Logged in as",
|
|
||||||
"login": "Log in",
|
|
||||||
"manage-accounts": "Manage accounts",
|
|
||||||
"month": "Month",
|
|
||||||
"n-days-ago": "{0} days ago",
|
|
||||||
"n-hours-ago": "{0} hours ago",
|
|
||||||
"n-minutes-ago": "{0} minutes ago",
|
|
||||||
"new-note": "New page",
|
|
||||||
"no-account-sign-up": "Don’t have an account?",
|
|
||||||
"no-tags": "No tags",
|
|
||||||
"not-found": "Not found",
|
|
||||||
"not-found-text": "The page at {0} does not exist",
|
|
||||||
"not-found-text-1": "The page at",
|
|
||||||
"not-found-text-2": "does not exist.",
|
|
||||||
"not-logged-in": "Not logged in",
|
|
||||||
"note-history": "Page history",
|
|
||||||
"notes-by-date": "Pages by date",
|
|
||||||
"notes-count": "Number of pages",
|
|
||||||
"notes-count-with-url": "Number of pages with URL set",
|
|
||||||
"notes-month-empty": "None found :(",
|
|
||||||
"notes-tagged": "Pages tagged",
|
|
||||||
"notes-tagged-empty": "None found :(",
|
|
||||||
"old-revision-notice": "Showing an old revision of the page as of",
|
|
||||||
"optional": "optional",
|
|
||||||
"other-dates": "Other dates",
|
|
||||||
"owner": "Owner",
|
|
||||||
"page-created": "Page created",
|
|
||||||
"page-id": "Page ID",
|
|
||||||
"password": "Password",
|
|
||||||
"privacy-policy": "Privacy Policy",
|
|
||||||
"random-page": "Random page",
|
|
||||||
"remember-me": "Remember me",
|
|
||||||
"remember-me-for": "Remember me for",
|
|
||||||
"revision-count": "Number of revisions",
|
|
||||||
"revision-count-per-page": "Average revisions per page",
|
|
||||||
"search": "Search",
|
|
||||||
"search-results": "Search results for",
|
|
||||||
"search-no-results": "No results for",
|
|
||||||
"show-all": "Show all",
|
|
||||||
"show-more-years": "Show more years",
|
|
||||||
"sign-up": "Sign up",
|
|
||||||
"tags": "Tags",
|
|
||||||
"terms-of-service": "Terms of Service",
|
|
||||||
"upload-file": "Upload file",
|
|
||||||
"user-generated-warning": "Any content in this site is user-generated and",
|
|
||||||
"user-liability-warning": "each user is responsible for what they publish",
|
|
||||||
"username": "Username",
|
|
||||||
"users-count": "Number of users",
|
|
||||||
"welcome": "Welcome to {0}!",
|
|
||||||
"write-a-comment": "Write a comment…",
|
|
||||||
"year": "Year"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
{
|
|
||||||
"fr": {
|
|
||||||
"easter": "Pâques",
|
|
||||||
"easter-date-calc": "Calculer la date de Pâques",
|
|
||||||
"homepage": "Page de démarrage",
|
|
||||||
"latest-notes": "Dernières notes",
|
|
||||||
"latest-uploads": "Derniers téléchargements",
|
|
||||||
"new-note": "Créer un page",
|
|
||||||
"other-dates": "Autres dates",
|
|
||||||
"welcome": "Bienvenue à {0}!"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,73 +0,0 @@
|
||||||
{
|
|
||||||
"it": {
|
|
||||||
"access-denied": "Accesso negato",
|
|
||||||
"access-denied-text": "Non hai il permesso per accedere a questa risorsa",
|
|
||||||
"action-edit": "Modifica",
|
|
||||||
"action-history": "Cronologia",
|
|
||||||
"action-view-source": "Visualizza sorgente",
|
|
||||||
"already-have-account": "Hai già un account?",
|
|
||||||
"back-to": "Torna a",
|
|
||||||
"backlinks": "Collegamenti in entrata",
|
|
||||||
"backlinks-empty": "Nessuna altra pagina punta qui. Questa pagina è orfana?",
|
|
||||||
"bad-request": "Richiesta non conforme",
|
|
||||||
"calculate": "Calcola",
|
|
||||||
"calendar": "Calendario",
|
|
||||||
"confirm-password": "Conferma password",
|
|
||||||
"easter-date-calc": "Calcolo della data di Pasqua",
|
|
||||||
"easter": "Pasqua",
|
|
||||||
"email": "E-mail",
|
|
||||||
"groups-count": "Numero di gruppi utente",
|
|
||||||
"have-read-terms": "Ho letto i {0} e la {1}",
|
|
||||||
"homepage": "Pagina iniziale",
|
|
||||||
"include-tags": "Includi etichette",
|
|
||||||
"input-tags": "Etichette (separate da virgola)",
|
|
||||||
"jump-to-actions": "Salta alle azioni",
|
|
||||||
"just-now": "poco fa",
|
|
||||||
"last-changed": "Ultima modifica",
|
|
||||||
"latest-notes": "Pagine pi\u00f9 recenti",
|
|
||||||
"latest-uploads": "Caricamenti pi\u00f9 recenti",
|
|
||||||
"login": "Entra",
|
|
||||||
"logged-in-as": "Autenticato come",
|
|
||||||
"month": "Mese",
|
|
||||||
"n-minutes-ago": "{0} minuti fa",
|
|
||||||
"n-hours-ago": "{0} ore fa",
|
|
||||||
"n-days-ago": "{0} giorni fa",
|
|
||||||
"new-note": "Crea nota",
|
|
||||||
"no-account-sign-up": "Non hai un account?",
|
|
||||||
"no-tags": "Nessuna etichetta",
|
|
||||||
"not-found": "Non trovato",
|
|
||||||
"not-found-text": "La pagina con url {0} non esiste",
|
|
||||||
"not-found-text-1": "La pagina con url",
|
|
||||||
"not-found-text-2": "non esiste",
|
|
||||||
"not-logged-in": "Non autenticato",
|
|
||||||
"note-history": "Cronologia della pagina",
|
|
||||||
"notes-count": "Numero di pagine",
|
|
||||||
"notes-count-with-url": "Numero di pagine con URL impostato",
|
|
||||||
"notes-month-empty": "Non c\u2019\u00e8 nulla :(",
|
|
||||||
"notes-tagged": "Pagine con etichetta",
|
|
||||||
"notes-tagged-empty": "Non c\u2019\u00e8 nulla :(",
|
|
||||||
"old-revision-notice": "\u00c8 mostrata una revisione vecchia della pagina, risalente al",
|
|
||||||
"optional": "opzionale",
|
|
||||||
"other-dates": "Altre date",
|
|
||||||
"page-created": "Pagina creata",
|
|
||||||
"owner": "Proprietario",
|
|
||||||
"page-id": "ID pagina",
|
|
||||||
"password": "Password",
|
|
||||||
"privacy-policy": "Politica sulla riservatezza",
|
|
||||||
"random-page": "Pagina casuale",
|
|
||||||
"remember-me-for": "Ricordami per",
|
|
||||||
"revision-count": "Numero di revisioni",
|
|
||||||
"revision-count-per-page": "Media di revisioni per pagina",
|
|
||||||
"search": "Cerca",
|
|
||||||
"search-no-results": "Nessun risultato per",
|
|
||||||
"show-all": "Mostra tutto",
|
|
||||||
"sign-up": "Registrati",
|
|
||||||
"tags": "Etichette",
|
|
||||||
"terms-of-service": "Termini di Servizio",
|
|
||||||
"username": "Nome utente",
|
|
||||||
"users-count": "Numero di utenti",
|
|
||||||
"welcome": "Benvenuti in {0}!",
|
|
||||||
"write-a-comment": "Scrivi un commento…",
|
|
||||||
"year": "Anno"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
{
|
|
||||||
"ru":{
|
|
||||||
"new-note": "Новая страница",
|
|
||||||
"welcome": "Добро пожаловать в {0}!"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
[project]
|
|
||||||
name = "sakuragasaki46_salvi"
|
|
||||||
authors = [
|
|
||||||
{ name = "Sakuragasaki46" }
|
|
||||||
]
|
|
||||||
dynamic = ["version"]
|
|
||||||
dependencies = [
|
|
||||||
"Flask>=3.0",
|
|
||||||
"SQLAlchemy>=2.0",
|
|
||||||
"Flask-SQLAlchemy",
|
|
||||||
"Flask-RestX",
|
|
||||||
"Alembic",
|
|
||||||
"markdown",
|
|
||||||
"Flask-Login",
|
|
||||||
"Flask-WTF",
|
|
||||||
"python-dotenv>=1.0.0",
|
|
||||||
"pymysql",
|
|
||||||
"sakuragasaki46-suou>=0.7.0"
|
|
||||||
]
|
|
||||||
requires-python = ">=3.10"
|
|
||||||
classifiers = [
|
|
||||||
"Private :: X"
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
[tool.setuptools]
|
|
||||||
packages = ["salvi"]
|
|
||||||
|
|
||||||
[tool.setuptools.dynamic]
|
|
||||||
version = { attr = "salvi.__version__" }
|
|
||||||
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
Flask>=3.0
|
|
||||||
SQLAlchemy>=2.0
|
|
||||||
Flask-SQLAlchemy
|
|
||||||
Alembic
|
|
||||||
markdown
|
|
||||||
Flask-Login
|
|
||||||
Flask-WTF
|
|
||||||
python-dotenv
|
|
||||||
python-i18n
|
|
||||||
pymysql
|
|
||||||
|
|
||||||
## DEPRECATED use pyproject.toml instead
|
|
||||||
|
|
@ -2,5 +2,3 @@ User-Agent: *
|
||||||
Noindex: /edit/
|
Noindex: /edit/
|
||||||
Noindex: /history/
|
Noindex: /history/
|
||||||
Disallow: /accounts/
|
Disallow: /accounts/
|
||||||
Noindex: /admin/
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,187 +0,0 @@
|
||||||
# (C) 2020-2023 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.
|
|
||||||
'''
|
|
||||||
|
|
||||||
__version__ = '1.1.0-dev40'
|
|
||||||
|
|
||||||
from flask import (
|
|
||||||
Flask, g, make_response, redirect,
|
|
||||||
request, render_template, send_from_directory
|
|
||||||
)
|
|
||||||
from markupsafe import Markup
|
|
||||||
from flask_login import LoginManager
|
|
||||||
from flask_wtf import CSRFProtect
|
|
||||||
from sqlalchemy import select
|
|
||||||
from suou.configparse import ConfigOptions, ConfigParserConfigSource, ConfigValue
|
|
||||||
from suou.flask import add_context_from_config
|
|
||||||
from werkzeug.routing import BaseConverter
|
|
||||||
import html, os
|
|
||||||
from functools import partial
|
|
||||||
from configparser import ConfigParser
|
|
||||||
import dotenv
|
|
||||||
|
|
||||||
APP_BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
|
||||||
|
|
||||||
dotenv.load_dotenv(os.path.join(APP_BASE_DIR, '.env'))
|
|
||||||
|
|
||||||
## CONFIG ##
|
|
||||||
|
|
||||||
class SiteConfig(ConfigOptions):
|
|
||||||
app_name = ConfigValue(default='Salvi', legacy_src='site.title', public=True)
|
|
||||||
## v--- will change to server_name in 2.0.0
|
|
||||||
domain_name = ConfigValue(public=True)
|
|
||||||
database_url = ConfigValue(legacy_src='database.url', required=True)
|
|
||||||
secret_key = ConfigValue(required=True)
|
|
||||||
default_group = ConfigValue(prefix='salvi_', cast=int, default=1)
|
|
||||||
material_icons_url = ConfigValue(default='https://fonts.googleapis.com/icon?family=Material+Icons', public=True)
|
|
||||||
# v--- pending deprecation
|
|
||||||
default_items_per_page = ConfigValue(prefix='salvi_', legacy_src='appearance.items_per_page', default=20, cast=int)
|
|
||||||
...
|
|
||||||
|
|
||||||
app_config = SiteConfig()
|
|
||||||
# add site.conf (deprecated)
|
|
||||||
legacy_cfp = ConfigParser()
|
|
||||||
legacy_conf_file = os.getenv('SALVI_CONF', os.path.join(APP_BASE_DIR, 'site.conf'))
|
|
||||||
if os.path.exists(legacy_conf_file):
|
|
||||||
legacy_cfp.read_file([legacy_conf_file])
|
|
||||||
app_config.add_source('legacy', ConfigParserConfigSource(legacy_cfp))
|
|
||||||
|
|
||||||
## end CONFIG
|
|
||||||
|
|
||||||
## DON'T ADD LOCAL IMPORTS ABOVE THIS LINE!
|
|
||||||
from .i18n import get_string
|
|
||||||
from .constants import SLUG_RE
|
|
||||||
from .colors import theme_classes, theme_style_tag
|
|
||||||
from .models import User, db
|
|
||||||
from .renderer import md_and_toc
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
|
||||||
app.secret_key = app_config.secret_key
|
|
||||||
app.config['SQLALCHEMY_DATABASE_URI'] = app_config.database_url
|
|
||||||
|
|
||||||
db.init_app(app)
|
|
||||||
|
|
||||||
## TODO add an installer? And do it online or offline?
|
|
||||||
## The installer must contain the creation of the admin account
|
|
||||||
## and the default group.
|
|
||||||
|
|
||||||
class SlugConverter(BaseConverter):
|
|
||||||
regex = SLUG_RE
|
|
||||||
|
|
||||||
app.url_map.converters['slug'] = SlugConverter
|
|
||||||
|
|
||||||
csrf = CSRFProtect(app)
|
|
||||||
|
|
||||||
login_manager = LoginManager(app)
|
|
||||||
login_manager.login_view = 'accounts.login'
|
|
||||||
|
|
||||||
### ROUTES ###
|
|
||||||
|
|
||||||
def _get_lang():
|
|
||||||
if request.args.get('uselang') is not None:
|
|
||||||
lang = request.args['uselang']
|
|
||||||
else:
|
|
||||||
for l in request.headers.get('accept-language', 'it,en').split(','):
|
|
||||||
if ';' in l:
|
|
||||||
l, _ = l.split(';')
|
|
||||||
lang = l
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
lang = 'en'
|
|
||||||
return lang
|
|
||||||
|
|
||||||
def _get_theme():
|
|
||||||
c = request.cookies.get('dark', '0')
|
|
||||||
try:
|
|
||||||
return int(c)
|
|
||||||
except Exception:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
@app.before_request
|
|
||||||
def _before_request():
|
|
||||||
g.lang = _get_lang()
|
|
||||||
|
|
||||||
add_context_from_config(app, app_config)
|
|
||||||
|
|
||||||
@app.context_processor
|
|
||||||
def _inject_variables():
|
|
||||||
return {
|
|
||||||
'T': partial(get_string, _get_lang()),
|
|
||||||
'strong': lambda x: Markup('<strong>{0}</strong>').format(x),
|
|
||||||
'app_name': app_config.app_name,
|
|
||||||
'domain_name': app_config.domain_name,
|
|
||||||
'material_icons_url': app_config.material_icons_url,
|
|
||||||
'app_version': __version__,
|
|
||||||
'min': min,
|
|
||||||
'max': max,
|
|
||||||
'icon': lambda x: Markup('<span class="material-icons">{0}</span>').format(x),
|
|
||||||
'theme_style_tag': theme_style_tag,
|
|
||||||
'theme_classes': theme_classes,
|
|
||||||
'color_theme': _get_theme() # TEMP
|
|
||||||
}
|
|
||||||
|
|
||||||
@login_manager.user_loader
|
|
||||||
def _inject_user(userid):
|
|
||||||
u: User | None = db.session.execute(select(User).where(User.id == int(userid))).scalar()
|
|
||||||
if u is None:
|
|
||||||
return None
|
|
||||||
if not u.is_disabled:
|
|
||||||
return u
|
|
||||||
|
|
||||||
## filters here
|
|
||||||
|
|
||||||
@app.template_filter()
|
|
||||||
def linebreaks(text):
|
|
||||||
text = html.escape(text)
|
|
||||||
text = text.replace("\n\n", '</p><p>').replace('\n', '<br />')
|
|
||||||
return Markup(text)
|
|
||||||
|
|
||||||
app.template_filter(name='markdown')((lambda x: md_and_toc(x)[0]))
|
|
||||||
|
|
||||||
@app.route('/robots.txt')
|
|
||||||
def robots():
|
|
||||||
return send_from_directory(APP_BASE_DIR, 'robots.txt')
|
|
||||||
|
|
||||||
@app.route('/favicon.ico')
|
|
||||||
def favicon():
|
|
||||||
return send_from_directory(APP_BASE_DIR, 'favicon.ico')
|
|
||||||
|
|
||||||
@app.errorhandler(400)
|
|
||||||
def error_400(body):
|
|
||||||
return render_template('400.html'), 400
|
|
||||||
|
|
||||||
@app.errorhandler(403)
|
|
||||||
def error_403(body):
|
|
||||||
return render_template('403.html'), 403
|
|
||||||
|
|
||||||
@app.errorhandler(404)
|
|
||||||
def error_404(body):
|
|
||||||
return render_template('404.html'), 404
|
|
||||||
|
|
||||||
@app.errorhandler(500)
|
|
||||||
def error_500(body):
|
|
||||||
g.no_user = True
|
|
||||||
return render_template('500.html'), 500
|
|
||||||
|
|
||||||
@app.route('/theme-switch')
|
|
||||||
def theme_switch():
|
|
||||||
try:
|
|
||||||
cook = int(request.cookies.get('dark'))
|
|
||||||
except Exception:
|
|
||||||
cook = 0
|
|
||||||
resp = make_response(redirect(request.args.get('next', '/')))
|
|
||||||
resp.set_cookie('dark', str(cook + (256 if cook < 256 else -256)), max_age=31556952, path='/')
|
|
||||||
return resp
|
|
||||||
|
|
||||||
from .routes import blueprints
|
|
||||||
|
|
||||||
for bp in blueprints:
|
|
||||||
app.register_blueprint(bp)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
from collections import namedtuple
|
|
||||||
from types import ModuleType
|
|
||||||
from typing import Iterable
|
|
||||||
|
|
||||||
from markupsafe import Markup
|
|
||||||
|
|
||||||
ColorTheme = namedtuple('ColorTheme', 'code name fg_sharp fg_medium fg_dark fg_light')
|
|
||||||
|
|
||||||
## actual color codes are set in CSS
|
|
||||||
|
|
||||||
color_themes = [
|
|
||||||
ColorTheme(0, 'Default', 0xff7300, 0, 0, 0),
|
|
||||||
ColorTheme(1, 'Rei', 0xff7300, 0, 0, 0),
|
|
||||||
ColorTheme(2, 'Ai', 0xf837cb, 0, 0, 0),
|
|
||||||
ColorTheme(3, 'Aqua', 0x38b8ff, 0, 0, 0),
|
|
||||||
ColorTheme(4, 'Neru', 0xffe338, 0, 0, 0),
|
|
||||||
ColorTheme(5, 'Gumi', 0x78f038, 0, 0, 0),
|
|
||||||
ColorTheme(6, 'Emu', 0xff9aae, 0, 0, 0),
|
|
||||||
ColorTheme(7, 'Spacegray', 0x606080, 0, 0, 0),
|
|
||||||
ColorTheme(8, 'Haku', 0xaeaac0, 0, 0, 0),
|
|
||||||
ColorTheme(9, 'Miku', 0x3ae0b8, 0, 0, 0),
|
|
||||||
ColorTheme(10, 'Defoko', 0x8828ea, 0, 0, 0),
|
|
||||||
ColorTheme(11, 'Kaito', 0x1871d8, 0, 0, 0),
|
|
||||||
ColorTheme(12, 'Meiko', 0x885a18, 0, 0, 0),
|
|
||||||
ColorTheme(13, 'Leek', 0x38a856, 0, 0, 0),
|
|
||||||
ColorTheme(14, 'Teto', 0xff3018, 0, 0, 0),
|
|
||||||
ColorTheme(15, 'Ruby', 0xff1668, 0, 0, 0)
|
|
||||||
]
|
|
||||||
|
|
||||||
def split_color(color: int) -> tuple[int, int, int]:
|
|
||||||
return ((color >> 16) % 256, (color >> 8) % 256, color % 256)
|
|
||||||
|
|
||||||
|
|
||||||
def join_color(it: tuple[int, int, int]) -> int:
|
|
||||||
return (it[0] << 16) | (it[1] << 8) | it[2]
|
|
||||||
|
|
||||||
def make_color_theme(it: ColorTheme) -> ColorTheme:
|
|
||||||
fs = split_color(it.fg_sharp)
|
|
||||||
f_dark = it.fg_dark or join_color((int(fs[0] * .75), int(fs[1] * .75), int(fs[2] * .75)))
|
|
||||||
f_light = it.fg_light or join_color((
|
|
||||||
255 - int((255 - fs[0]) * .75),
|
|
||||||
255 - int((255 - fs[1]) * .75),
|
|
||||||
255 - int((255 - fs[2]) * .75)
|
|
||||||
))
|
|
||||||
f_medium = it.fg_medium or join_color([(i + j) // 2 for i, j in zip(split_color(f_light), split_color(f_dark))])
|
|
||||||
return ColorTheme(it.code, it.name, it.fg_sharp, f_medium, f_dark, f_light)
|
|
||||||
|
|
||||||
color_themes = [make_color_theme(x) for x in color_themes]
|
|
||||||
|
|
||||||
def theme_classes(color_code: int):
|
|
||||||
cl = []
|
|
||||||
sch, th = divmod(color_code, 256)
|
|
||||||
if sch == 1:
|
|
||||||
cl.append('color-scheme-light')
|
|
||||||
if sch == 2:
|
|
||||||
cl.append('color-scheme-dark')
|
|
||||||
if 1 <= th <= 15:
|
|
||||||
cl.append(f'color-theme-{th}')
|
|
||||||
|
|
||||||
return ' '.join(cl)
|
|
||||||
|
|
||||||
def t_rgba(color: int, opacity: float = 1):
|
|
||||||
return f'rgba({(color >> 16) % 256}, {(color >> 8) % 256}, {color % 256}, {opacity})'
|
|
||||||
|
|
||||||
def t_hex(color: int):
|
|
||||||
return f'#{color:06x}'
|
|
||||||
|
|
||||||
def theme_style_tag(*, defcode = 9):
|
|
||||||
rules1 = []
|
|
||||||
rules2 = []
|
|
||||||
for it in color_themes:
|
|
||||||
rules1.append(f'--c{it.code}-accent-sharp: {t_hex(it.fg_sharp)}; --c{it.code}-accent-medium: {t_hex(it.fg_medium)}; --c{it.code}-accent-dark: {t_hex(it.fg_dark)}; --c{it.code}-accent-light: {t_hex(it.fg_light)}; --c{it.code}-accent-bg: {t_rgba(it.fg_sharp, .25)};')
|
|
||||||
rules2.append(f'.color-theme-{it.code} {{ --accent-sharp: var(--c{it.code}-accent-sharp); --accent-medium: var(--c{it.code}-accent-medium); --accent-dark: var(--c{it.code}-accent-dark); --accent-light: var(--c{it.code}-accent-light); --accent-bg: var(--c{it.code}-accent-bg); }}')
|
|
||||||
return Markup('<style>:root {' + '\n'.join(rules1) + f'''
|
|
||||||
--accent-sharp: var(--c{defcode}-accent-sharp); --accent-medium: var(--c{defcode}-accent-medium); --accent-dark: var(--c{defcode}-accent-dark); --accent-light: var(--c{defcode}-accent-light); --accent-bg: var(--c{defcode}-accent-bg);
|
|
||||||
''' + '}\n' + '\n'.join(rules2) + '\n</style>')
|
|
||||||
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
# (C) 2020-2023 Sakuragasaki46.
|
|
||||||
# See LICENSE for copying info.
|
|
||||||
|
|
||||||
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'(?<!\w)@(' + USERNAME_RE + r')'
|
|
||||||
|
|
||||||
|
|
||||||
FORBIDDEN_URLS = [
|
|
||||||
'about', 'accounts', 'ajax', 'backlinks', 'calendar', 'circles', 'create',
|
|
||||||
'easter', 'edit', 'embed', 'group', 'help', 'history', 'init-config',
|
|
||||||
'manage', 'media', 'p', 'privacy', 'protect', 'rules', 'search', 'static',
|
|
||||||
'stats', 'tags', 'terms', 'theme-switch', 'timeline', 'u', 'upload', 'upload-info', 'v1'
|
|
||||||
]
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
from suou.functools import deprecated
|
|
||||||
|
|
||||||
@deprecated('use suou.configparse.MissingConfigError instead')
|
|
||||||
class MissingConfigError(LookupError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
import datetime
|
|
||||||
from flask import g
|
|
||||||
import os
|
|
||||||
from functools import partial
|
|
||||||
|
|
||||||
from suou.i18n import JsonI18n
|
|
||||||
|
|
||||||
from . import APP_BASE_DIR
|
|
||||||
|
|
||||||
i18n = JsonI18n(os.path.join(APP_BASE_DIR, 'i18n'), 'salvi')
|
|
||||||
|
|
||||||
def get_string(loc, s) -> str:
|
|
||||||
return i18n.lang(loc).t(s)
|
|
||||||
|
|
||||||
def human_elapsed_time(then: datetime.datetime, lang = None) -> str:
|
|
||||||
if lang is None: ## XXX make it explicit?
|
|
||||||
try:
|
|
||||||
lang = g.lang
|
|
||||||
except AttributeError:
|
|
||||||
lang = None ## TODO replace with default lang (?)
|
|
||||||
delta = datetime.datetime.now() - then
|
|
||||||
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 then.strftime('%B %-d, %Y')
|
|
||||||
|
|
||||||
627
salvi/models.py
627
salvi/models.py
|
|
@ -1,627 +0,0 @@
|
||||||
# (C) 2020-2023 Sakuragasaki46.
|
|
||||||
# See LICENSE for copying info.
|
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from functools import partial, wraps
|
|
||||||
from getpass import getpass
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
from typing import Any, Callable, Iterable, List, Mapping
|
|
||||||
import datetime
|
|
||||||
import gzip
|
|
||||||
|
|
||||||
from flask import abort, flash
|
|
||||||
from flask_login import AnonymousUserMixin, current_user, login_required
|
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
|
||||||
from markupsafe import Markup
|
|
||||||
|
|
||||||
# sqlalchemy imports
|
|
||||||
from sqlalchemy.orm import Mapped, Relationship, declarative_base, mapped_column, relationship
|
|
||||||
from sqlalchemy import Index, Integer, SmallInteger, String, DateTime, BigInteger, ForeignKey, UniqueConstraint, BLOB as Blob, delete, func, insert, or_, select, text, update
|
|
||||||
|
|
||||||
from suou.functools import deprecated, deprecated_alias, not_implemented
|
|
||||||
from werkzeug.security import generate_password_hash
|
|
||||||
|
|
||||||
from . import app_config
|
|
||||||
from .constants import FORBIDDEN_URLS, ILINK_RE, SLUG_RE, USERNAME_RE
|
|
||||||
from .renderer import md_and_toc, remove_tags
|
|
||||||
from .i18n import human_elapsed_time
|
|
||||||
|
|
||||||
current_user: User
|
|
||||||
|
|
||||||
# Helper for interactive session management
|
|
||||||
from suou.sqlalchemy import bool_column, bound_fk, create_session, declarative_base, BitSelector, unbound_fk
|
|
||||||
|
|
||||||
CSI = create_session_interactively = partial(create_session, app_config.database_url)
|
|
||||||
|
|
||||||
Base = declarative_base(app_config.domain_name, app_config.secret_key)
|
|
||||||
|
|
||||||
db = SQLAlchemy(model_class=Base)
|
|
||||||
|
|
||||||
class User(db.Model):
|
|
||||||
__tablename__ = 'user'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
username: Mapped[str] = mapped_column(String(32), unique=True)
|
|
||||||
email: Mapped[str | None] = mapped_column(String(256), nullable=True)
|
|
||||||
password: Mapped[str] = mapped_column(String(255))
|
|
||||||
join_date: Mapped[int] = mapped_column(DateTime, server_default=func.current_timestamp())
|
|
||||||
karma: Mapped[int] = mapped_column(Integer, server_default=text('1'))
|
|
||||||
is_admin: Mapped[bool] = bool_column()
|
|
||||||
is_disabled: Mapped[int] = bool_column()
|
|
||||||
color_theme: Mapped[int] = mapped_column(SmallInteger, server_default=text('0'))
|
|
||||||
|
|
||||||
owned_pages: Relationship[List[Page]] = relationship('Page', back_populates='owner')
|
|
||||||
group_memberships: Relationship[UserGroupMembership] = relationship('UserGroupMembership', back_populates='user')
|
|
||||||
contributions: Relationship[PageRevision] = relationship("PageRevision", back_populates='user')
|
|
||||||
|
|
||||||
__table_args__ = (
|
|
||||||
UniqueConstraint(username, name='user_username'),
|
|
||||||
)
|
|
||||||
|
|
||||||
# helpers for flask_login
|
|
||||||
@property
|
|
||||||
def is_anonymous(self) -> False:
|
|
||||||
return False
|
|
||||||
@property
|
|
||||||
def is_active(self) -> bool:
|
|
||||||
return not self.is_disabled
|
|
||||||
@property
|
|
||||||
def is_authenticated(self) -> True:
|
|
||||||
return True
|
|
||||||
|
|
||||||
def groups(self) -> Iterable[UserGroup]:
|
|
||||||
return db.session.execute(
|
|
||||||
select(UserGroup).join(UserGroupMembership, UserGroupMembership.group_id == UserGroup.id)
|
|
||||||
.where(UserGroupMembership.user_id == self.id)
|
|
||||||
).scalars()
|
|
||||||
|
|
||||||
def get_perms(self) -> int:
|
|
||||||
if self.is_admin:
|
|
||||||
return PERM_ALL
|
|
||||||
|
|
||||||
perm = 0
|
|
||||||
|
|
||||||
for gr in self.groups():
|
|
||||||
perm |= gr.permissions
|
|
||||||
|
|
||||||
return perm
|
|
||||||
|
|
||||||
def has_perms_on_page(self, flags: int, page: Page | None = None):
|
|
||||||
if page:
|
|
||||||
perm = page.get_perms(user)
|
|
||||||
else:
|
|
||||||
perm = self.get_perms()
|
|
||||||
|
|
||||||
if perm & flags:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
has_perms = has_perms_on_page
|
|
||||||
|
|
||||||
def owns(self, other: Page) -> bool:
|
|
||||||
return other.owner == self
|
|
||||||
|
|
||||||
def get_id(self) -> str:
|
|
||||||
return str(self.id)
|
|
||||||
|
|
||||||
# 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_READ
|
|
||||||
|
|
||||||
class UserGroup(db.Model):
|
|
||||||
__tablename__ = 'usergroup'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
name: Mapped[str] = mapped_column(String(32), unique=True)
|
|
||||||
permissions: Mapped[int] = mapped_column(BigInteger, server_default=text('0'))
|
|
||||||
can_read: Mapped[bool] = BitSelector(permissions, PERM_READ)
|
|
||||||
can_edit: Mapped[bool] = BitSelector(permissions, PERM_EDIT)
|
|
||||||
can_create: Mapped[bool] = BitSelector(permissions, PERM_CREATE)
|
|
||||||
can_set_url: Mapped[bool] = BitSelector(permissions, PERM_SET_URL)
|
|
||||||
can_set_tags: Mapped[bool] = BitSelector(permissions, PERM_SET_TAGS)
|
|
||||||
|
|
||||||
__table_args__ = (
|
|
||||||
UniqueConstraint(name, name='usergroup_name'),
|
|
||||||
)
|
|
||||||
|
|
||||||
user_memberships: Relationship[UserGroupMembership] = relationship('UserGroupMembership', back_populates='group')
|
|
||||||
page_permissions: Relationship[PagePermission] = relationship('PagePermission', back_populates = 'group')
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def get_default(cls) -> UserGroup:
|
|
||||||
return db.session.execute(
|
|
||||||
select(cls).where(or_(
|
|
||||||
cls.id == app_config.default_group,
|
|
||||||
cls.name == 'default'
|
|
||||||
))
|
|
||||||
).scalar()
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
@deprecated('shortened to get_default()')
|
|
||||||
def get_default_group(cls):
|
|
||||||
return cls.get_default()
|
|
||||||
|
|
||||||
class UserGroupMembership(db.Model):
|
|
||||||
__tablename__ = 'usergroupmembership'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key = True)
|
|
||||||
user_id: Mapped[int] = mapped_column(Integer, ForeignKey('user.id'))
|
|
||||||
group_id: Mapped[int] = mapped_column(Integer, ForeignKey('usergroup.id'))
|
|
||||||
since: Mapped[datetime.datetime] = mapped_column(DateTime, default=datetime.datetime.now)
|
|
||||||
|
|
||||||
__table_args__ = (
|
|
||||||
UniqueConstraint(user_id, group_id, name="usergroupmembership_user_id_group_id"),
|
|
||||||
)
|
|
||||||
|
|
||||||
user: Relationship[User] = relationship("User", back_populates='group_memberships')
|
|
||||||
group: Relationship[UserGroup] = relationship("UserGroup", back_populates='user_memberships')
|
|
||||||
|
|
||||||
|
|
||||||
class Page(db.Model):
|
|
||||||
__tablename__ = 'page'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
# v--- url will be moved to a separate table in 1.2 (?)
|
|
||||||
url: Mapped[str | None] = mapped_column(String(64), unique=True)
|
|
||||||
title: Mapped[str] = mapped_column(String(256))
|
|
||||||
touched: Mapped[datetime.datetime] = mapped_column(DateTime)
|
|
||||||
calendar: Mapped[datetime.datetime | None] = mapped_column(DateTime, index=True)
|
|
||||||
owner_id: Mapped[int | None] = mapped_column(Integer, ForeignKey('user.id'))
|
|
||||||
flags: Mapped[int] = mapped_column(BigInteger, server_default=text('0'))
|
|
||||||
is_redirect: Mapped[bool] = BitSelector(flags, 1)
|
|
||||||
is_sync: Mapped[bool] = BitSelector(flags, 2)
|
|
||||||
is_math_enabled: Mapped[bool] = BitSelector(flags, 4)
|
|
||||||
is_locked: Mapped[bool] = BitSelector(flags, 8)
|
|
||||||
is_cw: Mapped[bool] = BitSelector(flags, 16)
|
|
||||||
|
|
||||||
__table_args__ = (
|
|
||||||
Index('page_title', title),
|
|
||||||
Index('page_touched', touched),
|
|
||||||
UniqueConstraint(url, name='page_url'),
|
|
||||||
Index('page_calendar', calendar)
|
|
||||||
)
|
|
||||||
|
|
||||||
revisions: Relationship[List[PageRevision]] = relationship("PageRevision", back_populates = 'page')
|
|
||||||
owner: Relationship[User] = relationship('User', back_populates = 'owned_pages')
|
|
||||||
tags: Relationship[List[PageTag]] = relationship('PageTag', back_populates = 'page')
|
|
||||||
properties: Relationship[List[PageProperty]] = relationship('PageProperty', back_populates = 'page')
|
|
||||||
forward_links: Relationship[List[PageLink]] = relationship('PageLink', primaryjoin=lambda: PageLink.from_page_id == Page.id, back_populates = 'from_page')
|
|
||||||
back_links: Relationship[List[PageLink]] = relationship('PageLink', primaryjoin=lambda: PageLink.to_page_id == Page.id, back_populates = 'to_page')
|
|
||||||
permission_overrides: Relationship[List[PagePermission]] = relationship('PagePermission', back_populates = 'page')
|
|
||||||
|
|
||||||
def latest(self) -> PageRevision:
|
|
||||||
return db.session.execute(
|
|
||||||
select(PageRevision).where(PageRevision.page_id == self.id).order_by(PageRevision.pub_date.desc()).limit(1)
|
|
||||||
).scalar()
|
|
||||||
|
|
||||||
def get_url(self):
|
|
||||||
return f'/{self.url}/' if self.url else f'/p/{self.id}/'
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def by_url(cls, url: str):
|
|
||||||
return db.session.execute(db.select(Page).where(Page.url == url)).scalar()
|
|
||||||
|
|
||||||
@deprecated('usage of inefficient and deprecated remove_tags()')
|
|
||||||
def short_desc(self) -> str:
|
|
||||||
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=False)
|
|
||||||
return text[:200] + ('\u2026' if len(text) > 200 else '')
|
|
||||||
|
|
||||||
def get_perms(self, user: User | AnonymousUserMixin) -> int:
|
|
||||||
if user.is_anonymous:
|
|
||||||
return UserGroup.get_default().permissions & PERM_LOCK
|
|
||||||
if user.is_admin:
|
|
||||||
return PERM_ALL
|
|
||||||
perm = 0
|
|
||||||
|
|
||||||
user_groups = user.groups()
|
|
||||||
for gr in user_groups:
|
|
||||||
perm |= gr.permissions
|
|
||||||
|
|
||||||
for ov in self.permission_overrides:
|
|
||||||
ov: PagePermission
|
|
||||||
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 tag_names(self) -> list[str]:
|
|
||||||
return [x.name for x in self.tags]
|
|
||||||
|
|
||||||
def change_tags(self, taglist: Iterable[str]):
|
|
||||||
old_tags = set(self.tag_names())
|
|
||||||
new_tags = set(taglist)
|
|
||||||
db.session.execute(delete(PageTag).where(PageTag.page == self, PageTag.name.in_(list(old_tags - new_tags))))
|
|
||||||
for t in (new_tags - old_tags):
|
|
||||||
db.session.execute(insert(PageTag).values(page=self, name=t))
|
|
||||||
# commit handled by caller!
|
|
||||||
|
|
||||||
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.isoformat('T'),
|
|
||||||
is_editable = self.is_editable_by(current_user),
|
|
||||||
latest = latest.js_info(),
|
|
||||||
tags = [x.name for x in self.tags]
|
|
||||||
)
|
|
||||||
|
|
||||||
@deprecated('meta name="keywords" is nowadays ignored by search engines')
|
|
||||||
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)
|
|
||||||
|
|
||||||
def is_owned_by(self, user: User, /) -> bool:
|
|
||||||
return self.owner_id == user.id
|
|
||||||
|
|
||||||
def is_editable_by(self, /, user: User | AnonymousUserMixin) -> bool:
|
|
||||||
if not isinstance(user, User):
|
|
||||||
return False
|
|
||||||
perm = self.get_perms(user)
|
|
||||||
return bool(perm & PERM_EDIT or (user.owns(self) & PERM_CREATE))
|
|
||||||
|
|
||||||
can_edit = deprecated_alias(is_editable_by)
|
|
||||||
|
|
||||||
@deprecated('use explicit .is_editable_by(current_user) instead')
|
|
||||||
def is_editable(self) -> bool:
|
|
||||||
return self.is_editable_by(current_user)
|
|
||||||
|
|
||||||
|
|
||||||
def current_text(self) -> str:
|
|
||||||
## XXX is it needed? It's just better to .latest().text()?
|
|
||||||
return self.latest().text()
|
|
||||||
|
|
||||||
@deprecated('use get_prop() and set_prop() instead')
|
|
||||||
def prop(self) -> _PagePropertyDict:
|
|
||||||
return _PagePropertyDict(self)
|
|
||||||
|
|
||||||
def get_prop(self, key: str, /, default = None):
|
|
||||||
kv = db.session.execute(
|
|
||||||
select(PageProperty).where(PageProperty.page == self, PageProperty.key == key)
|
|
||||||
).scalar()
|
|
||||||
return kv.value if kv else default
|
|
||||||
|
|
||||||
def set_prop(self, key: str, value, /, commit: bool = False):
|
|
||||||
if self.has_prop(key):
|
|
||||||
db.session.execute(update(PageProperty).where(PageProperty.page_id == self.id, PageProperty.key == key)
|
|
||||||
.values(value=value))
|
|
||||||
else:
|
|
||||||
db.session.execute(insert(PageProperty).values(
|
|
||||||
page=self,
|
|
||||||
key=key,
|
|
||||||
value=value
|
|
||||||
))
|
|
||||||
|
|
||||||
if commit:
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
def has_prop(self, key: str, /) -> bool:
|
|
||||||
return db.session.execute(
|
|
||||||
select(PageProperty).where(PageProperty.page == self, PageProperty.key == key)
|
|
||||||
).scalar() != None
|
|
||||||
|
|
||||||
|
|
||||||
class PageText(db.Model):
|
|
||||||
__tablename__ = 'pagetext'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
content: Mapped[bytes] = mapped_column(Blob)
|
|
||||||
flags: Mapped[int] = mapped_column(BigInteger, default=0)
|
|
||||||
is_gzipped: Mapped[bool] = BitSelector(flags, 2)
|
|
||||||
def get_content(self) -> str:
|
|
||||||
c = self.content
|
|
||||||
if self.is_gzipped:
|
|
||||||
c = gzip.decompress(c)
|
|
||||||
return c.decode('utf-8', 'replace')
|
|
||||||
@classmethod
|
|
||||||
def create_content(cls, text: str, *, treshold=600, search_dup = True) -> PageText:
|
|
||||||
c: bytes = text.encode('utf-8')
|
|
||||||
use_gzip = len(c) > treshold
|
|
||||||
if use_gzip and gzip:
|
|
||||||
c = gzip.compress(c)
|
|
||||||
if search_dup:
|
|
||||||
item = db.session.execute(select(cls).where(cls.content == c, cls.is_gzipped == use_gzip)).scalar()
|
|
||||||
if item:
|
|
||||||
return item
|
|
||||||
return db.session.execute(insert(cls).values(
|
|
||||||
content = c,
|
|
||||||
is_gzipped = use_gzip
|
|
||||||
).returning(cls)).scalar()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class PageRevision(db.Model):
|
|
||||||
__tablename__ = 'pagerevision'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
page_id: Mapped[int] = bound_fk(Page.id)
|
|
||||||
user_id: Mapped[int | None] = unbound_fk(User.id)
|
|
||||||
comment: Mapped[str] = mapped_column(String(1024), default='')
|
|
||||||
textref_id: Mapped[int] = bound_fk(PageText.id)
|
|
||||||
pub_date: Mapped[datetime.datetime] = mapped_column(DateTime, index=True)
|
|
||||||
length: Mapped[int] = mapped_column()
|
|
||||||
|
|
||||||
__table_args__ = (
|
|
||||||
Index('ix_pagerevision_pub_date', pub_date),
|
|
||||||
|
|
||||||
)
|
|
||||||
|
|
||||||
page: Relationship[Page] = relationship("Page", back_populates='revisions')
|
|
||||||
user: Relationship[User] = relationship("User", back_populates='contributions')
|
|
||||||
textref: Relationship[PageText] = relationship("PageText")
|
|
||||||
|
|
||||||
|
|
||||||
def text(self) -> str:
|
|
||||||
return self.textref.get_content()
|
|
||||||
|
|
||||||
def html_and_toc(self) -> tuple[Markup, Any | None]:
|
|
||||||
return md_and_toc(self.text())
|
|
||||||
|
|
||||||
def js_info(self) -> dict:
|
|
||||||
return dict(
|
|
||||||
id = self.id,
|
|
||||||
length = self.length,
|
|
||||||
pub_date = self.pub_date.isoformat('T')
|
|
||||||
)
|
|
||||||
|
|
||||||
@deprecated('use .html_and_toc() instead')
|
|
||||||
def html(self) -> Markup:
|
|
||||||
return self.html_and_toc()[0]
|
|
||||||
|
|
||||||
@deprecated('use utils.human_elapsed_time() instead')
|
|
||||||
def human_pub_date(self):
|
|
||||||
return human_elapsed_time(self.pub_date)
|
|
||||||
|
|
||||||
|
|
||||||
class PageTag(db.Model):
|
|
||||||
__tablename__ = 'pagetag'
|
|
||||||
__table_args__ = (
|
|
||||||
UniqueConstraint('page_id', 'name', name='pagetag_page_id_name'),
|
|
||||||
Index('ix_pagetag_name', 'name')
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
page_id: Mapped[int] = bound_fk(Page.id)
|
|
||||||
name: Mapped[str] = mapped_column(String(64), index=True)
|
|
||||||
|
|
||||||
page = relationship('Page', back_populates='tags')
|
|
||||||
|
|
||||||
def popularity(self) -> int:
|
|
||||||
return db.session.execute(
|
|
||||||
select(func.count('*')).select_from(PageTag).where(PageTag.name == self.name)
|
|
||||||
).scalar()
|
|
||||||
|
|
||||||
|
|
||||||
class PageProperty(db.Model):
|
|
||||||
"""
|
|
||||||
XXX as of 1.1.0, PageProperty is unused
|
|
||||||
"""
|
|
||||||
__tablename__ = 'pageproperty'
|
|
||||||
__table_args__ = (
|
|
||||||
UniqueConstraint('page_id', 'key', name="pageproperty_page_id_key"),
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key = True)
|
|
||||||
page_id: Mapped[int] = mapped_column(Integer, ForeignKey('page.id'))
|
|
||||||
key: Mapped[str] = mapped_column(String(64))
|
|
||||||
value: Mapped[str] = mapped_column(String(8000))
|
|
||||||
|
|
||||||
page = relationship('Page', back_populates = 'properties')
|
|
||||||
|
|
||||||
|
|
||||||
# XXX PagePropertyDict?
|
|
||||||
@deprecated('is it *really* worth it to implement?')
|
|
||||||
class _PagePropertyDict(Mapping):
|
|
||||||
__slots__ = ('_page', )
|
|
||||||
def __init__(self, page: Page, /) -> tuple[str, Any]:
|
|
||||||
self._page = page
|
|
||||||
def items(self, /):
|
|
||||||
for kv in self._page.properties:
|
|
||||||
yield (kv.key, kv.value)
|
|
||||||
def keys(self, /):
|
|
||||||
for kv in self._page.properties:
|
|
||||||
yield kv.key
|
|
||||||
def values(self, /):
|
|
||||||
for kv in self._page.properties:
|
|
||||||
yield kv.value
|
|
||||||
__iter__ = keys
|
|
||||||
def __len__(self, /):
|
|
||||||
return len(self._page.properties)
|
|
||||||
def __contains__(self, key, /):
|
|
||||||
return self._page.has_prop(key)
|
|
||||||
def __getitem__(self, key, /):
|
|
||||||
if not key in self:
|
|
||||||
raise KeyError(key)
|
|
||||||
return self._page.get_prop(key)
|
|
||||||
def __setitem__(self, key, value, /):
|
|
||||||
return self._page.set_prop(key, value)
|
|
||||||
def __delitem__(self, key, /):
|
|
||||||
db.session.execute(delete(PageProperty).where(
|
|
||||||
PageProperty.page_id == self._page.id,
|
|
||||||
PageProperty.key == key
|
|
||||||
))
|
|
||||||
def get(self, key, /, default = None):
|
|
||||||
return self._page.get_prop(key, default)
|
|
||||||
def setdefault(self, key, /, default):
|
|
||||||
if key not in self:
|
|
||||||
return db.session.execute(insert(PageProperty).values(
|
|
||||||
page_id = self._page.id,
|
|
||||||
key = key,
|
|
||||||
value = default
|
|
||||||
).returning(PageProperty.value)).scalar()
|
|
||||||
else:
|
|
||||||
return self._page.get_prop(key)
|
|
||||||
|
|
||||||
|
|
||||||
class PageLink(db.Model):
|
|
||||||
__tablename__ = 'pagelink'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key = True)
|
|
||||||
from_page_id: Mapped[int] = bound_fk(Page.id)
|
|
||||||
to_page_id: Mapped[int] = bound_fk(Page.id)
|
|
||||||
|
|
||||||
__table_args__ = (
|
|
||||||
UniqueConstraint('from_page_id', 'to_page_id', name='pagelink_from_page_id_to_page_id'),
|
|
||||||
Index('to_page_id', to_page_id)
|
|
||||||
)
|
|
||||||
|
|
||||||
from_page: Relationship[Page] = relationship('Page', foreign_keys=[from_page_id], back_populates='forward_links')
|
|
||||||
to_page: Relationship[Page] = relationship('Page', foreign_keys=[to_page_id], back_populates='back_links')
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def parse_links(cls, from_page, text: str, erase=True):
|
|
||||||
with db.session.begin(nested=True):
|
|
||||||
old_links = set(db.session.execute(select(PageLink.id).where(cls.from_page == from_page)).scalars())
|
|
||||||
for mo in re.finditer(ILINK_RE, text):
|
|
||||||
try:
|
|
||||||
pageurl = mo.group(1)
|
|
||||||
if pageurl.startswith('p/'):
|
|
||||||
to_page_cond = Page.id == int(pageurl[2:])
|
|
||||||
else:
|
|
||||||
to_page_cond = Page.url == pageurl
|
|
||||||
to_page = db.session.execute(select(Page).where(to_page_cond)).scalar()
|
|
||||||
if to_page is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
linkobj = db.session.execute(select(PageLink).where(PageLink.from_page == from_page, PageLink.to_page == to_page)).scalar()
|
|
||||||
if linkobj is None:
|
|
||||||
linkobj = db.session.execute(insert(PageLink).values(
|
|
||||||
from_page=from_page, to_page=to_page
|
|
||||||
).returning(PageLink)).scalar()
|
|
||||||
if linkobj.id in old_links:
|
|
||||||
old_links.remove(linkobj.id)
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
if erase:
|
|
||||||
db.session.execute(delete(PageLink).where(PageLink.id.in_(old_links)))
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
|
|
||||||
# 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 db.session.execute(select(Page)).scalars():
|
|
||||||
cls.parse_links(p, p.current_text())
|
|
||||||
|
|
||||||
class PagePermission(db.Model):
|
|
||||||
__tablename__ = 'pagepermission'
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key = True)
|
|
||||||
page_id: Mapped[int] = bound_fk(Page.id)
|
|
||||||
group_id: Mapped[int] = bound_fk(UserGroup.id)
|
|
||||||
# v--- will be split in 1.2, otherwise sooner or later
|
|
||||||
permissions: Mapped[int] = mapped_column(BigInteger, server_default=text('0'))
|
|
||||||
can_read: Mapped[bool] = BitSelector(permissions, PERM_READ)
|
|
||||||
can_edit: Mapped[bool] = BitSelector(permissions, PERM_EDIT)
|
|
||||||
can_create: Mapped[bool] = BitSelector(permissions, PERM_CREATE)
|
|
||||||
can_set_url: Mapped[bool] = BitSelector(permissions, PERM_SET_URL)
|
|
||||||
can_set_tags: Mapped[bool] = BitSelector(permissions, PERM_SET_TAGS)
|
|
||||||
|
|
||||||
__table_args__ = (
|
|
||||||
UniqueConstraint('page_id', 'group_id', name="pagepermission_page_id_group_id"),
|
|
||||||
Index('group_id', group_id)
|
|
||||||
)
|
|
||||||
|
|
||||||
page = relationship('Page', back_populates = 'permission_overrides')
|
|
||||||
group = relationship('UserGroup', back_populates = 'page_permissions')
|
|
||||||
|
|
||||||
# END MODELS
|
|
||||||
|
|
||||||
def is_username(username: str):
|
|
||||||
return bool(re.fullmatch(USERNAME_RE, username))
|
|
||||||
|
|
||||||
## TODO move page_url to separate table in 1.1 (?)
|
|
||||||
def is_valid_url(url):
|
|
||||||
return re.fullmatch(SLUG_RE, url)
|
|
||||||
|
|
||||||
def is_url_available(url):
|
|
||||||
return url not in FORBIDDEN_URLS and Page.by_url(url) == None
|
|
||||||
|
|
||||||
|
|
||||||
def perms_required(perms: int, *, message: str | None = None):
|
|
||||||
## XXX experimental, does not work at all times!
|
|
||||||
def decorator(func: Callable):
|
|
||||||
@wraps(func)
|
|
||||||
@login_required
|
|
||||||
def wrapper(*a, **ka):
|
|
||||||
if not current_user.has_perms_on_page(perms):
|
|
||||||
if message:
|
|
||||||
flash(message)
|
|
||||||
abort(403)
|
|
||||||
return func(*a, **ka)
|
|
||||||
return wrapper
|
|
||||||
return decorator
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def create_first_user():
|
|
||||||
"""
|
|
||||||
Rudimentary installer. Untested: use at your own risk.
|
|
||||||
"""
|
|
||||||
first_user = db.session.execute(select(User).limit(1)).scalar()
|
|
||||||
if first_user is not None:
|
|
||||||
print('Superuser already exists!')
|
|
||||||
return first_user
|
|
||||||
|
|
||||||
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
|
|
||||||
try:
|
|
||||||
db.metadata.create_all()
|
|
||||||
ua = db.session.execute(insert(User).values(
|
|
||||||
username = username,
|
|
||||||
email = email,
|
|
||||||
password = generate_password_hash(password),
|
|
||||||
join_date = datetime.datetime.now(),
|
|
||||||
is_admin = True
|
|
||||||
).returning(User)).scalar()
|
|
||||||
ug = db.session.execute(insert(UserGroup).values(
|
|
||||||
name = 'default',
|
|
||||||
permissions = int(default_permissions)
|
|
||||||
).returning(UserGroup)).scalar()
|
|
||||||
db.session.execute(insert(UserGroupMembership).values(
|
|
||||||
user_id = ua.id,
|
|
||||||
group_id = ug.id
|
|
||||||
))
|
|
||||||
db.session.commit()
|
|
||||||
print('Installed successfully!')
|
|
||||||
return ua
|
|
||||||
except Exception:
|
|
||||||
sys.excepthook(*sys.exc_info())
|
|
||||||
db.session.rollback()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
# (C) 2020-2025 Sakuragasaki46.
|
|
||||||
# See LICENSE for copying info.
|
|
||||||
|
|
||||||
from typing import Any
|
|
||||||
import markdown
|
|
||||||
import re
|
|
||||||
|
|
||||||
from markupsafe import Markup
|
|
||||||
from suou import deprecated
|
|
||||||
from suou.markdown import StrikethroughExtension, SpoilerExtension
|
|
||||||
|
|
||||||
SpoilerExtension.patch_blockquote_processor()
|
|
||||||
|
|
||||||
def error_p(text: str) -> Markup:
|
|
||||||
return Markup(f'<p class="error">{0}</p>').format(text)
|
|
||||||
|
|
||||||
def md_and_toc(text) -> tuple[Markup, Any | None]:
|
|
||||||
extensions = ['tables', 'footnotes', 'fenced_code', 'sane_lists', 'toc',
|
|
||||||
StrikethroughExtension(), SpoilerExtension()]
|
|
||||||
extension_configs = {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
converter: markdown.Markdown = markdown.Markdown(extensions=extensions, extension_configs=extension_configs)
|
|
||||||
markup = Markup(converter.convert(text))
|
|
||||||
toc = Markup(converter.toc)
|
|
||||||
return markup, toc
|
|
||||||
except Exception as e:
|
|
||||||
return error_p('Error during rendering: {0}: {1}')
|
|
||||||
|
|
||||||
@deprecated('inefficient, needs to call markdown engine just to discard any tags')
|
|
||||||
def remove_tags(text, convert=True, headings=True):
|
|
||||||
if headings:
|
|
||||||
text = re.sub(r'\#[^\n]*', '', text)
|
|
||||||
if convert:
|
|
||||||
text = md_and_toc(text)[0]
|
|
||||||
return re.sub(r'<.*?>', '', text)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
from flask import render_template, request
|
|
||||||
from suou.functools import deprecated
|
|
||||||
from ..models import db
|
|
||||||
|
|
||||||
blueprints = []
|
|
||||||
|
|
||||||
@deprecated('use db.paginate()')
|
|
||||||
def render_paginated_template(template_name, query_name, **kwargs):
|
|
||||||
query = kwargs.pop(query_name)
|
|
||||||
page = int(request.args.get('page', 1))
|
|
||||||
kwargs[query_name] = pag_query = db.paginate(query)
|
|
||||||
return render_template(
|
|
||||||
template_name,
|
|
||||||
page_n = page,
|
|
||||||
total_count = pag_query.total,
|
|
||||||
**kwargs
|
|
||||||
)
|
|
||||||
|
|
||||||
from .accounts import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .admin import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .calendar import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .edit import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .embed import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .home import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .legal import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .search import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .stats import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
from .view import bp
|
|
||||||
blueprints.append(bp)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,95 +0,0 @@
|
||||||
|
|
||||||
import datetime
|
|
||||||
from flask import Blueprint, abort, flash, redirect, render_template, request
|
|
||||||
from flask_login import current_user, login_user, logout_user
|
|
||||||
from sqlalchemy import insert, select
|
|
||||||
from sqlalchemy.exc import IntegrityError
|
|
||||||
from werkzeug.security import check_password_hash, generate_password_hash
|
|
||||||
|
|
||||||
from ..models import PageRevision, User, UserGroup, UserGroupMembership, db, is_username
|
|
||||||
|
|
||||||
bp = Blueprint('accounts', __name__)
|
|
||||||
|
|
||||||
current_user: User
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/u/<username>/')
|
|
||||||
def contributions_legacy_url(username):
|
|
||||||
return redirect(f'/@{username}/')
|
|
||||||
|
|
||||||
@bp.route('/@<username>/')
|
|
||||||
def contributions(username):
|
|
||||||
user = db.session.execute(select(User).where(User.username == username)).scalar()
|
|
||||||
if user is None:
|
|
||||||
abort(404)
|
|
||||||
|
|
||||||
contributions = db.paginate(select(PageRevision).where(PageRevision.user == user).order_by(PageRevision.pub_date.desc()))
|
|
||||||
return render_template('contributions.html',
|
|
||||||
u=user,
|
|
||||||
contributions=contributions,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/accounts/login/', methods=['GET','POST'])
|
|
||||||
def login():
|
|
||||||
if current_user.is_authenticated:
|
|
||||||
return redirect(request.args.get('next', '/'))
|
|
||||||
if request.method == 'POST':
|
|
||||||
username = request.form['username']
|
|
||||||
user = db.session.execute(select(User).where(User.username == username)).scalar()
|
|
||||||
if user is None or not check_password_hash(user.password, request.form['password']):
|
|
||||||
flash('Invalid username or password.')
|
|
||||||
return render_template('login.html')
|
|
||||||
|
|
||||||
if user.is_disabled:
|
|
||||||
flash("Your account is disabled.")
|
|
||||||
return render_template("login.html")
|
|
||||||
|
|
||||||
remember_for = 'remember' in request.form
|
|
||||||
if remember_for:
|
|
||||||
login_user(user, remember=True,
|
|
||||||
duration=datetime.timedelta(days=30))
|
|
||||||
else:
|
|
||||||
login_user(user)
|
|
||||||
return redirect(request.args.get('next', '/'))
|
|
||||||
return render_template('login.html')
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/accounts/register/', methods=['GET','POST'])
|
|
||||||
def register():
|
|
||||||
if request.method == 'POST':
|
|
||||||
username = request.form['username']
|
|
||||||
password = request.form['password']
|
|
||||||
if not is_username(username):
|
|
||||||
flash('Invalid username: usernames can contain only letters, numbers, underscores and hyphens.')
|
|
||||||
return render_template('register.html')
|
|
||||||
if request.form['password'] != request.form['confirm_password']:
|
|
||||||
flash('Passwords do not match.')
|
|
||||||
return render_template('register.html')
|
|
||||||
if not request.form['legal']:
|
|
||||||
flash('You must accept Terms in order to register.')
|
|
||||||
return render_template('register.html')
|
|
||||||
try:
|
|
||||||
with db.session.begin():
|
|
||||||
u = db.session.execute(insert(User).values(
|
|
||||||
username = username,
|
|
||||||
email = request.form.get('email'),
|
|
||||||
password = generate_password_hash(password),
|
|
||||||
join_date = datetime.datetime.now()
|
|
||||||
).returning(User)).scalar()
|
|
||||||
db.session.execute(insert(UserGroupMembership).values(
|
|
||||||
user_id = u.id,
|
|
||||||
group_id = UserGroup.get_default().id
|
|
||||||
))
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
login_user(u)
|
|
||||||
return redirect(request.args.get('next', '/'))
|
|
||||||
except IntegrityError:
|
|
||||||
flash('Username taken')
|
|
||||||
return render_template('register.html')
|
|
||||||
|
|
||||||
@bp.route('/accounts/logout/')
|
|
||||||
def accounts_logout():
|
|
||||||
logout_user()
|
|
||||||
return redirect(request.args.get('next', '/'))
|
|
||||||
|
|
@ -1,93 +0,0 @@
|
||||||
|
|
||||||
import datetime
|
|
||||||
from flask import Blueprint, flash, render_template, request
|
|
||||||
from flask_login import current_user, login_required
|
|
||||||
from sqlalchemy import Select, select
|
|
||||||
|
|
||||||
from salvi.transfer import Exporter, Importer
|
|
||||||
|
|
||||||
from ..models import Page, PageTag, User, db
|
|
||||||
|
|
||||||
current_user : User
|
|
||||||
|
|
||||||
|
|
||||||
bp = Blueprint('admin', __name__)
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/manage/')
|
|
||||||
def manage_main():
|
|
||||||
return render_template('administration.html')
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/manage/export/', methods=['GET', 'POST'])
|
|
||||||
def exportpages():
|
|
||||||
if request.method == 'POST':
|
|
||||||
raw_list = request.form['export-list']
|
|
||||||
q_list: list[Select] = []
|
|
||||||
for item in raw_list.split('\n'):
|
|
||||||
item = item.strip()
|
|
||||||
if len(item) < 2:
|
|
||||||
continue
|
|
||||||
if item.startswith('+'):
|
|
||||||
q_list.append(select(Page).where(Page.id == item[1:]))
|
|
||||||
elif item.startswith('#'):
|
|
||||||
q_list.append(select(Page).join(PageTag, PageTag.page_id == Page.id).where(PageTag.name == item[1:]))
|
|
||||||
elif item.startswith('/'):
|
|
||||||
q_list.append(select(Page).where(Page.url == item[1:].rstrip('/')))
|
|
||||||
else:
|
|
||||||
q_list.append(select(Page).where(Page.title == item))
|
|
||||||
if not q_list:
|
|
||||||
flash('Failed to export pages: The list is empty!')
|
|
||||||
return render_template('exportpages.jinja2')
|
|
||||||
q_union = q_list.pop(0)
|
|
||||||
while q_list:
|
|
||||||
q_union = q_union.union(q_list.pop(0))
|
|
||||||
e = Exporter()
|
|
||||||
e.add_page_list(db.session.execute(q_union).scalars(), include_history='history' in request.form)
|
|
||||||
return e.export(), {'Content-Type': 'application/json', 'Content-Disposition': 'attachment; ' +
|
|
||||||
'filename=export-{}.json'.format(datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))}
|
|
||||||
return render_template('exportpages.html')
|
|
||||||
|
|
||||||
@bp.route('/manage/import/', methods=['GET', 'POST'])
|
|
||||||
@login_required
|
|
||||||
def importpages():
|
|
||||||
if not current_user.is_admin:
|
|
||||||
flash('Pages can be imported by Administrators only!')
|
|
||||||
return render_template('403.html'), 403
|
|
||||||
if request.method == 'POST':
|
|
||||||
f = request.files['import']
|
|
||||||
overwrite_urls = request.form.get('ovwurls')
|
|
||||||
im = Importer(f.read(), overwrite_urls=overwrite_urls)
|
|
||||||
im.claim(current_user)
|
|
||||||
res = im.execute()
|
|
||||||
flash(f'Imported successfully {res[0]} pages and {res[1]} revisions')
|
|
||||||
|
|
||||||
return render_template('importpages.html')
|
|
||||||
|
|
||||||
@bp.route('/manage/accounts/', methods=['GET', 'POST'])
|
|
||||||
@login_required
|
|
||||||
def manage_accounts():
|
|
||||||
users_q = select(User).order_by(User.join_date.desc())
|
|
||||||
if request.method == 'POST':
|
|
||||||
if current_user.is_admin:
|
|
||||||
action = request.form.get("action")
|
|
||||||
userids = []
|
|
||||||
if action == "disable":
|
|
||||||
for key in request.form.keys():
|
|
||||||
if key.startswith("u") and key[1:].isdigit():
|
|
||||||
userids.append(int(key[1:]))
|
|
||||||
uu = 0
|
|
||||||
for uid in userids:
|
|
||||||
u = db.session.execute(select(User).where(User.id == uid)).scalar()
|
|
||||||
if u is None:
|
|
||||||
continue
|
|
||||||
u.is_disabled = not u.is_disabled
|
|
||||||
db.session.add(u)
|
|
||||||
uu += 1
|
|
||||||
db.session.commit()
|
|
||||||
flash(f"Successfully disabled {uu} users!")
|
|
||||||
else:
|
|
||||||
flash("Unknown action")
|
|
||||||
else:
|
|
||||||
flash('Operation not permitted!')
|
|
||||||
return render_template('manageaccounts.html', users=db.paginate(users_q))
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
|
|
||||||
import datetime
|
|
||||||
from flask import Blueprint, render_template, request
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from ..models import Page, db
|
|
||||||
|
|
||||||
bp = Blueprint('calendar', __name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _advance_calendar(date: datetime.date, offset=0):
|
|
||||||
if offset == -2:
|
|
||||||
return datetime.date(date.year - 1, date.month, 1)
|
|
||||||
elif offset == -1:
|
|
||||||
return datetime.date(date.year, date.month - 1, 1) if date.month > 1 else datetime.date(date.year - 1, 12, 1)
|
|
||||||
elif offset == 1:
|
|
||||||
return datetime.date(date.year, date.month + 1, 1) if date.month < 12 else datetime.date(date.year + 1, 1, 1)
|
|
||||||
elif offset == 2:
|
|
||||||
return datetime.date(date.year + 1, date.month, 1)
|
|
||||||
else:
|
|
||||||
return date
|
|
||||||
|
|
||||||
@bp.route('/calendar/')
|
|
||||||
def calendar_view():
|
|
||||||
now = datetime.datetime.now()
|
|
||||||
return render_template('calendar.html', now=now,
|
|
||||||
from_year=int(request.args.get('from_year', now.year - 12)),
|
|
||||||
till_year=int(request.args.get('till_year', now.year + 5))
|
|
||||||
)
|
|
||||||
|
|
||||||
@bp.route('/calendar/<int:y>/<int:m>')
|
|
||||||
def calendar_month(y: int, m: int):
|
|
||||||
notes = db.paginate(select(Page).where(
|
|
||||||
(datetime.date(y, m, 1) <= Page.calendar),
|
|
||||||
(Page.calendar < datetime.date(y+1 if m==12 else y, 1 if m==12 else m+1, 1))
|
|
||||||
).order_by(Page.calendar)).scalars()
|
|
||||||
|
|
||||||
#toc_q = Page.select(fn.Month(Page.calendar).alias('month'), fn.Count(Page.id).alias('n_notes')).where(
|
|
||||||
# (datetime.date(y, 1, 1) <= Page.calendar) &
|
|
||||||
# (Page.calendar < datetime.date(y+1, 1, 1))
|
|
||||||
#).group_by()
|
|
||||||
toc = {}
|
|
||||||
#for i in toc_q:
|
|
||||||
# toc[i.month] = i.n_notes
|
|
||||||
|
|
||||||
return render_template('month.html', d=datetime.date(y, m, 1), notes=notes, advance_calendar=_advance_calendar, toc=toc)
|
|
||||||
|
|
||||||
|
|
@ -1,203 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
from typing import Mapping
|
|
||||||
from flask import Blueprint, abort, flash, g, jsonify, redirect, render_template, request
|
|
||||||
from flask_login import current_user, login_required
|
|
||||||
from sqlalchemy import select, insert
|
|
||||||
from suou import want_isodate
|
|
||||||
|
|
||||||
from salvi.i18n import get_string
|
|
||||||
|
|
||||||
from ..utils import parse_tag_list
|
|
||||||
from ..renderer import md_and_toc
|
|
||||||
|
|
||||||
from ..models import PERM_CREATE, PERM_EDIT, Page, PageLink, PageRevision, PageText, User, db, is_url_available, is_valid_url, perms_required
|
|
||||||
|
|
||||||
current_user: User
|
|
||||||
|
|
||||||
bp = Blueprint('edit', __name__)
|
|
||||||
|
|
||||||
def savepoint(form: Mapping, is_preview: bool = False, pageobj: Page | None = None):
|
|
||||||
'''Middle point during page editing.'''
|
|
||||||
|
|
||||||
if is_preview:
|
|
||||||
preview = md_and_toc(form['text'])[0]
|
|
||||||
else:
|
|
||||||
preview = None
|
|
||||||
pl_js_info = dict()
|
|
||||||
pl_js_info['editing'] = dict(
|
|
||||||
original_text = pageobj.current_text() if pageobj else None,
|
|
||||||
preview_text = form['text'],
|
|
||||||
page_id = pageobj.id if pageobj else None
|
|
||||||
)
|
|
||||||
return render_template(
|
|
||||||
'edit.html',
|
|
||||||
pl_url=form['url'],
|
|
||||||
pl_title=form['title'],
|
|
||||||
pl_text=form['text'],
|
|
||||||
pl_tags=form['tags'],
|
|
||||||
pl_comment=form['comment'],
|
|
||||||
pl_is_locked='lockpage' in form,
|
|
||||||
pl_owner_is_current_user=current_user.owns(pageobj) if pageobj else True,
|
|
||||||
preview=preview,
|
|
||||||
pl_js_info=pl_js_info,
|
|
||||||
pl_calendar=('usecalendar' in form) and form['calendar'],
|
|
||||||
pl_readonly=not pageobj.is_editable_by(current_user) if pageobj else False,
|
|
||||||
pl_cw=('cw' in form) and form['cw']
|
|
||||||
)
|
|
||||||
|
|
||||||
@bp.route('/create/', methods=['GET', 'POST'])
|
|
||||||
@perms_required(PERM_CREATE, message='You are not authorized to create pages.')
|
|
||||||
def create():
|
|
||||||
if request.method == 'POST':
|
|
||||||
if request.form.get('preview'):
|
|
||||||
return savepoint(request.form, is_preview=True)
|
|
||||||
p_url = request.form['url'] or None
|
|
||||||
p_title = request.form['title']
|
|
||||||
if p_url:
|
|
||||||
if not is_valid_url(p_url):
|
|
||||||
flash('Invalid URL. Valid URLs contain only letters, numbers and hyphens.')
|
|
||||||
return savepoint(request.form)
|
|
||||||
elif not is_url_available(p_url):
|
|
||||||
flash('This URL is not available.')
|
|
||||||
return savepoint(request.form)
|
|
||||||
|
|
||||||
try:
|
|
||||||
p_tags = parse_tag_list(request.form.get('tags', ''))
|
|
||||||
except ValueError:
|
|
||||||
flash('Invalid tags text. Tags contain only letters, numbers and hyphens, and are separated by comma.')
|
|
||||||
return savepoint(request.form)
|
|
||||||
|
|
||||||
p_calendar = datetime.date.fromisoformat(request.form["calendar"]) if 'usecalendar' in request.form else None
|
|
||||||
|
|
||||||
try:
|
|
||||||
p = db.session.execute(insert(Page).values(
|
|
||||||
url = p_url,
|
|
||||||
title = p_title,
|
|
||||||
is_redirect = False,
|
|
||||||
touched = datetime.datetime.now(),
|
|
||||||
owner_id = current_user.id,
|
|
||||||
calendar = p_calendar,
|
|
||||||
is_locked = 'lockpage' in request.form,
|
|
||||||
is_cw = 'cw' in request.form
|
|
||||||
).returning(Page)).scalar()
|
|
||||||
|
|
||||||
p.change_tags(p_tags)
|
|
||||||
|
|
||||||
pt = PageText.create_content(request.form['text'])
|
|
||||||
|
|
||||||
db.session.execute(insert(PageRevision).values(
|
|
||||||
page_id = p.id,
|
|
||||||
user_id = p.owner_id,
|
|
||||||
comment = request.form.get('comment', ''),
|
|
||||||
textref_id = pt.id,
|
|
||||||
pub_date = datetime.datetime.now(),
|
|
||||||
length = len(request.form['text'])
|
|
||||||
))
|
|
||||||
|
|
||||||
PageLink.parse_links(p, request.form['text'])
|
|
||||||
|
|
||||||
db.session.commit()
|
|
||||||
except Exception as e:
|
|
||||||
flash(f'An error occurred while saving this revision. Please be patient.')
|
|
||||||
sys.excepthook(*sys.exc_info())
|
|
||||||
return savepoint(request.form)
|
|
||||||
|
|
||||||
return redirect(p.get_url())
|
|
||||||
return savepoint(dict(url=request.args.get('url'), title='', text='', tags='', comment=get_string(g.lang, 'page_created')))
|
|
||||||
|
|
||||||
@bp.route('/edit/<int:id>', methods=['GET', 'POST'])
|
|
||||||
@perms_required(PERM_EDIT, message='You are not authorized to edit pages.')
|
|
||||||
def edit(id: int):
|
|
||||||
p = db.session.execute(select(Page).where(Page.id == id)).scalar()
|
|
||||||
if p is None:
|
|
||||||
abort(404)
|
|
||||||
|
|
||||||
p_latest = p.latest()
|
|
||||||
|
|
||||||
if request.method == 'POST':
|
|
||||||
if not p.can_edit(current_user):
|
|
||||||
flash('You are trying to edit a locked page!')
|
|
||||||
abort(403)
|
|
||||||
if request.form.get('preview'):
|
|
||||||
return savepoint(request.form, is_preview=True, pageobj=p)
|
|
||||||
p_url = request.form['url'] or None
|
|
||||||
if p_url:
|
|
||||||
if not is_valid_url(p_url):
|
|
||||||
flash('Invalid URL. Valid URLs contain only letters, numbers and hyphens.')
|
|
||||||
return savepoint(request.form, pageobj=p)
|
|
||||||
elif not is_url_available(p_url) and p_url != p.url:
|
|
||||||
flash('This URL is not available.')
|
|
||||||
return savepoint(request.form, pageobj=p)
|
|
||||||
p_tags = [x.strip().lower().replace(' ', '-').replace('_', '-').lstrip('#')
|
|
||||||
for x in request.form.get('tags', '').split(',')]
|
|
||||||
p_tags = [x for x in p_tags if x]
|
|
||||||
if any(not re.fullmatch(SLUG_RE, x) for x in p_tags):
|
|
||||||
flash('Invalid tags text. Tags contain only letters, numbers and hyphens, and are separated by comma.')
|
|
||||||
return savepoint(request.form, pageobj=p)
|
|
||||||
p.url = p_url
|
|
||||||
p.title = request.form['title']
|
|
||||||
p.touched = datetime.datetime.now()
|
|
||||||
p.is_locked = 'lockpage' in request.form
|
|
||||||
p.is_cw = 'cw' in request.form
|
|
||||||
p.calendar = datetime.date.fromisoformat(request.form["calendar"]) if 'usecalendar' in request.form else None
|
|
||||||
p.change_tags(p_tags)
|
|
||||||
if request.form['text'] != p_latest.text():
|
|
||||||
pt = PageText.create_content(request.form['text'])
|
|
||||||
|
|
||||||
db.session.execute(insert(PageRevision).values(
|
|
||||||
page_id=p.id,
|
|
||||||
user_id=current_user.id,
|
|
||||||
comment=request.form["comment"],
|
|
||||||
textref_id=pt.id,
|
|
||||||
pub_date=datetime.datetime.now(),
|
|
||||||
length=len(request.form['text'])
|
|
||||||
))
|
|
||||||
db.session.add(p)
|
|
||||||
db.session.commit()
|
|
||||||
return redirect(p.get_url())
|
|
||||||
|
|
||||||
form = dict(
|
|
||||||
url=p.url,
|
|
||||||
title=p.title,
|
|
||||||
text=p_latest.text(),
|
|
||||||
tags=','.join(x.name for x in p.tags),
|
|
||||||
comment=''
|
|
||||||
)
|
|
||||||
if p.is_locked:
|
|
||||||
form['lockpage'] = '1'
|
|
||||||
if p.calendar:
|
|
||||||
form['usecalendar'] = '1'
|
|
||||||
form['calendar'] = want_isodate(p.calendar).split('T')[0]
|
|
||||||
return savepoint(form, pageobj=p)
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/_jsoninfo/<int:id>', methods=['GET', 'POST'])
|
|
||||||
@bp.route('/p/<int:id>.json', methods=['GET'])
|
|
||||||
def page_jsoninfo(id):
|
|
||||||
p = db.session.execute(select(Page).where(Page.id == id)).scalar()
|
|
||||||
if p is None:
|
|
||||||
return jsonify({'status':'fail'}), 404
|
|
||||||
j = p.js_info()
|
|
||||||
j["status"] = "ok"
|
|
||||||
if request.method == "POST":
|
|
||||||
j["text"] = p.latest().text()
|
|
||||||
return jsonify(j)
|
|
||||||
|
|
||||||
@bp.route("/_jsoninfo/changed/<float:ts>")
|
|
||||||
def jsoninfo_changed(ts):
|
|
||||||
tse = str(datetime.datetime.fromtimestamp(ts).isoformat(" "))
|
|
||||||
ps = db.session.execute(select(Page).where(Page.touched >= tse)).scalars()
|
|
||||||
return jsonify({
|
|
||||||
"ids": [i.id for i in ps],
|
|
||||||
"status": "ok"
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import html
|
|
||||||
from sqlalchemy import select
|
|
||||||
from flask import Blueprint, abort
|
|
||||||
|
|
||||||
from salvi.models import Page, db
|
|
||||||
|
|
||||||
bp = Blueprint('embed', __name__)
|
|
||||||
|
|
||||||
## embed HTML is pending deprecation. Working on API.
|
|
||||||
|
|
||||||
@bp.route('/embed/<int:id>/')
|
|
||||||
def embed_view(id):
|
|
||||||
p = db.session.execute(select(Page).where(Page.id == id)).scalar()
|
|
||||||
if p is None:
|
|
||||||
return '', 404
|
|
||||||
rev = p.latest()
|
|
||||||
return "<h1>{0}</h1><div class=\"inner-content\">{1}</div>".format(
|
|
||||||
html.escape(p.title), rev.html())
|
|
||||||
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
|
|
||||||
from flask import Blueprint, abort, flash, redirect, render_template
|
|
||||||
from sqlalchemy import select, func
|
|
||||||
|
|
||||||
from ..models import Page, PageTag, db
|
|
||||||
from .. import app_config
|
|
||||||
|
|
||||||
bp = Blueprint('home', __name__)
|
|
||||||
|
|
||||||
@bp.route('/')
|
|
||||||
def homepage():
|
|
||||||
page_limit = app_config.default_items_per_page
|
|
||||||
new_notes = db.paginate(select(Page).order_by(Page.touched.desc()).limit(page_limit))
|
|
||||||
return render_template('home.html',
|
|
||||||
new_notes = new_notes)
|
|
||||||
|
|
||||||
@bp.route('/p/most_recent/')
|
|
||||||
def view_most_recent():
|
|
||||||
general_query = db.paginate(select(Page).order_by(Page.touched.desc()))
|
|
||||||
return render_template('listrecent.html', notes=general_query)
|
|
||||||
|
|
||||||
@bp.route('/p/random/')
|
|
||||||
def view_random():
|
|
||||||
page = None
|
|
||||||
page_count = db.session.execute(select(func.count()).select_from(Page)).scalar()
|
|
||||||
if page_count < 4:
|
|
||||||
flash('Too few pages in this site.')
|
|
||||||
abort(404)
|
|
||||||
while not page:
|
|
||||||
page = db.session.execute(select(Page).order_by(func.random())).scalar()
|
|
||||||
return redirect(page.get_url())
|
|
||||||
|
|
||||||
@bp.route('/p/leaderboard/')
|
|
||||||
def page_leaderboard():
|
|
||||||
headers = {
|
|
||||||
'Cache-Control': 'max-age=180, stale-while-revalidate=1800'
|
|
||||||
}
|
|
||||||
|
|
||||||
pages = []
|
|
||||||
## TODO make it a query
|
|
||||||
pages_q = db.session.execute(select(Page)).scalars()
|
|
||||||
for p in pages_q:
|
|
||||||
p_latest = p.latest()
|
|
||||||
score = (p_latest.length >> 10) + len(p.forward_links) + len(p.back_links)
|
|
||||||
## TODO make it a namedtuple
|
|
||||||
pages.append((p, score, len(p.back_links.count), len(p.forward_links), p_latest.length))
|
|
||||||
pages.sort(key = lambda x: (x[1], x[2], x[4], x[3]), reverse = True)
|
|
||||||
|
|
||||||
return render_template('leaderboard.html', pages=pages), headers
|
|
||||||
|
|
||||||
@bp.route('/tags/<slug:tag>/')
|
|
||||||
def listtag(tag):
|
|
||||||
general_query = select(Page).join(PageTag, PageTag.page_id == Page.id).where(PageTag.name == tag).order_by(Page.touched.desc())
|
|
||||||
return render_template('listtag.html', tagname=tag, tagged_notes=db.paginate(general_query))
|
|
||||||
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
|
|
||||||
from flask import Blueprint, render_template
|
|
||||||
|
|
||||||
bp = Blueprint('legal', __name__)
|
|
||||||
|
|
||||||
@bp.route('/terms/')
|
|
||||||
def terms():
|
|
||||||
return render_template('terms.html')
|
|
||||||
|
|
||||||
@bp.route('/privacy/')
|
|
||||||
def privacy():
|
|
||||||
return render_template('privacy.html')
|
|
||||||
|
|
||||||
@bp.route('/rules/')
|
|
||||||
def rules():
|
|
||||||
return render_template('rules.html')
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
|
|
||||||
from flask import Blueprint, render_template, request
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from ..models import Page, PageTag, db
|
|
||||||
|
|
||||||
bp = Blueprint('search', __name__)
|
|
||||||
|
|
||||||
@bp.route('/search/', methods=['GET', 'POST'])
|
|
||||||
def search():
|
|
||||||
if request.method == 'POST':
|
|
||||||
q = request.form['q']
|
|
||||||
include_tags = bool(request.form.get('include-tags'))
|
|
||||||
query = select(Page).where(Page.title.ilike('%' + q + '%'))
|
|
||||||
if include_tags:
|
|
||||||
query = query.union(select(Page).join(PageTag, PageTag.page_id == Page.id
|
|
||||||
).where(PageTag.name.ilike('%' + q + '%')))
|
|
||||||
query = query.order_by(Page.touched.desc())
|
|
||||||
return render_template('search.html', q=q, pl_include_tags=include_tags,
|
|
||||||
results=db.paginate(query))
|
|
||||||
return render_template('search.html', pl_include_tags=True)
|
|
||||||
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
from flask import Blueprint, abort, redirect, render_template, request
|
|
||||||
from sqlalchemy import func, select
|
|
||||||
|
|
||||||
from ..models import Page, PageRevision, User, UserGroup, db
|
|
||||||
|
|
||||||
bp = Blueprint('stats', __name__)
|
|
||||||
|
|
||||||
@bp.route('/backlinks/<int:id>/')
|
|
||||||
def backlinks(id):
|
|
||||||
p = db.session.execute(select(Page).where(Page.id == id)).scalar()
|
|
||||||
if p is None:
|
|
||||||
abort(404)
|
|
||||||
return render_template('backlinks.html', p=p, backlinks=p.back_links)
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/stats/')
|
|
||||||
def stats():
|
|
||||||
return render_template('stats.html',
|
|
||||||
notes_count = db.session.execute(select(func.count()).select_from(Page)).scalar(),
|
|
||||||
notes_with_url = db.session.execute(select(func.count()).select_from(Page).where(Page.url != None)).scalar(),
|
|
||||||
revision_count = db.session.execute(select(func.count()).select_from(PageRevision)).scalar(),
|
|
||||||
users_count = db.session.execute(select(func.count()).select_from(User)).scalar(),
|
|
||||||
groups_count = db.session.execute(select(func.count()).select_from(UserGroup)).scalar()
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
## easter egg (lol) ##
|
|
||||||
|
|
||||||
MNeaster = {
|
|
||||||
15: (22, 2), 16: (22, 2), 17: (23, 3), 18: (23, 4), 19: (24, 5), 20: (24, 5),
|
|
||||||
21: (24, 6), 22: (25, 0), 23: (26, 1), 24: (25, 1)}
|
|
||||||
|
|
||||||
def calculate_easter(y):
|
|
||||||
a, b, c = y % 19, y % 4, y % 7
|
|
||||||
M, N = (15, 6) if y < 1583 else MNeaster[y // 100]
|
|
||||||
d = (19 * a + M) % 30
|
|
||||||
e = (2 * b + 4 * c + 6 * d + N) % 7
|
|
||||||
if d + e < 10:
|
|
||||||
return datetime.date(y, 3, d + e + 22)
|
|
||||||
else:
|
|
||||||
day = d + e - 9
|
|
||||||
if day == 26:
|
|
||||||
day = 19
|
|
||||||
elif day == 25 and d == 28 and e == 6 and a > 10:
|
|
||||||
day = 18
|
|
||||||
return datetime.date(y, 4, day)
|
|
||||||
|
|
||||||
def stash_easter(y):
|
|
||||||
easter = calculate_easter(y)
|
|
||||||
natale = datetime.date(y, 12, 25)
|
|
||||||
avvento1 = natale - datetime.timedelta(days=22 + natale.weekday())
|
|
||||||
return dict(
|
|
||||||
easter = easter,
|
|
||||||
ceneri = easter - datetime.timedelta(days=47),
|
|
||||||
ascensione = easter + datetime.timedelta(days=42),
|
|
||||||
pentecoste = easter + datetime.timedelta(days=49),
|
|
||||||
avvento1 = avvento1
|
|
||||||
)
|
|
||||||
|
|
||||||
@bp.route('/easter/')
|
|
||||||
@bp.route('/easter/<int:y>/')
|
|
||||||
def easter_y(y=None):
|
|
||||||
if not y and 'y' in request.args:
|
|
||||||
return redirect('/easter/' + request.args['y'] + '/')
|
|
||||||
if y:
|
|
||||||
if y > 2499:
|
|
||||||
flash('Years above 2500 A.D. are currently not supported.')
|
|
||||||
return render_template('easter.jinja2')
|
|
||||||
return render_template('easter.html', y=y, easter_dates=stash_easter(y))
|
|
||||||
else:
|
|
||||||
return render_template('easter.html')
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
from flask import Blueprint, abort, redirect, render_template
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from salvi.constants import FORBIDDEN_URLS
|
|
||||||
from salvi.models import Page, PageRevision, db
|
|
||||||
|
|
||||||
|
|
||||||
bp = Blueprint('view', __name__)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/p/<int:id>/')
|
|
||||||
def view_unnamed(id):
|
|
||||||
p = db.session.execute(select(Page).where(Page.id == id)).scalar()
|
|
||||||
if p is None:
|
|
||||||
abort(404)
|
|
||||||
if p.url and p.url not in FORBIDDEN_URLS:
|
|
||||||
return redirect(p.get_url())
|
|
||||||
return render_template('view.html', p=p, rev=p.latest())
|
|
||||||
|
|
||||||
|
|
||||||
# for some reason, this must be the LAST view defined lol
|
|
||||||
@bp.route('/<slug:name>/')
|
|
||||||
def view_named(name):
|
|
||||||
p = db.session.execute(select(Page).where(Page.url == name)).scalar()
|
|
||||||
if p is None:
|
|
||||||
abort(404)
|
|
||||||
return render_template('view.html', p=p, rev=p.latest())
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/history/<int:id>/')
|
|
||||||
def history(id):
|
|
||||||
p = db.session.execute(select(Page).where(Page.id == id)).scalar()
|
|
||||||
if p is None:
|
|
||||||
abort(404)
|
|
||||||
revisions = db.session.execute(select(PageRevision).where(PageRevision.page_id == p.id).order_by(PageRevision.pub_date.desc())).scalars()
|
|
||||||
return render_template('history.html', p=p, history=revisions)
|
|
||||||
|
|
||||||
@bp.route('/history/revision/<int:revisionid>/')
|
|
||||||
def view_old(revisionid: int):
|
|
||||||
rev = db.session.execute(select(PageRevision).where(PageRevision.id == revisionid)).scalar()
|
|
||||||
if rev is None:
|
|
||||||
abort(404)
|
|
||||||
p = rev.page
|
|
||||||
return render_template('viewold.html', p=p, rev=rev)
|
|
||||||
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
(function() {
|
|
||||||
|
|
||||||
for (let i of document.getElementsByClassName('spoiler')) {
|
|
||||||
i.onclick = function() {
|
|
||||||
this.classList.toggle('revealed');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
})();
|
|
||||||
|
|
@ -1,241 +0,0 @@
|
||||||
/* Style for Salvi */
|
|
||||||
/* (c) 2020-2025 Sakuragasaki46 */
|
|
||||||
/* TODO rewrite to Sass in 1.1 */
|
|
||||||
|
|
||||||
/* variables */
|
|
||||||
:root {
|
|
||||||
--bg-main-light: #faf5e9;
|
|
||||||
--fg-main-light: #1f2528;
|
|
||||||
--bg-sharp-light: white;
|
|
||||||
--fg-sharp-light: black;
|
|
||||||
--fg-alt-light: #363636;
|
|
||||||
--bg-alt-light: #f9f9f9;
|
|
||||||
--bg-flash-light: #fff2b4;
|
|
||||||
--border-light: #ccc;
|
|
||||||
--border-flash-light: #ffe660;
|
|
||||||
--fg-error-light: #99081f;
|
|
||||||
--btn-error-light: #ff1800;
|
|
||||||
--btn-success-light: #37b92e;
|
|
||||||
--bg-header-light: #2754c0;
|
|
||||||
|
|
||||||
--bg-main-dark: #1f1f1f;
|
|
||||||
--fg-main-dark: #e5e5e5;
|
|
||||||
--bg-sharp-dark: black;
|
|
||||||
--fg-sharp-dark: white;
|
|
||||||
--fg-alt-dark: #cecece;
|
|
||||||
--bg-alt-dark: #333;
|
|
||||||
--bg-flash-dark: #771;
|
|
||||||
--border-dark: #555;
|
|
||||||
--border-flash-dark: #fd2;
|
|
||||||
--fg-error-dark: #ff4860;
|
|
||||||
--btn-error-dark: #e01400;
|
|
||||||
--btn-success-dark: #5d3;
|
|
||||||
--bg-header-dark: #183690;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* accent colors are defined by style tags */
|
|
||||||
|
|
||||||
/*@media (prefers-color-scheme:light) {*/
|
|
||||||
:root, .color-scheme-light {
|
|
||||||
--bg-main: var(--bg-main-light);
|
|
||||||
--fg-main: var(--fg-main-light);
|
|
||||||
--bg-sharp: var(--bg-sharp-light);
|
|
||||||
--fg-sharp: var(--fg-sharp-light);
|
|
||||||
--fg-alt: var(--fg-alt-light);
|
|
||||||
--bg-alt: var(--bg-alt-light);
|
|
||||||
--bg-flash: var(--bg-flash-light);
|
|
||||||
--border: var(--border-light);
|
|
||||||
--border-sharp: var(--border-sharp-light);
|
|
||||||
--border-flash: var(--border-flash-light);
|
|
||||||
--fg-error: var(--fg-error-light);
|
|
||||||
--btn-error: var(--btn-error-light);
|
|
||||||
--btn-success: var(--btn-success-light);
|
|
||||||
--fg-link: var(--fg-link-light);
|
|
||||||
--fg-link-visited: var(--fg-link-visited-light);
|
|
||||||
--fg-link-hover: var(--fg-link-hover-light);
|
|
||||||
--bg-link: var(--bg-link-light);
|
|
||||||
--bg-header: var(--bg-header-light);
|
|
||||||
}
|
|
||||||
/*}*/
|
|
||||||
|
|
||||||
@media (prefers-color-scheme:dark) {
|
|
||||||
:root {
|
|
||||||
--bg-main: var(--bg-main-dark);
|
|
||||||
--fg-main: var(--fg-main-dark);
|
|
||||||
--bg-sharp: var(--bg-sharp-dark);
|
|
||||||
--fg-sharp: var(--fg-sharp-dark);
|
|
||||||
--fg-alt: var(--fg-alt-dark);
|
|
||||||
--bg-alt: var(--bg-alt-dark);
|
|
||||||
--bg-flash: var(--bg-flash-dark);
|
|
||||||
--border: var(--border-dark);
|
|
||||||
--border-sharp: var(--border-sharp-dark);
|
|
||||||
--border-flash: var(--border-flash-dark);
|
|
||||||
--fg-error: var(--fg-error-dark);
|
|
||||||
--btn-error: var(--btn-error-dark);
|
|
||||||
--btn-success: var(--btn-success-dark);
|
|
||||||
--fg-link: var(--fg-link-dark);
|
|
||||||
--fg-link-visited: var(--fg-link-visited-dark);
|
|
||||||
--fg-link-hover: var(--fg-link-hover-dark);
|
|
||||||
--bg-link: var(--bg-link-dark);
|
|
||||||
--bg-header: var(--bg-header-dark);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.color-scheme-dark {
|
|
||||||
--bg-main: var(--bg-main-dark);
|
|
||||||
--fg-main: var(--fg-main-dark);
|
|
||||||
--bg-sharp: var(--bg-sharp-dark);
|
|
||||||
--fg-sharp: var(--fg-sharp-dark);
|
|
||||||
--fg-alt: var(--fg-alt-dark);
|
|
||||||
--bg-alt: var(--bg-alt-dark);
|
|
||||||
--bg-flash: var(--bg-flash-dark);
|
|
||||||
--border: var(--border-dark);
|
|
||||||
--border-sharp: var(--border-sharp-dark);
|
|
||||||
--border-flash: var(--border-flash-dark);
|
|
||||||
--fg-error: var(--fg-error-dark);
|
|
||||||
--btn-error: var(--btn-error-dark);
|
|
||||||
--btn-success: var(--btn-success-dark);
|
|
||||||
--fg-link: var(--fg-link-dark);
|
|
||||||
--fg-link-visited: var(--fg-link-visited-dark);
|
|
||||||
--fg-link-hover: var(--fg-link-hover-dark);
|
|
||||||
--bg-link: var(--bg-link-dark);
|
|
||||||
--bg-header: var(--bg-header-dark);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* basic styles */
|
|
||||||
* {box-sizing: border-box;}
|
|
||||||
body{font-family:sans-serif;background-color:var(--bg-main); color: var(--fg-main);margin:0;position:relative}
|
|
||||||
.site-content{margin: 3em 1.3em; position: relative}
|
|
||||||
.site-footer{text-align:center;}
|
|
||||||
|
|
||||||
/* header styles */
|
|
||||||
.site-header{padding:1em;display:flex;flex-direction:row;justify-content:space-between;position:sticky;top:0;background-color:var(--bg-alt); z-index: 99}
|
|
||||||
.site-name{font-size: 1.5em; font-weight: bold}
|
|
||||||
.site-header .site-header-blank {flex: 1; margin: 0 .5em}
|
|
||||||
.site-header ul{list-style:none;padding:0;margin:0;font-size:0.9em;border-left:var(--border) 1px solid}
|
|
||||||
.site-header ul > li{display:inline-block;padding-right:1em}
|
|
||||||
|
|
||||||
/* content styles */
|
|
||||||
.article-header {text-align: center;}
|
|
||||||
#firstHeading {font-family:sans-serif; text-align: center;font-size:3em; font-weight: normal}
|
|
||||||
@media (min-width:800px) {.homepage #firstHeading {font-size: 4.5em}}
|
|
||||||
.inner-content, .article-content {margin: 1.7em auto; max-width: 1280px;}
|
|
||||||
.article-content{font-family:serif; margin: 1.7em auto; max-width: 1280px; line-height: 1.9; color: var(--fg-main)}
|
|
||||||
.article-content em,.article-content strong{color: var(--fg-sharp)}
|
|
||||||
.article-content h1{color: var(--fg-error)}
|
|
||||||
.article-content table {font-family: sans-serif}
|
|
||||||
.article-content h2, .article-content h3, .article-content h4, .article-content h5, .article-content h6{font-family:sans-serif; color: var(--fg-sharp); font-weight: normal}
|
|
||||||
.article-content h2{border-bottom: 1px solid var(--border)}
|
|
||||||
.article-content h3{margin:0.8em 0}
|
|
||||||
.article-content h4{margin:0.6em 0}
|
|
||||||
.article-content h5{margin:0.5em 0}
|
|
||||||
.article-content h6{margin:0.4em 0}
|
|
||||||
.article-content p{text-indent: 1.9em; margin: 0}
|
|
||||||
.article-content li{margin: .3em 0}
|
|
||||||
.article-content blockquote{color:var(--fg-alt); border-left: 4px solid var(--bg-alt);margin-left:0;padding-left:12px}
|
|
||||||
.article-content table{border:var(--bg-alt) 1px solid;border-collapse:collapse;line-height: 1.5;overflow-x:auto}
|
|
||||||
.article-content table > * > tr > th, .article-content table > tr > th {background-color:var(--bg-alt);border:var(--border) 1px solid;padding:2px}
|
|
||||||
.article-content table > * > tr > td, .article-content table > tr > td {border:var(--border) 1px solid;padding:2px}
|
|
||||||
|
|
||||||
/* spoiler styles */
|
|
||||||
.spoiler {color: var(--fg-sharp); background-color: var(--fg-sharp)}
|
|
||||||
.spoiler.revealed {color: inherit; background-color: transparent}
|
|
||||||
|
|
||||||
/* interface styles */
|
|
||||||
.nl-list{list-style:none}
|
|
||||||
.nl-list > li{margin-bottom: 1em}
|
|
||||||
.nl-title{font-size:1.2em; font-weight: 500}
|
|
||||||
.nl-desc{font-size:0.9em;opacity:.75;font-family:serif}
|
|
||||||
.nl-new{margin:6px 0 12px 0;display:flex;justify-content:start; float: right}
|
|
||||||
.nl-new > a{margin-right:12px}
|
|
||||||
.nl-prev,.nl-next{text-align:center}
|
|
||||||
.nl-placeholder {font-style: italic; text-align: center;}
|
|
||||||
.nl-pagination {text-align: center; color: var(--fg-alt)}
|
|
||||||
.nl-item {padding: 12px; border: 1px solid gray; border-radius: 12px; box-shadow: 2px 2px 2px gray; background-color: var(--bg-alt);}
|
|
||||||
input{border:0;border-bottom:3px solid var(--border);font:inherit;color:var(--fg-main);background-color:transparent}
|
|
||||||
input:focus{color:var(--fg-sharp);border-bottom-color:var(--border-sharp)}
|
|
||||||
input.error{border-bottom-color:var(--btn-error)}
|
|
||||||
input[type="submit"],input[type="reset"],input[type="button"],button{font-family:inherit;border-radius:12px;border:1px solid var(--border);display:inline-block}
|
|
||||||
.submit-primary{color:var(--bg-main);background-color:var(--fg-link);font-family:inherit;border:1px solid var(--fg-link);font-size:1.2em;height:2em;min-width:8em}
|
|
||||||
.submit-secondary{color:var(--fg-main);background-color:var(--bg-main);font-family:inherit;border:1px solid var(--fg-link);font-size:1.2em;height:2em;min-width:8em}
|
|
||||||
.submit-quick{color:var(--bg-main);background-color:var(--fg-link);font-family:inherit;border:1px solid var(--fg-link);font-size:inherit;border-radius:6px}
|
|
||||||
.flash{background-color:var(--bg-flash);padding:12px;border-radius:4px;border:1px var(--border-flash) solid}
|
|
||||||
.page-tags p{display:inline-block}
|
|
||||||
.page-tags ul{padding:0;margin:0;list-style:none;display:inline-block}
|
|
||||||
.page-tags ul > li{padding:6px 12px;display:inline-block;margin:0 4px;border-radius:4px;background-color:var(--bg-link)}
|
|
||||||
.page-tags .tag-count{color: var(--btn-success);font-size:smaller;font-weight:600}
|
|
||||||
.search-wrapper {display:flex;width:90%;margin:auto}
|
|
||||||
.search-wrapper > input {flex:1}
|
|
||||||
.calendar-subtitle {text-align: center; margin-top: -1em}
|
|
||||||
.preview-subtitle {text-align: center; margin-top: -1em}
|
|
||||||
textarea {background-color: var(--bg-sharp); color: var(--fg-sharp)}
|
|
||||||
ul.inline {margin:0; padding:0; display: inline}
|
|
||||||
ul.inline > li {display: inline-block;}
|
|
||||||
ul.inline > li::after {content: "·"}
|
|
||||||
ul.inline > li:last-child::after {content: ""}
|
|
||||||
.wrap_responsive_cells {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
|
||||||
/* This is better for small screens, once min() is better supported */
|
|
||||||
/* grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr)); */
|
|
||||||
gap: 1rem;
|
|
||||||
}
|
|
||||||
.wrap_responsive_cells_narrow {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
|
||||||
/* This is better for small screens, once min() is better supported */
|
|
||||||
/* grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr)); */
|
|
||||||
gap: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* floating elements */
|
|
||||||
nav.toc{display:none}
|
|
||||||
@media only screen and (min-width:960px){
|
|
||||||
nav.toc{display:block;position:absolute; top: 0; right: 0; width: 240px;}
|
|
||||||
.inner-content {margin-right: 240px;}
|
|
||||||
}
|
|
||||||
@media only screen and (min-width:1200px){
|
|
||||||
.inner-content {margin-left: 240px}
|
|
||||||
}
|
|
||||||
.backontop{position:fixed;bottom:0;right:0}
|
|
||||||
@media print{
|
|
||||||
.backontop {display:none}
|
|
||||||
.site-header{position:static}
|
|
||||||
}
|
|
||||||
#__top{position:absolute;top:0;left:0}
|
|
||||||
|
|
||||||
/* editor */
|
|
||||||
input.title-input{overflow:visible;font-weight:bold;font-size:2em;width:100%;margin-top:1em}
|
|
||||||
.text-input{font:inherit;border-top:0;border-bottom:4px solid #80e;border-left:0;border-right:0;margin-bottom:12px;width:100%;height:20em}
|
|
||||||
.over-text-input{color:white;background-color:#80e;margin-top:12px;padding:4px}
|
|
||||||
.over-text-input select{padding: 0;border: 0;margin: 0;background: inherit;color: inherit;font: inherit;}
|
|
||||||
.text-input.ti-font-sans{font-family: sans-serif}
|
|
||||||
.text-input.ti-font-serif{font-family: serif}
|
|
||||||
.text-input.ti-font-monospace{font-family:monospace}
|
|
||||||
|
|
||||||
/* images */
|
|
||||||
.fig-right{float:right;clear:right}
|
|
||||||
.fig-gallery{display:inline-block}
|
|
||||||
.fig-right img, .fig-gallery img{width:220px}
|
|
||||||
|
|
||||||
/* links */
|
|
||||||
a:link{color:var(--fg-link)}
|
|
||||||
a:visited{color:var(--fg-link-visited)}
|
|
||||||
a:hover{color:var(--fg-link-hover)}
|
|
||||||
|
|
||||||
/* grids */
|
|
||||||
@media (min-width:800px) {
|
|
||||||
.nl-list {display: grid; grid-template-rows: auto; grid-template-columns: 1fr 1fr; column-gap: 1.5em}
|
|
||||||
.nl-list > .nl-prev, .nl-list > .nl-next {grid-column-end: span 2}
|
|
||||||
}
|
|
||||||
@media (min-width:1200px){
|
|
||||||
.nl-list {grid-template-columns: 1fr 1fr 1fr}
|
|
||||||
.nl-list > .nl-prev, .nl-list > .nl-next {grid-column-end: span 3}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* dark theme extra */
|
|
||||||
.color-scheme-dark .text-input{border-bottom-color: #60a}
|
|
||||||
.color-scheme-dark .over-text-input{background-color: #60a}
|
|
||||||
|
|
||||||
.color-scheme-light .dark-theme-toggle-off { display: none}
|
|
||||||
.color-scheme-dark .dark-theme-toggle-on { display: none}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('bad-request'), false) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main class="error-page">
|
|
||||||
<h1 id="firstHeading">Bad request</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<p>You sent a request the server can’t understand.</p>
|
|
||||||
<p>If you entered the URL manually please check your spelling and try again.</p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('access-denied'), False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main class="error-page">
|
|
||||||
<h1 id="firstHeading">{{ T('access-denied') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<p>{{ T('access-denied-text') }}.</p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag( T('not-found'), False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main class="error-page">
|
|
||||||
<h1 id="firstHeading">{{ T('not-found') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<p>{{ T('not-found-text').format(request.path) }}.</p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('% _ %', False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main class="error-page">
|
|
||||||
<h1 id="firstHeading">% _ %</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<p>We’re sorry, an unexpected error occurred. Try refreshing the page.</p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Administrative tools') }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1>Administrative tools</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
{% if current_user and current_user.is_admin %}
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
<a href="/manage/export">Export pages</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="/manage/import">Import pages</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="/manage/accounts">Manage accounts</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
{% else %}
|
|
||||||
<p>Administrative tools can be accessed by administrator users only.</p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{{ title_tag('Pages linking to “' + p.title '”', False) }}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1 id="firstHeading">{{ p.title }}</h1>
|
|
||||||
<div class="preview-subtitle">{{ T('backlinks') }}</div>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
{% if backlinks %}
|
|
||||||
<ul>
|
|
||||||
{% for op in backlinks %}
|
|
||||||
<li><a href="{{ op.get_url() }}">
|
|
||||||
{{ op.title }} (<strong>#{{ op.id }}</strong>)
|
|
||||||
</a></li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
{% else %}
|
|
||||||
<p class="placeholder">{{ T("backlinks-empty") }}</p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p>{{ T("back-to") }} <a href="{{ p.get_url() }}">{{ p.title }}</a>.</p>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="{{ g.lang }}">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
{% block title %}
|
|
||||||
<title>{{ app_name }}</title>
|
|
||||||
{% endblock %}
|
|
||||||
<!-- material icons -->
|
|
||||||
<link rel="stylesheet" href="{{ material_icons_url }}">
|
|
||||||
{{ theme_style_tag() }}
|
|
||||||
<style>:root {
|
|
||||||
--fg-link-light: var(--accent-medium);
|
|
||||||
--fg-link-visited-light: var(--accent-dark);
|
|
||||||
--fg-link-hover-light: var(--accent-sharp);
|
|
||||||
--bg-link-light: var(--accent-bg);
|
|
||||||
--border-sharp-light: var(--accent-sharp);
|
|
||||||
|
|
||||||
--fg-link-dark: var(--accent-medium);
|
|
||||||
--fg-link-visited-dark: var(--accent-light);
|
|
||||||
--fg-link-hover-dark: var(--accent-sharp);
|
|
||||||
--fg-link-hover-dark: var(--accent-sharp);
|
|
||||||
--bg-link-dark: var(--accent-bg);
|
|
||||||
--border-sharp-dark: var(--accent-sharp);
|
|
||||||
}</style>
|
|
||||||
<link rel="stylesheet" href="/static/style.css">
|
|
||||||
{% block json_info %}{% endblock %}
|
|
||||||
</head>
|
|
||||||
<body {% if color_theme %} class="{{ theme_classes(color_theme) }}"{% endif %}>
|
|
||||||
<div id="__top"></div>
|
|
||||||
<header class="site-header">
|
|
||||||
<span class="site-name">
|
|
||||||
<a href="/">{{ app_name }}</a>
|
|
||||||
</span>
|
|
||||||
<span class="site-header-blank"> </span>
|
|
||||||
<ul class="top-menu">
|
|
||||||
<li class="dark-theme-toggle-anchor">
|
|
||||||
<a href="{{ url_for('theme_switch', next=request.path) }}" onclick="toggleDarkTheme(true);return false" class="dark-theme-toggle-on" title="Dark theme">{{ icon('brightness_3') }}</a>{#
|
|
||||||
#}<a href="{{ url_for('theme_switch', next=request.path) }}" onclick="toggleDarkTheme(false);return false" class="dark-theme-toggle-off" title="Light theme">{{ icon('brightness_5') }}</a>
|
|
||||||
<script>/*<![CDATA[*/function toggleDarkTheme(a){ document.cookie="dark="+(256*a+256+(document.cookie.match(/dark=([0-9]+)/)||0)%256)+";max-age=31556952;path=/;SameSite=Strict";document.body.classList.toggle("light",!a);document.body.classList.toggle("dark",a); }; toggleDarkTheme(/dark=5[0-9][0-9]/.test(document.cookie) || !/dark=2[0-9][0-9]/.test(document.cookie));/*]]>*/</script>
|
|
||||||
</li>
|
|
||||||
<li><a href="/search/" title="{{ T('search') }}" rel="nofollow">{{ icon('search') }}</a></li>
|
|
||||||
<li><a href="/p/random/" title="{{ T('random-page') }}" rel="nofollow">{{ icon('shuffle') }}</a></li>
|
|
||||||
<li><a href="/create/" title="{{ T('new-note') }}" rel="nofollow">{{ icon('create') }}</a></li>
|
|
||||||
</ul>
|
|
||||||
<ul class="user-menu">
|
|
||||||
{% if g.no_user %} <!-- login failure -->
|
|
||||||
{% elif current_user.is_authenticated %}
|
|
||||||
<li><a href="/@{{ current_user.username }}/">{{ current_user.username }}</a></li>
|
|
||||||
<li><a href="/accounts/logout/" title="{{ T('logout') }}" rel="nofollow">{{ icon('logout') }}</a></li>
|
|
||||||
{% else %}
|
|
||||||
<li><a href="/accounts/login/" title="{{ T('login') }}" rel="nofollow">{{ icon('login') }}</a></li>
|
|
||||||
{% endif %}
|
|
||||||
</ul>
|
|
||||||
</header>
|
|
||||||
<div class="site-content">
|
|
||||||
{% for msg in get_flashed_messages() %}
|
|
||||||
<div class="flash">{{ icon('info') }} {{ msg }}</div>
|
|
||||||
{% endfor %}
|
|
||||||
{% block content %}{% endblock %}
|
|
||||||
{% block toc %}{% endblock %}
|
|
||||||
</div>
|
|
||||||
<footer class="site-footer">
|
|
||||||
<div class="footer-copyright">© 2020-2025 Sakuragasaki46.</div>
|
|
||||||
<div class="footer-liability">{{ T('user-generated-warning')}} <u>{{ T('user-liability-warning') }}</u>.</div>
|
|
||||||
{% if not g.no_user %}
|
|
||||||
<div class="footer-loggedinas">
|
|
||||||
{% if current_user.is_authenticated %}
|
|
||||||
<span class="material-icons">person</span> {{ T('logged-in-as') }}: <strong>{{ current_user.username }}</strong>
|
|
||||||
{% else %}
|
|
||||||
<span class="material-icons">person_off</span> {{ T('not-logged-in') }}. <a href="/accounts/login">{{ T("login") }}</a>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
<div class="footer-actions" id="page-actions">{% block footer_actions %}{% endblock %}</div>
|
|
||||||
<div class="footer-versions">{{app_name}} version {{app_version}}</div>
|
|
||||||
</footer>
|
|
||||||
<div class="backontop"><a href="#__top" title="Back on top"><span class="material-icons">arrow_upward</span></a></div>
|
|
||||||
{% block scripts %}{% endblock %}
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('calendar')) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1 id="firstHeading">{{ T('calendar') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<ul>
|
|
||||||
{% for year in range(till_year, from_year-1, -1) %}
|
|
||||||
<li>
|
|
||||||
<strong>{% if year == now.year %}<mark>{% endif %}{{ year }}{% if year == now.year %}</mark>{% endif %}</strong>:
|
|
||||||
<ul class="inline">
|
|
||||||
{% for month in range(1, 13) %}
|
|
||||||
<li><a href="/calendar/{{year}}/{{month}}">{{ year }}.{{ month }}</a></li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
{{ T('show-more-years') }}:
|
|
||||||
<ul class="inline">
|
|
||||||
<li>
|
|
||||||
<a href="?till_year={{ till_year + 15 }}">{{ T('in-the-future') }}</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="?from_year={{ from_year - 15 }}">{{ T('in-the-past') }}</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{{ title_tag('Contributions of ' + u.username , False) }}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1 id="firstHeading">{{ u.username }}</h1>
|
|
||||||
<p class="preview-subtitle">Contributions</p>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<p class="nl-pagination">Showing results <strong>{{ contributions.page * 20 - 19 }}</strong> to <strong>{{ min(contributions.page * 20, contributions.total) }}</strong> of <strong>{{ total_count }}</strong> total.</p>
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
{% if contributions.page > 1 %}
|
|
||||||
<li class="nl-prev"><a href="?page={{ contributions.page - 1 }}">« Previous page</a></li>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
|
|
||||||
{% for rev in contributions %}
|
|
||||||
<li>
|
|
||||||
<a href="/history/revision/{{ rev.id }}/">
|
|
||||||
#{{ rev.id }}
|
|
||||||
·
|
|
||||||
{{ rev.pub_date.strftime("%B %-d, %Y %H:%M:%S") }}
|
|
||||||
{% if rev.comment %}
|
|
||||||
“{{ rev.comment }}”
|
|
||||||
{% endif %}
|
|
||||||
</a>
|
|
||||||
on
|
|
||||||
<a href="{{ rev.page.get_url() }}">
|
|
||||||
{{ rev.page.title }}
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
|
||||||
|
|
||||||
{% if contributions.has_next %}
|
|
||||||
<li class="nl-next"><a href="?page={{ contributions.page + 1 }}">Next page »</a></li>
|
|
||||||
{% endif %}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('easter-date-calc')) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1>{{ T('easter-date-calc') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<form>
|
|
||||||
<div>
|
|
||||||
<label for="y">{{ T('year') }}: </label>
|
|
||||||
<input type="text" name="y" value="{{ y }}">
|
|
||||||
<input type="submit" value="{{ T('calculate') }}" class="submit-quick">
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{% if easter_dates %}
|
|
||||||
<div class="easter-results">
|
|
||||||
<p class="easter-date">{{ T('easter') }}: <strong>{{ easter_dates['easter'].strftime('%B %-d, %Y') }}</strong></p>
|
|
||||||
|
|
||||||
<h2>{{ T('other-dates') }}</h2>
|
|
||||||
<ul>
|
|
||||||
<li>Mercoledì delle Ceneri: <strong>{{ easter_dates['ceneri'].strftime('%B %-d, %Y') }}</strong></li>
|
|
||||||
<li>Ascensione: <strong>{{ easter_dates['ascensione'].strftime('%B %-d, %Y') }}</strong></li>
|
|
||||||
<li>Pentecoste: <strong>{{ easter_dates['pentecoste'].strftime('%B %-d, %Y') }}</strong></li>
|
|
||||||
<li>Prima Domenica d'Avvento: <strong>{{ easter_dates['avvento1'].strftime('%B %-d, %Y') }}</strong></li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{{ title_tag("Editing “{{ pl_title }}”" if pl_title else "Edit note", False) }}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block json_info %}<script>/*<![CDATA[*/window.page_info={{ ( pl_js_info or {} )|tojson|safe }};/*]]>*/</script>{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
{% if preview %}
|
|
||||||
<article>
|
|
||||||
<h1 id="firstHeading">{{ pl_title }}</h1>
|
|
||||||
<div class="preview-subtitle">Preview</div>
|
|
||||||
|
|
||||||
<div class="preview-area">
|
|
||||||
<div class="preview-warning">
|
|
||||||
Remember this is only a preview.
|
|
||||||
<strong>Your changes were not saved yet!</strong>
|
|
||||||
<a href="#editing-area">Jump to editing area</a></div>
|
|
||||||
<div class="inner-content article-content">{{ preview|safe }}</div>
|
|
||||||
<div style="clear:both"></div>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
{% endif %}
|
|
||||||
<div class="inner-content">
|
|
||||||
<form method="POST">
|
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
|
|
||||||
<div>
|
|
||||||
<label for="title"><span class="material-icons">link</span> /</label>
|
|
||||||
<input type="text" name="url" class="url-input" placeholder="(No URL)" maxlength="64" value="{{ pl_url or '' }}" {% if pl_readonly %}disabled=""{% endif %}>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="text" required name="title" placeholder="Title (required)" class="title-input" maxlength="256" value="{{ pl_title }}" {% if pl_readonly %}disabled=""{% endif %}>
|
|
||||||
</div>
|
|
||||||
<div id="editing-area">
|
|
||||||
{% if not pl_readonly %}
|
|
||||||
<div class="pre-text-input">
|
|
||||||
<p>This editor is using Markdown for text formatting (e.g. bold, italic, headers and tables). <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" rel="nofollow">More info on Markdown</a>.</p>
|
|
||||||
</div>
|
|
||||||
<div class="over-text-input"></div>
|
|
||||||
{% else %}
|
|
||||||
<div class="pre-text-input">
|
|
||||||
<p>This page was locked by the owner, and is therefore not editable. You can still copy the source text.</p>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
<textarea name="text" class="text-input" {% if pl_readonly %}disabled=""{% endif %}>{{ pl_text }}</textarea>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label for="tags">{{ T('input-tags') }}:</label>
|
|
||||||
<input type="text" name="tags" class="tags-input" placeholder="{{ T('no-tags') }}" value="{{ pl_tags }}" {% if pl_readonly %}disabled=""{% endif %}>
|
|
||||||
</div>
|
|
||||||
{% if not pl_readonly %}
|
|
||||||
<div>
|
|
||||||
<input type="submit" value="Save" id="save-button" class="submit-primary">
|
|
||||||
<input type="submit" name="preview" value="Preview" id="preview-button" class="submit-secondary">
|
|
||||||
<input type="text" name="comment" value="{{ pl_comment }}" placeholder="{{ T('write-a-comment') }}" />
|
|
||||||
</div>
|
|
||||||
<h3>Advanced options</h3>
|
|
||||||
{% if pl_owner_is_current_user %}
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" id="CB__lockpage" name="lockpage" {% if pl_is_locked %}checked=""{% endif %}>
|
|
||||||
<label for="CB__lockpage">Lock page for editing by other users</label>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" id="CB__usecalendar" name="usecalendar" {% if pl_calendar %}checked=""{% endif %}>
|
|
||||||
<label for="CB__usecalendar">Use calendar:</label>
|
|
||||||
<input type="date" name="calendar" {% if pl_calendar %}value="{{ pl_calendar }}"{% endif %}>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" id="CB__cw" name="cw" {% if pl_cw %}checked=""{% endif %}>
|
|
||||||
<label for="CB__cw">Content Warning</label>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block scripts %}
|
|
||||||
<script src="/static/edit.js"></script>
|
|
||||||
<script src="/static/content.js"></script>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Export pages', False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1>Export pages</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<p>You can export how many pages you want, that will be downloaded in JSON format and can be imported in another {{ app_name }} instance.</p>
|
|
||||||
|
|
||||||
<p>In order to add page to export list, please enter exact title, /url, #tag or +id. Entering a tag will add all pages with that tag to list. Each page or tag is separated by a newline.</p>
|
|
||||||
|
|
||||||
<form method="POST">
|
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
|
|
||||||
<div>
|
|
||||||
<textarea style="height:20em;width:100%" name="export-list" placeholder="Title, /url, #tag, or +id, newline-separated"></textarea>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" name="history" value="1"><label>Include history (file can be very large!)</label>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="submit" value="Download">
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('note-history'), False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1 id="firstHeading">{{ p.title }}</h1>
|
|
||||||
<div class="preview-subtitle">Page history</div>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<ul>
|
|
||||||
{% for rev in history %}
|
|
||||||
<li>
|
|
||||||
<a href="/history/revision/{{ rev.id }}/">
|
|
||||||
#{{ rev.id }}
|
|
||||||
·
|
|
||||||
{{ rev.pub_date.strftime("%B %-d, %Y %H:%M:%S") }}
|
|
||||||
</a>
|
|
||||||
{% if rev.comment %}
|
|
||||||
“{{ rev.comment }}”
|
|
||||||
{% endif %}
|
|
||||||
by
|
|
||||||
{% if rev.user_id %}
|
|
||||||
<a href="/@{{ rev.user.username }}">
|
|
||||||
{{ rev.user.username }}
|
|
||||||
</a>
|
|
||||||
{% else %}
|
|
||||||
<span><em>unknown user</em></span>
|
|
||||||
{% endif %}
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p>{{ T("back-to") }} <a href="{{ p.get_url() }}">{{ p.title }}</a>.</p>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
{% from "macros/nl.html" import nl_list with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('homepage')) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main class="homepage">
|
|
||||||
<h1 id="firstHeading">{{ T('welcome').format(app_name) }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<div class="nl-new">
|
|
||||||
<a href="/create/">
|
|
||||||
<button class="submit-primary"><span class="material-icons">create</span> {{ T('new-note') }}</button>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h2>{{ T('latest-notes') }}</h2>
|
|
||||||
|
|
||||||
<br style="clear:both" />
|
|
||||||
|
|
||||||
{{ nl_list(new_notes, is_main=True) }}
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Import pages', False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1>Import pages</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
{% if current_user.is_admin %}
|
|
||||||
|
|
||||||
<p>
|
|
||||||
You can import files produced by the <a href="/manage/export">exporter tool</a>, in JSON format.
|
|
||||||
Importing pages can be done by users with Admin permissions only.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
|
|
||||||
<form enctype="multipart/form-data" method="POST">
|
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
|
|
||||||
<div>
|
|
||||||
<input type="file" accept="application/json" name="import" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" name="ovwurls" value="1" checked="" />
|
|
||||||
<label for="ovwurls">Overwrite URLs</label>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="submit" value="Import" />
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
{% else %}
|
|
||||||
<p>Importing pages can be done by users with Admin permissions only.</p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
{% from "macros/nl.html" import nl_list with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('notes-by-date')) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1 id="firstHeading">{{ T('notes-by-date') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
{{ nl_list(notes) }}
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
{% from "macros/nl.html" import nl_list with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Notes tagged #' + tagname ) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1 id="firstHeading">#{{ tagname }}</h1>
|
|
||||||
<div class="preview-subtitle">{{ T('notes-tagged') }}</div>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
{% if tagged_notes.total > 0 %}
|
|
||||||
{{ nl_list(tagged_notes, hl_tags=(tagname,), other_url='tags/' + tagname) }}
|
|
||||||
{% else %}
|
|
||||||
<p class="nl-placeholder">{{ T('notes-tagged-empty') }}</p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</main>
|
|
||||||
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('login'), False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1>{{ T('login') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<form method="POST">
|
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
|
|
||||||
<div>
|
|
||||||
<label>{{ T('username') }}:</label>
|
|
||||||
<input type="text" name="username" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>{{ T('password') }}:</label>
|
|
||||||
<input type="password" name="password" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" id="CB__remember" name="remember" value="1" />
|
|
||||||
<label for="CB__remember">{{ T('remember-me') }}</label>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<button type="submit">{{ T('login') }}</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p>{{ T('no-account-sign-up') }} <a href="/accounts/register" rel="nofollow">{{ T("sign-up") }}</a></p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{#
|
|
||||||
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 %}
|
|
||||||
<p class="nl-pagination">
|
|
||||||
Showing results <strong>{{ page_n * 20 - 19 }}</strong> to <strong>{{ min(page_n * 20, total_count) }}</strong>
|
|
||||||
of <strong>{{ l.total }}</strong> total.</p>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
<ul class="nl-list">
|
|
||||||
{% if page_n and page_n > 1 %}
|
|
||||||
<li class="nl-prev"><a href="/{{ other_url }}/?page={{ page_n - 1 }}">« Previous page</a></li>
|
|
||||||
{% endif %}
|
|
||||||
{% for n in l %}
|
|
||||||
<li>
|
|
||||||
<article class="nl-item">
|
|
||||||
<a href="{{ n.get_url() }}" class="nl-title">{{ n.title }}</a>
|
|
||||||
<p class="nl-desc">{{ n.short_desc() }}</p>
|
|
||||||
{% if n.tags %}
|
|
||||||
<p class="nl-tags">
|
|
||||||
<span class="material-icons">tag</span>
|
|
||||||
{{ T('tags') }}:
|
|
||||||
{% for tag in n.tags %}
|
|
||||||
{% set tn = tag.name %}
|
|
||||||
{% if tn in hl_tags %}
|
|
||||||
<strong class="nl-tag-hl">#{{ tn }}</strong>
|
|
||||||
{% else %}
|
|
||||||
<a href="/tags/{{ tn }}/" class="nl-tag">#{{ tn }}</a>
|
|
||||||
{% endif %}
|
|
||||||
{% endfor %}
|
|
||||||
</p>
|
|
||||||
{% endif %}
|
|
||||||
{% if n.calendar %}
|
|
||||||
<p class="nl-calendar">
|
|
||||||
<span class="material-icons">calendar_today</span>
|
|
||||||
{% if hl_calendar and hl_calendar.y == n.calendar.y and hl_calendar.m == n.calendar.m %}
|
|
||||||
<strong>
|
|
||||||
<time datetime="{{ n.calendar.isoformat() }}">{{ n.calendar.strftime('%B %-d, %Y') }}</time>
|
|
||||||
</strong>
|
|
||||||
{% else %}
|
|
||||||
<a href="/calendar/{{ n.calendar.year }}/{{ n.calendar.month }}">
|
|
||||||
<time datetime="{{ n.calendar.isoformat() }}">{{ n.calendar.strftime('%B %-d, %Y') }}</time>
|
|
||||||
</a>
|
|
||||||
{% endif %}
|
|
||||||
</p>
|
|
||||||
{% endif %}
|
|
||||||
</article>
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
|
||||||
|
|
||||||
{% if is_main %}
|
|
||||||
<li class="nl-next"><a href="/{{ other_url }}/">{{ T('show-all') }}</a></li>
|
|
||||||
{% elif page_n <= (l.total - 1) // 20 %}
|
|
||||||
<li class="nl-next"><a href="/{{ other_url }}/?page={{ page_n + 1 }}">Next page »</a></li>
|
|
||||||
{% endif %}
|
|
||||||
</ul>
|
|
||||||
{% endmacro %}
|
|
||||||
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
|
|
||||||
|
|
||||||
{% macro title_tag(name, robots=True) %}
|
|
||||||
<title>
|
|
||||||
{%- if name -%}
|
|
||||||
{{ name }} | {{ app_name }}
|
|
||||||
{%- else -%}
|
|
||||||
{{ app_name }}
|
|
||||||
{%- endif -%}
|
|
||||||
</title>
|
|
||||||
{% if robots %}
|
|
||||||
<meta name="robots" content="noai,noimageai" />
|
|
||||||
{% else %}
|
|
||||||
<meta name="robots" content="noindex,nofollow,noai,noimageai" />
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% endmacro %}
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('manage-accounts'), False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1>{{ T('manage-accounts') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
{% if current_user.is_admin %}
|
|
||||||
<p>
|
|
||||||
Here is the list of users registered on {{ app_name }}, in reverse chronological order.
|
|
||||||
<strong>Beware: you are managing sensitive informations.</strong>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p class="nl-pagination">{{ T('search-results') }} <strong>{{ users.page * 20 - 19 }}</strong> to <strong>{{ min(users.page * 20, users.total) }}</strong> of <strong>{{ users.total }}</strong> total.</p>
|
|
||||||
|
|
||||||
<form enctype="multipart/form-data" method="POST">
|
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
{% if users.has_prev %}
|
|
||||||
<li class="nl-prev"><a href="?page={{ users.page - 1 }}">« Previous page</a></li>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% for u in users %}
|
|
||||||
<li>
|
|
||||||
<input type="checkbox" name="u{{ u.id }}" value="1">
|
|
||||||
{% if u.is_disabled %}<del>{% endif %}
|
|
||||||
<a href="/@{{ u.username }}">{{ u.username }}</a>
|
|
||||||
{% if u.is_disabled %}</del>{% endif %}
|
|
||||||
{% if u == current_user %}<strong>(you)</strong>{% endif %}
|
|
||||||
{% if u.is_disabled %}<strong>(disabled)</strong>{% endif %}
|
|
||||||
-
|
|
||||||
Groups:
|
|
||||||
<ul class="inline">
|
|
||||||
{% for ug in u.groups() %}
|
|
||||||
<li>{{ ug.name }}</li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
-
|
|
||||||
Registered on:
|
|
||||||
{{ u.join_date }}
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
|
||||||
|
|
||||||
{% if users.has_next %}
|
|
||||||
<li class="nl-next"><a href="?page={{ users.page + 1 }}">Next page »</a></li>
|
|
||||||
{% endif %}
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<select name="action">
|
|
||||||
<option selected value="-">Select an action</option>
|
|
||||||
<option value="disable">Disable selected accounts</option>
|
|
||||||
</select>
|
|
||||||
|
|
||||||
<input type="submit" value="Submit">
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
{% else %}
|
|
||||||
<p>Managing accounts can be done by users with Admin permissions only.</p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,51 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(d.strftime("%B %Y")) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1 id="firstHeading">{{ d.strftime("%B %Y") }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
{% if total_count > 0 %}
|
|
||||||
{% from "macros/nl.jinja2" import nl_list with context %}
|
|
||||||
{{ nl_list(notes, total_count=total_count, page_n=page_n, hl_calendar=d) }}
|
|
||||||
|
|
||||||
{% else %}
|
|
||||||
<p class="nl-placeholder">{{ T('notes-month-empty') }}</p>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% set past_year = advance_calendar(d, -2) %}
|
|
||||||
{% set past_month = advance_calendar(d, -1) %}
|
|
||||||
{% set next_month = advance_calendar(d, 1) %}
|
|
||||||
{% set next_year = advance_calendar(d, 2) %}
|
|
||||||
<div class="calendar-navigation">
|
|
||||||
<ul class="inline">
|
|
||||||
<li>« <a href="/calendar/{{ past_year.year }}/{{ past_year.month }}">{{ past_year.strftime("%B %Y") }}</a></li>
|
|
||||||
<li><a href="/calendar/{{ past_month.year }}/{{ past_month.month }}">{{ past_month.strftime("%B %Y") }}</a></li>
|
|
||||||
<li><strong>{{ d.strftime("%B %Y") }}</strong></li>
|
|
||||||
<li><a href="/calendar/{{ next_month.year }}/{{ next_month.month }}">{{ next_month.strftime("%B %Y") }}</a></li>
|
|
||||||
<li><a href="/calendar/{{ next_year.year }}/{{ next_year.month }}">{{ next_year.strftime("%B %Y") }}</a> »</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p>{{ T('back-to') }} <a href="/calendar">{{ T('calendar') }}</a></p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block toc %}
|
|
||||||
<nav class="toc">
|
|
||||||
<h3>{{ d.year }}</h3>
|
|
||||||
|
|
||||||
<ul>
|
|
||||||
{% for i in range(1, 13) %}
|
|
||||||
<li>
|
|
||||||
<a href="/calendar/{{ d.year }}/{{ i }}">{{ (new_datetime(d.year, i)).strftime('%B %Y') }}</a>
|
|
||||||
<strong>({{ toc[i] }})</strong>
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,45 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Privacy Policy') }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1 id="firstHeading">Privacy Policy</h1>
|
|
||||||
|
|
||||||
<div class="inner-content article-content">
|
|
||||||
{% filter markdown %}
|
|
||||||
# Privacy
|
|
||||||
|
|
||||||
## Cookies
|
|
||||||
|
|
||||||
{{ app_name }} uses one cryptographically signed cookie to maintain secure authenticated sessions. This cookie is randomized with each new session.
|
|
||||||
|
|
||||||
This cookie is used for the following purposes:
|
|
||||||
|
|
||||||
* Authentication
|
|
||||||
* Abuse mitigation
|
|
||||||
* Per-device settings like light/dark theme selection.
|
|
||||||
|
|
||||||
This cookie is mandatory and cannot be opted out. Manual alteration or removal of this cookie will result in deauthentication and reversion to default per-device settings.
|
|
||||||
|
|
||||||
## Your information
|
|
||||||
|
|
||||||
We collect basic information in order to operate the platform, and to mitigate abuse. This includes:
|
|
||||||
|
|
||||||
* Your email address, if you choose to provide it.
|
|
||||||
* The IP address from which content is submitted.
|
|
||||||
* Whether or not you have indicated that you are 18 years of age.
|
|
||||||
* Other saved personal preferances, which you can edit from your account settings.
|
|
||||||
|
|
||||||
We use - and then promptly forget - the following information about you from third parties:
|
|
||||||
|
|
||||||
* Verification from our captcha provider that you aren't a bot, during account registration
|
|
||||||
|
|
||||||
{{ app_name }} will not release your information to third parties, except:
|
|
||||||
|
|
||||||
* As required by Italian law
|
|
||||||
* At our discretion, {{ app_name }} may share your information with Italian law enforcement in the event of an emergency, if we have good cause to believe that doing so would avert or mitigate the emergency.
|
|
||||||
{% endfilter %}
|
|
||||||
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('sign-up')) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1>{{ T('sign-up') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<form method="POST">
|
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
|
|
||||||
<div>
|
|
||||||
<label>{{ T('username') }}:</label>
|
|
||||||
<input type="text" name="username" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>{{ T('password') }}:</label>
|
|
||||||
<input type="password" name="password" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>{{ T('confirm-password') }}:</label>
|
|
||||||
<input type="password" name="confirm_password" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>{{ T('email') }} ({{ T('optional') }}):</label>
|
|
||||||
<input type="text" name="email" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" name="legal" value="1" />
|
|
||||||
<label>{{ T('have-read-terms').format(('<a href="/terms/">%s</a>' | safe) % T('terms-of-service'), ('<a href="/privacy/">%s</a>' | safe) % T('privacy-policy')) }}</label>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="submit" value="{{ T('sign-up') }}" />
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p>{{ T('already-have-account') }} <a href="/accounts/login" rel="nofollow">{{ T("login") }}</a></p>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Content Policy') }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1 id="firstHeading">Content Policy</h1>
|
|
||||||
|
|
||||||
<div class="inner-content article-content">
|
|
||||||
{% filter markdown %}
|
|
||||||
__THIS POLICY IS OUTDATED AND SUPERSEDED. SEE <https://ndspir.it/rules>__
|
|
||||||
|
|
||||||
These are the Rules of {{ app_name }}.
|
|
||||||
|
|
||||||
{{ app_name }} is a Free Speech environment. However, in order to ensure
|
|
||||||
the safety of our users as well as the longevity of the platform, there are a
|
|
||||||
few things you are not permitted to do with the platform.
|
|
||||||
|
|
||||||
By using {{ app_name }}, you agree to follow these rules.
|
|
||||||
Violations may lead to the suspension or terminaton of your {{ app_name }} account.
|
|
||||||
|
|
||||||
## 1. Intellectual Property
|
|
||||||
|
|
||||||
You may not upload to, embed within, or link out from {{ app_name }}:
|
|
||||||
|
|
||||||
1. Copyrighted material that you are not authorized to distribute
|
|
||||||
2. Anything not legal to publish within, or export from, intentionally
|
|
||||||
|
|
||||||
## 2. Digital Safety
|
|
||||||
|
|
||||||
You may not upload to, embed within, or link out from {{ app_name }}:
|
|
||||||
|
|
||||||
1. IP or token grabbers
|
|
||||||
2. Viruses or exploits
|
|
||||||
3. URL shorteners
|
|
||||||
4. Anything with the intent of breaking {{ app_name }}
|
|
||||||
|
|
||||||
## 3. User Safety
|
|
||||||
|
|
||||||
You may not use {{ app_name }} to do any of the following:
|
|
||||||
|
|
||||||
1. Threaten, intimidate, or harass other users
|
|
||||||
2. Impersonate other users, real life people, or {{ app_name }} staff
|
|
||||||
3. Solicit, collect, or publish personally identifiable information (PII), be it yours or the one
|
|
||||||
of another individual
|
|
||||||
4. Spam (the definition of “spam” is at {{ app_name }}’s own discretion)
|
|
||||||
|
|
||||||
## 4. Sexual Content
|
|
||||||
|
|
||||||
You may not upload to, embed within, or link out from {{ app_name }}:
|
|
||||||
|
|
||||||
1. Sexual or sexually suggestive material not marked "NSFW"
|
|
||||||
2. Sexual or sexually suggestive material involving individuals under the age of 18, including fictitious content. Solicitation of such material is also prohibited.
|
|
||||||
3. Sexual or sexually suggestive material involving individuals who did not consent to its creation and distribution (commonly called "revenge pornography" or "involuntary pornography"). Solicitation of such material is also prohibited.
|
|
||||||
|
|
||||||
## 5. IRL Safety
|
|
||||||
|
|
||||||
You may not use {{ app_name }} to do any of the following:
|
|
||||||
|
|
||||||
1. Incite, plan, or execute unlawful or violent activity
|
|
||||||
2. Engage in fraud
|
|
||||||
|
|
||||||
## 6. Evil
|
|
||||||
|
|
||||||
While it would be nice to be able to entertain all viewpoints, certain ideologies are ontologically evil. We have a zero tolerance policy on advocacy, propaganda, recruitment, and any other forms of promotion of evil.
|
|
||||||
|
|
||||||
Evil ideologies prohibited from {{ app_name }} include, but are not limited to:
|
|
||||||
|
|
||||||
* Ethnic, racial, or sex-based supremecism
|
|
||||||
* Pedophile acceptance/normalization
|
|
||||||
* Terrorism
|
|
||||||
|
|
||||||
Discussion of these topics as they relate to current events or other subject matter is permitted; advocacy or promotion of them is not.
|
|
||||||
|
|
||||||
## 7. Additional Rules
|
|
||||||
|
|
||||||
Additional rules may be put in place by the {{ app_name }} administrator.
|
|
||||||
|
|
||||||
{% endfilter %}
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag(T('search-results', "“" + q + "”") if q else T('search'), False) }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1>{{ T('search') }}</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<form method="POST">
|
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
|
|
||||||
<div class="search-wrapper">
|
|
||||||
<label for="q">Search for: </label>
|
|
||||||
<input type="search" name="q" value="{{ q }}" class="search-input">
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input type="checkbox" name="include-tags" value="1" {% if pl_include_tags %}checked{% endif %}>
|
|
||||||
<label for="include-tags">{{ T('include-tags') }}</label>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{% if results %}
|
|
||||||
<h2>{{ T('search-results') }} <em>{{ q }}</em></h2>
|
|
||||||
|
|
||||||
{% from "macros/nl.jinja2" import nl_list with context %}
|
|
||||||
{{ nl_list(results, other_url=None) }}
|
|
||||||
{% elif q %}
|
|
||||||
<h2>{{ T('search-no-results') }} <em>{{ q }}</em></h2>
|
|
||||||
{% else %}
|
|
||||||
<p><u>Please note that search queries <u>do not search for page text</u>.</u></p>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Statistics') }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<main>
|
|
||||||
<h1>Statistics</h1>
|
|
||||||
|
|
||||||
<div class="inner-content">
|
|
||||||
<ul>
|
|
||||||
<li>{{ T("notes-count") }}: <strong>{{ notes_count }}</strong></li>
|
|
||||||
<li>{{ T("notes-count-with-url") }}: <strong>{{ notes_with_url }}</strong></li>
|
|
||||||
<li>{{ T("revision-count") }}: <strong>{{ revision_count }}</strong></li>
|
|
||||||
<li>{{ T("revision-count-per-page") }}: <strong>{{ (revision_count / notes_count)|round(2) }}</strong></li>
|
|
||||||
<li>{{ T('users-count') }}: <strong>{{ users_count }}</strong></li>
|
|
||||||
<li>{{ T('groups-count') }}: <strong>{{ groups_count }}</strong></li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
{% block content %}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,147 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}{{ title_tag('Terms of Service') }}{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<h1 id="firstHeading">Terms of Service</h1>
|
|
||||||
|
|
||||||
<div class="inner-content article-content">
|
|
||||||
{% filter markdown %}
|
|
||||||
## Scope and Definitions
|
|
||||||
|
|
||||||
These terms of service ("Terms") are between {{ app_name }}
|
|
||||||
("{{ request.headers['Host'] }}") and You, regarding Your use of the social platform
|
|
||||||
{{ app_name }}, and any other services or test servers which may exist
|
|
||||||
now or in the future (collectively "{{ app_name }}").
|
|
||||||
|
|
||||||
Content on this page displayed in blockquotes is provided for convenience
|
|
||||||
and readability only. Blockquote text is not part of the terms of service.
|
|
||||||
|
|
||||||
## Conduct and content
|
|
||||||
|
|
||||||
You agree to follow the Content Policy [here](/rules/).
|
|
||||||
The Content Policy is incorporated into these Terms by this reference.
|
|
||||||
|
|
||||||
## Age
|
|
||||||
|
|
||||||
You warrant that You are at least 13 years old.
|
|
||||||
You warrant that You are at least 18 years old,
|
|
||||||
if You indicate as such in Your user settings.
|
|
||||||
|
|
||||||
|
|
||||||
## Account Access
|
|
||||||
|
|
||||||
Your {{ app_name }} account is nontransferable. You will not buy, sell, gift, loan, or otherwise grant a third party access to Your {{ app_name }} account. You will not provide a third party with Your {{ app_name }} password or two-factor authentication codes.
|
|
||||||
|
|
||||||
In the event that Your {{ app_name }} account is accessed by a third party anyways, You remain accountable for all actions taken by Your account.
|
|
||||||
|
|
||||||
## Liability
|
|
||||||
|
|
||||||
{{ app_name }} shall not be liable for Your damages arising from any of the following:
|
|
||||||
|
|
||||||
* Use of the {{ app_name }} platform
|
|
||||||
* Technical failure of {{ app_name }}
|
|
||||||
* Administrative actions performed by {{ app_name }}, including both automatic and manual actions
|
|
||||||
* Unauthorized access of a third party to Your {{ app_name }} account
|
|
||||||
* Loss or breach of {{ app_name }} data
|
|
||||||
* Force majeur
|
|
||||||
|
|
||||||
You accept full liability for all content You upload to, or embed within, {{ app_name }}, and indemnify {{ app_name }} from all such liability.
|
|
||||||
|
|
||||||
> You are responsible for everything You do, and everything that happens with, with Your {{ app_name }} account. Don't use {{ app_name }} to store important data or sensitive data.
|
|
||||||
|
|
||||||
## Intellectual Property
|
|
||||||
|
|
||||||
You grant {{ app_name }} a permanent, worldwide, and irrevocable license to store, modify, copy, and distribute all content that You submit to or upload to {{ app_name }}, including any creative works. Additionally, You grant {{ app_name }} a permanent, worldwide, and irrevocable license to sublicense these same rights to {{ app_name }}'s service providers. Additionally, You warrant that You are authorized to grant {{ app_name }} these rights.
|
|
||||||
|
|
||||||
You retain all other intellectual property rights, including ownership.
|
|
||||||
|
|
||||||
> We need to be able to store, copy, and distribute Your content, because that's just how websites like {{ app_name }} work. We also need to be able to modify it for security and formatting purposes.
|
|
||||||
|
|
||||||
## Acceptable Use
|
|
||||||
|
|
||||||
You will not use {{ app_name }} as a means to support any other website or service without written permission by {{ app_name }}.
|
|
||||||
|
|
||||||
You will not attempt to gain access to a {{ app_name }} account that does not belong to You.
|
|
||||||
|
|
||||||
You will not use {{ app_name }} to engage in child sexual abuse activities, as defined in the [CSAM Policy](/help/csam). The CSAM Policy is incorporated into these terms by this reference.
|
|
||||||
|
|
||||||
## Multiple Accounts
|
|
||||||
|
|
||||||
You are permitted to create and use multiple {{ app_name }} accounts.
|
|
||||||
|
|
||||||
You will not use multiple accounts to circumvent per-user limits.
|
|
||||||
|
|
||||||
Additionally, these terms apply to all of Your accounts, which may exist now or in the future. {{ app_name }} reserves the right to take administrative action against all of Your accounts in the event of a terms of service violation on any of Your accounts.
|
|
||||||
|
|
||||||
## Your Privacy
|
|
||||||
|
|
||||||
{{ app_name }} will never intentionally share Your personal information with third parties, except:
|
|
||||||
|
|
||||||
* As required by United States law.
|
|
||||||
* We will share Your data with our own service providers that are necessary for {{ app_name }} operations.
|
|
||||||
* At our discretion, {{ app_name }} may share Your information with United States law enforcement in the event of an emergency, if we have good cause to believe that doing so would avert or mitigate the emergency.
|
|
||||||
|
|
||||||
{{ app_name }} will make all reasonable efforts to ensure that user information is kept confidential.
|
|
||||||
|
|
||||||
## Legal Forms
|
|
||||||
|
|
||||||
{{ app_name }} grants You the ability to use Your {{ app_name }} account to send us certain types of legal forms through our help portal. These include, but are not limited to:
|
|
||||||
|
|
||||||
* DMCA takedown request
|
|
||||||
* DMCA takedown counter-request
|
|
||||||
* Subpoenas and court orders
|
|
||||||
|
|
||||||
You acknowledge that these forms are provided for the sake of convenience and speed, and that {{ app_name }} does not waive any of its rights regarding legal process, including the right to object for lack of proper service.
|
|
||||||
|
|
||||||
You agree to refrain from making abusive, frivolous, or otherwise improper submissions to these forms. This includes, but is not limited to:
|
|
||||||
|
|
||||||
* Nonsensical or incomplete requests
|
|
||||||
* Duplicate submissions
|
|
||||||
* DMCA takedown requests not made in good faith
|
|
||||||
* DMCA takedown requests for content protected by Fair Use
|
|
||||||
* DMCA takedown requests for content that you are not authorized to claim.
|
|
||||||
* Legal demands not based in fact and/or not backed by appropriate law.
|
|
||||||
* Legal documents from courts or law enforcement that lack jurisdiction inside the United States
|
|
||||||
* Legal documents that are not in English and are not accompanied by an official English translation.
|
|
||||||
|
|
||||||
## Enforcement
|
|
||||||
|
|
||||||
{{ app_name }} retains sole discretion in all determinations regarding content policy and terms of service violations.
|
|
||||||
|
|
||||||
{{ app_name }} reserves the right to remove content that we deem to violate content policy or the terms of service, and to deactivate accounts responsible for such violations.
|
|
||||||
|
|
||||||
## Severability
|
|
||||||
|
|
||||||
If one clause of these Terms or the Content Policy is determined by a court to be unenforceable, the remainder of the Terms and Content Policy shall remain in force.
|
|
||||||
|
|
||||||
## No Implied Waiver
|
|
||||||
|
|
||||||
A failure by {{ app_name }} in one or more instances to insist upon Your strict adherence to these terms or the Content Policy, shall not be construed as a waiver of any continuing or subsequent violations of these terms or the Content Policy.
|
|
||||||
|
|
||||||
## Completeness
|
|
||||||
|
|
||||||
These Terms, together with the other policies incorporated into them by reference, contain all the terms and conditions agreed upon by You and {{ app_name }} regarding Your use of the {{ app_name }} service. No other agreement, oral or otherwise, will be deemed to exist or to bind either of the parties to this Agreement.
|
|
||||||
|
|
||||||
## Governing Law
|
|
||||||
|
|
||||||
These terms of service are governed by, and shall be interpreted in accordance with, the laws of Italy. You consent to the sole jurisdiction of Italy for all disputes between You and {{ app_name }}, and You consent to the sole application of Italian and E.U. law for all such disputes.
|
|
||||||
|
|
||||||
## Updates
|
|
||||||
|
|
||||||
{{ app_name }} may periodically update these terms of service and/or the Content Policy. When this happens, {{ app_name }} will make reasonable efforts to notify You of such changes.
|
|
||||||
|
|
||||||
Whenever {{ app_name }} updates these terms of service or the Content Policy, Your continued use of the {{ app_name }} platform constitutes Your agreement to the updated terms of service.
|
|
||||||
|
|
||||||
## Translations
|
|
||||||
|
|
||||||
If there is any inconsistency between these terms and any translation into other languages, the English language version takes precedence.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{% endfilter %}
|
|
||||||
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
{% extends "base.html" %}
|
|
||||||
{% from "macros/title.html" import title_tag with context %}
|
|
||||||
|
|
||||||
{% block title %}
|
|
||||||
{{ title_tag(p.title) }}
|
|
||||||
<meta name="description" content="{{ p.short_desc() }}" />
|
|
||||||
<!-- PSA: meta name="keywords" is DEPRECATED -->
|
|
||||||
<meta name="keywords" content="{{ p.seo_keywords() }}" />
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block json_info %}<script>window.page_info={{ p.js_info()|tojson|safe }};</script>{% endblock %}
|
|
||||||
|
|
||||||
{% set html_and_toc = rev.html_and_toc() %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<article>
|
|
||||||
<header class="article-header">
|
|
||||||
<h1 id="firstHeading">{{ p.title }}</h1>
|
|
||||||
|
|
||||||
{% if p.calendar %}
|
|
||||||
<p class="calendar-subtitle">
|
|
||||||
<span class="material-icons">calendar_today</span>
|
|
||||||
<a href="/calendar/{{ p.calendar.year }}/{{ p.calendar.month }}">
|
|
||||||
<time datetime="{{ p.calendar.isoformat() }}">{{ p.calendar.strftime('%B %-d, %Y') }}</time>
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
<ul class="article-actions inline">
|
|
||||||
{% if current_user and current_user.is_authenticated %}
|
|
||||||
{% if p.is_editable() %}
|
|
||||||
<li><span class="material-icons">edit</span><a href="/edit/{{ p.id }}">{{ T('action-edit') }}</a></li>
|
|
||||||
{% else %}
|
|
||||||
<li><span class="material-icons">code</span><a href="/edit/{{ p.id }}">{{ T('action-view-source') }}</a></li>
|
|
||||||
{% endif %}
|
|
||||||
{% endif %}
|
|
||||||
<li><span class="material-icons">history</span><a href="/history/{{ p.id }}">{{ rev.human_pub_date() }}</a></li>
|
|
||||||
</ul>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{% block history_nav %}{% endblock %}
|
|
||||||
|
|
||||||
{% if p.is_cw %}
|
|
||||||
<div class="flash">
|
|
||||||
<strong>Content Warning</strong> -
|
|
||||||
this page may contain shocking or unexpected content, spoilers, or similar.
|
|
||||||
Proceed with caution.
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
<div class="inner-content article-content">
|
|
||||||
{{ html_and_toc[0]|safe }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{% if p.tags %}
|
|
||||||
<div class="page-tags">
|
|
||||||
<p>{{ T('tags') }}:</p>
|
|
||||||
<ul>
|
|
||||||
{% for tag in p.tags %}
|
|
||||||
<li><a href="/tags/{{ tag.name }}/">#{{ tag.name }}</a> <span class="tag-count">({{ tag.popularity() }})</span></li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
</article>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block actions %}
|
|
||||||
{# This block for the actions at the __bottom__. #}
|
|
||||||
<a href="/edit/{{ p.id }}/">{{ T('action-edit') }}</a> -
|
|
||||||
<a href="/history/{{ p.id }}/">{{ T('action-history') }}</a> -
|
|
||||||
<a href="/backlinks/{{ p.id }}/">Backlinks</a> -
|
|
||||||
{{ T('last-changed') }} <time datetime="{{ rev.pub_date.isoformat() }}">{{ rev.pub_date.strftime('%B %-d, %Y at %H:%M:%S') }}</time> -
|
|
||||||
{{ T('page-id') }}: {{ p.id }} -
|
|
||||||
{{ T('owner') }}: {{ p.owner.username }}
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block toc %}
|
|
||||||
<nav class="toc">
|
|
||||||
{{ html_and_toc[1] }}
|
|
||||||
</nav>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block scripts %}
|
|
||||||
<script src="/static/content.js"></script>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
@ -1,104 +0,0 @@
|
||||||
"""
|
|
||||||
Utilities for import / export
|
|
||||||
"""
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
from typing import Iterable
|
|
||||||
from sqlalchemy import insert, select
|
|
||||||
from suou import want_datetime, want_isodate
|
|
||||||
|
|
||||||
from .models import Page, PageRevision, PageText, db
|
|
||||||
|
|
||||||
|
|
||||||
class Exporter(object):
|
|
||||||
root: dict
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.root = {'pages': [], 'users': {}}
|
|
||||||
def add_page(self, p: Page, include_history=True, include_users=False):
|
|
||||||
pobj = {}
|
|
||||||
pobj['title'] = p.title
|
|
||||||
pobj['url'] = p.url
|
|
||||||
pobj['tags'] = [tag.name for tag in p.tags]
|
|
||||||
pobj['calendar'] = want_isodate(p.calendar) if p.calendar else None
|
|
||||||
pobj['flags'] = p.flags
|
|
||||||
if include_users:
|
|
||||||
pobj['owner'] = p.owner_id
|
|
||||||
hist = []
|
|
||||||
for rev in (p.revisions if include_history else [p.latest]):
|
|
||||||
revobj = {}
|
|
||||||
revobj['text'] = rev.text
|
|
||||||
revobj['timestamp'] = rev.pub_date.timestamp()
|
|
||||||
if include_users:
|
|
||||||
revobj['user'] = rev.user_id
|
|
||||||
if rev.user_id not in self.root['users']:
|
|
||||||
## PageRevision.user_info() was never implemented
|
|
||||||
self.root['users'][rev.user_id] = None#rev.user_info()
|
|
||||||
else:
|
|
||||||
revobj['user'] = None
|
|
||||||
revobj['comment'] = rev.comment
|
|
||||||
revobj['length'] = rev.length
|
|
||||||
hist.append(revobj)
|
|
||||||
pobj['history'] = hist
|
|
||||||
self.root['pages'].append(pobj)
|
|
||||||
def add_page_list(self, pl: Iterable[Page], include_history=True, include_users=False):
|
|
||||||
for p in pl:
|
|
||||||
self.add_page(p, include_history=include_history, include_users=include_users)
|
|
||||||
def export(self):
|
|
||||||
return json.dumps(self.root)
|
|
||||||
|
|
||||||
|
|
||||||
class Importer(object):
|
|
||||||
def __init__(self, dump, *, overwrite_urls = True):
|
|
||||||
self.root = json.loads(dump)
|
|
||||||
self.owner = None
|
|
||||||
self.overwrite_urls = overwrite_urls
|
|
||||||
def claim(self, owner):
|
|
||||||
self.owner = owner
|
|
||||||
def execute(self):
|
|
||||||
no_pages = 0
|
|
||||||
no_revs = 0
|
|
||||||
for pobj in self.root['pages']:
|
|
||||||
purl = pobj.get("url")
|
|
||||||
try:
|
|
||||||
if purl:
|
|
||||||
p2 = db.session.execute(select(Page).where(Page.url == purl)).scalar()
|
|
||||||
if p2:
|
|
||||||
p2.url = None
|
|
||||||
db.session.add(p2)
|
|
||||||
|
|
||||||
p = db.session.execute(insert(Page).values(
|
|
||||||
url = purl if self.overwrite_urls else None,
|
|
||||||
title = pobj['title'],
|
|
||||||
calendar = want_datetime(pobj["calendar"]) if 'calendar' in pobj else None,
|
|
||||||
owner = self.owner.id,
|
|
||||||
flags = pobj.get('flags'),
|
|
||||||
touched = datetime.datetime.now()
|
|
||||||
).returning(Page))
|
|
||||||
p.change_tags(pobj.get('tags'))
|
|
||||||
no_pages += 1
|
|
||||||
|
|
||||||
for revobj in pobj['history']:
|
|
||||||
textref = PageText.create_content(
|
|
||||||
revobj['text']
|
|
||||||
)
|
|
||||||
|
|
||||||
db.session.execute(insert(PageRevision).values(
|
|
||||||
page = p,
|
|
||||||
user_id = self.owner.id,
|
|
||||||
textref = textref,
|
|
||||||
comment = revobj.get('comment'),
|
|
||||||
pub_date = want_datetime(revobj['timestamp']),
|
|
||||||
length = revobj['length']
|
|
||||||
))
|
|
||||||
no_revs += 1
|
|
||||||
|
|
||||||
# one commit per page
|
|
||||||
db.session.commit()
|
|
||||||
except Exception as e:
|
|
||||||
db.session.rollback()
|
|
||||||
sys.excepthook(*sys.exc_info())
|
|
||||||
continue
|
|
||||||
return no_pages, no_revs
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
"""
|
|
||||||
Miscellaneous utilities.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
(C) 2020-2025 Sakuragasaki46.
|
|
||||||
See LICENSE for copying info.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import re
|
|
||||||
from suou import deprecated
|
|
||||||
|
|
||||||
from .constants import SLUG_RE
|
|
||||||
|
|
||||||
@deprecated('use suou.makelist() instead')
|
|
||||||
def makelist(l):
|
|
||||||
if isinstance(l, (str, bytes, bytearray)):
|
|
||||||
return [l]
|
|
||||||
elif hasattr(l, '__iter__'):
|
|
||||||
return list(l)
|
|
||||||
elif l:
|
|
||||||
return [l]
|
|
||||||
else:
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def parse_tag_list(s: str) -> list[str]:
|
|
||||||
l = [x.strip().lower().replace(' ', '-').replace('_', '-').lstrip('#')
|
|
||||||
for x in s.split(',') if x]
|
|
||||||
if any(not re.fullmatch(SLUG_RE, x) for x in l):
|
|
||||||
raise ValueError('illegal characters in tags')
|
|
||||||
return l
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -8,17 +8,11 @@
|
||||||
var textInput = getFirst(document.getElementsByClassName('text-input'));
|
var textInput = getFirst(document.getElementsByClassName('text-input'));
|
||||||
var overTextInput = getFirst(document.getElementsByClassName('over-text-input'));
|
var overTextInput = getFirst(document.getElementsByClassName('over-text-input'));
|
||||||
|
|
||||||
// saving draft
|
|
||||||
var autosaveInterval = null;
|
|
||||||
|
|
||||||
page_info.editing = page_info.editing || {};
|
|
||||||
|
|
||||||
overTextInput.innerHTML = [
|
overTextInput.innerHTML = [
|
||||||
'<span class="oti-modified"> </span>',
|
'<span class="oti-modified"> </span>',
|
||||||
'<span class="oti-charcount">? chars</span>',
|
'<span class="oti-charcount">? chars</span>',
|
||||||
'<span class="oti-fontselect"><select><option value="sans">Sans-serif</option><option value="serif">Serif</option><option value="monospace">Monospace</option></select></span>',
|
'<span class="oti-fontselect"><select><option value="sans">Sans-serif</option><option value="serif">Serif</option><option value="monospace">Monospace</option></select></span>',
|
||||||
//'<span class="oti-linkpage">Link page</span>',
|
//'<span class="oti-linkpage">Link page</span>',
|
||||||
'<span class="oti-draft">' + (localStorage.getItem('draft' + (page_info.editing.page_id || 'new')) !== null? '<a href="javascript:restoreDraft();">Draft found</a>': '') + '</span>'
|
|
||||||
].join(' ');
|
].join(' ');
|
||||||
|
|
||||||
// character counter
|
// character counter
|
||||||
|
|
@ -28,9 +22,8 @@
|
||||||
if(newText != oldText){
|
if(newText != oldText){
|
||||||
oldText = newText;
|
oldText = newText;
|
||||||
|
|
||||||
overTextInput.children[0].innerHTML = newText === originalText? ' ' : '(*)';
|
overTextInput.children[0].innerHTML = newText == originalText? ' ' : '(*)';
|
||||||
overTextInput.children[1].innerHTML = newText.length + ' char' + (newText.length == 1? '' : 's');
|
overTextInput.children[1].innerHTML = newText.length + ' char' + (newText.length == 1? '' : 's');
|
||||||
if (!autosaveInterval) autosaveInterval = setInterval(autosaveText, 30000);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
overTextInput.children[1].innerHTML = originalText.length + ' char' + (originalText.length == 1? '' : 's');
|
overTextInput.children[1].innerHTML = originalText.length + ' char' + (originalText.length == 1? '' : 's');
|
||||||
|
|
@ -60,7 +53,6 @@
|
||||||
var saveButton = document.getElementById('save-button');
|
var saveButton = document.getElementById('save-button');
|
||||||
saveButton.onclick = function(){
|
saveButton.onclick = function(){
|
||||||
window.onbeforeunload = null;
|
window.onbeforeunload = null;
|
||||||
localStorage.removeItem('draft' + (page_info.editing.page_id || 'new'));
|
|
||||||
}
|
}
|
||||||
var previewButton = document.getElementById('preview-button');
|
var previewButton = document.getElementById('preview-button');
|
||||||
previewButton.onclick = function(){
|
previewButton.onclick = function(){
|
||||||
|
|
@ -74,14 +66,4 @@
|
||||||
|
|
||||||
// TODO tag editor
|
// TODO tag editor
|
||||||
var tagsInput = getFirst(document.getElementsByClassName('tags-input'));
|
var tagsInput = getFirst(document.getElementsByClassName('tags-input'));
|
||||||
|
|
||||||
// draft management
|
|
||||||
function autosaveText(){
|
|
||||||
localStorage.setItem('draft' + (page_info.editing.page_id || 'new'), textInput.value);
|
|
||||||
}
|
|
||||||
|
|
||||||
window.restoreDraft = function(){
|
|
||||||
textInput.value = localStorage.getItem('draft' + (page_info.editing.page_id || 'new'));
|
|
||||||
overTextInput.querySelector('.oti-draft').innerHTML = '';
|
|
||||||
}
|
|
||||||
})();
|
})();
|
||||||
161
static/style.css
Normal file
161
static/style.css
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
/* basic styles */
|
||||||
|
body{font-family:sans-serif}
|
||||||
|
.content{margin: 3em 1.3em}
|
||||||
|
|
||||||
|
/* content styles */
|
||||||
|
#firstHeading {font-family: 'Oswald','Anton','Impact',sans-serif; text-align: center;font-size:3em}
|
||||||
|
.inner-content{font-family:serif; margin: 1.7em auto; max-width: 1280px; line-height: 1.9; color: #1f2528}
|
||||||
|
.inner-content em,.inner-content strong{color: black}
|
||||||
|
.inner-content h1{color: #99081f}
|
||||||
|
.inner-content table, .inner-content h2, .inner-content h3, .inner-content h4, .inner-content h5, .inner-content h6{font-family:sans-serif; color: black}
|
||||||
|
.inner-content h3{margin:0.8em 0}
|
||||||
|
.inner-content h4{margin:0.6em 0}
|
||||||
|
.inner-content h5{margin:0.5em 0}
|
||||||
|
.inner-content h6{margin:0.4em 0}
|
||||||
|
.inner-content p{text-indent: 1.9em; margin: 0}
|
||||||
|
.inner-content li{margin: .3em 0}
|
||||||
|
.inner-content blockquote{color:#363636; border-left: 4px solid #ccc;margin-left:0;padding-left:12px}
|
||||||
|
.inner-content table{border:#ccc 1px solid;border-collapse:collapse;line-height: 1.5;overflow-x:auto}
|
||||||
|
.inner-content table > * > tr > th, .inner-content table > tr > th {background-color:#f9f9f9;border:#ccc 1px solid;padding:2px}
|
||||||
|
.inner-content table > * > tr > td, .inner-content table > tr > td {border:#ccc 1px solid;padding:2px}
|
||||||
|
|
||||||
|
|
||||||
|
/* interface styles */
|
||||||
|
.nl-list{list-style:none}
|
||||||
|
.nl-list > li{margin-bottom: 1em}
|
||||||
|
.nl-title{font-size:1.2em; font-weight: 500}
|
||||||
|
.nl-desc{font-size:0.9em;opacity:.75;font-family:serif}
|
||||||
|
.nl-new{margin:6px 0 12px 0;display:flex;justify-content:start; float: right}
|
||||||
|
.nl-new > a{margin-right:12px}
|
||||||
|
.nl-prev,.nl-next{text-align:center}
|
||||||
|
input{border:0;border-bottom:3px solid #ccc;font:inherit;color:#181818;background-color:transparent}
|
||||||
|
input:focus{color:black;border-bottom-color:#09f}
|
||||||
|
input.error{border-bottom-color:#ff1800}
|
||||||
|
input[type="submit"],input[type="reset"],input[type="button"],button{font-family:inherit;border-radius:12px;border:1px solid #ccc;display:inline-block}
|
||||||
|
.submit-primary{color:white;background-color:#37b92e;font-family:inherit;border:1px solid #37b92e;font-size:1.2em;height:2em;min-width:8em}
|
||||||
|
.submit-secondary{color:black;background-color:white;font-family:inherit;border:1px solid #809980;font-size:1.2em;height:2em;min-width:8em}
|
||||||
|
.submit-quick{color:white;background-color:#37b92e;font-family:inherit;border:1px solid #37b92e;font-size:inherit;border-radius:6px}
|
||||||
|
.flash{background-color:#fff2b4;padding:12px;border-radius:4px;border:1px #ffe660 solid}
|
||||||
|
.page-tags p{display:inline-block}
|
||||||
|
.page-tags ul{padding:0;margin:0;list-style:none;display:inline-block}
|
||||||
|
.page-tags ul > li{padding:6px 12px;display:inline-block;margin:0 4px;border-radius:4px;background-color:aliceblue}
|
||||||
|
.page-tags .tag-count{color:#3c3;font-size:smaller;font-weight:600}
|
||||||
|
.search-wrapper {display:flex;width:90%;margin:auto}
|
||||||
|
.search-wrapper > input {flex:1}
|
||||||
|
|
||||||
|
/* Circles extension */
|
||||||
|
.circles-red{color: #e14}
|
||||||
|
.circles-orange{color: #f72}
|
||||||
|
.circles-green{color: #6e4}
|
||||||
|
.circles-yellow{color: #fc6}
|
||||||
|
.circles-list{list-style: none}
|
||||||
|
.circles-list > li{margin: .5em 0;}
|
||||||
|
.circles-list > li::before{font-size: 24px;transform:translatey(50%);font-weight:bold;margin-right:8px}
|
||||||
|
.circles-list > li.circles-red::before{color: #e14; content: '❌︎'}
|
||||||
|
.circles-list > li.circles-orange::before{color: #f72; content: '△'}
|
||||||
|
.circles-list > li.circles-yellow::before{color: #fc6; content: '◇'}
|
||||||
|
.circles-list > li.circles-green::before{color: #6e4; content: '○'}
|
||||||
|
.circles-add-form{display:table}
|
||||||
|
.circles-add-form > div{display:table-row}
|
||||||
|
.circles-add-form > div > *{display:table-cell}
|
||||||
|
.circles-add-form > div > label{text-align:right}
|
||||||
|
.circles-li-code {font-size: 120%}
|
||||||
|
|
||||||
|
/* ContactNova extension */
|
||||||
|
.contactnova-issues {padding-left: 12px; border-left: 4px solid #fc6}
|
||||||
|
.contactnova-col-code {font-size: 1.25em; font-weight: bold}
|
||||||
|
.contactnova-status_1 .material-icons {color: #6e4}
|
||||||
|
.contactnova-status_2 .material-icons {color: #fc6}
|
||||||
|
.contactnova-list td {vertical-align: middle}
|
||||||
|
|
||||||
|
|
||||||
|
/* floating elements */
|
||||||
|
.top-menu{list-style:none;padding:0;margin:0;font-size:0.9em;position:absolute;right:0;top:.5em;text-transform:lowercase}
|
||||||
|
.top-menu li{display:inline-block;padding-right:1em}
|
||||||
|
.toc{float:right}
|
||||||
|
@media (max-width:639px){
|
||||||
|
.toc{display:none}
|
||||||
|
}
|
||||||
|
.backontop{position:fixed;bottom:0;right:0}
|
||||||
|
@media print{
|
||||||
|
.backontop {display:none}
|
||||||
|
}
|
||||||
|
#__top{position:absolute;top:0;left:0}
|
||||||
|
|
||||||
|
/* editor */
|
||||||
|
input.title-input{overflow:visible;font-weight:bold;font-size:2em;width:100%;margin-top:1em}
|
||||||
|
.text-input{font:inherit;border-top:0;border-bottom:4px solid #80e;border-left:0;border-right:0;margin-bottom:12px;width:100%;height:20em}
|
||||||
|
.over-text-input{color:white;background-color:#80e;margin-top:12px;padding:4px}
|
||||||
|
.over-text-input select{padding: 0;border: 0;margin: 0;background: inherit;color: inherit;font: inherit;}
|
||||||
|
.text-input.ti-font-sans{font-family: sans-serif}
|
||||||
|
.text-input.ti-font-serif{font-family: serif}
|
||||||
|
.text-input.ti-font-monospace{font-family:monospace}
|
||||||
|
|
||||||
|
/* images */
|
||||||
|
.fig-right{float:right;clear:right}
|
||||||
|
.fig-gallery{display:inline-block}
|
||||||
|
.fig-right img, .fig-gallery img{width:220px}
|
||||||
|
|
||||||
|
/* links */
|
||||||
|
a:link{color:#239b89}
|
||||||
|
a:visited{color:#2f6a5f}
|
||||||
|
a:hover{color:#0088ff}
|
||||||
|
.metro-links{padding:12px;color:white;background-color:#333}
|
||||||
|
.metro-links a{color:white}
|
||||||
|
.metro-prev{float:left}
|
||||||
|
.metro-next{float:right}
|
||||||
|
.metro-links.metro-1{background-color:red}
|
||||||
|
.metro-links.metro-2{background-color:blue}
|
||||||
|
.metro-links.metro-3{background-color:green}
|
||||||
|
.metro-links.metro-4{background-color:orange}
|
||||||
|
.metro-links.metro-5{background-color:teal}
|
||||||
|
.metro-links.metro-6{background-color:purple}
|
||||||
|
.metro-divider{height:1px;background-color:white;clear:both}
|
||||||
|
.metro-badge{background-color:#333;border-radius:4px;color:white;font-size:80%}
|
||||||
|
|
||||||
|
/* grids */
|
||||||
|
@media (min-width:800px) {
|
||||||
|
.nl-list {display: grid; grid-template-rows: auto; grid-template-columns: 1fr 1fr; column-gap: 1.5em}
|
||||||
|
.nl-list > .nl-prev, .nl-list > .nl-next {grid-column-end: span 2}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* dark theme */
|
||||||
|
body.dark, .dark input, .dark textarea{background-color: #1f1f1f; color: white}
|
||||||
|
.dark .inner-content{color: #e5e5e5}
|
||||||
|
.dark .inner-content em,.dark .inner-content strong,.dark .inner-content h2,.dark .inner-content h3,.dark .inner-content h4,.dark .inner-content h5,.dark .inner-content h6,.dark .inner-content table{color: white}
|
||||||
|
.dark .inner-content h1{color:#ff4860}
|
||||||
|
.dark .inner-content blockquote{color:#cecece;border-left-color:#555}
|
||||||
|
.dark .inner-content table,.dark .inner-content table > * > tr > th,.dark .inner-content table > * > tr > td,.dark .inner-content table > tr > th,.dark .inner-content table > tr > td{border-color:#555}
|
||||||
|
.dark .inner-content table > * > tr > th,.dark .inner-content table > tr > th{background-color:#333;}
|
||||||
|
.dark input[type="text"]{border-bottom-color:#555}
|
||||||
|
.dark input[type="text"]:focus{border-bottom-color:#4bf;color:white}
|
||||||
|
.dark input[type="text"].error{border-bottom-color:#e01400}
|
||||||
|
.dark .submit-primary,.dark .submit-quick{background-color: #5d3; border-color: #5d3}
|
||||||
|
.dark .submit-secondary{color: white; background-color: #1f1f1f; border-color: #9d3}
|
||||||
|
.dark .page-tags .tag-count{color: #ee0}
|
||||||
|
.dark .flash{background-color: #771; border-color: #fd2}
|
||||||
|
.dark .page-tags ul > li{background-color: #555}
|
||||||
|
.dark .text-input{border-bottom-color: #60a}
|
||||||
|
.dark .over-text-input{background-color: #60a}
|
||||||
|
.dark a:link{color:#99cadc}
|
||||||
|
.dark a:visited{color:#a2e2de}
|
||||||
|
.dark a:hover{color:#33ffaa}
|
||||||
|
a.dark-theme-toggle-off{display: none}
|
||||||
|
.dark a.dark-theme-toggle-off{display: inline}
|
||||||
|
.dark a.dark-theme-toggle-on{display: none}
|
||||||
|
|
||||||
|
/* ?????? */
|
||||||
|
.wrap_responsive_cells {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||||
|
/* This is better for small screens, once min() is better supported */
|
||||||
|
/* grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr)); */
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
.wrap_responsive_cells_narrow {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||||
|
/* This is better for small screens, once min() is better supported */
|
||||||
|
/* grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr)); */
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
29
strings.csv
Normal file
29
strings.csv
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
welcome,Welcome to {0}!,Benvenuti in {0}!
|
||||||
|
homepage,Homepage,Pagina iniziale
|
||||||
|
latest-notes,Latest notes,Note più recenti
|
||||||
|
latest-uploads,Latest uploads,Caricamenti più recenti
|
||||||
|
new-note,New note,Crea nota
|
||||||
|
upload-file,Upload file,Carica immagine
|
||||||
|
easter-date-calc,Easter date calculation,Calcolo della data di Pasqua
|
||||||
|
easter,Easter,Pasqua
|
||||||
|
other-dates,Other dates,Altre date
|
||||||
|
jump-to-actions,Jump to actions,Salta alle azioni
|
||||||
|
last-changed,Last changed,Ultima modifica
|
||||||
|
page-id,Page ID,ID pagina
|
||||||
|
action-edit,Edit,Modifica
|
||||||
|
action-history,History,Cronologia
|
||||||
|
tags,Tags,Etichette
|
||||||
|
old-revision-notice,Showing an old revision of the page as of,"È mostrata una revisione vecchia della pagina, risalente al"
|
||||||
|
notes-tagged,Notes tagged,Note con etichetta
|
||||||
|
include-tags,Include tags,Includi etichette
|
||||||
|
notes-tagged-empty,None found :(,Non c’è nulla :(
|
||||||
|
search-no-results,No results for,Nessun risultato per
|
||||||
|
random-page,Random page,Pagina casuale
|
||||||
|
search,Search,Cerca
|
||||||
|
year,Year,Anno
|
||||||
|
calculate,Calculate,Calcola
|
||||||
|
show-all,Show all,Mostra tutto
|
||||||
|
just-now,just now,poco fa
|
||||||
|
n-minutes-ago,{0} minutes ago,{0} minuti fa
|
||||||
|
n-hours-ago,{0} hours ago,{0} ore fa
|
||||||
|
n-days-ago,{0} days ago,{0} giorni fa
|
||||||
|
9
templates/badrequest.html
Normal file
9
templates/badrequest.html
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Bad Request - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Bad request</h1>
|
||||||
|
|
||||||
|
<p>You sent a request the server can’t understand. If you entered the URL manually please check your spelling and try again.</p>
|
||||||
|
{% endblock %}
|
||||||
36
templates/base.html
Normal file
36
templates/base.html
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>{% block title %}{{ app_name }}{% endblock %}</title>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
{% block meta %}{% endblock %}
|
||||||
|
<link rel="stylesheet" href="/static/style.css">
|
||||||
|
<!-- material icons -->
|
||||||
|
<link rel="stylesheet" href="https://cdn.sakuragasaki46.local/common/material-icons.css">
|
||||||
|
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
|
||||||
|
{% block json_info %}{% endblock %}
|
||||||
|
</head>
|
||||||
|
<body{% if request.cookies.get('dark') == '1' %} class="dark"{% endif %}>
|
||||||
|
<div id="__top"></div>
|
||||||
|
<div class="content">
|
||||||
|
{% for msg in get_flashed_messages() %}
|
||||||
|
<div class="flash">{{ msg }}</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% block content %}{% endblock %}
|
||||||
|
</div>
|
||||||
|
<ul class="top-menu">
|
||||||
|
<li class="dark-theme-toggle-anchor"><a href="{{ url_for('theme_switch', next=request.path) }}" onclick="toggleDarkTheme(true);return false" class="dark-theme-toggle-on" title="Dark theme"><span class="material-icons">brightness_3</span></a><a href="{{ url_for('theme_switch', next=request.path) }}" onclick="toggleDarkTheme(false);return false" class="dark-theme-toggle-off" title="Light theme"><span class="material-icons">brightness_5</span></a><script>function toggleDarkTheme(a){document.cookie="dark="+(+a)+";max-age=31556952;path=/;SameSite=Strict";document.body.classList.toggle("dark",a)}</script></li>
|
||||||
|
<li><a href="/" title="{{ T('homepage') }}"><span class="material-icons">home</span></a></li>
|
||||||
|
<li><a href="/search/" title="{{ T('search') }}" rel="nofollow"><span class="material-icons">search</span></a></li>
|
||||||
|
<li><a href="/p/random/" title="{{ T('random-page') }}" rel="nofollow"><span class="material-icons">shuffle</span></a></li>
|
||||||
|
<li><a href="/create/" title="{{ T('new-note') }}" rel="nofollow"><span class="material-icons">create</span></a></li>
|
||||||
|
</ul>
|
||||||
|
<div class="footer">
|
||||||
|
<div class="footer-copyright">© 2020–2021 Sakuragasaki46.</div>
|
||||||
|
<div class="footer-actions" id="page-actions">{% block actions %}{% endblock %}</div>
|
||||||
|
</div>
|
||||||
|
<div class="backontop"><a href="#__top" title="Back on top"><span class="material-icons">arrow_upward</span></a></div>
|
||||||
|
{% block scripts %}{% endblock %}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
58
templates/circles/add.html
Normal file
58
templates/circles/add.html
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Circles – {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<form method="POST" class="circles-add-form">
|
||||||
|
{% if returnto %}<input type="hidden" name="returnto" value="{{ returnto }}">{% endif %}
|
||||||
|
<div>
|
||||||
|
<label>#</label>
|
||||||
|
<input type="number" name="code" placeholder="00000" required="" maxlength="6" value="{{ pl.code if pl else '' }}" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Display name</label>
|
||||||
|
<input type="text" name="display_name" placeholder="Display name" required="" value="{{ pl.display_name if pl else '' }}" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>First name</label>
|
||||||
|
<input type="text" name="first_name" placeholder="First name" value="{{ pl.first_name if pl else '' }}" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Last name</label>
|
||||||
|
<input type="text" name="last_name" placeholder="Last name" value="{{ pl.last_name if pl else '' }}" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Type</label>
|
||||||
|
<select name="type">
|
||||||
|
<option disabled=""{% if not pl %} selected=""{% endif %}>(Choose)</option>
|
||||||
|
{% set typ_list = [
|
||||||
|
'INTJ', 'INTP', 'INFJ', 'INFP', 'ENTJ', 'ENTP',
|
||||||
|
'ENFJ', 'ENFP', 'ISTJ', 'ISTP', 'ISFJ', 'ISFP',
|
||||||
|
'ESTJ', 'ESTP', 'ESFJ', 'ESFP', '1x38B'] %}
|
||||||
|
{% for typ in typ_list %}
|
||||||
|
<option value="{{ typ }}"{% if pl and typ == pl.type %} selected=""{% endif %}>{{ typ }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Status</label>
|
||||||
|
<select name="status">
|
||||||
|
<option value="-1">Red</option>
|
||||||
|
<option value="0"{% if pl and 0 == pl.status %} selected=""{% endif %}>Orange</option>
|
||||||
|
<option value="1"{% if pl and 1 == pl.status %} selected=""{% endif %}>Yellow</option>
|
||||||
|
<option value="2"{% if pl and 2 == pl.status %} selected=""{% endif %}>Green</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Area</label>
|
||||||
|
<input type="number" name="area" value="{{ pl.area if pl and pl.area else 0 }}">
|
||||||
|
</div>
|
||||||
|
<input type="submit" value="Save">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% if not pl %}
|
||||||
|
<p>Looking for mass addition? Try <a href="/circles/csv">CSV adding form</a> instead.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
21
templates/circles/csv.html
Normal file
21
templates/circles/csv.html
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Circles – {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<form method="POST" enctype="multipart/form-data">
|
||||||
|
<p>Enter the contacts you want to bulk add, in comma-separated values (CSV) format, one by line.<br />Order matters.</p>
|
||||||
|
<textarea name="text" style="width:100%;height:20em" placeholder="00000,First,Last,Display,Type"></textarea>
|
||||||
|
<input type="checkbox" disabled="" id="autoConsent" name="consent" value="y" />
|
||||||
|
<input type="submit" value="Save" />
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
setTimeout(() => {
|
||||||
|
let ac = document.getElementById("autoConsent");
|
||||||
|
ac.disabled = false;
|
||||||
|
ac.selected = false;
|
||||||
|
}, 10000)
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
65
templates/circles/list.html
Normal file
65
templates/circles/list.html
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Circles – {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<p>Showing: <strong>{{ cat }}</strong></p>
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<legend>Show by:</legend>
|
||||||
|
<p><strong>Type</strong>:
|
||||||
|
{% set typ_list = [
|
||||||
|
'INTJ', 'INTP', 'INFJ', 'INFP', 'ENTJ', 'ENTP',
|
||||||
|
'ENFJ', 'ENFP', 'ISTJ', 'ISTP', 'ISFJ', 'ISFP',
|
||||||
|
'ESTJ', 'ESTP', 'ESFJ', 'ESFP'] %}
|
||||||
|
{% for t in typ_list %}
|
||||||
|
<a href="/circles/{{ t.lower() }}">{{ t }}</a> ·
|
||||||
|
{% endfor %}
|
||||||
|
</p>
|
||||||
|
<p><strong>Status</strong>:
|
||||||
|
{% set typ_list = ['Green', 'Yellow', 'Orange', 'Red'] %}
|
||||||
|
{% for t in typ_list %}
|
||||||
|
<a href="/circles/{{ t.lower() }}">{{ t }}</a> ·
|
||||||
|
{% endfor %}
|
||||||
|
</p>
|
||||||
|
<p><strong>Area</strong>:
|
||||||
|
{% for t in range(1, 13) %}
|
||||||
|
<a href="/circles/area-{{ t }}">{{ t }}</a> ·
|
||||||
|
{% endfor %}
|
||||||
|
<a href="/circles/no-area">Unassigned</a>
|
||||||
|
</p>
|
||||||
|
<p><a href="/circles/stats">Stats</a> · <a href="/circles/new">Add new</a>.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if count > people.count() %}
|
||||||
|
<p>Showing <strong>{{ people.count() }}</strong> people of <strong>{{ count }}</strong> total.</p>
|
||||||
|
{% if count > pageno * 50 %}
|
||||||
|
<p><a href="?page={{ pageno + 1 }}" rel="nofollow">Next page</a>{% if pageno > 1 %} · <a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a>{% endif %}</p>
|
||||||
|
{% elif pageno > 1 %}
|
||||||
|
<a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a></p>
|
||||||
|
{% endif %}
|
||||||
|
{% else %}
|
||||||
|
<p><strong>{{ count }}</strong> people.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<ul class="circles-list">
|
||||||
|
{% for p in people %}
|
||||||
|
<li class="circles-{{ 'red' if p.status == -1 else 'green' if p.status == 2 else 'yellow' if p.status == 1 else 'orange' }}">
|
||||||
|
<span class="circles-li-code">{{ p.code }}</span>
|
||||||
|
<span>{{ p.display_name }} – {{ p.type }} – {% if p.area %}Area {{ p.area }}{% else %}No area{% endif %} (<a href="/circles/edit/{{ p.code }}">edit</a>)</span>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
{% if count > people.count() %}
|
||||||
|
<p>Showing <strong>{{ people.count() }}</strong> people of <strong>{{ count }}</strong> total.</p>
|
||||||
|
{% if count > pageno * 50 %}
|
||||||
|
<p><a href="?page={{ pageno + 1 }}" rel="nofollow">Next page</a>{% if pageno > 1 %} · <a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a>{% endif %}</p>
|
||||||
|
{% elif pageno > 1 %}
|
||||||
|
<a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a></p>
|
||||||
|
{% endif %}
|
||||||
|
{% else %}
|
||||||
|
<p><strong>{{ count }}</strong> people.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
30
templates/circles/stats.html
Normal file
30
templates/circles/stats.html
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Circles – {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Stats</h1>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>All people: <strong>{{ count }}</strong></li>
|
||||||
|
<li>People by type:</li>
|
||||||
|
<ul class="wrap_responsive_cells_narrow">
|
||||||
|
{% for k in typed_count.items() %}
|
||||||
|
<li>{{ k[0] }}: <strong>{{ k[1] }}</strong></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
<li>People by status zone:</li>
|
||||||
|
<ul>
|
||||||
|
{% for k in status_count.items() %}
|
||||||
|
<li>{{ k[0] }}: <strong>{{ k[1] }}</strong></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
<li>People by area:</li>
|
||||||
|
<ul class="wrap_responsive_cells_narrow">
|
||||||
|
{% for k in area_count.items() %}
|
||||||
|
<li>Area {{ k[0] }}: <strong>{{ k[1] }}</strong></li>
|
||||||
|
{% endfor %}
|
||||||
|
<li>No area: <strong>{{ no_area_count }}</strong></li>
|
||||||
|
</ul>
|
||||||
|
</ul>
|
||||||
|
{% endblock %}
|
||||||
59
templates/contactnova/list.html
Normal file
59
templates/contactnova/list.html
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}List of contacts – {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<p>Showing: <strong>{{ cat }}</strong> · <a href="/kt/new">New contact</a></p>
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<legend>Show by:</legend>
|
||||||
|
<p><strong>Letter</strong>:
|
||||||
|
{% set typ_list = 'ABCDEFGHIJKLMNOPQRSTUVWYZ' %}
|
||||||
|
{% for t in typ_list %}
|
||||||
|
<a href="/kt/{{ t }}">{{ t }}</a> ·
|
||||||
|
{% endfor %}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<a href="/kt/">All</a> ·
|
||||||
|
<a href="/kt/expired">Expired</a> ·
|
||||||
|
<a href="/kt/ok">Sane</a>
|
||||||
|
</p>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
{% if count > people.count() %}
|
||||||
|
<p>Showing <strong>{{ people.count() }}</strong> people of <strong>{{ count }}</strong> total.</p>
|
||||||
|
{% if count > pageno * 50 %}
|
||||||
|
<p><a href="?page={{ pageno + 1 }}" rel="nofollow">Next page</a>{% if pageno > 1 %} · <a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a>{% endif %}</p>
|
||||||
|
{% elif pageno > 1 %}
|
||||||
|
<a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a></p>
|
||||||
|
{% endif %}
|
||||||
|
{% else %}
|
||||||
|
<p><strong>{{ count }}</strong> people.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<table class="contactnova-list">
|
||||||
|
<thead>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for p in people %}
|
||||||
|
<tr class="contactnova-status_{{ p.status }}">
|
||||||
|
<td><span class="material-icons">{{ p.status_str() }}</span></td>
|
||||||
|
<td class="contactnova-col-code"><a href="/kt/{{ p.code }}">{{ p.code }}</a></td>
|
||||||
|
<td>{{ p.display_name }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
{% if count > people.count() %}
|
||||||
|
<p>Showing <strong>{{ people.count() }}</strong> people of <strong>{{ count }}</strong> total.</p>
|
||||||
|
{% if count > pageno * 50 %}
|
||||||
|
<p><a href="?page={{ pageno + 1 }}" rel="nofollow">Next page</a>{% if pageno > 1 %} · <a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a>{% endif %}</p>
|
||||||
|
{% elif pageno > 1 %}
|
||||||
|
<a href="?page={{ pageno - 1 }}" rel="nofollow">Prev page</a></p>
|
||||||
|
{% endif %}
|
||||||
|
{% else %}
|
||||||
|
<p><strong>{{ count }}</strong> people.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
72
templates/contactnova/new.html
Normal file
72
templates/contactnova/new.html
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Create new contact – {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<form method="POST" class="circles-add-form">
|
||||||
|
{% if returnto %}<input type="hidden" name="returnto" value="{{ returnto }}">{% endif %}
|
||||||
|
{% if not pl %}
|
||||||
|
<div>
|
||||||
|
<label>Letter</label>
|
||||||
|
<select id="ktCodeLetter" name="letter">
|
||||||
|
<option value="-" disabled="" selected="">(Choose)</option>
|
||||||
|
{% set typ_list = 'ABCDEFGHIJKLMNOPQRSTUVWYZ' %}
|
||||||
|
{% for t in typ_list %}
|
||||||
|
<option value="{{ t }}">{{ t }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<div>
|
||||||
|
<label>Code</label>
|
||||||
|
<strong id="ktNewCode">---</strong>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Display name</label>
|
||||||
|
<input name="display_name" maxlength="50"{% if pl %} value="{{ pl.display_name }}"{% endif %}>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Status</label>
|
||||||
|
<select name="status">
|
||||||
|
{% set statuses = {
|
||||||
|
0: 'Variable',
|
||||||
|
1: 'OK',
|
||||||
|
2: 'Issues',
|
||||||
|
} %}
|
||||||
|
{% for k, v in statuses.items() %}
|
||||||
|
<option value="{{ k }}"{% if pl and pl.status == k %} selected=""{% endif %}>{{ v }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Issues</label>
|
||||||
|
<textarea maxlength="500" name="issues">{{ pl and pl.issues }}</textarea>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Description</label>
|
||||||
|
<textarea maxlength="5000" name="description">{{ pl and pl.description }}</textarea>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Due</label>
|
||||||
|
<input name="due" required="" type="date" value="{{ pl.due if pl else pl_date }}" min="2020-01-01" />
|
||||||
|
</div>
|
||||||
|
<input type="submit" id="ktSubmit" value="Save">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
{% if not pl %}
|
||||||
|
ktSubmit.disabled = true;
|
||||||
|
{% endif %}
|
||||||
|
ktCodeLetter.onchange = function(){
|
||||||
|
let x = new XMLHttpRequest;
|
||||||
|
x.open('GET', '/kt/_newcode/' + ktCodeLetter.value);
|
||||||
|
x.onreadystatechange = () => {
|
||||||
|
if (x.readyState === XMLHttpRequest.DONE && x.status == 200) {
|
||||||
|
ktNewCode.textContent = x.responseText;
|
||||||
|
ktSubmit.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
x.send();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
24
templates/contactnova/single.html
Normal file
24
templates/contactnova/single.html
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Contact {{ p.code }} – {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>{{ p.code }}</h1>
|
||||||
|
|
||||||
|
<p>aka: <strong>{{ p.display_name }}</strong></p>
|
||||||
|
|
||||||
|
{% if p.issues %}
|
||||||
|
<p class="contactnova-issues">{{ p.issues }}</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<p class="contactnova-description">
|
||||||
|
{{ p.description or "No description available." |linebreaks }}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p> </p>
|
||||||
|
|
||||||
|
<p>Expires: {{ p.due.strftime('%B %-d, %Y') }}</p>
|
||||||
|
|
||||||
|
<p><a href="/kt/">Back</a> · <a href="/kt/edit/{{ p.code }}?returnto=/kt/{{ p.code }}">Edit contact</a></p>
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
29
templates/easter.html
Normal file
29
templates/easter.html
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{{ T('easter-date-calc') }} - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>{{ T('easter-date-calc') }}</h1>
|
||||||
|
|
||||||
|
<form>
|
||||||
|
<div>
|
||||||
|
<label for="y">{{ T('year') }}: </label>
|
||||||
|
<input type="text" name="y" value="{{ y }}">
|
||||||
|
<input type="submit" value="{{ T('calculate') }}" class="submit-quick">
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% if easter_dates %}
|
||||||
|
<div class="easter-results">
|
||||||
|
<p class="easter-date">{{ T('easter') }}: <strong>{{ easter_dates['easter'].strftime('%B %-d, %Y') }}</strong></p>
|
||||||
|
|
||||||
|
<h2>{{ T('other-dates') }}</h2>
|
||||||
|
<ul>
|
||||||
|
<li>Mercoledì delle Ceneri: <strong>{{ easter_dates['ceneri'].strftime('%B %-d, %Y') }}</strong></li>
|
||||||
|
<li>Ascensione: <strong>{{ easter_dates['ascensione'].strftime('%B %-d, %Y') }}</strong></li>
|
||||||
|
<li>Pentecoste: <strong>{{ easter_dates['pentecoste'].strftime('%B %-d, %Y') }}</strong></li>
|
||||||
|
<li>Prima Domenica d'Avvento: <strong>{{ easter_dates['avvento1'].strftime('%B %-d, %Y') }}</strong></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
59
templates/edit.html
Normal file
59
templates/edit.html
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
|
||||||
|
{% block title %}
|
||||||
|
{% if pl_title %}Editing “{{ pl_title }}”
|
||||||
|
{% else %}Edit note{% endif %}
|
||||||
|
- {{ app_name }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block meta %}
|
||||||
|
<meta name="robots" content="noindex,nofollow" />
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block json_info %}<script>window.page_info={{ ( pl_js_info or {} )|tojson|safe }};</script>{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
{% if preview %}
|
||||||
|
<h1>{{ pl_title }} (preview)</h1>
|
||||||
|
|
||||||
|
<div class="preview-area">
|
||||||
|
<div class="preview-warning">
|
||||||
|
Remember this is only a preview.
|
||||||
|
<strong>Your changes were not saved yet!</strong>
|
||||||
|
<a href="#editing-area">Jump to editing area</a></div>
|
||||||
|
<div class="inner-content">{{ preview|safe }}</div>
|
||||||
|
<div style="clear:both"></div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="POST">
|
||||||
|
<div>
|
||||||
|
<label for="title">URL: </label>
|
||||||
|
<input type="text" name="url" class="url-input" placeholder="No URL" maxlength="64" value="{{ pl_url or '' }}">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="text" required name="title" placeholder="Title (required)" class="title-input" maxlength="256" value="{{ pl_title }}">
|
||||||
|
</div>
|
||||||
|
<div id="editing-area">
|
||||||
|
<div class="pre-text-input">
|
||||||
|
<p>This editor is using Markdown for text formatting (e.g. bold, italic, headers and tables). <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" rel="nofollow">More info on Markdown</a>.</p>
|
||||||
|
</div>
|
||||||
|
<div class="over-text-input"></div>
|
||||||
|
<textarea name="text" class="text-input">{{ pl_text }}</textarea>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="tags">Tags (comma separated):</label>
|
||||||
|
<input type="text" name="tags" class="tags-input" placeholder="No tags" value="{{ pl_tags }}">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="submit" value="Save" id="save-button" class="submit-primary">
|
||||||
|
<input type="submit" name="preview" value="Preview" id="preview-button" class="submit-secondary">
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}
|
||||||
|
<script src="/static/edit.js"></script>
|
||||||
|
{% endblock %}
|
||||||
20
templates/exportpages.html
Normal file
20
templates/exportpages.html
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Export pages - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Export pages</h1>
|
||||||
|
|
||||||
|
<p>You can export how many pages you want, that will be downloaded in JSON format and can be imported in another {{ app_name }} instance.</p>
|
||||||
|
|
||||||
|
<p>In order to add page to export list, please enter exact title, /url, #tag or +id. Entering a tag will add all pages with that tag to list. Each page or tag is separated by a newline.</p>
|
||||||
|
|
||||||
|
<form method="POST">
|
||||||
|
<div>
|
||||||
|
<textarea style="height:20em;width:100%" name="export-list" placeholder="Title, /url, #tag, or +id, newline-separated"></textarea>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="submit" value="Download">
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
9
templates/forbidden.html
Normal file
9
templates/forbidden.html
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Access Denied - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Forbidden</h1>
|
||||||
|
|
||||||
|
<p>You don’t have permission to access this resource.</p>
|
||||||
|
{% endblock %}
|
||||||
21
templates/history.html
Normal file
21
templates/history.html
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Page history - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block meta %}
|
||||||
|
<meta name="robots" content="noindex,nofollow" />
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Page history for "{{ p.title }}"</h1>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
{% for rev in history %}
|
||||||
|
<li><a href="/history/revision/{{ rev.id }}/">
|
||||||
|
#{{ rev.id }}
|
||||||
|
·
|
||||||
|
{{ rev.pub_date.strftime("%B %-d, %Y %H:%M:%S") }}
|
||||||
|
</a></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
{% endblock %}
|
||||||
38
templates/home.html
Normal file
38
templates/home.html
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{{ T('homepage') }} - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>{{ T('welcome').format(app_name) }}</h1>
|
||||||
|
|
||||||
|
<div class="nl-new">
|
||||||
|
<a href="/create/"><button class="submit-primary">{{ T('new-note') }}</button></a>
|
||||||
|
<a href="/upload/"><button class="submit-secondary">{{ T('upload-file') }}</button></a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>{{ T('latest-notes') }}</h2>
|
||||||
|
|
||||||
|
<br style="clear:both">
|
||||||
|
<ul class="nl-list">
|
||||||
|
{% for n in new_notes %}
|
||||||
|
<li>
|
||||||
|
<a href="{{ n.get_url() }}" class="nl-title">{{ n.title }}</a>
|
||||||
|
<p class="nl-desc">{{ n.short_desc() }}</p>
|
||||||
|
{% if n.tags %}
|
||||||
|
<p class="nl-tags">{{ T('tags') }}:
|
||||||
|
{% for tag in n.tags %}
|
||||||
|
{% set tn = tag.name %}
|
||||||
|
<a href="/tags/{{ tn }}/" class="nl-tag">#{{ tn }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
<li><a href="/p/most_recent/">{{ T('show-all') }}</a></li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>{{ T('latest-uploads') }}</h2>
|
||||||
|
|
||||||
|
{# TODO security flaw; find a way to do this in a more safe manner! #}
|
||||||
|
{{ gallery|safe }}
|
||||||
|
{% endblock %}
|
||||||
14
templates/includes/nl_item.html
Normal file
14
templates/includes/nl_item.html
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
<p class="nl-title">
|
||||||
|
<a href="{{ n.get_url() }}" class="nl-title">{{ n.title }}</a>
|
||||||
|
</p>
|
||||||
|
<p class="nl-desc">{{ n.short_desc() }}</p>
|
||||||
|
<p class="nl-tags">Tags:
|
||||||
|
{% for tag in n.tags %}
|
||||||
|
{% set tn = tag.name %}
|
||||||
|
{% if hl_tag_name and tn == hl_tag_name %}
|
||||||
|
<strong class="nl-tag-hl">#{{ tn }}</strong>
|
||||||
|
{% else %}
|
||||||
|
<a href="/tags/{{ tn }}/" class="nl-tag">#{{ tn }}</a>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
</p>
|
||||||
27
templates/listrecent.html
Normal file
27
templates/listrecent.html
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Notes by date</h1>
|
||||||
|
|
||||||
|
<p class="nl-pagination">Showing results <strong>{{ page_n * 20 - 19 }}</strong> to <strong>{{ min(page_n * 20, total_count) }}</strong> of <strong>{{ total_count }}</strong> total.</p>
|
||||||
|
|
||||||
|
<ul class="nl-list">
|
||||||
|
{% if page_n > 1 %}
|
||||||
|
<li class="nl-prev"><a href="/p/most_recent/{{ page_n - 1 }}">« Previous page</a></li>
|
||||||
|
{% endif %}
|
||||||
|
{% for n in notes %}
|
||||||
|
<li>
|
||||||
|
<a href="{{ n.get_url() }}" class="nl-title">{{ n.title }}</a>
|
||||||
|
<p class="nl-desc">{{ n.short_desc() }}</p>
|
||||||
|
<p class="nl-tags">Tags:
|
||||||
|
{% for tag in n.tags %}
|
||||||
|
<a href="/tags/{{ tag.name }}/" class="nl-tag">#{{ tag.name }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
{% if page_n <= total_count // 20 %}
|
||||||
|
<li class="nl-next"><a href="/p/most_recent/{{ page_n + 1 }}/">Next page »</a></li>
|
||||||
|
{% endif %}
|
||||||
|
</ul>
|
||||||
|
{% endblock %}
|
||||||
40
templates/listtag.html
Normal file
40
templates/listtag.html
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Notes tagged #{{ tagname }} - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>{{ T('notes-tagged') }} #{{ tagname }}</h1>
|
||||||
|
|
||||||
|
{% if total_count > 0 %}
|
||||||
|
<p class="nl-pagination">Showing results <strong>{{ page_n * 20 - 19 }}</strong> to <strong>{{ min(page_n * 20, total_count) }}</strong> of <strong>{{ total_count }}</strong> total.</p>
|
||||||
|
|
||||||
|
<ul class="nl-list">
|
||||||
|
{% if page_n > 1 %}
|
||||||
|
<li class="nl-prev"><a href="/tags/{{ tagname }}/{{ page_n - 1 }}/">« Previous page</a></li>
|
||||||
|
{% endif %}
|
||||||
|
{% for n in tagged_notes %}
|
||||||
|
<li>
|
||||||
|
<a href="{{ n.get_url() }}" class="nl-title">{{ n.title }}</a>
|
||||||
|
<p class="nl-desc">{{ n.short_desc() }}</p>
|
||||||
|
<p class="nl-tags">Tags:
|
||||||
|
{% for tag in n.tags %}
|
||||||
|
{% set tn = tag.name %}
|
||||||
|
{% if tn == tagname %}
|
||||||
|
<strong class="nl-tag-hl">#{{ tn }}</strong>
|
||||||
|
{% else %}
|
||||||
|
<a href="/tags/{{ tn }}/" class="nl-tag">#{{ tn }}</a>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
{% if page_n < total_count // 20 %}
|
||||||
|
<li class="nl-next"><a href="/tags/{{ tagname }}/{{ page_n + 1 }}/">Next page »</a></li>
|
||||||
|
{% endif %}
|
||||||
|
</ul>
|
||||||
|
{% else %}
|
||||||
|
<p class="nl-placeholder">{{ T('notes-tagged-empty') }}</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
9
templates/notfound.html
Normal file
9
templates/notfound.html
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Not found - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Not Found</h1>
|
||||||
|
|
||||||
|
<p>The url at <strong>{{ request.path }}</strong> does not exist.</p>
|
||||||
|
{% endblock %}
|
||||||
31
templates/search.html
Normal file
31
templates/search.html
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{% if q %}Search results for "{{ q }}"{% else %}Search{% endif %} - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Search</h1>
|
||||||
|
|
||||||
|
<form method="POST">
|
||||||
|
<div class="search-wrapper">
|
||||||
|
<label for="q">Search for: </label>
|
||||||
|
<input type="search" name="q" value="{{ q }}" class="search-input">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="include-tags" value="1" {% if pl_include_tags %}checked{% endif %}>
|
||||||
|
<label for="include-tags">{{ T('include-tags') }}</label>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% if results %}
|
||||||
|
<h2>Search results for <em>{{ q }}</em></h2>
|
||||||
|
|
||||||
|
<ul class="nl-list">
|
||||||
|
{% for n in results %}
|
||||||
|
<li>{% include "includes/nl_item.html" %}</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
{% elif q %}
|
||||||
|
<h2>{{ T('search-no-results') }} <em>{{ q }}</em></h2>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
15
templates/stats.html
Normal file
15
templates/stats.html
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Statistics - {{ app_name }}{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Statistics</h1>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>Number of pages: <strong>{{ notes_count }}</strong></li>
|
||||||
|
<li>Number of pages with URL set: <strong>{{ notes_with_url }}</strong></li>
|
||||||
|
<li>Number of uploads: <strong>{{ upload_count }}</strong></li>
|
||||||
|
<li>Number of revisions: <strong>{{ revision_count }}</strong></li>
|
||||||
|
<li>Average revisions per page: <strong>{{ (revision_count / notes_count)|round(2) }}</strong></li>
|
||||||
|
</ul>
|
||||||
|
{% endblock %}
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue