Compare commits

...

138 Commits

Author SHA1 Message Date
Matthew Wild
7411f4a9e1 prosodyclient: Use empty name if none provided by the server
In parallel, I have updated the server to use the group name for groups with
no name (the MUCs with no name are typically the default auto-created group
MUC).
2023-12-14 12:43:59 +00:00
Matthew Wild
d63ae4768a infra: Fix string to use correct translation function name 2023-12-14 12:43:52 +00:00
Weblate
92a8da724f Update translation files
Updated by "Update PO files to match POT (msgmerge)" hook in Weblate.

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/
2023-12-12 18:25:32 +00:00
Matthew Wild
ea3a081b6c Merge pull request #167 from snikket-im/fix/remove-useless-qr-js
Remove broken/needless JS from certain pages
2023-12-12 18:25:20 +00:00
Matthew Wild
0647ba2601 Remove broken/needless JS from certain pages 2023-12-12 18:24:01 +00:00
Kim Alvefur
2769036f94 Translated using Weblate (Swedish)
Currently translated at 100.0% (361 of 361 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/sv/
2023-12-09 16:59:59 +00:00
Weblate
c76befad1c Update translation files
Updated by "Update PO files to match POT (msgmerge)" hook in Weblate.

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/
2023-12-08 12:14:28 +00:00
Matthew Wild
74ecfb8653 Merge pull request #166 from snikket-im/feature/admin-users-ui-updates-dec-23
Admin user management UI updates (Dec 23)
2023-12-08 12:14:19 +00:00
Matthew Wild
55b195cd7f Update translations 2023-12-08 12:08:43 +00:00
Matthew Wild
46a7d0c37d Fix some type annotations 2023-12-08 12:06:43 +00:00
Matthew Wild
c63b95c6e0 Align avatar flush with left edge of container 2023-12-08 11:42:30 +00:00
Matthew Wild
6848691141 css: Remove avatar border and round the edges to match the app 2023-12-08 11:42:03 +00:00
Matthew Wild
1e83881a24 Ensure we only have a single primary button to reduce confusion 2023-12-08 11:12:26 +00:00
Matthew Wild
35e6bec328 Improvements for admin user listing view 2023-12-08 11:11:31 +00:00
Matthew Wild
d345f0d98d css: Fix dark mode contrast issue for legend text 2023-12-08 11:11:02 +00:00
Matthew Wild
f5ccb7d858 admin: Support for unlocking/restoring locked/deleted user accounts 2023-12-08 11:10:32 +00:00
Matthew Wild
f7c8bccfa2 import-icons.sh: Use sensible defaults where possible 2023-12-08 10:52:48 +00:00
Matthew Wild
e5d06877a4 prosodyclient: Update for new mod_http_admin_api (5c589fab6f53)
This adds new features including:

- User account enabled/disabled status (read and write)
- Deletion status (if an account is scheduled for deletion)
- Avatar metadata
2023-12-08 10:50:23 +00:00
Matthew Wild
e7ed9dd176 infra: Extend time/date utilities 2023-12-08 10:50:06 +00:00
Matthew Wild
6778557db8 On success, return to user listing (edit is complete) 2023-12-08 10:49:26 +00:00
Matthew Wild
73f3f25515 Add lock_open and restore_from_trash icons 2023-12-08 10:45:08 +00:00
Matthew Wild
bd66600d05 Merge pull request #165 from snikket-im/feature/multiple-circle-mucs
Support circles with multiple group chats, remove default group chat
2023-11-06 14:26:11 +00:00
Matthew Wild
db363367da Support circles with multiple group chats, remove default group chat 2023-11-06 13:52:30 +00:00
Matthew Wild
7ce13b55ac Merge pull request #162 from snikket-im/feature/policies-and-contacts
Add policy URLs and contact addresses for instances in the relevant places
2023-10-25 16:19:44 +01:00
Matthew Wild
d6d4bb5afb Add policy URLs and contact addresses for instances in the relevant places 2023-10-25 16:18:12 +01:00
Kim Alvefur
da52771ebe Merge pull request #161 from Zash/fix-logout
Fix revokation of token on logout
2023-10-21 15:57:46 +02:00
Kim Alvefur
e39b6ca8bb Fix revokation of token on logout
In OAuth 2.0, you don't authenticate with the revocation endpoint using
the token you are revoking, but rather the OAuth client credentials.
2023-10-07 17:39:37 +02:00
Kim Alvefur
14368c5e9a Merge pull request #158 from Zash/prosody-split-user-roles
Update for role changes in Prosody
2023-10-07 14:17:58 +02:00
Kim Alvefur
2cdcf7f282 Update for role changes in Prosody
See https://hg.prosody.im/trunk/rev/082c7d856e61
2023-10-07 12:59:43 +02:00
Kim Alvefur
0f1e76e38c Merge pull request #157 from Zash/debian12
Switch base image to Debian 12
2023-10-07 12:58:58 +02:00
Kim Alvefur
ad9af20f12 Workaround for Flask context change 2023-10-04 23:27:05 +02:00
Kim Alvefur
9672cd6870 Install as many packages as possible from Debian
The only missing piece appears to be environ-config.

This **fails to start** with

```
ImportError: cannot import name '_app_ctx_stack' from 'quart' (/usr/lib/python3/dist-packages/quart/__init__.py)
```
2023-10-04 23:27:05 +02:00
Kim Alvefur
d3a6be7bec Switch base image to Debian 12 2023-08-07 08:47:55 +02:00
Kim Alvefur
7a4b56914c Switch to sassc for CSS building
Because https://github.com/Kronuz/pyScss/pull/426 is not yet in a
release, also just look at the diffstat!
2023-08-02 22:35:32 +02:00
Roberto Resoli
0f74b1b8f2 Translated using Weblate (Italian)
Currently translated at 91.8% (294 of 320 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/it/
2023-07-13 11:17:54 +00:00
misiek
df78e8a8b0 Translated using Weblate (Polish)
Currently translated at 100.0% (320 of 320 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/pl/
2023-04-04 14:11:31 +00:00
Kim Alvefur
77ccdd5eed Translated using Weblate (Swedish)
Currently translated at 100.0% (320 of 320 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/sv/
2023-04-02 15:17:18 +00:00
uira
54b6cad7cd Translated using Weblate (Indonesian)
Currently translated at 100.0% (320 of 320 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/id/
2023-04-02 15:17:15 +00:00
Jonas Schäfer
fbb618c178 Translated using Weblate (German)
Currently translated at 100.0% (320 of 320 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/de/
2023-04-01 11:13:44 +00:00
Weblate
bd3d56851b Update translation files
Updated by "Update PO files to match POT (msgmerge)" hook in Weblate.

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/
2023-04-01 10:17:56 +00:00
Jonas Schäfer
c475b83c02 Merge pull request #154 from snikket-im/feature/protect-circle-deletion
Add confirmation step to circle deletion
2023-04-01 10:22:23 +02:00
Jonas Schäfer
d9b73055a8 Add confirmation step to circle deletion
Deleting a circle is highly destructive. It removes the group chat
alongside history, as well as the user list. It should definitely be
protected by a confirmation dialogue, I have no clue why it wasn't.

Fixes #153.
2023-04-01 10:08:52 +02:00
Matthew Wild
f37270594e Merge pull request #152 from snikket-im/fix/role-config
Follow new role scheme in Prosody
2023-03-29 20:16:36 +01:00
Jonas Schäfer
fcfcdbeb23 Follow new role scheme in Prosody
Prosody changed its role scheme to only support a single primary role
for each user. In addition, the names of the built-in roles have been
changed. We thus follow those changes to be compatible with the most
recent trunk.

One open question is whether we should switch admin -> operator here,
too (operator being a server-wide admin), but so far there's no need
to.
2023-03-29 18:42:53 +02:00
Jonas Schäfer
fd566b7f30 Merge pull request #151 from snikket-im/fix/user-listing-roles
Make AdminUserInfo compatible with new API
2023-03-28 22:23:06 +02:00
Jonas Schäfer
2762304ae8 Make AdminUserInfo compatible with new API
The mod_http_admin_api changed recently [1], so we need to follow
suit.

Fixes #149.

   [1]: https://hg.prosody.im/prosody-modules/rev/d68348323406
2023-03-28 22:21:07 +02:00
Jonas Schäfer
49bbc3ab09 Merge pull request #148 from Zash/newscopes
Update to match new Prosody scope naming scheme
2023-03-28 21:42:00 +02:00
Kim Alvefur
8f1f80b7d7 Update to match new Prosody scope naming scheme
Ref https://hg.prosody.im/prosody-modules/rev/5ab134b7e510

Thanks Jonas
2023-03-28 21:14:20 +02:00
Jonas Schäfer
13bc283a3e Merge pull request #140 from snikket-im/feature/site-name-consistency
entrypoint: default SNIKKET_WEB_SITE_NAME to SNIKKET_SITE_NAME
2023-03-28 20:59:17 +02:00
Jonas Schäfer
abc0af3918 entrypoint: default SNIKKET_WEB_SITE_NAME to SNIKKET_SITE_NAME
The documentation only talks about SNIKKET_SITE_NAME,
and users thus do not know that they must
set SNIKKET_WEB_SITE_NAME to make
their site name appear on the portal.
2023-03-28 20:54:47 +02:00
Jonas Schäfer
0aff4fc99d Merge pull request #144 from snikket-im/fix/invite-link-header
Fix Link header on invite pages
2023-03-28 20:48:59 +02:00
Jonas Schäfer
40562d16f6 Fix Link header on invite pages
Thanks @singpolyma.
2023-03-28 19:19:43 +02:00
Jonas Schäfer
48a4a8f587 Merge pull request #147 from snikket-im/fix/i18n-lint
Fix i18n CI linting
2023-03-28 19:19:35 +02:00
Jonas Schäfer
664112bf53 Fix i18n CI linting
It diffs the things, and we're in 2023 now.
2023-03-28 19:16:27 +02:00
Jonas Schäfer
2dfc39e757 Merge pull request #141 from snikket-im/fix/quart-dep
Update WTForms and pin quart version
2023-03-28 19:14:30 +02:00
Jonas Schäfer
31b743a97f Update WTForms and pin quart version
The quart pin is required to fix an attribute error which otherwise
occurs during startup. Hence, this should be a good qualifier to know
when it's safe to upgrade.

Note that this is not a problem in Quart, but in flask-WTForms. But
downgrading flask-wtforms does not help [1], so we don't revert that
uprade.

```
AttributeError: module 'quart.json' has no attribute 'JSONEncoder'
```

   [1]: https://github.com/pallets/quart/issues/163
2022-10-24 10:14:03 +02:00
Weblate
14a335bb06 Update translation files
Updated by "Update PO files to match POT (msgmerge)" hook in Weblate.

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/
2022-06-07 20:34:03 +00:00
Jonas Schäfer
6c8c213a88 Merge pull request #100 from snikket-im/feature/drop-xmpp-qr-code
Remove XMPP URI QR code
2022-06-07 22:33:53 +02:00
Jonas Schäfer
2e224d96ce Remove XMPP URI QR code
At the same time, we can also drop the CSS used for that makeshift tab
box. I always felt a bit uneasy about it, a11y-wise, so it's good
riddance.

Fixes #99.
2022-06-07 22:31:40 +02:00
Weblate
b70cb57497 Update translation files
Updated by "Update PO files to match POT (msgmerge)" hook in Weblate.

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/
2022-06-06 17:55:08 +00:00
Jonas Schäfer
124e0ce145 Merge pull request #137 from snikket-im/premerge
Merge a bunch of things together
2022-06-06 19:54:54 +02:00
Jonas Schäfer
f2c79044e0 Clean up post-merge lint
I am a *bit* sorry for this commit, because ideally this would've been
folded into 6d50b1c2c7 and whatever the
source of the other "conflict" was.

However, as the things have been merged in a batch, I can't do much more
than this.
2022-06-06 19:52:24 +02:00
Jonas Schäfer
13bc4bb227 Merge branch 'fix/babel-extraction' into premerge 2022-06-06 19:46:59 +02:00
Jonas Schäfer
f1351eb5cc Merge branch 'fix/use-english-default' into premerge 2022-06-06 19:46:49 +02:00
Jonas Schäfer
41573569af Merge branch 'feature/export-back-button' into premerge 2022-06-06 19:46:43 +02:00
Jonas Schäfer
b1f3026b8a Merge branch 'feature/wtforms-3' into premerge 2022-06-06 19:46:32 +02:00
Jonas Schäfer
6794314a59 Merge branch 'feature/vary-accept-language' into premerge 2022-06-06 19:46:25 +02:00
Jonas Schäfer
077e957a00 Merge branch 'feature/ci-extract-translations' into premerge 2022-06-06 19:46:19 +02:00
Jonas Schäfer
4902941145 Merge branch 'feature/strip-versions' into premerge 2022-06-06 19:46:09 +02:00
Jonas Schäfer
5222c8eafe Merge branch 'feature/hypercorn-stdout' into premerge 2022-06-06 19:44:39 +02:00
Jonas Schäfer
03ca7ac5bb Unbreak translation text extraction
It was broken because of the same jinja2 update (presumably) which
prompted 68f72743c5.
2022-05-30 20:51:37 +02:00
Matthew Wild
56cee8bab6 Merge pull request #135 from snikket-im/feature/update-dependencies
Update dependencies
2022-05-30 16:59:22 +01:00
Jonas Schäfer
b36fc0d5ac Bump hsluv to 5.x
Fixes #134.
2022-05-30 17:38:18 +02:00
Jonas Schäfer
68f72743c5 Bump quart to version 0.17
This is needed because jinja2 had an update which caused the portal to
not work at all:

```
ImportError: cannot import name 'escape' from 'jinja2'
```

Quart needed updating for that.

This update required a lot of typefixes. Apparently, the "canned"
responses (like redirect) are now plain werkzeug responses, while
quart.Response does not inherit from werkzeug.Response (otherwise, we
could've changed the type annotations to werkzeug.Response everywhere,
but that doesn't work because a quart.Response is not a
werkzeug.Response).

P.S.: This time, I *did* check that avatar uploads don't break (see
b007afc).
2022-05-30 17:37:54 +02:00
Daniel Holmgaard
8741efb2c4 Translated using Weblate (Danish)
Currently translated at 100.0% (321 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/da/
2022-05-30 14:01:08 +00:00
Daniel Holmgaard
a0e8933b64 Translated using Weblate (Danish)
Currently translated at 95.6% (307 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/da/
2022-05-26 23:01:53 +00:00
Zack Zhou
edb3154127 Translated using Weblate (Chinese (Simplified))
Currently translated at 100.0% (321 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/zh_Hans/
2022-05-20 00:01:45 +00:00
Jonas Schäfer
eb22688302 Use english as default language instead of danish
It is more likely that a user for whose language no translation exists
can read english than danish.

The fallback to english was apparently introduced in c58ce845, though it
is possible that `best_match` did that internally before.

Fixes #131.
2022-05-15 14:12:51 +02:00
Jonas Schäfer
c278d4ace9 Merge pull request #132 from Raka-loah/master
Add Simplified Chinese support
2022-05-15 08:14:08 +02:00
Raka-loah
bbfe8624ef Add Simplified Chinese support 2022-05-14 17:53:40 +08:00
David Baraniak
8bcf619cef Translated using Weblate (French)
Currently translated at 100.0% (321 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/fr/
2022-04-11 13:00:44 +00:00
Kim Alvefur
73fda3d623 Add a Back button from export panel for consistency
The other user related sections all have a Back button so it makes sense
that this one ought to have one as well.
2022-02-19 16:28:38 +01:00
Matthew Wild
846a5e49fd Merge pull request #122 from snikket-im/feature/autocomplete-hints
Add autocomplete hints to password forms
2022-02-07 11:43:20 +00:00
Matthew Wild
b3ff7f04b5 Merge pull request #127 from snikket-im/fix/unhealthy
Install netcat in final image instead of build image
2022-02-07 11:42:40 +00:00
Jonas Schäfer
0ac4ab8142 Install netcat in final image instead of build image
`nc` (from netcat) is required for the healthcheck. In
c1cf6ab1e5, the installation was
erroneously moved to the builder image, instead of the final image, so
it was missing since then from the actual application image, causing it
to always show as unhealthy.

Fixes #126.
2022-02-05 13:51:30 +01:00
Matthew Wild
d4a38f5049 Merge pull request #125 from snikket-im/fix/support-requirements-compilation
Dockerfile: Add dev headers required for building deps
2022-02-01 09:09:50 +00:00
Matthew Wild
344a4d3e93 Dockerfile: Add dev headers required for building deps 2022-02-01 09:04:25 +00:00
Matthew Wild
57f1047526 Merge pull request #124 from snikket-im/fix/support-requirements-compilation
Dockerfile: Ensure a compiler is available while pip-installing requirements
2022-02-01 08:16:33 +00:00
Matthew Wild
b036caa85e Dockerfile: Ensure a compiler is available while pip-installing requirements
Dependencies are not necessarily packaged for all architectures. In some cases
(such as aiohttp, and others, on ARM) pip will attempt to compile the
dependency from scratch. Since switching to multi-stage builds, we have been
installing these without a compiler present which caused the build to fail on
ARM architectures.

This commit temporarily installs build-essential packages while running pip,
then removes them again afterwards.
2022-01-31 21:45:39 +00:00
Matthew Wild
08845cb9f0 Merge pull request #123 from snikket-im/hotfix/error-handling
Fix error handling when building image
2022-01-31 18:11:58 +00:00
Jonas Schäfer
6aa6e12680 Fix error handling when building image
Apparently, we managed to publish an image without working aiohttp
because of this.

Partially a regression from 5d7183a.
2022-01-31 19:09:03 +01:00
Jonas Schäfer
4bd58c1104 Add autocomplete hints to password forms
This allows user agents to do smart things like filling in the current
password only where it makes sense or integrate nicely with a password
manager.

Fixes #94.
2022-01-22 15:34:27 +01:00
Jonas Schäfer
a998348804 Make hypercorn log to stdout in Docker
This may help with debugging issues, because we now actually see
incoming requests also on the hypercorn layer.

Fixes #97.
2022-01-22 15:20:36 +01:00
Jonas Schäfer
20abe4b903 Add Vary: Accept-Language to all pages using that information
It was found during testing that some user agents cache aggressively
even between switches of the UI language. To properly indicate that the
pages actually depend on that information, we add the correct Vary
header.

Fixes #106.
2022-01-22 15:19:29 +01:00
Jonas Schäfer
a1ecb4ce80 Port to WTForms 3.x
Fixes #103.
2022-01-22 15:17:48 +01:00
Jonas Schäfer
b84b84b394 Add check for a missing make extract_translations
Forgetting to run that causes weblate (or other translation tools) to
show outdated strings and not import new strings, which is bad for the
collaboration.

Fixes #118.
2022-01-22 14:57:59 +01:00
misiek
4f7a4fb5d4 Translated using Weblate (Polish)
Currently translated at 100.0% (321 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/pl/
2022-01-21 15:00:36 +00:00
Jonas Schäfer
6d50b1c2c7 Do not show dependency versions even to admins by default
Dependency versions are generally not useful, unless you are developing
or otherwise outside of a normal release situation: If you are on a
normal release, we can figure out the dep versions by looking at the
docker image.

To reduce the amount of information displayed and the amount of
information which needs to be conveyed in case of problems, we only show
the web portal and prosody versions to admins, unless debug mode is
enabled.

The behaviour that versions are only shown to logged in admins (unless
debug mode is enabled) remains unchanged.

Fixes #115.
2022-01-20 18:11:47 +01:00
uira
34a23f8505 Translated using Weblate (Indonesian)
Currently translated at 100.0% (321 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/id/
2022-01-18 14:59:01 +00:00
Jonas Schäfer
ebcb083b6a Translated using Weblate (German)
Currently translated at 100.0% (321 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/de/
2022-01-18 14:59:01 +00:00
Kim Alvefur
2f0b38b149 Translated using Weblate (Swedish)
Currently translated at 100.0% (321 of 321 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/sv/
2022-01-18 09:21:29 +00:00
Weblate
6244ad5c8a Update translation files
Updated by "Update PO files to match POT (msgmerge)" hook in Weblate.

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/
2022-01-17 16:27:36 +00:00
Jonas Schäfer
07fa1f0abd Fix missing space in string 2022-01-17 17:27:26 +01:00
Weblate
3d22458f9b Update translation files
Updated by "Update PO files to match POT (msgmerge)" hook in Weblate.

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/
2022-01-17 16:26:16 +00:00
Jonas Schäfer
3b768fe220 Extract translations 2022-01-17 17:26:02 +01:00
Matthew Wild
19cf82e894 Merge pull request #111 from snikket-im/fix/byte-scaling
Fix corner cases of byte number formatting
2022-01-17 15:47:57 +00:00
Matthew Wild
fe0316708b Merge pull request #113 from snikket-im/feature/flake8-print
Include flake8-print plugin
2022-01-17 15:47:21 +00:00
Jonas Schäfer
81b0a58dc9 Merge pull request #107 from Zash/storagestats
Show how much storage space is used by shared files
2022-01-17 16:40:16 +01:00
Jonas Schäfer
08aea153f9 Merge pull request #110 from snikket-im/feature/account-export
Feature: account import/export
2022-01-17 16:38:04 +01:00
Jonas Schäfer
958b3365f7 Remove strange greeting copied over from user_home 2022-01-17 16:34:30 +01:00
Matthew Wild
05caf38d37 Use PUT method instead of POST, as expected by API 2022-01-17 16:33:46 +01:00
Matthew Wild
390ecded42 Include PEP data in export/import 2022-01-17 16:33:29 +01:00
Matthew Wild
f6395d4d9c Complete the implementation of data import 2022-01-17 16:33:00 +01:00
Matthew Wild
32179c72cd Add account data import UI on registration success page 2022-01-17 16:24:00 +01:00
Matthew Wild
3cb8185b1a prosodyclient: Add API to import XEP-0227 account data 2022-01-17 16:23:58 +01:00
Matthew Wild
481379d03f Switch to HTTP 204 to indicate no data to export
This is more robust, as it indicates the request was successfully
authenticated and processed, but that there is no data to export. This is
different from the URL not existing (which would also happen if the module was
unavailable, which should be a notable error instead).
2022-01-17 16:23:57 +01:00
Matthew Wild
275b302531 Add UI for exporting user account data 2022-01-17 16:23:56 +01:00
Matthew Wild
e18f727db0 prosodyclient: Add support for exporting a user's account data 2022-01-17 16:23:55 +01:00
Matthew Wild
f7429413cd Add more icons to the repertoire 2022-01-17 16:23:35 +01:00
Jonas Schäfer
d5a46b69a6 Include flake8-print plugin
This alerts us of stray print statements, which should never occur
because this is a non-TUI application.
2022-01-15 17:07:16 +01:00
Jonas Schäfer
51f2ebbd13 Handle the correct exception when formatting extremely high amounts of bytes
Found in production. Yes really. Due to some borked LXC integration, my
snikket host reports

```
MemTotal:       9007199254740991 kB
MemFree:        9007199254690591 kB
MemAvailable:   9007199254690591 kB
```

That is more than 1024 TiB, so it tries to go further up in the scale,
which then causes a Guru Meditation because of the uncaught IndexError.
2022-01-10 17:32:11 +01:00
Jonas Schäfer
b4e6ee8943 Fix formatting of zero bytes
Previously, that would raise a ValueError (math domain error), because
log(0) is undefined.
2022-01-10 17:31:50 +01:00
Jonas Schäfer
52d8047546 Correctly detect presence of storage metric
If there have been no uploads yet, the metric will be zero, so the if
condition would fail the test, so it would render as "unknown".
2022-01-10 16:56:31 +01:00
Jonas Schäfer
aed9ad1cde Merge pull request #93 from Zash/debianbullseye
Dockerfile: Switch base image to Debian 11
2022-01-10 16:40:28 +01:00
Kim Alvefur
b545c137b1 Dockerfile: Switch base image to Debian 11 2022-01-10 16:27:38 +01:00
Matthew Wild
47642dc384 Merge pull request #108 from snikket-im/feature/multi-stage-dockerfile
Dockerfile: Split build into multiple stages
2022-01-10 14:21:57 +00:00
Jonas Schäfer
5d7183a0b8 Reinstate cache deletion in multi-stage build
Previously, the multi-stage build increased the image size by about 30
MiB (163MiB -> 191MiB). Dropping the caches reduces the image size down
to 159MiB, leading to a net improvement of 4 MiB.
2022-01-08 13:29:28 +01:00
Matthew Wild
c1cf6ab1e5 Dockerfile: Split build into multiple stages
Currently the Dockerfile has a single RUN directive with all the needed
commands in it. This optimizes for image size by not creating too many
"layers" (which are only additive). However it means the result that gets
cached can basically never be reused, because any change to the source code
will need to execute the whole RUN block again.

This commit switches to a docker "multi-stage" build, where we have a build
image that is separate from the final one that gets published. The build
image can be cached locally, and size is no longer a significant concern.

This approach allows the single RUN command to be split up into multiple RUN
commands that only execute when strictly needed (i.e. when their result
is not cached locally).

This drastically improves the build time when rebuilding the image after
a simple code change, because the build image doesn't have to install all
the apt packages, for example. This leads to a nicer developer experience
when using docker locally for development and testing.
2022-01-08 13:17:52 +01:00
Jonas Schäfer
aee53a2e1a Merge pull request #109 from snikket-im/feature/fix-mypy
Fix mypy false positives
2022-01-08 13:14:28 +01:00
Jonas Schäfer
3a81a0140b Revert "Fix spurious mypy error"
This reverts commit 28ff19c19c.
2022-01-08 13:12:30 +01:00
Jonas Schäfer
5b4d4ddd36 Fix some mypy regression 2022-01-08 13:12:30 +01:00
Jonas Schäfer
28ff19c19c Fix spurious mypy error
For whatever reason, it thinks that babel has no __version__ field, but
it in fact does.
2022-01-08 12:52:31 +01:00
uira
8e3837f704 Translated using Weblate (Indonesian)
Currently translated at 100.0% (303 of 303 strings)

Translation: Snikket/Web Portal
Translate-URL: http://i18n.sotecware.net/projects/snikket/web-portal/id/
2021-12-12 07:00:42 +00:00
Kim Alvefur
4af78f635e Show how much storage space is used by shared files
Requires at least https://hg.prosody.im/prosody-modules/rev/883ad8b0a7c0
2021-11-18 19:50:47 +01:00
Matthew Wild
98e7de3166 Merge pull request #104 from snikket-im/feature/enable-restricted-users
admin: Show restricted user role in the UI
2021-11-09 17:03:08 +00:00
Matthew Wild
61c71b2145 admin: Inline restricted user role name
It was a variable only for the benefit of translators while disabled.
2021-11-09 17:00:59 +00:00
Matthew Wild
6b35e9a259 admin: Show restricted user role in the UI 2021-11-09 16:40:50 +00:00
Matthew Wild
58c2112fec Merge pull request #102 from snikket-im/feature/pin-wtforms
Pin wtforms to 2.x
2021-11-09 10:48:18 +00:00
64 changed files with 10669 additions and 3658 deletions

View File

@@ -45,11 +45,34 @@ jobs:
- name: Install
run: |
set -euo pipefail
pip install flake8
pip install flake8 flake8-print
- name: Linting
run: |
python -m flake8 snikket_web
translation-check:
runs-on: ubuntu-latest
name: 'lint: i18n'
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: '3.9'
- name: Install
run: |
set -euo pipefail
pip install flask-babel
- name: Linting
run: |
sed -ri '/^"POT-Creation-Date: /d' snikket_web/translations/messages.pot
git add snikket_web/translations/messages.pot
make extract_translations
sed -ri '/^"POT-Creation-Date: /d' snikket_web/translations/messages.pot
git diff --exit-code --color -- snikket_web/translations/messages.pot
build:
runs-on: ubuntu-latest

View File

@@ -1,13 +1,31 @@
FROM debian:buster-slim
FROM debian:bookworm-slim AS build
RUN set -eu; \
export DEBIAN_FRONTEND=noninteractive ; \
apt-get update ; \
apt-get install -y --no-install-recommends \
python3 python3-mypy python3-dotenv python3-toml python3-babel python3-distutils \
sassc make;
COPY Makefile /opt/snikket-web-portal/Makefile
COPY snikket_web/ /opt/snikket-web-portal/snikket_web
COPY babel.cfg /opt/snikket-web-portal/babel.cfg
WORKDIR /opt/snikket-web-portal
RUN make
FROM debian:bookworm-slim
ARG BUILD_SERIES=dev
ARG BUILD_ID=0
COPY requirements.txt /opt/snikket-web-portal/requirements.txt
COPY build-requirements.txt /opt/snikket-web-portal/build-requirements.txt
COPY Makefile /opt/snikket-web-portal/Makefile
COPY snikket_web/ /opt/snikket-web-portal/snikket_web
COPY babel.cfg /opt/snikket-web-portal/babel.cfg
COPY docker/env.py /etc/snikket-web-portal/env.py
ENV SNIKKET_WEB_PYENV=/etc/snikket-web-portal/env.py
ENV SNIKKET_WEB_PROSODY_ENDPOINT=http://127.0.0.1:5280/
WORKDIR /opt/snikket-web-portal
@@ -15,28 +33,20 @@ RUN set -eu; \
export DEBIAN_FRONTEND=noninteractive ; \
apt-get update ; \
apt-get install -y --no-install-recommends \
python3 python3-pip python3-setuptools python3-wheel \
libpython3-dev \
make build-essential \
netcat \
; \
pip3 install -r requirements.txt; \
pip3 install -r build-requirements.txt; \
make; \
pip3 uninstall -yr build-requirements.txt; \
apt-get remove -y build-essential make libpython3-dev; \
apt-get autoremove -y; \
pip3 install hypercorn; \
rm -rf /root/.cache; \
apt-get clean ; rm -rf /var/lib/apt/lists
COPY docker/env.py /etc/snikket-web-portal/env.py
ENV SNIKKET_WEB_PYENV=/etc/snikket-web-portal/env.py
ENV SNIKKET_WEB_PROSODY_ENDPOINT=http://127.0.0.1:5280/
netcat-traditional python3 python3-setuptools python3-pip \
python3-aiohttp python3-email-validator python3-flask-babel \
python3-flaskext.wtf python3-hsluv python3-hypercorn \
python3-quart python3-typing-extensions python3-wtforms ; \
pip3 install --break-system-packages environ-config ; \
apt-get remove -y --purge python3-pip python3-setuptools; \
apt-get clean ; rm -rf /var/lib/apt/lists; \
rm -rf /root/.cache;
HEALTHCHECK CMD nc -zv ${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_INTERFACE:-127.0.0.1} ${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_PORT:-5765}
COPY --from=build /opt/snikket-web-portal/snikket_web/ /opt/snikket-web-portal/snikket_web
COPY babel.cfg /opt/snikket-web-portal/babel.cfg
RUN echo "$BUILD_SERIES $BUILD_ID" > /opt/snikket-web-portal/.app_version
ADD docker/entrypoint.sh /entrypoint.sh

View File

@@ -6,7 +6,7 @@ translation_basepath = snikket_web/translations
pot_file = $(translation_basepath)/messages.pot
PYTHON3 ?= python3
SCSSC ?= $(PYTHON3) -m scss --load-path snikket_web/scss/
SCSSC ?= sassc --load-path snikket_web/scss/
all: build_css compile_translations
@@ -14,7 +14,7 @@ build_css: $(generated_css_files)
$(generated_css_files): snikket_web/static/css/%.css: snikket_web/scss/%.scss $(scss_files) $(scss_includes)
mkdir -p snikket_web/static/css/
$(SCSSC) -o "$@" "$<"
$(SCSSC) "$<" "$@"
clean:
rm -f $(generated_css_files)

View File

@@ -1,4 +1,3 @@
[python: snikket_web/**.py]
[jinja2: snikket_web/templates/**.html]
[jinja2: snikket_web/templates/**.j2]
extensions=jinja2.ext.autoescape,jinja2.ext.with_

View File

@@ -1,4 +1,3 @@
pyscss~=1.3
mypy
python-dotenv~=0.15
types-toml

View File

@@ -1,8 +1,16 @@
#!/bin/sh
export SNIKKET_WEB_DOMAIN="$SNIKKET_DOMAIN"
if [ -n "${SNIKKET_SITE_NAME:-}" ]; then
export SNIKKET_WEB_SITE_NAME="$SNIKKET_SITE_NAME"
fi
export SNIKKET_WEB_TOS_URI="${SNIKKET_TOS_URI}"
export SNIKKET_WEB_PRIVACY_URI="${SNIKKET_PRIVACY_URI}"
export SNIKKET_WEB_ABUSE_EMAIL="${SNIKKET_ABUSE_EMAIL}"
export SNIKKET_WEB_SECURITY_EMAIL="${SNIKKET_SECURITY_EMAIL}"
export SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_INTERFACE="${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_INTERFACE-127.0.0.1}"
export SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_PORT="${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_PORT-5765}"
exec hypercorn -b "${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_INTERFACE}:${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_PORT}" 'snikket_web:create_app()'
exec hypercorn -b "${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_INTERFACE}:${SNIKKET_TWEAK_PORTAL_INTERNAL_HTTP_PORT}" --access-logfile=- --log-file=- 'snikket_web:create_app()'

View File

@@ -1,9 +1,9 @@
aiohttp~=3.6
quart~=0.11,<0.15
flask-wtf~=0.14
hsluv~=0.0.2
quart~=0.17,<0.18
flask-wtf~=1.0
hsluv~=5.0
flask-babel~=1.0
email-validator~=1.1
environ-config~=20.0
wtforms~=2.3
wtforms~=3.0
typing-extensions

View File

@@ -18,6 +18,8 @@ from quart import (
jsonify,
)
import werkzeug.exceptions
import environ
from . import colour, infra
@@ -40,7 +42,7 @@ async def proc() -> typing.Dict[str, typing.Any]:
try:
user_info = await infra.client.get_user_info()
except (aiohttp.ClientError, quart.exceptions.HTTPException):
except (aiohttp.ClientError, werkzeug.exceptions.HTTPException):
user_info = {}
return {
@@ -105,16 +107,16 @@ async def backend_error_handler(exc: Exception) -> quart.Response:
async def generic_http_error(
exc: quart.exceptions.HTTPException,
exc: werkzeug.exceptions.HTTPException,
) -> quart.Response:
return quart.Response(
await render_template(
"generic_http_error.html",
status=exc.status_code,
status=exc.code,
description=exc.description,
name=exc.name,
),
status=exc.status_code,
status=exc.code,
)
@@ -145,14 +147,19 @@ class AppConfig:
site_name = environ.var("")
avatar_cache_ttl = environ.var(1800, converter=int)
languages = environ.var([
# Keep `en` as the first language, because it is used as a fallback
# if the language negotiation cannot find another match. It is more
# likely that users are able to read english (or find a suitable
# online translator) than, for instance, danish.
"en",
"da",
"de",
"en",
"fr",
"id",
"it",
"pl",
"sv",
"zh_Hans_CN",
], converter=autosplit)
apple_store_url = environ.var(
"https://apps.apple.com/us/app/snikket/id1545164189",
@@ -163,6 +170,10 @@ class AppConfig:
# tools may also very well override it.
max_avatar_size = environ.var(1024*1024, converter=int)
show_metrics = environ.bool_var(True)
tos_uri = environ.var("")
privacy_uri = environ.var("")
abuse_email = environ.var("")
security_email = environ.var("")
_UPPER_CASE = "".join(map(chr, range(ord("A"), ord("Z")+1)))
@@ -195,23 +206,27 @@ def create_app() -> quart.Quart:
app.config["APPLE_STORE_URL"] = config.apple_store_url
app.config["MAX_AVATAR_SIZE"] = config.max_avatar_size
app.config["SHOW_METRICS"] = config.show_metrics
app.config["TOS_URI"] = config.tos_uri
app.config["PRIVACY_URI"] = config.privacy_uri
app.config["ABUSE_EMAIL"] = config.abuse_email
app.config["SECURITY_EMAIL"] = config.security_email
app.context_processor(proc)
app.register_error_handler(
aiohttp.ClientConnectorError,
backend_error_handler, # type:ignore
backend_error_handler,
)
app.register_error_handler(
quart.exceptions.HTTPException,
werkzeug.exceptions.HTTPException,
generic_http_error, # type:ignore
)
app.register_error_handler(
Exception,
generic_error_handler, # type:ignore
generic_error_handler,
)
@app.route("/")
async def index() -> quart.Response:
async def index() -> werkzeug.Response:
if infra.client.has_session:
return redirect(url_for('user.index'))

View File

@@ -7,10 +7,11 @@ from datetime import datetime
import aiohttp
import werkzeug.exceptions
import quart.flask_patch
import wtforms
import wtforms.fields.html5
from quart import (
Blueprint,
@@ -63,9 +64,6 @@ async def users() -> str:
)
_LIMITED_ROLE_NAME = _("Limited")
class EditUserForm(BaseForm):
localpart = wtforms.StringField(
_l("Login name"),
@@ -78,10 +76,8 @@ class EditUserForm(BaseForm):
role = wtforms.RadioField(
_l("Access Level"),
choices=[
# NOTE: enable this only after something has been done which
# actually enforces the described restrictions :).
# ("prosody:restricted", _LIMITED_ROLE_NAME),
("prosody:normal", _l("Normal user")),
("prosody:restricted", _("Limited")),
("prosody:registered", _l("Normal user")),
("prosody:admin", _l("Administrator")),
],
)
@@ -90,6 +86,14 @@ class EditUserForm(BaseForm):
_l("Update user"),
)
action_restore = wtforms.SubmitField(
_l("Restore account"),
)
action_enable = wtforms.SubmitField(
_l("Unlock account"),
)
action_create_reset = wtforms.SubmitField(
_l("Create password reset link"),
)
@@ -97,7 +101,7 @@ class EditUserForm(BaseForm):
@bp.route("/user/<localpart>/", methods=["GET", "POST"])
@client.require_admin_session()
async def edit_user(localpart: str) -> typing.Union[quart.Response, str]:
async def edit_user(localpart: str) -> typing.Union[werkzeug.Response, str]:
target_user_info = await client.get_user_by_localpart(localpart)
form = EditUserForm()
@@ -116,18 +120,44 @@ async def edit_user(localpart: str) -> typing.Union[quart.Response, str]:
".user_password_reset_link",
id_=reset_link.id_,
))
elif form.action_restore.data or form.action_enable.data:
await client.enable_user_account(localpart)
try:
if form.action_restore.data:
await flash(
_("User account restored"),
"success",
)
else:
await flash(
_("User account unlocked"),
"success",
)
return redirect(url_for(".users"))
except aiohttp.ClientResponseError:
if form.action_restore.data:
await flash(
_("Could not restore user account"),
"alert",
)
else:
await flash(
_("Could not unlock user account"),
"alert",
)
return redirect(url_for(".edit_user", localpart=localpart))
await client.update_user(
localpart,
display_name=form.display_name.data,
roles=[form.role.data],
role=form.role.data,
)
await flash(
_("User information updated."),
"success",
)
return redirect(url_for(".edit_user", localpart=localpart))
return redirect(url_for(".users"))
elif request.method == "GET":
form.localpart.data = target_user_info.localpart
@@ -135,7 +165,7 @@ async def edit_user(localpart: str) -> typing.Union[quart.Response, str]:
if target_user_info.roles:
form.role.data = target_user_info.roles[0]
else:
form.role.data = "prosody:normal"
form.role.data = "prosody:registered"
return await render_template(
"admin_edit_user.html",
@@ -152,7 +182,7 @@ class DeleteUserForm(BaseForm):
@bp.route("/user/<localpart>/delete", methods=["GET", "POST"])
@client.require_admin_session()
async def delete_user(localpart: str) -> typing.Union[str, quart.Response]:
async def delete_user(localpart: str) -> typing.Union[str, werkzeug.Response]:
target_user_info = await client.get_user_by_localpart(localpart)
form = DeleteUserForm()
if form.validate_on_submit():
@@ -191,7 +221,7 @@ async def debug_user(localpart: str) -> typing.Union[str, quart.Response]:
@client.require_admin_session()
async def user_password_reset_link(
id_: str,
) -> typing.Union[str, quart.Response]:
) -> typing.Union[str, werkzeug.Response]:
invite_info = await client.get_invite_by_id(
id_,
)
@@ -283,7 +313,7 @@ class InvitePost(BaseForm):
@bp.route("/invitations", methods=["GET", "POST"])
@client.require_admin_session()
async def invitations() -> typing.Union[str, quart.Response]:
async def invitations() -> typing.Union[str, werkzeug.Response]:
invites = sorted(
(
invite
@@ -329,7 +359,7 @@ class InviteForm(BaseForm):
@bp.route("/invitation/-/new", methods=["POST"])
@client.require_admin_session()
async def create_invite() -> typing.Union[str, quart.Response]:
async def create_invite() -> typing.Union[str, werkzeug.Response]:
form = InvitePost()
circles = await client.list_groups()
form.circles.choices = [
@@ -357,7 +387,7 @@ async def create_invite() -> typing.Union[str, quart.Response]:
@bp.route("/invitation/<id_>", methods=["GET", "POST"])
@client.require_admin_session()
async def edit_invite(id_: str) -> typing.Union[str, quart.Response]:
async def edit_invite(id_: str) -> typing.Union[str, werkzeug.Response]:
try:
invite_info = await client.get_invite_by_id(id_)
except aiohttp.ClientResponseError as exc:
@@ -423,7 +453,7 @@ async def circles() -> str:
@bp.route("/circle/-/new", methods=["POST"])
@client.require_admin_session()
async def create_circle() -> typing.Union[str, quart.Response]:
async def create_circle() -> typing.Union[str, werkzeug.Response]:
create_form = CirclePost()
if create_form.validate_on_submit():
circle = await client.create_group(
@@ -456,20 +486,18 @@ class EditCircleForm(BaseForm):
_l("Update circle")
)
action_delete = wtforms.SubmitField(
_l("Delete circle permanently")
)
action_remove_user = wtforms.StringField()
action_add_user = wtforms.SubmitField(
_l("Add user")
)
action_remove_group_chat = wtforms.StringField()
@bp.route("/circle/<id_>", methods=["GET", "POST"])
@client.require_admin_session()
async def edit_circle(id_: str) -> typing.Union[str, quart.Response]:
async def edit_circle(id_: str) -> typing.Union[str, werkzeug.Response]:
async with client.authenticated_session() as session:
try:
circle = await client.get_group_by_id(
@@ -519,13 +547,6 @@ async def edit_circle(id_: str) -> typing.Union[str, quart.Response]:
_("Circle data updated"),
"success",
)
elif form.action_delete.data:
await client.delete_group(id_)
await flash(
_("Circle deleted"),
"success",
)
return redirect(url_for(".circles"))
elif form.action_add_user.data:
if form.user_to_add.data in valid_users:
await client.add_group_member(
@@ -545,20 +566,119 @@ async def edit_circle(id_: str) -> typing.Union[str, quart.Response]:
_("User removed from circle"),
"success",
)
elif form.action_remove_group_chat.data:
await client.remove_group_chat(
id_,
form.action_remove_group_chat.data,
)
await flash(
_("Chat removed from circle"),
"success",
)
return redirect(url_for(".edit_circle", id_=id_))
else:
print(form.errors)
return await render_template(
"admin_edit_circle.html",
target_circle=circle,
form=form,
circle_chats=circle.chats,
circle_members=circle_members,
invite_form=invite_form,
)
class DeleteCircleForm(BaseForm):
action_delete = wtforms.SubmitField(
_l("Delete circle permanently")
)
@bp.route("/circle/<id_>/delete", methods=["GET", "POST"])
@client.require_admin_session()
async def delete_circle(id_: str) -> typing.Union[str, werkzeug.Response]:
async with client.authenticated_session() as session:
try:
circle = await client.get_group_by_id(
id_,
session=session,
)
except aiohttp.ClientResponseError as exc:
if exc.status == 404:
await flash(
_("No such circle exists"),
"alert",
)
return redirect(url_for(".circles"))
raise
form = DeleteCircleForm()
if form.validate_on_submit():
if form.action_delete.data:
await client.delete_group(id_)
await flash(
_("Circle deleted"),
"success",
)
return redirect(url_for(".circles"))
return await render_template(
"admin_delete_circle.html",
target_circle=circle,
form=form,
)
class AddCircleChatForm(BaseForm):
name = wtforms.StringField(
_l("Group chat name"),
validators=[wtforms.validators.InputRequired()],
)
action_save = wtforms.SubmitField(
_l("Create group chat")
)
@bp.route("/circle/<id_>/add_chat", methods=["GET", "POST"])
@client.require_admin_session()
async def edit_circle_add_chat(
id_: str
) -> typing.Union[str, werkzeug.Response]:
async with client.authenticated_session() as session:
try:
circle = await client.get_group_by_id(
id_,
session=session,
)
except aiohttp.ClientResponseError as exc:
if exc.status == 404:
await flash(
_("No such circle exists"),
"alert",
)
return redirect(url_for(".circles"))
raise
form = AddCircleChatForm()
if form.validate_on_submit():
if form.action_save.data:
await client.add_group_chat(id_, form.name.data)
await flash(
_("New group chat added to circle"),
"success",
)
return redirect(url_for(".edit_circle", id_=id_))
return await render_template(
"admin_create_circle_chat.html",
target_circle=circle,
group_chat_form=form,
)
_CPU_EPOCH = time.process_time()
_MONOTONIC_EPOCH = time.monotonic()
@@ -633,7 +753,7 @@ class AnnouncementForm(BaseForm):
@bp.route("/system/", methods=["GET", "POST"])
@client.require_admin_session()
async def system() -> typing.Union[str, quart.Response]:
async def system() -> typing.Union[str, werkzeug.Response]:
form = AnnouncementForm()
if form.validate_on_submit():
@@ -664,7 +784,7 @@ async def system() -> typing.Union[str, quart.Response]:
now = time.time()
try:
prosody_metrics = await client.get_system_metrics()
except quart.exceptions.NotFound:
except werkzeug.exceptions.NotFound:
# server does not offer the endpoint for whatever reason -- ignore
prosody_metrics = {}
@@ -687,6 +807,11 @@ async def system() -> typing.Union[str, quart.Response]:
except KeyError:
pass
try:
metrics["prosody_uploads"] = prosody_metrics["uploads"]
except KeyError:
pass
for k in list(metrics.keys()):
if metrics[k] is None:
# so that defaulting in jinja works

View File

@@ -4,15 +4,19 @@ import math
import secrets
import typing
from datetime import datetime, timedelta, timezone
import quart.flask_patch # noqa:F401
from quart import (
current_app,
request,
g,
)
import flask_babel
import flask_wtf
from flask_babel import _
from flask_babel import lazy_gettext as _l
import flask_babel as _
from . import prosodyclient
@@ -34,6 +38,7 @@ BYTE_UNIT_SCALE_MAP = [
@babel.localeselector # type:ignore
def selected_locale() -> str:
g.language_header_accessed = True
selected = request.accept_languages.best_match(
current_app.config['LANGUAGES']
) or current_app.config['LANGUAGES'][0]
@@ -48,16 +53,19 @@ def flatten(a: typing.Iterable, levels: int = 1) -> typing.Iterable:
def circle_name(c: typing.Any) -> str:
if c.id_ == "default" and c.name == "default":
return _("Main")
return _l("Main")
return c.name
def format_bytes(n: float) -> str:
scale = math.floor(math.log(n, 1024))
try:
scale = max(math.floor(math.log(n, 1024)), 0)
except ValueError:
scale = 0
try:
unit = BYTE_UNIT_SCALE_MAP[scale]
factor = 1024**scale
except ValueError:
except IndexError:
unit = "TiB"
factor = 1024**4
if factor > 1:
@@ -65,6 +73,49 @@ def format_bytes(n: float) -> str:
return "{}{}".format(n, unit)
def format_last_activity(timestamp: typing.Optional[int]) -> str:
if timestamp is None:
return _l("Never")
last_active = datetime.fromtimestamp(timestamp, tz=timezone.utc)
# TODO: This 'now' should use the user's local time zone, but we
# don't have that information. Thus 'today'/'yesterday' may be
# slightly inaccurate, but compared to alternative solutions it
# should hopefully be "good enough".
now = datetime.now(tz=timezone.utc)
time_ago = now - last_active
yesterday = now - timedelta(days=1)
if (
last_active.year == now.year
and last_active.month == now.month
and last_active.day == now.day
):
return _l("Today")
elif (
last_active.year == yesterday.year
and last_active.month == yesterday.month
and last_active.day == yesterday.day
):
return _l("Yesterday")
return _.gettext(
"%(time)s ago",
time=flask_babel.format_timedelta(time_ago, granularity="day"),
)
def template_now() -> typing.Dict[str, typing.Any]:
return dict(now=lambda: datetime.now(timezone.utc))
def add_vary_language_header(resp: quart.Response) -> quart.Response:
if getattr(g, "language_header_accessed", False):
resp.vary.add("Accept-Language")
return resp
def init_templating(app: quart.Quart) -> None:
app.template_filter("repr")(repr)
app.template_filter("format_datetime")(flask_babel.format_datetime)
@@ -75,6 +126,9 @@ def init_templating(app: quart.Quart) -> None:
app.template_filter("format_bytes")(format_bytes)
app.template_filter("flatten")(flatten)
app.template_filter("circle_name")(circle_name)
app.template_filter("format_last_activity")(format_last_activity)
app.context_processor(template_now)
app.after_request(add_vary_language_header)
def generate_error_id() -> str:

View File

@@ -10,13 +10,16 @@ from quart import (
current_app,
render_template,
redirect,
request,
url_for,
session as http_session,
)
import werkzeug
import wtforms
from flask_babel import lazy_gettext as _l
from flask_babel import lazy_gettext as _l, gettext
from .infra import client, selected_locale, BaseForm
@@ -26,6 +29,11 @@ bp = Blueprint("invite", __name__)
INVITE_SESSION_JID = "invite-session-jid"
MAX_IMPORT_DATA_SIZE = 5*1024*1024 # 5MB
SUPPORTED_IMPORT_TYPES = ["application/xml", "text/xml"]
EIMPORTTOOBIG = _l("The account data you tried to import is too large to"
" upload. Please contact your Snikket operator.")
# https://play.google.com/store/apps/details?id=org.snikket.android&referrer={uri|urlescape}&pcampaignid=pcampaignidMKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1
@@ -40,14 +48,14 @@ def apple_store_badge() -> str:
@bp.context_processor
def context() -> typing.Mapping[str, typing.Any]:
def context() -> typing.Dict[str, typing.Any]:
return {
"apple_store_badge": apple_store_badge,
}
@bp.route("/<id_>")
async def view_old(id_: str) -> quart.Response:
async def view_old(id_: str) -> werkzeug.Response:
return redirect(url_for(".view", id_=id_))
@@ -96,7 +104,7 @@ async def view(id_: str) -> typing.Union[quart.Response,
return quart.Response(
body,
headers={
"Link": "<{}> rel=\"alternate\"".format(invite.xmpp_uri),
"Link": "<{}>; rel=\"alternate\"".format(invite.xmpp_uri),
}
)
@@ -125,7 +133,7 @@ class RegisterForm(BaseForm):
@bp.route("/<id_>/register", methods=["GET", "POST"])
async def register(id_: str) -> typing.Union[str, quart.Response]:
async def register(id_: str) -> typing.Union[str, werkzeug.Response]:
try:
invite = await client.get_public_invite_by_id(id_)
except aiohttp.ClientResponseError as exc:
@@ -163,6 +171,7 @@ async def register(id_: str) -> typing.Union[str, quart.Response]:
raise
else:
http_session[INVITE_SESSION_JID] = jid
await client.login(jid, form.password.data)
return redirect(url_for(".success"))
return await render_template(
@@ -192,7 +201,7 @@ class ResetForm(BaseForm):
@bp.route("/<id_>/reset", methods=["GET", "POST"])
async def reset(id_: str) -> typing.Union[str, quart.Response]:
async def reset(id_: str) -> typing.Union[str, werkzeug.Response]:
try:
invite = await client.get_public_invite_by_id(id_)
except aiohttp.ClientResponseError as exc:
@@ -232,11 +241,55 @@ async def reset(id_: str) -> typing.Union[str, quart.Response]:
)
class DataImportForm(BaseForm):
account_data_file = wtforms.FileField(
_l("Account data file")
)
action_import = wtforms.SubmitField(
_l("Import data")
)
@bp.route("/success", methods=["GET", "POST"])
@client.require_session()
async def success() -> str:
form = DataImportForm()
if form.validate_on_submit():
ok = True
file_info = (await request.files).get(form.account_data_file.name)
if file_info is not None:
mimetype = file_info.mimetype
data = file_info.stream.read()
if len(data) > MAX_IMPORT_DATA_SIZE:
form.account_data_file.errors.append(EIMPORTTOOBIG)
ok = False
elif mimetype not in SUPPORTED_IMPORT_TYPES:
form.account_data_file.errors.append(
# not breaking the line here to avoid extract
# translations failing (defensive)
gettext("The account data you tried to import is in an unknown format. Please upload an XML file in XEP-0227 format (provided format: %(mimetype)s).", mimetype=mimetype), # noqa:E501
)
ok = False
elif len(data) > 0:
await client.import_account_data(data)
if ok:
# Re-render success page, this time with no import option
return await render_template(
"invite_success.html",
jid=http_session.get(INVITE_SESSION_JID, ""),
migration_success=True,
)
return await render_template(
"invite_success.html",
jid=http_session.get(INVITE_SESSION_JID, ""),
migration_success=False,
form=form,
max_import_size=MAX_IMPORT_DATA_SIZE,
import_too_big_warning_header=_l("Error"),
import_too_big_warning=EIMPORTTOOBIG,
)
@@ -249,5 +302,5 @@ async def reset_success() -> str:
@bp.route("/-")
async def index() -> quart.Response:
async def index() -> werkzeug.Response:
return redirect(url_for("index"))

View File

@@ -18,6 +18,8 @@ from quart import (
flash,
)
import werkzeug.exceptions
import babel
import wtforms
@@ -32,7 +34,7 @@ bp = quart.Blueprint("main", __name__)
class LoginForm(BaseForm):
address = wtforms.TextField(
address = wtforms.StringField(
_l("Address"),
validators=[wtforms.validators.InputRequired()],
)
@@ -48,7 +50,7 @@ class LoginForm(BaseForm):
@bp.route("/-")
async def index() -> quart.Response:
async def index() -> werkzeug.Response:
return redirect(url_for("index"))
@@ -56,7 +58,7 @@ ERR_CREDENTIALS_INVALID = _l("Invalid username or password.")
@bp.route("/login", methods=["GET", "POST"])
async def login() -> typing.Union[str, quart.Response]:
async def login() -> typing.Union[str, werkzeug.Response]:
if client.has_session and (await client.test_session()):
return redirect(url_for('user.index'))
@@ -76,7 +78,7 @@ async def login() -> typing.Union[str, quart.Response]:
password = form.password.data
try:
await client.login(jid, password)
except quart.exceptions.Unauthorized:
except werkzeug.exceptions.Unauthorized:
form.password.errors.append(ERR_CREDENTIALS_INVALID)
else:
await flash(
@@ -91,24 +93,30 @@ async def login() -> typing.Union[str, quart.Response]:
@bp.route("/meta/about.html")
async def about() -> str:
version = None
core_versions = {}
extra_versions = {}
if current_app.debug or client.is_admin_session:
version = _version.version
extra_versions["Quart"] = quart.__version__
try:
core_versions["Prosody"] = await client.get_server_version()
except werkzeug.exceptions.Unauthorized:
core_versions["Prosody"] = "unknown"
if current_app.debug:
extra_versions["aiohttp"] = aiohttp.__version__
extra_versions["babel"] = babel.__version__
extra_versions["wtforms"] = wtforms.__version__
extra_versions["flask-wtf"] = flask_wtf.__version__
try:
extra_versions["Prosody"] = await client.get_server_version()
except quart.exceptions.Unauthorized:
except werkzeug.exceptions.Unauthorized:
extra_versions["Prosody"] = "unknown"
return await render_template(
"about.html",
version=version,
extra_versions=extra_versions,
core_versions=core_versions,
)
@@ -165,6 +173,42 @@ async def avatar(from_: str, code: str) -> quart.Response:
return response
@bp.route("/terms")
async def terms() -> Response:
if not current_app.config["TOS_URI"]:
return Response("", 404)
return Response("", status=303, headers={
"Location": current_app.config["TOS_URI"],
})
@bp.route("/privacy")
async def privacy() -> Response:
if not current_app.config["PRIVACY_URI"]:
return Response("", 404)
return Response("", status=303, headers={
"Location": current_app.config["PRIVACY_URI"],
})
# This is linked from the iOS app and about page
@bp.route("/policies/")
async def policies() -> str:
return await render_template(
"policies.html",
)
@bp.route("/.well-known/security.txt")
async def securitytxt() -> Response:
return Response(
await render_template("security.txt"),
mimetype="text/plain;charset=UTF-8",
)
@bp.route("/_health")
async def health() -> Response:
return Response("STATUS OK", content_type="text/plain")

View File

@@ -9,24 +9,28 @@ import types
import typing
import typing_extensions
from datetime import datetime
from datetime import datetime, timezone
import aiohttp
import xml.etree.ElementTree as ET
from quart import (
current_app, _app_ctx_stack, session as http_session, abort, redirect,
current_app, session as http_session, abort, redirect,
url_for,
)
import quart.exceptions
import quart
from flask import g as _app_ctx_stack
import werkzeug.exceptions
from . import xmpputil
from .xmpputil import split_jid
SCOPE_DEFAULT = "prosody:scope:default"
SCOPE_ADMIN = "prosody:scope:admin"
SCOPE_DEFAULT = "prosody:registered"
SCOPE_ADMIN = "prosody:admin"
T = typing.TypeVar("T")
@@ -38,6 +42,52 @@ class TokenInfo:
scopes: typing.Collection[str]
@dataclasses.dataclass(frozen=True)
class UserDeletionRequestInfo:
deleted_at: datetime
pending_until: datetime
@classmethod
def from_api_response(
cls,
data: typing.Optional[typing.Mapping[str, typing.Any]],
) -> typing.Optional["UserDeletionRequestInfo"]:
if data is None:
return None
return cls(
deleted_at=datetime.fromtimestamp(
data["deleted_at"],
tz=timezone.utc
),
pending_until=datetime.fromtimestamp(
data["pending_until"],
tz=timezone.utc
)
)
@dataclasses.dataclass(frozen=True)
class AvatarMetadata:
bytes: int
hash: str
type: str
width: typing.Optional[int]
height: typing.Optional[int]
@classmethod
def from_api_response(
cls,
data: typing.Mapping[str, typing.Any],
) -> "AvatarMetadata":
return cls(
hash=data["hash"],
bytes=data["bytes"],
type=data["type"],
width=data.get("width") or None,
height=data.get("height") or None,
)
@dataclasses.dataclass(frozen=True)
class AdminUserInfo:
localpart: str
@@ -45,6 +95,10 @@ class AdminUserInfo:
email: typing.Optional[str]
phone: typing.Optional[str]
roles: typing.Optional[typing.List[str]]
enabled: bool
last_active: typing.Optional[int]
deletion_request: typing.Optional[UserDeletionRequestInfo]
avatar_info: typing.List[AvatarMetadata]
@property
def has_admin_role(self) -> bool:
@@ -59,12 +113,27 @@ class AdminUserInfo:
cls,
data: typing.Mapping[str, typing.Any],
) -> "AdminUserInfo":
try:
roles: typing.Optional[typing.List[str]] = [data["role"]]
assert roles is not None # make mypy happy
roles.extend(data.get("secondary_roles", []))
except KeyError:
roles = data.get("roles")
return cls(
localpart=data["username"],
display_name=data.get("display_name") or None,
email=data.get("email") or None,
phone=data.get("phone") or None,
roles=data.get("roles"),
roles=roles,
enabled=data.get("enabled", True),
last_active=data.get("last_active") or None,
deletion_request=UserDeletionRequestInfo.from_api_response(
data.get("deletion_request")
),
avatar_info=[
AvatarMetadata.from_api_response(avatar_info)
for avatar_info in data.get("avatar_info", [])
],
)
@@ -107,12 +176,30 @@ class AdminInviteInfo:
)
@dataclasses.dataclass(frozen=True)
class AdminGroupChatInfo:
id_: str
jid: str
name: str
@classmethod
def from_api_response(
cls,
data: typing.Mapping[str, typing.Any],
) -> "AdminGroupChatInfo":
return cls(
id_=data["id"],
jid=data["jid"],
name=data.get("name", ""),
)
@dataclasses.dataclass(frozen=True)
class AdminGroupInfo:
id_: str
name: str
muc_jid: typing.Optional[str]
members: typing.Collection[str]
chats: typing.Collection[AdminGroupChatInfo]
@classmethod
def from_api_response(
@@ -122,8 +209,11 @@ class AdminGroupInfo:
return cls(
id_=data["id"],
name=data["name"],
muc_jid=data.get("muc_jid") or None,
members=data.get("members", []),
chats=[
AdminGroupChatInfo.from_api_response(x)
for x in data.get("chats", [])
]
)
@@ -158,7 +248,7 @@ class HTTPSessionManager:
})
async def teardown(self, exc: typing.Optional[BaseException]) -> None:
app_ctx = _app_ctx_stack.top
app_ctx = _app_ctx_stack
try:
session = getattr(app_ctx, self._app_context_attribute)
except AttributeError:
@@ -175,7 +265,7 @@ class HTTPSessionManager:
await session.__aexit__(exc_type, exc, traceback)
async def __aenter__(self) -> aiohttp.ClientSession:
app_ctx = _app_ctx_stack.top
app_ctx = _app_ctx_stack
try:
return getattr(app_ctx, self._app_context_attribute)
except AttributeError:
@@ -296,6 +386,9 @@ class ProsodyClient:
def _public_v1_endpoint(self, subpath: str) -> str:
return "{}/register_api{}".format(self._endpoint_base, subpath)
def _xep227_endpoint(self, subpath: str) -> str:
return "{}/xep227{}".format(self._endpoint_base, subpath)
async def _oauth2_bearer_token(self,
session: aiohttp.ClientSession,
jid: str,
@@ -383,16 +476,16 @@ class ProsodyClient:
) -> typing.Callable[
[typing.Callable[..., typing.Awaitable[T]]],
typing.Callable[..., typing.Awaitable[
typing.Union[T, quart.Response]]]]:
typing.Union[T, quart.Response, werkzeug.Response]]]]:
def decorator(
f: typing.Callable[..., typing.Awaitable[T]],
) -> typing.Callable[..., typing.Awaitable[
typing.Union[T, quart.Response]]]:
typing.Union[T, quart.Response, werkzeug.Response]]]:
@functools.wraps(f)
async def wrapped(
*args: typing.Any,
**kwargs: typing.Any,
) -> typing.Union[T, quart.Response]:
) -> typing.Union[T, quart.Response, werkzeug.Response]:
if not self.has_session or not (await self.test_session()):
redirect_to_value = redirect_to
if redirect_to_value is not False:
@@ -412,17 +505,17 @@ class ProsodyClient:
) -> typing.Callable[
[typing.Callable[..., typing.Awaitable[T]]],
typing.Callable[..., typing.Awaitable[
typing.Union[T, quart.Response]]]]:
typing.Union[T, quart.Response, werkzeug.Response]]]]:
def decorator(
f: typing.Callable[..., typing.Awaitable[T]],
) -> typing.Callable[..., typing.Awaitable[
typing.Union[T, quart.Response]]]:
typing.Union[T, quart.Response, werkzeug.Response]]]:
@functools.wraps(f)
@self.require_session(redirect_to=redirect_to)
async def wrapped(
*args: typing.Any,
**kwargs: typing.Any,
) -> typing.Union[T, quart.Response]:
) -> typing.Union[T, quart.Response, werkzeug.Response]:
if not self.is_admin_session:
raise abort(403, "This is not for you.")
@@ -489,7 +582,7 @@ class ProsodyClient:
session=session,
)
avatar_hash = avatar_info["sha1"]
except quart.exceptions.HTTPException:
except werkzeug.exceptions.HTTPException:
avatar_hash = None
return {
@@ -641,7 +734,7 @@ class ProsodyClient:
new_access_model,
)
))
except quart.exceptions.NotFound:
except werkzeug.exceptions.NotFound:
if ignore_not_found:
return
raise
@@ -771,7 +864,7 @@ class ProsodyClient:
session: aiohttp.ClientSession,
) -> str:
access_models = filter(
lambda x: not isinstance(x, quart.exceptions.NotFound),
lambda x: not isinstance(x, werkzeug.exceptions.NotFound),
await asyncio.gather(
self.get_avatar_access_model(session=session),
self.get_nickname_access_model(session=session),
@@ -874,7 +967,7 @@ class ProsodyClient:
localpart: str,
*,
display_name: typing.Optional[str],
roles: typing.Optional[typing.Collection[str]],
role: typing.Optional[str],
session: aiohttp.ClientSession,
) -> None:
payload: typing.Dict[str, typing.Any] = {
@@ -882,8 +975,8 @@ class ProsodyClient:
}
if display_name is not None:
payload["display_name"] = display_name
if roles is not None:
payload["roles"] = list(roles)
if role is not None:
payload["role"] = role
async with session.put(
self._admin_v1_endpoint("/users/{}".format(localpart)),
@@ -891,6 +984,36 @@ class ProsodyClient:
) as resp:
self._raise_error_from_response(resp)
@autosession
async def enable_user_account(
self,
localpart: str,
*,
session: aiohttp.ClientSession,
) -> None:
async with session.patch(
self._admin_v1_endpoint("/users/{}".format(localpart)),
json={
"enabled": True,
},
) as resp:
self._raise_error_from_response(resp)
@autosession
async def disable_user_account(
self,
localpart: str,
*,
session: aiohttp.ClientSession,
) -> None:
async with session.patch(
self._admin_v1_endpoint("/users/{}".format(localpart)),
json={
"enabled": False,
},
) as resp:
self._raise_error_from_response(resp)
@autosession
async def get_user_debug_info(
self,
@@ -1019,7 +1142,7 @@ class ProsodyClient:
self,
name: str,
*,
create_muc: bool = True,
create_muc: bool = False,
session: aiohttp.ClientSession,
) -> AdminGroupInfo:
payload = {
@@ -1094,6 +1217,27 @@ class ProsodyClient:
) as resp:
self._raise_error_from_response(resp)
@autosession
async def add_group_chat(
self,
id_: str,
name: str,
*,
session: aiohttp.ClientSession,
) -> None:
payload: typing.Dict[str, typing.Any] = {
"name": name,
}
async with session.post(
self._admin_v1_endpoint(
"/groups/{}/chats".format(id_)
),
json=payload,
) as resp:
self._raise_error_from_response(resp)
@autosession
async def remove_group_member(
self,
@@ -1109,6 +1253,21 @@ class ProsodyClient:
) as resp:
self._raise_error_from_response(resp)
@autosession
async def remove_group_chat(
self,
group_id: str,
chat_id: str,
*,
session: aiohttp.ClientSession,
) -> None:
async with session.delete(
self._admin_v1_endpoint(
"/groups/{}/chats/{}".format(group_id, chat_id)
),
) as resp:
self._raise_error_from_response(resp)
@autosession
async def delete_group(
self,
@@ -1122,6 +1281,33 @@ class ProsodyClient:
self._raise_error_from_response(resp)
@autosession
async def export_account_data(
self,
*,
session: aiohttp.ClientSession,
) -> typing.Optional[str]:
async with session.get(
self._xep227_endpoint("/export?stores=roster,vcard,pep,pep_data"), # noqa:E501
) as resp:
self._raise_error_from_response(resp)
if resp.status == 204:
return None
return await resp.text()
@autosession
async def import_account_data(
self,
user_xml: str,
*,
session: aiohttp.ClientSession,
) -> bool:
async with session.put(
self._xep227_endpoint("/import?stores=roster,vcard,pep,pep_data"), # noqa:E501
data=user_xml,
) as resp:
self._raise_error_from_response(resp)
return True
async def revoke_token(
self,
*,
@@ -1135,7 +1321,8 @@ class ProsodyClient:
async def logout(self) -> None:
try:
await self.revoke_token()
async with self._plain_session as session:
await self.revoke_token(session=session)
except aiohttp.ClientError:
self.logger.warn("failed to revoke token!",
exc_info=True)

View File

@@ -275,22 +275,22 @@ div.form.layout-expanded {
}
@each $type in $text-entry-inputs {
input[type=$type] {
input[type=#{$type}] {
width: 100%;
border: none;
border-bottom: $w-s4 solid $primary-500;
margin-bottom: -$w-s4;
}
input[type=$type].has-error {
input[type=#{$type}].has-error {
border-right: $w-s4 solid $alert-500;
}
input[type=$type]:hover {
input[type=#{$type}]:hover {
border-bottom-color: $primary-700;
}
input[type=$type]:focus {
input[type=#{$type}]:focus {
border-bottom-color: $primary-800;
}
}
@@ -646,69 +646,6 @@ input[type="submit"], button, .button {
/* button, .button {
margin: 0 $w-s2;
}
button.lv-primary, .button.lv-primary {
background-color: $gray-500;
color: $gray-900;
border-radius: $w-s4;
border: $w-s4 solid $gray-400;
@each $type, $values in $colours {
&.c-#{$type} {
border-color: nth($values, 4);
background-color: nth($values, 5);
color: nth($values, 9);
}
&.c-#{$type}:hover {
background-color: nth($values, 4);
}
}
}
button.lv-secondary, .button.lv-secondary {
background-color: $gray-700;
color: $gray-100;
border-radius: $w-s4;
@each $type, $values in $colours {
&.c-#{$type} {
background-color: nth($values, 7);
color: nth($values, 1);
}
}
}
button.lv-tertiary, .button.lv-tertiary {
background-color: inherit;
color: $gray-300;
border-radius: $w-s4;
text-decoration: underline;
@each $type, $values in $colours {
&.c-#{$type} {
color: nth($values, 3);
}
}
}
*/
/*
button.lv-secondary.c-#{$type}, .button.lv-secondary.c-#{$type} {
background-color: nth($values, 7);
color: nth($values, 1);
}
button.lv-tertiary.c-#{$type}, .button.lv-tertiary.c-#{$type} {
color: nth($values, 3);
text-decoration: underline;
background-color: transparent;
}
}*/
/* boxes */
.box {
@@ -771,8 +708,7 @@ button.lv-tertiary, .button.lv-tertiary {
height: 1.5em;
vertical-align: middle;
background-size: cover;
box-shadow: inset 0px 0px 0px 2px rgba(0, 0, 0, 0.2);
border-radius: $w-s4;
border-radius: 10%;
margin: 0 0.25em;
@@ -1121,7 +1057,7 @@ pre.guru-meditation {
}
@each $type in $text-entry-inputs {
input[type=$type] {
input[type=#{$type}] {
background-color: black;
}
@@ -1131,6 +1067,10 @@ pre.guru-meditation {
}
}
label, legend {
color: $gray-800 !important;
}
.box {
background-color: black;
border-color: $gray-800;
@@ -1265,6 +1205,13 @@ pre.guru-meditation {
p.form-desc.weak, p.field-desc.weak {
color: $gray-700;
}
.user-badge-icon {
color: $gray-900 !important;
background-color: $gray-100 !important;
border-color: $gray-300 !important;
box-shadow: black 0 0 2px !important;
}
}
/* tooltip magic */
@@ -1315,3 +1262,46 @@ pre.guru-meditation {
.with-tooltip:hover:before, .with-tooltip:hover:after {
display: block;
}
.username-with-avatar {
display: flex;
align-items: center;
.avatar-container {
position: relative;
.avatar {
margin-left: 0;
}
}
.user-badge-icon {
position: absolute;
bottom: -10px;
right: 0px;
background: white;
border-radius: 50%;
width: 1.2em;
height: 1.2em;
border-color: $gray-500;
border-width: 1px;
border-style: solid;
text-align: center;
margin: 0;
padding: 0;
margin: 0;
padding: 0;
box-shadow: $gray-500 0px 0px 2px;
line-height: 1;
.icon {
/* vertical-align: text-bottom; */
padding: 0.1em;
}
}
.user-info-container {
margin-left: 0.5em;
}
}

View File

@@ -80,60 +80,6 @@ img.fdroid {
height: $w-l3;
}
.tabbox {
display: flex;
flex-direction: column;
margin: $w-l1 0;
> nav.tabs {
display: flex;
flex-direction: row;
> a {
display: inline-block;
padding: $w-s2;
border-top-left-radius: $w-s4;
border-top-right-radius: $w-s4;
&, &:visited {
color: inherit;
text-decoration: underline;
text-decoration-color: $accent-500;
}
&:hover {
background: $accent-900;
border-color: $accent-800;
color: black;
}
&.active {
text-decoration: none;
background: linear-gradient(0deg, $accent-600, $accent-700);
color: $accent-200;
&:hover, &:focus {
background: linear-gradient(0deg, $accent-700, $accent-800);
}
&:active {
background: $accent-600;
}
}
}
}
> .tab-pane {
display: none;
padding: 0 $w-0;
background: $accent-900;
&.active {
display: block;
}
}
}
.qr {
margin: $w-l1 0;
display: flex;

View File

@@ -42,6 +42,21 @@ licensed under the terms of the Apache 2.0 License -->
<g fill="none"><path d="M0 0h24v24H0V0z" /><path d="M0 0h24v24H0V0z" opacity=".87" /></g>
<path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM9 8V6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9z" />
</symbol>
<!-- from: action/lock_open/materialiconsround/24px.svg -->
<symbol id="icon-lock_open" viewBox="0 0 24 24">
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M12 13c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6-5h-1V6c0-2.76-2.24-5-5-5-2.28 0-4.27 1.54-4.84 3.75-.14.54.18 1.08.72 1.22.53.14 1.08-.18 1.22-.72C9.44 3.93 10.63 3 12 3c1.65 0 3 1.35 3 3v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 11c0 .55-.45 1-1 1H7c-.55 0-1-.45-1-1v-8c0-.55.45-1 1-1h10c.55 0 1 .45 1 1v8z" />
</symbol>
<!-- from: action/restore_from_trash/materialiconsround/24px.svg -->
<symbol id="icon-restore_from_trash" viewBox="0 0 24 24">
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v10zm5.65-8.65c.2-.2.51-.2.71 0L16 14h-2v4h-4v-4H8l3.65-3.65zM15.5 4l-.71-.71c-.18-.18-.44-.29-.7-.29H9.91c-.26 0-.52.11-.7.29L8.5 4H6c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1h-2.5z" />
</symbol>
<!-- from: communication/import_export/materialiconsround/24px.svg -->
<symbol id="icon-import_export" viewBox="0 0 24 24">
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M8.65 3.35L5.86 6.14c-.32.31-.1.85.35.85H8V13c0 .55.45 1 1 1s1-.45 1-1V6.99h1.79c.45 0 .67-.54.35-.85L9.35 3.35c-.19-.19-.51-.19-.7 0zM16 17.01V11c0-.55-.45-1-1-1s-1 .45-1 1v6.01h-1.79c-.45 0-.67.54-.35.85l2.79 2.78c.2.19.51.19.71 0l2.79-2.78c.32-.31.09-.85-.35-.85H16z" />
</symbol>
<!-- from: communication/qr_code/materialiconsround/24px.svg -->
<symbol id="icon-qrcode" viewBox="0 0 24 24">
<g><rect fill="none" height="24" width="24" /><rect fill="none" height="24" width="24" /></g>
@@ -88,6 +103,21 @@ licensed under the terms of the Apache 2.0 License -->
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M3.4 20.4l17.45-7.48c.81-.35.81-1.49 0-1.84L3.4 3.6c-.66-.29-1.39.2-1.39.91L2 9.12c0 .5.37.93.87.99L17 12 2.87 13.88c-.5.07-.87.5-.87 1l.01 4.61c0 .71.73 1.2 1.39.91z" />
</symbol>
<!-- from: file/file_download/materialicons/24px.svg -->
<symbol id="icon-download" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" fill="none" />
<path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
</symbol>
<!-- from: file/file_upload/materialicons/24px.svg -->
<symbol id="icon-upload" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" fill="none" />
<path d="M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z" />
</symbol>
<!-- from: file/folder/materialiconsround/24px.svg -->
<symbol id="icon-folder" viewBox="0 0 24 24">
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M10.59 4.59C10.21 4.21 9.7 4 9.17 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-1.41-1.41z" />
</symbol>
<!-- from: navigation/arrow_back/materialiconsround/24px.svg -->
<symbol id="icon-back" viewBox="0 0 24 24">
<path d="M0 0h24v24H0V0z" fill="none" />

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -6,24 +6,32 @@
{% block body %}
<main>
<div class="box el-2">
<h1>{% trans %}About Snikket{% endtrans %}</h1>
<p>{% trans snikket_url="https://snikket.org" %}To learn more about Snikket, visit the <a href="{{ snikket_url}}">Snikket website</a>.{% endtrans %}</p>
<h2>{% trans %}About this Service{% endtrans %}</h2>
<p>{% trans site_name=config["SITE_NAME"] %}This is the Snikket service <em>{{ site_name }}</em>.{% endtrans %}</p>
<p>{% trans site_name=config["SITE_NAME"] %}This is the Snikket service <em>{{ site_name }}</em>, running open-source software from the Snikket project.{% endtrans %}</p>
<p>{% trans snikket_url="https://snikket.org" %}To learn more about Snikket, visit the <a href="{{ snikket_url}}">Snikket website</a>.{% endtrans %}</p>
<p><a href="/policies/">{% trans %}View service policies{% endtrans %}</a>
<h3>{% trans %}Licenses{% endtrans %}</h3>
<p>{% trans agpl_url="https://www.gnu.org/licenses/agpl.html" %}The web portal software is licensed under the terms of the <a href="{{ agpl_url }}">Affero GNU General Public License, version 3.0 or later</a>. The full terms of the license can be reviewed using the aforementioned link.{% endtrans %}</p>
<p>{% trans source_url="https://github.com/snikket-im/snikket-web-portal/" %}The source code of the web portal can be downloaded and viewed in <a href="{{ source_url }}">its GitHub repository</a>.{% endtrans %}</p>
<p>{% trans source_url="https://material.io/resources/icons/", apache20_url="https://www.apache.org/licenses/LICENSE-2.0.txt" %}The icons used in the web portal are <a href="{{ source_url }}">Googles Material Icons</a>, made available by Google under the terms of the <a href="{{ apache20_url }}">Apache 2.0 License</a>.{% endtrans %}</p>
<h3>{% trans %}Trademarks{% endtrans %}</h3>
<p>{% trans trademarks_url="https://snikket.org/about/trademarks/" %}“Snikket” and the parrot logo are trademarks of Snikket Community Interest Company. For more information about the trademarks, visit the <a href="{{ trademarks_url }}">Snikket Trademarks information page</a>.{% endtrans %}
<h3>{% trans %}Software Versions{% endtrans %}</h3>
<pre>Snikket Server
Domain: {{ config["SNIKKET_DOMAIN"] }}
Snikket Web Portal{% if version %} ({{ version }}){% endif %}
<pre>Domain: {{ config["SNIKKET_DOMAIN"] }}
Web Portal{% if version %} ({{ version }}){% endif %}
{%- if core_versions -%}
{% for name, version in core_versions.items() %}
{{ name }} ({{ version }}){% endfor %}
{%- endif -%}
{%- if extra_versions -%}
{% for name, version in extra_versions.items() %}
{{ name }} ({{ version }}){% endfor %}
{%- endif -%}</pre>
<p>
{%- call standard_button("back", url_for("index"), class="primary") -%}
{% trans %}Back to the main page{% endtrans %}

View File

@@ -3,7 +3,7 @@
{% block content %}
<h1>{% trans %}Manage circles{% endtrans %}</h1>
<p>{% trans %}<em>Circles</em> aim to help people who are in the same social circle find each other on your service.{% endtrans %}</p>
<p>{% trans %}Users who are in the same circle will see each other in their contact list. In addition, each circle has a group chat where the circle members are included.{% endtrans %}</p>
<p>{% trans %}Users who are in the same circle will see each other in their contact list. In addition, each circle may have group chats where the circle members are included.{% endtrans %}</p>
{%- if circles -%}
<form method="POST" action="{{ url_for(".create_invite") }}">
{{- invite_form.csrf_token -}}

View File

@@ -0,0 +1,5 @@
{% extends "admin_app.html" %}
{% block content %}
<h1>{{ target_circle.name }}</h1>
{%- include "admin_create_circle_group_chat_form.html" -%}
{% endblock %}

View File

@@ -0,0 +1,15 @@
{% from "library.j2" import form_button, render_errors %}
<form method="POST" action="{{ url_for(".edit_circle_add_chat", id_=target_circle.id_) }}">
{{- group_chat_form.csrf_token -}}
<div class="form layout-expanded">
<h2 class="form-title">{% trans %}Create new circle group chat{% endtrans %}</h2>
<p class="form-descr weak">{% trans %}Add a chat to your circle so its members can hold group discussions.{% endtrans %}</p>
<p class="form-descr weak"><strong>{% trans %}Tip:{% endtrans %}</strong> {% trans %}This is only for creating group chats that automatically include <em>all</em> members of the circle. If you want a normal group chat, create it in the Snikket app instead.{% endtrans %}</p>
<div class="f-ebox">
{{ group_chat_form.name.label }}
{{ group_chat_form.name }}
</div>
<div class="f-bbox">
{%- call form_button("add", group_chat_form.action_save, class="primary") %}{% endcall -%}
</div>
</div></form>

View File

@@ -0,0 +1,21 @@
{% extends "admin_app.html" %}
{% from "library.j2" import box, form_button, standard_button %}
{% block content %}
<h1>{% trans circle_name=target_circle.name %}Delete circle {{ circle_name }}{% endtrans %}</h1>
<div class="form layout-expanded"><form method="POST">
<h2 class="form-title">{% trans %}Delete circle{% endtrans %}</h2>
{{ form.csrf_token }}
<p class="form-descr">{% trans %}Are you sure you want to delete the following circle?{% endtrans %}</p>
<dl>
<dt>{% trans %}Name{% endtrans %}</dt>
<dd>{{ target_circle.name }}</dd>
</dl>
{% call box("alert", _("Danger")) %}
<p>{% trans %}The circle and the corresponding chat will be deleted, permanently and immediately upon pushing the below button. <strong>There is no way back!</strong>{% endtrans %}</p>
{% endcall %}
<div class="f-bbox">
{%- call standard_button("back", url_for(".edit_circle", id_=target_circle.id_), class="tertiary") %}{% trans %}Back{% endtrans %}{% endcall -%}
{%- call form_button("delete", form.action_delete, class="primary danger") %}{% endcall -%}
</div>
</form></div>
{% endblock %}

View File

@@ -13,13 +13,6 @@
<div class="box hint form layout-expanded">
<header>{% trans %}This is your main circle{% endtrans %}</header>
<p>{% trans %}This circle is managed automatically and cannot be removed or renamed.{% endtrans %}</p>
{%- if target_circle.muc_jid -%}
<div><label for="circle-muc-jid">{% trans %}Group chat address{% endtrans %}</label></div>
<div><input type="text" readonly="readonly" id="circle-muc-jid" value="{{ target_circle.muc_jid }}"></div>
{%- call clipboard_button(target_circle.muc_jid, show_label=True) -%}
{%- trans -%}Copy address{%- endtrans -%}
{%- endcall -%}
{%- endif -%}
</div>
{%- else -%}
<div class="form layout-expanded">
@@ -28,17 +21,6 @@
{{ form.name.label }}
{{ form.name }}
</div>
<div class="f-ebox">
{%- if target_circle.muc_jid -%}
<label for="circle-muc-jid">{% trans %}Group chat address{% endtrans %}</label>
<input type="text" readonly="readonly" id="circle-muc-jid" value="{{ target_circle.muc_jid }}">
{%- call clipboard_button(target_circle.muc_jid, show_label=True) -%}
{%- trans -%}Copy address{%- endtrans -%}
{%- endcall -%}
{%- else -%}
<p>{% trans %}This circle has no group chat associated.{% endtrans %}<p>
{%- endif -%}
</div>
<div class="f-bbox">
{%- call standard_button("back", url_for(".circles"), class="tertiary") -%}
{% trans %}Return to circle list{% endtrans %}
@@ -48,11 +30,43 @@
<h3 class="form-title">{% trans %}Delete circle{% endtrans %}</h3>
<p class="form-desc">{% trans %}Deleting a circle does not delete any users in the circle.{% endtrans %}</p>
<div class="f-bbox">
{%- call form_button("delete", form.action_delete, class="secondary danger") %}{% endcall -%}
{%- call standard_button("delete", url_for(".delete_circle", id_=target_circle.id_), class="secondary danger") %}{% trans %}Delete circle{% endtrans %}{% endcall -%}
</div>
</div>
{%- endif -%}
<h2 id="chats">{% trans %}Group chats{% endtrans %}</h2>
<p>{% trans %}These group chats will be available to all members of the circle.{% endtrans %}</p>
{%- if circle_chats -%}
<div class="el-2 elevated"><table>
<thead>
<th>{% trans %}Name{% endtrans %}</th>
<th>{% trans %}Actions{% endtrans %}</th>
</thead>
<tbody>
{%- for chat in circle_chats -%}
<tr>
<td class="collapsible">{% call value_or_hint(chat.name) %}{% endcall %}</td>
<td class="nowrap">
{%- call custom_form_button("delete", form.action_remove_group_chat.name, chat.id_, class="primary danger", slim=True) -%}
{% trans name=chat.name %}Delete group chat '{{ name }}'{% endtrans %}
{%- endcall -%}
</td>
</tr>
{%- endfor -%}
</tbody>
</table></div>
{%- else -%}
<p>{% trans %}This circle currently has no group chats.{% endtrans %}</p>
{%- endif -%}
{%- call standard_button("add", url_for(".edit_circle_add_chat", id_=target_circle.id_), class="secondary") -%}
{% trans %}Add group chat{% endtrans %}
{%- endcall -%}
<h2 id="members">{% trans %}Circle members{% endtrans %}</h2>
<p>{% trans %}All members of the circle will see each other in their contact list.{% endtrans %}</p>
{%- if circle_members -%}
<div class="el-2 elevated"><table>
<thead>

View File

@@ -3,7 +3,7 @@
{% macro access_level_description(role, caller=None) %}
{%- if role == "prosody:restricted" -%}
{% trans %}Limited users can interact with users on the same Snikket service and be members of circles.{% endtrans %}
{%- elif role == "prosody:normal" -%}
{%- elif role == "prosody:registered" -%}
{% trans %}Like limited users and can also interact with users on other Snikket services.{% endtrans %}
{%- elif role == "prosody:admin" -%}
{% trans %}Like normal users and can access the admin panel in the web portal.{% endtrans %}
@@ -19,12 +19,33 @@
{% block content %}
<h1>{% trans user_name=target_user.localpart %}Edit user {{ user_name }}{% endtrans %}</h1>
<form method="POST">{{ form.csrf_token }}<div class="form layout-expanded">
{% if target_user.deletion_request %}
<div class="box alert">
<header>{% trans %}This user account is pending deletion{% endtrans %}</header>
<p>{% trans date=target_user.deletion_request.deleted_at | format_datetime %}The owner of the account sent a deletion request on {{ date }} using their app.{% endtrans %}
<p>{% trans time=(target_user.deletion_request.pending_until - now())|format_timedelta %}The account has been locked, and will be automatically deleted permanently in {{ time }}.{% endtrans %}</p>
<p>{% trans %}If this was a mistake, you can cancel the deletion and restore the account.{% endtrans %}</p>
{%- call form_button("restore_from_trash", form.action_restore, class="secondary") %}{% endcall %}
</div>
{% elif not target_user.enabled %}
<div class="box alert">
<header>{% trans %}This user account is locked{% endtrans %}</header>
<p>{% trans %}The user will not be able to log in to their account until it is unlocked again.{% endtrans %}</p>
{%- call form_button("lock_open", form.action_enable, class="secondary") %}{% endcall %}
</div>
{% endif %}
<h2 class="form-title">{% trans %}Edit user{% endtrans %}</h2>
<div class="f-ebox">
{{ form.localpart.label }}
{{ form.localpart(readonly="readonly") }}
<p class="form-desc weak">{% trans %}The login name cannot be changed.{% endtrans %}</p>
</div>
<div class="f-ebox">
{{ form.display_name.label }}
{{ form.display_name }}
@@ -63,14 +84,14 @@
{% trans %}If the user has lost their password, you can use the button below to create a special link which allows to change the password of the account, once.{% endtrans %}
</p>
<div class="f-bbox">
{%- call form_button("passwd", form.action_create_reset, class="primary") -%}{%- endcall -%}
{%- call form_button("passwd", form.action_create_reset, class="secondary") -%}{%- endcall -%}
</div>
<h2 class="form-title">{% trans %}Debug information{% endtrans %}</h2>
<p class="form-desc">
{% trans %}In some cases, extended information about the user account and the connected devices is necessary to troubleshoot issues. The button below reveals this (sensitive) information.{% endtrans %}
</p>
<div class="f-bbox">
{%- call standard_button("bug_report", url_for(".debug_user", localpart=target_user.localpart), class="primary") -%}
{%- call standard_button("bug_report", url_for(".debug_user", localpart=target_user.localpart), class="secondary") -%}
{%- trans -%}Show debug information{%- endtrans -%}
{%- endcall -%}
</div>

View File

@@ -68,6 +68,14 @@
<em>{% trans %}unknown{% endtrans %}</em>
{%- endif -%}
</dd>
<dt>{% trans %}Storage used by shared files{% endtrans %}</dt>
<dd>
{%- if metrics.prosody_uploads | default(None) is not none -%}
{{ metrics.prosody_uploads | format_bytes }}
{%- else -%}
<em>{% trans %}unknown{% endtrans %}</em>
{%- endif -%}
</dd>
<dt>{% trans %}Connected devices{% endtrans %}</dt>
<dd>
{%- if metrics.prosody_devices | default(None) is not none -%}

View File

@@ -1,12 +1,12 @@
{% extends "admin_app.html" %}
{% from "library.j2" import action_button, icon, value_or_hint, custom_form_button %}
{% from "library.j2" import action_button, avatar, icon, render_user, value_or_hint, custom_form_button with context %}
{% block content %}
<h1>{% trans %}Manage users{% endtrans %}</h1>
<div class="elevated el-2"><table>
<thead>
<tr>
<th>{% trans %}Login name{% endtrans %}</th>
<th>{% trans %}Display name{% endtrans %}</th>
<th>{% trans %}User{% endtrans %}</th>
<th>{% trans %}Last active{% endtrans %}</th>
<th>{% trans %}Actions{% endtrans %}</th>
</tr>
</thead>
@@ -14,15 +14,15 @@
{% for user in users %}
<tr>
<td>
{{- user.localpart -}}
{%- if user.has_admin_role -%}
<span class="with-tooltip above" data-tooltip="{% trans %}The user is an administrator.{% endtrans %}">{% call icon("admin") %}{% trans %} (Administrator){% endtrans %}{% endcall %}</span>
{%- endif -%}
{%- if user.has_restricted_role -%}
<span class="with-tooltip above" data-tooltip="{% trans %}The user is restricted.{% endtrans %}">{% call icon("lock") %}{% trans %} (Restricted){% endtrans %}{% endcall %}</span>
{%- endif -%}
{%- call render_user(user) -%}{%- endcall -%}
</td>
<td>{% call value_or_hint(user.display_name) %}{% endcall %}</td>
{% if user.enabled %}
<td>{{ user.last_active | format_last_activity }}</td>
{% elif user.deletion_request %}
<td>{% trans %}Deleted{% endtrans %}</td>
{% else %}
<td>{% trans %}Locked{% endtrans %}</td>
{% endif %}
<td class="nowrap">
{%- call action_button("edit", url_for(".edit_user", localpart=user.localpart), class="primary") -%}
{% trans user_name=user.localpart %}Edit user {{ user_name }}{% endtrans %}

View File

@@ -28,12 +28,12 @@
</div>
<div class="f-ebox">
{{ form.password.label }}
{{ form.password }}
{{ form.password(autocomplete="new-password") }}
<p class="field-desc weak">{% trans %}Enter a secure password that you do not use anywhere else.{% endtrans %}</p>
</div>
<div class="f-ebox">
{{ form.password_confirm.label }}
{{ form.password_confirm }}
{{ form.password_confirm(autocomplete="new-password") }}
</div>
<div class="f-bbox">
{%- call form_button("done", form.action_register, class="primary") -%}{%- endcall -%}

View File

@@ -7,7 +7,6 @@
{% block head_lead %}
{{ super() }}
<title>{% trans %}Reset your password | Snikket{% endtrans %}</title>
<script async type="text/javascript" src="{{ url_for("static", filename="js/qrcode.min.js") }}"></script>
{% endblock %}
{% block content %}
<form method="POST"><div class="form layout-expanded">
@@ -17,19 +16,14 @@
{%- call render_errors(form) %}{% endcall -%}
<div class="f-ebox">
{{ form.password.label }}
{{ form.password }}
{{ form.password(autocomplete="new-password") }}
</div>
<div class="f-ebox">
{{ form.password_confirm.label }}
{{ form.password_confirm }}
{{ form.password_confirm(autocomplete="new-password") }}
</div>
<div class="f-bbox">
{%- call form_button("passwd", form.action_reset, class="primary") -%}{%- endcall -%}
</div>
</div></form>
<script type="text/javascript">
var onload = function() {
apply_qr_code(document.getElementById("qr-uri"));
};
</script>
{% endblock %}

View File

@@ -1,6 +1,6 @@
{% extends "invite.html" %}
{% set body_id = "invite" %}
{% from "library.j2" import form_button, clipboard_button %}
{% from "library.j2" import form_button, clipboard_button, render_errors %}
{% block head_lead %}
<title>{% trans site_name=config["SITE_NAME"] %}Successfully registered on {{ site_name }} | Snikket{% endtrans %}</title>
{%- include "copy-snippet.html" -%}
@@ -16,5 +16,46 @@
{%- endcall -%}
<p>{% trans %}You can now set up your legacy XMPP client with the above address and the password you chose during registration.{% endtrans %}</p>
<p>{% trans login_url=url_for('main.login') %}You can now safely close this page, or log in to the web portal to <a href="{{ login_url }}">manage your account</a>.{% endtrans %}</p>
{% if migration_success %}
<h2>{% trans %}Import successful{% endtrans %}</h2>
<p>{% trans %}Congratulations! Your account data has been successfully imported.{% endtrans %}</p>
{% endif %}
{% if form %}
<h2>{% trans %}Moving to Snikket?{% endtrans %}</h2>
<p>{% trans %}If you are moving from a different Snikket instance or another XMPP-compatible service, you may optionally import the data (contacts, profile information, etc.) from your previous account. When you have exported the data from your previous account, upload it using the form below.{% endtrans %}</p>
<div class="form layout-expanded"><form method="POST" enctype="multipart/form-data">
<h3 class="form-title">{% trans %}Upload account data{% endtrans %}</h3>
{{ form.csrf_token }}
{% call render_errors(form) %}{% endcall %}
<div class="f-ebox">
{{ form.account_data_file.label }}
{{ form.account_data_file(accept="application/xml",
data_maxsize=max_import_size,
data_warning_header=import_too_big_warning_header,
data_maxsize_warning=import_too_big_warning) }}
</div>
<div class="f-bbox">
{%- call form_button("upload", form.action_import, class="secondary") %}{% endcall -%}
</div>
<script type="text/javascript">
document.getElementById("{{ form.account_data_file.id }}").onchange = function() {
var maxsize_s = this.dataset.maxsize;
var maxsize = parseInt(maxsize_s);
if (this.files[0].size > maxsize) {
var warning_header = this.dataset.warningHeader;
var warning_text = this.dataset.maxsizeWarning;
this.setCustomValidity(warning_text);
this.reportValidity();
this.value = null;
} else {
this.setCustomValidity("");
}
};
</script>
</form></div>
{% endif %}
</div>
{% endblock %}

View File

@@ -17,6 +17,13 @@
{%- else -%}
<p>{% trans site_name=config["SITE_NAME"] %}You have been invited to chat on {{ site_name }} using Snikket, a secure, privacy-friendly chat app.{% endtrans %}</p>
{%- endif -%}
{%- if config["TOS_URI"] and config["PRIVACY_URI"] -%}
<p>
{% trans site_name=config["SITE_NAME"], tos_uri=config["TOS_URI"], privacy_uri=config["PRIVACY_URI"] %}By continuing, you agree to the <a href="{{tos_uri}}">Terms of Service</a> and <a href="{{privacy_uri}}">Privacy Policy</a>.{% endtrans %}
</p>
{%- endif -%}
<h2>{% trans %}Get started{% endtrans %}</h2>
{%- if apple_store_url -%}
<p>{% trans %}Install the Snikket App on your Android or iOS device.{% endtrans %}</p>
@@ -56,29 +63,7 @@
{%- endcall -%}
</header>
<p>{% trans %}You can transfer this invite to your mobile device by scanning a code with your camera. You can use either a QR scanner app or the Snikket app itself.{% endtrans %}</p>
<div class="tabbox">
{#- -#}
<nav class="tabs" role="tablist">
{#- -#}
<a href="#qr-info-url" class="active" role="tab" aria-controls="qr-info-url" aria-selected="true" onclick="select_tab(this); return false;">{% trans %}Using a QR code scanner{% endtrans %}</a>
{#- -#}
<a href="#qr-info-uri" role="tab" aria-controls="qr-info-uri" aria-selected="false" onclick="select_tab(this); return false;">{% trans %}Using the Snikket app{% endtrans %}</a>
{#- -#}
</nav>
{#- -#}
<div id="qr-info-url" class="tab-pane active">
<p>{% trans %}Use a <em>QR code</em> scanner on your mobile device to scan the code below:{% endtrans %}</p>
<div id="qr-invite-page" data-qrdata="{{ url_for(".view", id_=invite_id, _external=True, _scheme="https") }}" class="qr"></div>
</div>
{#- -#}
<div id="qr-info-uri" class="tab-pane">
<img class="float-right" id="tutorial-scan" aria-hidden="true" alt="" src="{{ url_for("static", filename="img/tutorial-scan.png") }}">
<p>{% trans %}Install the Snikket app on your mobile device, open it, and tap the 'Scan' button at the top.{% endtrans %}</p>
<p>{% trans %}Your camera will turn on. Point it at the square code below until it is within the highlighted square on your screen, and wait until the app recognises it.{% endtrans %}</p>
<div id="qr-uri" data-qrdata="{{ invite.xmpp_uri }}" class="qr"></div>
</div>
{#- -#}
</div>
<div id="qr-invite-page" data-qrdata="{{ url_for(".view", id_=invite_id, _external=True, _scheme="https") }}" class="qr"></div>
{#- -#}
{%- call standard_button("close", "#", onclick="close_modal(this.parentNode.parentNode); return false;", class="primary") -%}
{% trans %}Close{% endtrans %}
@@ -149,7 +134,6 @@
var onload = function() {
apply_qr_code(document.getElementById("qr-invite-page"));
apply_qr_code(document.getElementById("qr-uri"));
var popover_as = document.getElementsByClassName("popover");
for (var i = 0; i < popover_as.length; ++i) {
var a = popover_as[i];

View File

@@ -10,6 +10,29 @@
{%- endif -%}
{%- endmacro %}
{% macro render_user(user, caller=None) -%}
<div class="username-with-avatar">
<div class="avatar-container">
{%- call avatar(user.localpart+"@"+config["SNIKKET_DOMAIN"], user.avatar_info[0].hash if user.avatar_info | length > 0 else None ) %}{% endcall -%}
{%- if user.has_admin_role -%}
<div class="user-badge-icon">
<span class="with-tooltip above" data-tooltip="{% trans %}The user is an administrator.{% endtrans %}">{% call icon("admin") %}{% trans %} (Administrator){% endtrans %}{% endcall %}</span>
</div>
{%- elif user.has_restricted_role -%}
<div class="user-badge-icon">
<span class="with-tooltip above" data-tooltip="{% trans %}The user is restricted.{% endtrans %}">{% call icon("lock") %}{% trans %} (Restricted){% endtrans %}{% endcall %}</span>
</div>
{%- endif -%}
</div>
<div class="user-info-container">
<div class="user-localpart">{{- user.localpart -}}</div>
{%- if user.display_name %}
<div class="user-display-name">{{- user.display_name -}}</div>
{%- endif %}
</div>
</div>
{%- endmacro -%}
{% macro showuri(uri, caller=None, id_=None) %}
{%- if uri is none -%}
<em>—</em>

View File

@@ -0,0 +1,39 @@
{% extends "base.html" %}
{% from "library.j2" import standard_button %}
{% block head_lead %}
<title>{% trans %}Policies{% endtrans %} - {{ config["SITE_NAME"] }}</title>
{% endblock %}
{% block body %}
<main>
<div class="box el-2">
<h1>{{ config["SITE_NAME"] }}</h1>
<h2>{% trans %}Policies{% endtrans %}</h2>
{% if config["TOS_URI"] or config["PRIVACY_URI"] -%}
<p>{% trans %}Use of this service is subject to the following policies:{% endtrans %}</p>
<ul>
{%- if config["TOS_URI"] %}
<li><a href="{{ config["TOS_URI"] }}">{% trans %}Terms of Service{% endtrans %}</a></li>
{%- endif %}
{%- if config["PRIVACY_URI"] %}
<li><a href="{{ config["PRIVACY_URI"] }}">{% trans %}Privacy Policy{% endtrans %}</a></li>
{%- endif %}
</ul>
{%- else -%}
<p>{% trans %}Please contact the administrator of this instance if you have questions about policies.{% endtrans %}</p>
{% endif -%}
<p>{% trans url="https://snikket.org/app/privacy/" %}Use of the Snikket apps is subject to the <a href="{{url}}">Snikket Apps Privacy Policy</a>.{% endtrans %}</p>
{%- if config["ABUSE_EMAIL"] %}
<p>{% trans email=config["ABUSE_EMAIL"], domain=config["SNIKKET_DOMAIN"] %}To report policy violations or other abuse from this service, please send an email to {{email}}. Specify the domain name of this instance ({{domain}}) and include details of the incident(s).{% endtrans %}</p>
{%- endif %}
<p>
{%- call standard_button("back", url_for("index"), class="primary") -%}
{% trans %}Back to the main page{% endtrans %}
{%- endcall -%}
</p>
</div>
</main>
{% endblock %}

View File

@@ -0,0 +1,16 @@
# {{ config["SNIKKET_DOMAIN"] }} is running open-source software
# from the Snikket project: https://snikket.org/
{% if config["SECURITY_EMAIL"] -%}
# Security issues related to this service should be addressed to the
# following security contact:
Contact: mailto:{{ config["SECURITY_EMAIL"] }}
{% else -%}
# This service does not have a public security contact. You might find
# more information about the service at the following link:
Contact: https://{{ config["SNIKKET_DOMAIN"] }}/policies/
{%- endif %}
# Please report software defects to the project developers, per the
# instructions at the following link:
Contact: https://snikket.org/security/

View File

@@ -30,6 +30,7 @@
<div>
<div>{% call standard_button("edit", url_for(".profile"), class="primary") %}{% trans %}Edit profile{% endtrans %}{% endcall %}</div>
<div>{% call standard_button("passwd", url_for(".change_pw"), class="secondary") %}{% trans %}Change password{% endtrans %}{% endcall %}</div>
<div>{% call standard_button("folder", url_for(".manage_data"), class="secondary") %}{% trans %}Manage your data{% endtrans %}{% endcall %}</div>
</div>
{#- -#}
</li>

View File

@@ -0,0 +1,24 @@
{% extends "app.html" %}
{% from "library.j2" import standard_button, form_button, render_errors, avatar with context %}
{% block content %}
<h1>{% trans %}Manage your data{% endtrans %}</h1>
<nav class="welcome">
<ul>
<li>
<h2>{% trans %}Export account{% endtrans %}</h2>
<p>{% trans %}Download your account data as a file for backup purposes or to move your account to another service.{% endtrans %}</p>
{% call render_errors(form) %}{% endcall %}
<div class="f-bbox">
{%- call standard_button("back", url_for('.index'), class="tertiary") %}{% trans %}Back{% endtrans %}{% endcall -%}
<form method="POST">
{{ form.csrf_token }}
{%- call form_button("download", form.action_export, class="primary") %}{% endcall -%}
</form>
</div>
</li>
</ul>
</nav>
{% endblock %}

View File

@@ -9,15 +9,15 @@
{%- endcall -%}
<div class="f-ebox">
{{ form.current_password.label(class="required") }}
{{ form.current_password(class=("has-error" if form.current_password.name in form.errors else "")) }}
{{ form.current_password(class=("has-error" if form.current_password.name in form.errors else ""), autocomplete="current-password") }}
</div>
<div class="f-ebox">
{{ form.new_password.label(class="required") }}
{{ form.new_password }}
{{ form.new_password(autocomplete="new-password") }}
</div>
<div class="f-ebox">
{{ form.new_password_confirm.label(class="required") }}
{{ form.new_password_confirm(class=("has-error" if form.new_password_confirm.name in form.errors else "")) }}
{{ form.new_password_confirm(class=("has-error" if form.new_password_confirm.name in form.errors else ""), autocomplete="new-password") }}
</div>
<div class="box warning">
<header>{% trans %}Warning{% endtrans %}</header>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,11 @@
import asyncio
import typing
import urllib
import quart.flask_patch
from quart import (
Blueprint,
Response,
render_template,
request,
redirect,
@@ -11,7 +13,7 @@ from quart import (
flash,
current_app,
)
import quart.exceptions
import werkzeug.exceptions
import wtforms
@@ -57,7 +59,7 @@ _ACCESS_MODEL_CHOICES = [
class ProfileForm(BaseForm):
nickname = wtforms.TextField(
nickname = wtforms.StringField(
_l("Display name"),
)
@@ -75,6 +77,16 @@ class ProfileForm(BaseForm):
)
class ImportAccountDataForm(BaseForm):
account_data_file = wtforms.FileField(
_l("Account data")
)
action_upload = wtforms.SubmitField(
_l("Upload"),
)
@bp.route("/")
@client.require_session()
async def index() -> str:
@@ -84,7 +96,7 @@ async def index() -> str:
@bp.route('/passwd', methods=["GET", "POST"])
@client.require_session()
async def change_pw() -> typing.Union[str, quart.Response]:
async def change_pw() -> typing.Union[str, werkzeug.Response]:
form = ChangePasswordForm()
if form.validate_on_submit():
try:
@@ -92,8 +104,8 @@ async def change_pw() -> typing.Union[str, quart.Response]:
form.current_password.data,
form.new_password.data,
)
except (quart.exceptions.Unauthorized,
quart.exceptions.Forbidden):
except (werkzeug.exceptions.Unauthorized,
werkzeug.exceptions.Forbidden):
# server refused current password, set an appropriate error
form.current_password.errors.append(
_("Incorrect password."),
@@ -116,7 +128,7 @@ EAVATARTOOBIG = _l(
@bp.route("/profile", methods=["GET", "POST"])
@client.require_session()
async def profile() -> typing.Union[str, quart.Response]:
async def profile() -> typing.Union[str, werkzeug.Response]:
max_avatar_size = current_app.config["MAX_AVATAR_SIZE"]
form = ProfileForm()
@@ -138,7 +150,6 @@ async def profile() -> typing.Union[str, quart.Response]:
mimetype = file_info.mimetype
data = file_info.stream.read()
if len(data) > max_avatar_size:
print(len(data), max_avatar_size)
form.avatar.errors.append(EAVATARTOOBIG)
ok = False
elif len(data) > 0:
@@ -168,9 +179,49 @@ async def profile() -> typing.Union[str, quart.Response]:
avatar_too_big_warning=EAVATARTOOBIG)
class DataExportForm(BaseForm):
action_export = wtforms.SubmitField(
_l("Export")
)
@bp.route("/manage_data", methods=["GET", "POST"])
@client.require_session()
async def manage_data() -> typing.Union[str, quart.Response]:
form = DataExportForm()
if form.validate_on_submit():
user_info = await client.get_user_info()
# The UTF-8 version of the filename needs to be percent-encoded
encoded_address = urllib.parse.quote(
user_info["address"].encode(encoding='utf-8', errors='strict')
)
account_data = await client.export_account_data()
if account_data is None:
await flash(
_("You currently have no account data to export."),
"alert"
)
else:
return Response(account_data,
mimetype="application/xml",
headers={
# We provide the UTF-8 filename, but the ASCII
# one will be used as a fallback for legacy
# browsers (RFC 5987)
"Content-Disposition": (
'attachment; filename="account-data.xml"; '
'filename*="UTF-8\'\'account-data-{}.xml"'
).format(encoded_address)
})
return await render_template("user_manage_data.html",
form=form,
)
@bp.route("/logout", methods=["GET", "POST"])
@client.require_session()
async def logout() -> typing.Union[quart.Response, str]:
async def logout() -> typing.Union[werkzeug.Response, str]:
form = LogoutForm()
if form.validate_on_submit():
await client.logout()

View File

@@ -4,7 +4,7 @@ import typing
import xml.etree.ElementTree as ET
from quart import abort
import quart.exceptions
import werkzeug.exceptions
TAG_XMPP_ERROR = "error"
@@ -207,7 +207,7 @@ def make_avatar_metadata_set_request(
item,
"metadata", xmlns=NS_USER_AVATAR_METADATA)
attr: typing.MutableMapping[str, str] = {
attr: typing.Dict[str, str] = {
"id": id_,
"bytes": str(size),
"type": mimetype,
@@ -217,7 +217,12 @@ def make_avatar_metadata_set_request(
if height is not None:
attr["height"] = str(height)
ET.SubElement(metadata_wrap, "info", xmlns=NS_USER_AVATAR_METADATA, **attr)
ET.SubElement(
metadata_wrap,
"info",
xmlns=NS_USER_AVATAR_METADATA,
**attr, # type: ignore
)
return req
@@ -234,7 +239,7 @@ def extract_pubsub_item_get_reply(
) -> typing.Optional[ET.Element]:
try:
pubsub = extract_iq_reply(iq_tree, TAG_PUBSUB)
except quart.exceptions.NotFound:
except werkzeug.exceptions.NotFound:
return None
if pubsub is None:

View File

@@ -6,6 +6,9 @@ action/logout:logout
action/login:login
action/exit_to_app:exit_to_app
action/lock:lock
action/lock_open:lock_open
action/restore_from_trash:restore_from_trash
communication/import_export:import_export
communication/qr_code:qrcode
communication/vpn_key:passwd
communication/rss_feed:broadcast
@@ -15,6 +18,9 @@ content/remove_circle_outline:remove
content/content_copy:copy
content/link_off:remove_link
content/send:send
file/file_download:download
file/file_upload:upload
file/folder:folder
navigation/arrow_back:back
navigation/arrow_forward:forward
navigation/cancel:cancel

6
tools/import-icons.sh Normal file → Executable file
View File

@@ -9,9 +9,9 @@ set -euo pipefail
# FLAVOR one of '', 'round', 'sharp', 'outlined', 'twoshade'
# SVGOUT path to the newly created SVG file
root="$1/src"
iconlist_file="$2"
flavor="$3"
output_file="$4"
iconlist_file="${2-tools/icons.list}"
flavor="${3-round}"
output_file="${4-snikket_web/static/img/icons.svg}"
printf '<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n<defs>\n' > "$output_file"
printf '<!-- These icons are sourced from Googles Material Icons set,\nlicensed under the terms of the Apache 2.0 License -->\n' >> "$output_file"