slidge 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (102) hide show
  1. slidge/__init__.py +3 -5
  2. slidge/__main__.py +2 -197
  3. slidge/__version__.py +5 -0
  4. slidge/command/adhoc.py +40 -17
  5. slidge/command/admin.py +24 -12
  6. slidge/command/base.py +10 -8
  7. slidge/command/categories.py +13 -3
  8. slidge/command/chat_command.py +29 -2
  9. slidge/command/register.py +32 -16
  10. slidge/command/user.py +106 -13
  11. slidge/contact/contact.py +254 -50
  12. slidge/contact/roster.py +124 -53
  13. slidge/core/config.py +19 -13
  14. slidge/core/dispatcher/__init__.py +3 -0
  15. slidge/core/{gateway → dispatcher}/caps.py +12 -8
  16. slidge/core/{gateway → dispatcher}/disco.py +10 -18
  17. slidge/core/dispatcher/message/__init__.py +10 -0
  18. slidge/core/dispatcher/message/chat_state.py +40 -0
  19. slidge/core/dispatcher/message/marker.py +62 -0
  20. slidge/core/dispatcher/message/message.py +397 -0
  21. slidge/core/dispatcher/muc/__init__.py +12 -0
  22. slidge/core/dispatcher/muc/admin.py +98 -0
  23. slidge/core/{gateway → dispatcher/muc}/mam.py +25 -17
  24. slidge/core/dispatcher/muc/misc.py +121 -0
  25. slidge/core/dispatcher/muc/owner.py +96 -0
  26. slidge/core/{gateway → dispatcher/muc}/ping.py +11 -17
  27. slidge/core/dispatcher/presence.py +176 -0
  28. slidge/core/dispatcher/registration.py +85 -0
  29. slidge/core/{gateway → dispatcher}/search.py +9 -16
  30. slidge/core/dispatcher/session_dispatcher.py +84 -0
  31. slidge/core/dispatcher/util.py +174 -0
  32. slidge/core/{gateway/vcard_temp.py → dispatcher/vcard.py} +35 -19
  33. slidge/core/{gateway/base.py → gateway.py} +176 -153
  34. slidge/core/mixins/__init__.py +11 -1
  35. slidge/core/mixins/attachment.py +106 -67
  36. slidge/core/mixins/avatar.py +94 -25
  37. slidge/core/mixins/base.py +10 -4
  38. slidge/core/mixins/db.py +18 -0
  39. slidge/core/mixins/disco.py +0 -10
  40. slidge/core/mixins/lock.py +10 -8
  41. slidge/core/mixins/message.py +11 -195
  42. slidge/core/mixins/message_maker.py +17 -9
  43. slidge/core/mixins/message_text.py +211 -0
  44. slidge/core/mixins/presence.py +17 -4
  45. slidge/core/pubsub.py +114 -288
  46. slidge/core/session.py +101 -40
  47. slidge/db/__init__.py +4 -0
  48. slidge/db/alembic/__init__.py +0 -0
  49. slidge/db/alembic/env.py +64 -0
  50. slidge/db/alembic/old_user_store.py +183 -0
  51. slidge/db/alembic/script.py.mako +26 -0
  52. slidge/db/alembic/versions/09f27f098baa_add_missing_attributes_in_room.py +36 -0
  53. slidge/db/alembic/versions/15b0bd83407a_remove_bogus_unique_constraints_on_room_.py +85 -0
  54. slidge/db/alembic/versions/2461390c0af2_store_contacts_caps_verstring_in_db.py +36 -0
  55. slidge/db/alembic/versions/29f5280c61aa_store_subject_setter_in_room.py +37 -0
  56. slidge/db/alembic/versions/2b1f45ab7379_store_room_subject_setter_by_nickname.py +41 -0
  57. slidge/db/alembic/versions/3071e0fa69d4_add_contact_client_type.py +52 -0
  58. slidge/db/alembic/versions/45c24cc73c91_add_bob.py +42 -0
  59. slidge/db/alembic/versions/5bd48bfdffa2_lift_room_legacy_id_constraint.py +61 -0
  60. slidge/db/alembic/versions/82a4af84b679_add_muc_history_filled.py +48 -0
  61. slidge/db/alembic/versions/8b993243a536_add_vcard_content_to_contact_table.py +43 -0
  62. slidge/db/alembic/versions/8d2ced764698_rely_on_db_to_store_contacts_rooms_and_.py +139 -0
  63. slidge/db/alembic/versions/aa9d82a7f6ef_db_creation.py +101 -0
  64. slidge/db/alembic/versions/abba1ae0edb3_store_avatar_legacy_id_in_the_contact_.py +79 -0
  65. slidge/db/alembic/versions/b33993e87db3_move_everything_to_persistent_db.py +214 -0
  66. slidge/db/alembic/versions/b64b1a793483_add_source_and_legacy_id_for_archived_.py +52 -0
  67. slidge/db/alembic/versions/c4a8ec35a0e8_per_room_user_nick.py +34 -0
  68. slidge/db/alembic/versions/e91195719c2c_store_users_avatars_persistently.py +26 -0
  69. slidge/db/avatar.py +205 -0
  70. slidge/db/meta.py +72 -0
  71. slidge/db/models.py +405 -0
  72. slidge/db/store.py +1257 -0
  73. slidge/group/archive.py +58 -14
  74. slidge/group/bookmarks.py +89 -65
  75. slidge/group/participant.py +111 -44
  76. slidge/group/room.py +402 -213
  77. slidge/main.py +202 -0
  78. slidge/migration.py +45 -1
  79. slidge/slixfix/__init__.py +31 -1
  80. slidge/{core/gateway → slixfix}/delivery_receipt.py +1 -1
  81. slidge/slixfix/roster.py +13 -4
  82. slidge/slixfix/xep_0292/vcard4.py +1 -87
  83. slidge/util/archive_msg.py +2 -1
  84. slidge/util/db.py +4 -228
  85. slidge/util/test.py +91 -4
  86. slidge/util/types.py +39 -4
  87. slidge/util/util.py +45 -2
  88. {slidge-0.1.2.dist-info → slidge-0.2.0.dist-info}/METADATA +10 -5
  89. slidge-0.2.0.dist-info/RECORD +131 -0
  90. slidge-0.2.0.dist-info/entry_points.txt +3 -0
  91. slidge/core/cache.py +0 -183
  92. slidge/core/gateway/__init__.py +0 -3
  93. slidge/core/gateway/muc_admin.py +0 -35
  94. slidge/core/gateway/presence.py +0 -95
  95. slidge/core/gateway/registration.py +0 -53
  96. slidge/core/gateway/session_dispatcher.py +0 -795
  97. slidge/util/schema.sql +0 -126
  98. slidge/util/sql.py +0 -508
  99. slidge-0.1.2.dist-info/RECORD +0 -96
  100. slidge-0.1.2.dist-info/entry_points.txt +0 -3
  101. {slidge-0.1.2.dist-info → slidge-0.2.0.dist-info}/LICENSE +0 -0
  102. {slidge-0.1.2.dist-info → slidge-0.2.0.dist-info}/WHEEL +0 -0
@@ -0,0 +1,214 @@
1
+ """Move everything to persistent DB
2
+
3
+ Revision ID: b33993e87db3
4
+ Revises: e91195719c2c
5
+ Create Date: 2024-06-25 16:09:36.663953
6
+
7
+ """
8
+
9
+ import shutil
10
+ from typing import Sequence, Union
11
+
12
+ import sqlalchemy as sa
13
+ from alembic import op
14
+
15
+ import slidge.db.meta
16
+ from slidge import global_config
17
+
18
+ # revision identifiers, used by Alembic.
19
+ revision: str = "b33993e87db3"
20
+ down_revision: Union[str, None] = "e91195719c2c"
21
+ branch_labels: Union[str, Sequence[str], None] = None
22
+ depends_on: Union[str, Sequence[str], None] = None
23
+
24
+
25
+ def upgrade() -> None:
26
+ # ### commands auto generated by Alembic - please adjust! ###
27
+ op.create_table(
28
+ "avatar",
29
+ sa.Column("id", sa.Integer(), nullable=False),
30
+ sa.Column("filename", sa.String(), nullable=False),
31
+ sa.Column("hash", sa.String(), nullable=False),
32
+ sa.Column("height", sa.Integer(), nullable=False),
33
+ sa.Column("width", sa.Integer(), nullable=False),
34
+ sa.Column("legacy_id", sa.String(), nullable=True),
35
+ sa.Column("url", sa.String(), nullable=True),
36
+ sa.Column("etag", sa.String(), nullable=True),
37
+ sa.Column("last_modified", sa.String(), nullable=True),
38
+ sa.PrimaryKeyConstraint("id"),
39
+ sa.UniqueConstraint("filename"),
40
+ sa.UniqueConstraint("hash"),
41
+ sa.UniqueConstraint("legacy_id"),
42
+ )
43
+ op.create_table(
44
+ "attachment",
45
+ sa.Column("id", sa.Integer(), nullable=False),
46
+ sa.Column("user_account_id", sa.Integer(), nullable=False),
47
+ sa.Column("legacy_file_id", sa.String(), nullable=True),
48
+ sa.Column("url", sa.String(), nullable=False),
49
+ sa.Column("sims", sa.String(), nullable=True),
50
+ sa.Column("sfs", sa.String(), nullable=True),
51
+ sa.ForeignKeyConstraint(
52
+ ["user_account_id"],
53
+ ["user_account.id"],
54
+ ),
55
+ sa.PrimaryKeyConstraint("id"),
56
+ )
57
+ op.create_index(
58
+ op.f("ix_attachment_legacy_file_id"),
59
+ "attachment",
60
+ ["legacy_file_id"],
61
+ unique=False,
62
+ )
63
+ op.create_index(op.f("ix_attachment_url"), "attachment", ["url"], unique=False)
64
+ op.create_table(
65
+ "contact",
66
+ sa.Column("id", sa.Integer(), nullable=False),
67
+ sa.Column("user_account_id", sa.Integer(), nullable=False),
68
+ sa.Column("legacy_id", sa.String(), nullable=False),
69
+ sa.Column("jid", slidge.db.meta.JIDType(), nullable=False),
70
+ sa.Column("avatar_id", sa.Integer(), nullable=True),
71
+ sa.Column("nick", sa.String(), nullable=True),
72
+ sa.Column("cached_presence", sa.Boolean(), nullable=False),
73
+ sa.Column("last_seen", sa.DateTime(), nullable=True),
74
+ sa.Column("ptype", sa.String(), nullable=True),
75
+ sa.Column("pstatus", sa.String(), nullable=True),
76
+ sa.Column("pshow", sa.String(), nullable=True),
77
+ sa.ForeignKeyConstraint(
78
+ ["avatar_id"],
79
+ ["avatar.id"],
80
+ ),
81
+ sa.ForeignKeyConstraint(
82
+ ["user_account_id"],
83
+ ["user_account.id"],
84
+ ),
85
+ sa.PrimaryKeyConstraint("id"),
86
+ sa.UniqueConstraint("user_account_id", "jid"),
87
+ sa.UniqueConstraint("user_account_id", "legacy_id"),
88
+ )
89
+ op.create_table(
90
+ "legacy_ids_multi",
91
+ sa.Column("id", sa.Integer(), nullable=False),
92
+ sa.Column("user_account_id", sa.Integer(), nullable=False),
93
+ sa.Column("legacy_id", sa.String(), nullable=False),
94
+ sa.ForeignKeyConstraint(
95
+ ["user_account_id"],
96
+ ["user_account.id"],
97
+ ),
98
+ sa.PrimaryKeyConstraint("id"),
99
+ )
100
+ op.create_index(
101
+ "legacy_ids_multi_user_account_id_legacy_id",
102
+ "legacy_ids_multi",
103
+ ["user_account_id", "legacy_id"],
104
+ unique=True,
105
+ )
106
+ op.create_table(
107
+ "room",
108
+ sa.Column("id", sa.Integer(), nullable=False),
109
+ sa.Column("user_account_id", sa.Integer(), nullable=False),
110
+ sa.Column("legacy_id", sa.String(), nullable=False),
111
+ sa.Column("jid", slidge.db.meta.JIDType(), nullable=False),
112
+ sa.Column("avatar_id", sa.Integer(), nullable=True),
113
+ sa.Column("name", sa.String(), nullable=True),
114
+ sa.ForeignKeyConstraint(
115
+ ["avatar_id"],
116
+ ["avatar.id"],
117
+ ),
118
+ sa.ForeignKeyConstraint(
119
+ ["user_account_id"],
120
+ ["user_account.id"],
121
+ ),
122
+ sa.PrimaryKeyConstraint("id"),
123
+ sa.UniqueConstraint("jid"),
124
+ sa.UniqueConstraint("legacy_id"),
125
+ )
126
+ op.create_table(
127
+ "xmpp_to_legacy_ids",
128
+ sa.Column("id", sa.Integer(), nullable=False),
129
+ sa.Column("user_account_id", sa.Integer(), nullable=False),
130
+ sa.Column("xmpp_id", sa.String(), nullable=False),
131
+ sa.Column("legacy_id", sa.String(), nullable=False),
132
+ sa.Column(
133
+ "type",
134
+ sa.Enum("DM", "GROUP_CHAT", "THREAD", name="xmpptolegacyenum"),
135
+ nullable=False,
136
+ ),
137
+ sa.ForeignKeyConstraint(
138
+ ["user_account_id"],
139
+ ["user_account.id"],
140
+ ),
141
+ sa.PrimaryKeyConstraint("id"),
142
+ )
143
+ op.create_index(
144
+ "xmpp_legacy",
145
+ "xmpp_to_legacy_ids",
146
+ ["user_account_id", "xmpp_id", "legacy_id"],
147
+ unique=True,
148
+ )
149
+ op.create_table(
150
+ "mam",
151
+ sa.Column("id", sa.Integer(), nullable=False),
152
+ sa.Column("room_id", sa.Integer(), nullable=False),
153
+ sa.Column("stanza_id", sa.String(), nullable=False),
154
+ sa.Column("timestamp", sa.DateTime(), nullable=False),
155
+ sa.Column("author_jid", slidge.db.meta.JIDType(), nullable=False),
156
+ sa.Column("stanza", sa.String(), nullable=False),
157
+ sa.ForeignKeyConstraint(
158
+ ["room_id"],
159
+ ["room.id"],
160
+ ),
161
+ sa.PrimaryKeyConstraint("id"),
162
+ sa.UniqueConstraint("room_id", "stanza_id"),
163
+ )
164
+ op.create_table(
165
+ "xmpp_ids_multi",
166
+ sa.Column("id", sa.Integer(), nullable=False),
167
+ sa.Column("user_account_id", sa.Integer(), nullable=False),
168
+ sa.Column("xmpp_id", sa.String(), nullable=False),
169
+ sa.Column("legacy_ids_multi_id", sa.Integer(), nullable=False),
170
+ sa.ForeignKeyConstraint(
171
+ ["legacy_ids_multi_id"],
172
+ ["legacy_ids_multi.id"],
173
+ ),
174
+ sa.ForeignKeyConstraint(
175
+ ["user_account_id"],
176
+ ["user_account.id"],
177
+ ),
178
+ sa.PrimaryKeyConstraint("id"),
179
+ )
180
+ op.create_index(
181
+ "legacy_ids_multi_user_account_id_xmpp_id",
182
+ "xmpp_ids_multi",
183
+ ["user_account_id", "xmpp_id"],
184
+ unique=True,
185
+ )
186
+
187
+ try:
188
+ shutil.rmtree(global_config.HOME_DIR / "slidge_avatars_v2")
189
+ except (FileNotFoundError, AttributeError):
190
+ pass
191
+
192
+ # ### end Alembic commands ###
193
+
194
+
195
+ def downgrade() -> None:
196
+ # ### commands auto generated by Alembic - please adjust! ###
197
+ op.drop_index(
198
+ "legacy_ids_multi_user_account_id_xmpp_id", table_name="xmpp_ids_multi"
199
+ )
200
+ op.drop_table("xmpp_ids_multi")
201
+ op.drop_table("mam")
202
+ op.drop_index("xmpp_legacy", table_name="xmpp_to_legacy_ids")
203
+ op.drop_table("xmpp_to_legacy_ids")
204
+ op.drop_table("room")
205
+ op.drop_index(
206
+ "legacy_ids_multi_user_account_id_legacy_id", table_name="legacy_ids_multi"
207
+ )
208
+ op.drop_table("legacy_ids_multi")
209
+ op.drop_table("contact")
210
+ op.drop_index(op.f("ix_attachment_url"), table_name="attachment")
211
+ op.drop_index(op.f("ix_attachment_legacy_file_id"), table_name="attachment")
212
+ op.drop_table("attachment")
213
+ op.drop_table("avatar")
214
+ # ### end Alembic commands ###
@@ -0,0 +1,52 @@
1
+ """Add source and legacy ID for archived messages
2
+
3
+ Revision ID: b64b1a793483
4
+ Revises: 82a4af84b679
5
+ Create Date: 2024-07-22 21:06:35.020569
6
+
7
+ """
8
+
9
+ from typing import Sequence, Union
10
+
11
+ import sqlalchemy as sa
12
+ from alembic import op
13
+
14
+ from slidge.db.models import ArchivedMessage
15
+
16
+ # revision identifiers, used by Alembic.
17
+ revision: str = "b64b1a793483"
18
+ down_revision: Union[str, None] = "82a4af84b679"
19
+ branch_labels: Union[str, Sequence[str], None] = None
20
+ depends_on: Union[str, Sequence[str], None] = None
21
+
22
+
23
+ def upgrade() -> None:
24
+ # since we don't want source to be nullable, we drop all rows first.
25
+ # This is what you get by using alpha versions!
26
+ op.execute(sa.delete(ArchivedMessage))
27
+
28
+ if op.get_bind().engine.name == "postgresql":
29
+ op.execute("CREATE TYPE archivedmessagesource AS ENUM ('LIVE', 'BACKFILL')")
30
+
31
+ # ### commands auto generated by Alembic - please adjust! ###
32
+
33
+ with op.batch_alter_table("mam", schema=None) as batch_op:
34
+ batch_op.add_column(
35
+ sa.Column(
36
+ "source",
37
+ sa.Enum("LIVE", "BACKFILL", name="archivedmessagesource"),
38
+ nullable=False,
39
+ )
40
+ )
41
+ batch_op.add_column(sa.Column("legacy_id", sa.String(), nullable=True))
42
+
43
+ # ### end Alembic commands ###
44
+
45
+
46
+ def downgrade() -> None:
47
+ # ### commands auto generated by Alembic - please adjust! ###
48
+ with op.batch_alter_table("mam", schema=None) as batch_op:
49
+ batch_op.drop_column("legacy_id")
50
+ batch_op.drop_column("source")
51
+
52
+ # ### end Alembic commands ###
@@ -0,0 +1,34 @@
1
+ """Per-room user nick
2
+
3
+ Revision ID: c4a8ec35a0e8
4
+ Revises: 09f27f098baa
5
+ Create Date: 2024-07-12 06:27:47.397925
6
+
7
+ """
8
+
9
+ from typing import Sequence, Union
10
+
11
+ import sqlalchemy as sa
12
+ from alembic import op
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = "c4a8ec35a0e8"
16
+ down_revision: Union[str, None] = "09f27f098baa"
17
+ branch_labels: Union[str, Sequence[str], None] = None
18
+ depends_on: Union[str, Sequence[str], None] = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ # ### commands auto generated by Alembic - please adjust! ###
23
+ with op.batch_alter_table("room", schema=None) as batch_op:
24
+ batch_op.add_column(sa.Column("user_nick", sa.String(), nullable=True))
25
+
26
+ # ### end Alembic commands ###
27
+
28
+
29
+ def downgrade() -> None:
30
+ # ### commands auto generated by Alembic - please adjust! ###
31
+ with op.batch_alter_table("room", schema=None) as batch_op:
32
+ batch_op.drop_column("user_nick")
33
+
34
+ # ### end Alembic commands ###
@@ -0,0 +1,26 @@
1
+ """Store users' avatars' hashes persistently
2
+
3
+ Revision ID: e91195719c2c
4
+ Revises: aa9d82a7f6ef
5
+ Create Date: 2024-06-01 14:14:51.984943
6
+
7
+ """
8
+
9
+ from typing import Sequence, Union
10
+
11
+ import sqlalchemy as sa
12
+ from alembic import op
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = "e91195719c2c"
16
+ down_revision: Union[str, None] = "aa9d82a7f6ef"
17
+ branch_labels: Union[str, Sequence[str], None] = None
18
+ depends_on: Union[str, Sequence[str], None] = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ op.add_column("user_account", sa.Column("avatar_hash", sa.String(), nullable=True))
23
+
24
+
25
+ def downgrade() -> None:
26
+ op.drop_column("user_account", "avatar_hash")
slidge/db/avatar.py ADDED
@@ -0,0 +1,205 @@
1
+ import asyncio
2
+ import hashlib
3
+ import io
4
+ import logging
5
+ import uuid
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from dataclasses import dataclass
8
+ from http import HTTPStatus
9
+ from pathlib import Path
10
+ from typing import Optional
11
+
12
+ import aiohttp
13
+ from multidict import CIMultiDictProxy
14
+ from PIL.Image import Image
15
+ from PIL.Image import open as open_image
16
+ from sqlalchemy import select
17
+
18
+ from slidge.core import config
19
+ from slidge.db.models import Avatar
20
+ from slidge.db.store import AvatarStore
21
+ from slidge.util.types import URL, AvatarType
22
+
23
+
24
+ @dataclass
25
+ class CachedAvatar:
26
+ pk: int
27
+ filename: str
28
+ hash: str
29
+ height: int
30
+ width: int
31
+ root: Path
32
+ etag: Optional[str] = None
33
+ last_modified: Optional[str] = None
34
+
35
+ @property
36
+ def data(self):
37
+ return self.path.read_bytes()
38
+
39
+ @property
40
+ def path(self):
41
+ return self.root / self.filename
42
+
43
+ @staticmethod
44
+ def from_store(stored: Avatar, root_dir: Path):
45
+ return CachedAvatar(
46
+ pk=stored.id,
47
+ filename=stored.filename,
48
+ hash=stored.hash,
49
+ height=stored.height,
50
+ width=stored.width,
51
+ etag=stored.etag,
52
+ root=root_dir,
53
+ last_modified=stored.last_modified,
54
+ )
55
+
56
+
57
+ class NotModified(Exception):
58
+ pass
59
+
60
+
61
+ class AvatarCache:
62
+ dir: Path
63
+ http: aiohttp.ClientSession
64
+ store: AvatarStore
65
+
66
+ def __init__(self):
67
+ self._thread_pool = ThreadPoolExecutor(config.AVATAR_RESAMPLING_THREADS)
68
+
69
+ def set_dir(self, path: Path):
70
+ self.dir = path
71
+ self.dir.mkdir(exist_ok=True)
72
+ with self.store.session():
73
+ for stored in self.store.get_all():
74
+ avatar = CachedAvatar.from_store(stored, root_dir=path)
75
+ if avatar.path.exists():
76
+ continue
77
+ log.warning(
78
+ "Removing avatar %s from store because %s does not exist",
79
+ avatar.hash,
80
+ avatar.path,
81
+ )
82
+ self.store.delete_by_pk(stored.id)
83
+
84
+ def close(self):
85
+ self._thread_pool.shutdown(cancel_futures=True)
86
+
87
+ def __get_http_headers(self, cached: Optional[CachedAvatar | Avatar]):
88
+ headers = {}
89
+ if cached and (self.dir / cached.filename).exists():
90
+ if last_modified := cached.last_modified:
91
+ headers["If-Modified-Since"] = last_modified
92
+ if etag := cached.etag:
93
+ headers["If-None-Match"] = etag
94
+ return headers
95
+
96
+ async def __download(
97
+ self,
98
+ url: str,
99
+ headers: dict[str, str],
100
+ ) -> tuple[Image, CIMultiDictProxy[str]]:
101
+ async with self.http.get(url, headers=headers) as response:
102
+ if response.status == HTTPStatus.NOT_MODIFIED:
103
+ log.debug("Using avatar cache for %s", url)
104
+ raise NotModified
105
+ return (
106
+ open_image(io.BytesIO(await response.read())),
107
+ response.headers,
108
+ )
109
+
110
+ async def __is_modified(self, url, headers) -> bool:
111
+ async with self.http.head(url, headers=headers) as response:
112
+ return response.status != HTTPStatus.NOT_MODIFIED
113
+
114
+ async def url_modified(self, url: URL) -> bool:
115
+ cached = self.store.get_by_url(url)
116
+ if cached is None:
117
+ return True
118
+ headers = self.__get_http_headers(cached)
119
+ return await self.__is_modified(url, headers)
120
+
121
+ def get_by_pk(self, pk: int) -> CachedAvatar:
122
+ stored = self.store.get_by_pk(pk)
123
+ assert stored is not None
124
+ return CachedAvatar.from_store(stored, self.dir)
125
+
126
+ @staticmethod
127
+ async def _get_image(avatar: AvatarType) -> Image:
128
+ if isinstance(avatar, bytes):
129
+ return open_image(io.BytesIO(avatar))
130
+ elif isinstance(avatar, Path):
131
+ return open_image(avatar)
132
+ raise TypeError("Avatar must be bytes or a Path", avatar)
133
+
134
+ async def convert_or_get(self, avatar: AvatarType) -> CachedAvatar:
135
+ if isinstance(avatar, (URL, str)):
136
+ with self.store.session():
137
+ stored = self.store.get_by_url(avatar)
138
+ try:
139
+ img, response_headers = await self.__download(
140
+ avatar, self.__get_http_headers(stored)
141
+ )
142
+ except NotModified:
143
+ assert stored is not None
144
+ return CachedAvatar.from_store(stored, self.dir)
145
+ else:
146
+ img = await self._get_image(avatar)
147
+ response_headers = None
148
+ with self.store.session() as orm:
149
+ resize = (size := config.AVATAR_SIZE) and any(x > size for x in img.size)
150
+ if resize:
151
+ await asyncio.get_event_loop().run_in_executor(
152
+ self._thread_pool, img.thumbnail, (size, size)
153
+ )
154
+ log.debug("Resampled image to %s", img.size)
155
+
156
+ filename = str(uuid.uuid1()) + ".png"
157
+ file_path = self.dir / filename
158
+
159
+ if (
160
+ not resize
161
+ and img.format == "PNG"
162
+ and isinstance(avatar, (str, Path))
163
+ and (path := Path(avatar))
164
+ and path.exists()
165
+ ):
166
+ img_bytes = path.read_bytes()
167
+ else:
168
+ with io.BytesIO() as f:
169
+ img.save(f, format="PNG")
170
+ img_bytes = f.getvalue()
171
+
172
+ with file_path.open("wb") as file:
173
+ file.write(img_bytes)
174
+
175
+ hash_ = hashlib.sha1(img_bytes).hexdigest()
176
+
177
+ stored = orm.execute(select(Avatar).where(Avatar.hash == hash_)).scalar()
178
+
179
+ if stored is not None:
180
+ return CachedAvatar.from_store(stored, self.dir)
181
+
182
+ stored = Avatar(
183
+ filename=filename,
184
+ hash=hash_,
185
+ height=img.height,
186
+ width=img.width,
187
+ url=avatar if isinstance(avatar, (URL, str)) else None,
188
+ )
189
+ if response_headers:
190
+ stored.etag = response_headers.get("etag")
191
+ stored.last_modified = response_headers.get("last-modified")
192
+
193
+ orm.add(stored)
194
+ orm.commit()
195
+ return CachedAvatar.from_store(stored, self.dir)
196
+
197
+
198
+ avatar_cache = AvatarCache()
199
+ log = logging.getLogger(__name__)
200
+ _download_lock = asyncio.Lock()
201
+
202
+ __all__ = (
203
+ "CachedAvatar",
204
+ "avatar_cache",
205
+ )
slidge/db/meta.py ADDED
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Union
5
+
6
+ import sqlalchemy as sa
7
+ from slixmpp import JID
8
+
9
+
10
+ class JIDType(sa.TypeDecorator[JID]):
11
+ """
12
+ Custom SQLAlchemy type for JIDs
13
+ """
14
+
15
+ impl = sa.types.TEXT
16
+ cache_ok = True
17
+
18
+ def process_bind_param(self, value: JID | None, dialect: sa.Dialect) -> str | None:
19
+ if value is None:
20
+ return value
21
+ return str(value)
22
+
23
+ def process_result_value(
24
+ self, value: str | None, dialect: sa.Dialect
25
+ ) -> JID | None:
26
+ if value is None:
27
+ return value
28
+ return JID(value)
29
+
30
+
31
+ class JSONEncodedDict(sa.TypeDecorator):
32
+ """
33
+ Custom SQLAlchemy type for dictionaries stored as JSON
34
+
35
+ Note that mutations of the dictionary are not detected by SQLAlchemy,
36
+ which is why use ``attributes.flag_modified()`` in ``UserStore.update()``
37
+ """
38
+
39
+ impl = sa.VARCHAR
40
+
41
+ cache_ok = True
42
+
43
+ def process_bind_param(self, value, dialect):
44
+ if value is not None:
45
+ value = json.dumps(value)
46
+
47
+ return value
48
+
49
+ def process_result_value(self, value, dialect):
50
+ if value is not None:
51
+ value = json.loads(value)
52
+ return value
53
+
54
+
55
+ JSONSerializableTypes = Union[str, float, None, "JSONSerializable"]
56
+ JSONSerializable = dict[str, JSONSerializableTypes]
57
+
58
+
59
+ class Base(sa.orm.DeclarativeBase):
60
+ type_annotation_map = {JSONSerializable: JSONEncodedDict, JID: JIDType}
61
+ naming_convention = {
62
+ "ix": "ix_%(column_0_label)s",
63
+ "uq": "uq_%(table_name)s_%(column_0_name)s",
64
+ "ck": "ck_%(table_name)s_`%(constraint_name)s`",
65
+ "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
66
+ "pk": "pk_%(table_name)s",
67
+ }
68
+
69
+
70
+ def get_engine(path: str) -> sa.Engine:
71
+ engine = sa.create_engine(path)
72
+ return engine