aboutsummaryrefslogtreecommitdiff
path: root/server/szurubooru/func/pools.py
blob: c3ea9f0f403e68be8556bb208933d3816ce59778 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import re
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Tuple

import sqlalchemy as sa

from szurubooru import config, db, errors, model, rest
from szurubooru.func import pool_categories, posts, serialization, util


class PoolNotFoundError(errors.NotFoundError):
    pass


class PoolAlreadyExistsError(errors.ValidationError):
    pass


class PoolIsInUseError(errors.ValidationError):
    pass


class InvalidPoolNameError(errors.ValidationError):
    pass


class InvalidPoolDuplicateError(errors.ValidationError):
    pass


class InvalidPoolCategoryError(errors.ValidationError):
    pass


class InvalidPoolDescriptionError(errors.ValidationError):
    pass


class InvalidPoolRelationError(errors.ValidationError):
    pass


class InvalidPoolNonexistentPostError(errors.ValidationError):
    pass


def _verify_name_validity(name: str) -> None:
    if util.value_exceeds_column_size(name, model.PoolName.name):
        raise InvalidPoolNameError("Name is too long.")
    name_regex = config.config["pool_name_regex"]
    if not re.match(name_regex, name):
        raise InvalidPoolNameError("Name must satisfy regex %r." % name_regex)


def _get_names(pool: model.Pool) -> List[str]:
    assert pool
    return [pool_name.name for pool_name in pool.names]


def _lower_list(names: List[str]) -> List[str]:
    return [name.lower() for name in names]


def _check_name_intersection(
    names1: List[str], names2: List[str], case_sensitive: bool
) -> bool:
    if not case_sensitive:
        names1 = _lower_list(names1)
        names2 = _lower_list(names2)
    return len(set(names1).intersection(names2)) > 0


def _duplicates(a: List[int]) -> List[int]:
    seen = set()
    dupes = []
    for x in a:
        if x not in seen:
            seen.add(x)
        else:
            dupes.append(x)
    return dupes


def sort_pools(pools: List[model.Pool]) -> List[model.Pool]:
    default_category_name = pool_categories.get_default_category_name()
    return sorted(
        pools,
        key=lambda pool: (
            default_category_name == pool.category.name,
            pool.category.name,
            pool.names[0].name,
        ),
    )


class PoolSerializer(serialization.BaseSerializer):
    def __init__(self, pool: model.Pool) -> None:
        self.pool = pool

    def _serializers(self) -> Dict[str, Callable[[], Any]]:
        return {
            "id": self.serialize_id,
            "names": self.serialize_names,
            "category": self.serialize_category,
            "version": self.serialize_version,
            "description": self.serialize_description,
            "creationTime": self.serialize_creation_time,
            "lastEditTime": self.serialize_last_edit_time,
            "postCount": self.serialize_post_count,
            "posts": self.serialize_posts,
        }

    def serialize_id(self) -> Any:
        return self.pool.pool_id

    def serialize_names(self) -> Any:
        return [pool_name.name for pool_name in self.pool.names]

    def serialize_category(self) -> Any:
        return self.pool.category.name

    def serialize_version(self) -> Any:
        return self.pool.version

    def serialize_description(self) -> Any:
        return self.pool.description

    def serialize_creation_time(self) -> Any:
        return self.pool.creation_time

    def serialize_last_edit_time(self) -> Any:
        return self.pool.last_edit_time

    def serialize_post_count(self) -> Any:
        return self.pool.post_count

    def serialize_posts(self) -> Any:
        return [
            post
            for post in [
                posts.serialize_micro_post(rel, None)
                for rel in self.pool.posts
            ]
        ]


def serialize_pool(
    pool: model.Pool, options: List[str] = []
) -> Optional[rest.Response]:
    if not pool:
        return None
    return PoolSerializer(pool).serialize(options)


def serialize_micro_pool(pool: model.Pool) -> Optional[rest.Response]:
    return serialize_pool(
        pool, options=["id", "names", "category", "description", "postCount"]
    )


def try_get_pool_by_id(pool_id: int) -> Optional[model.Pool]:
    return (
        db.session.query(model.Pool)
        .filter(model.Pool.pool_id == pool_id)
        .one_or_none()
    )


def get_pool_by_id(pool_id: int) -> model.Pool:
    pool = try_get_pool_by_id(pool_id)
    if not pool:
        raise PoolNotFoundError("Pool %r not found." % pool_id)
    return pool


def try_get_pool_by_name(name: str) -> Optional[model.Pool]:
    return (
        db.session.query(model.Pool)
        .join(model.PoolName)
        .filter(sa.func.lower(model.PoolName.name) == name.lower())
        .one_or_none()
    )


def get_pool_by_name(name: str) -> model.Pool:
    pool = try_get_pool_by_name(name)
    if not pool:
        raise PoolNotFoundError("Pool %r not found." % name)
    return pool


def get_pools_by_names(names: List[str]) -> List[model.Pool]:
    names = util.icase_unique(names)
    if len(names) == 0:
        return []
    return (
        db.session.query(model.Pool)
        .join(model.PoolName)
        .filter(
            sa.sql.or_(
                sa.func.lower(model.PoolName.name) == name.lower()
                for name in names
            )
        )
        .all()
    )


def get_or_create_pools_by_names(
    names: List[str],
) -> Tuple[List[model.Pool], List[model.Pool]]:
    names = util.icase_unique(names)
    existing_pools = get_pools_by_names(names)
    new_pools = []
    pool_category_name = pool_categories.get_default_category_name()
    for name in names:
        found = False
        for existing_pool in existing_pools:
            if _check_name_intersection(
                _get_names(existing_pool), [name], False
            ):
                found = True
                break
        if not found:
            new_pool = create_pool(
                names=[name], category_name=pool_category_name, post_ids=[]
            )
            db.session.add(new_pool)
            new_pools.append(new_pool)
    return existing_pools, new_pools


def delete(source_pool: model.Pool) -> None:
    assert source_pool
    db.session.delete(source_pool)


def merge_pools(source_pool: model.Pool, target_pool: model.Pool) -> None:
    assert source_pool
    assert target_pool
    if source_pool.pool_id == target_pool.pool_id:
        raise InvalidPoolRelationError("Cannot merge pool with itself.")

    def merge_pool_posts(source_pool_id: int, target_pool_id: int) -> None:
        alias1 = model.PoolPost
        alias2 = sa.orm.util.aliased(model.PoolPost)
        update_stmt = sa.sql.expression.update(alias1).where(
            alias1.pool_id == source_pool_id
        )
        update_stmt = update_stmt.where(
            ~sa.exists()
            .where(alias1.post_id == alias2.post_id)
            .where(alias2.pool_id == target_pool_id)
        )
        update_stmt = update_stmt.values(pool_id=target_pool_id)
        db.session.execute(update_stmt)

    merge_pool_posts(source_pool.pool_id, target_pool.pool_id)
    delete(source_pool)


def create_pool(
    names: List[str], category_name: str, post_ids: List[int]
) -> model.Pool:
    pool = model.Pool()
    pool.creation_time = datetime.utcnow()
    update_pool_names(pool, names)
    update_pool_category_name(pool, category_name)
    update_pool_posts(pool, post_ids)
    return pool


def update_pool_category_name(pool: model.Pool, category_name: str) -> None:
    assert pool
    pool.category = pool_categories.get_category_by_name(category_name)


def update_pool_names(pool: model.Pool, names: List[str]) -> None:
    # sanitize
    assert pool
    names = util.icase_unique([name for name in names if name])
    if not len(names):
        raise InvalidPoolNameError("At least one name must be specified.")
    for name in names:
        _verify_name_validity(name)

    # check for existing pools
    expr = sa.sql.false()
    for name in names:
        expr = expr | (sa.func.lower(model.PoolName.name) == name.lower())
    if pool.pool_id:
        expr = expr & (model.PoolName.pool_id != pool.pool_id)
    existing_pools = db.session.query(model.PoolName).filter(expr).all()
    if len(existing_pools):
        raise PoolAlreadyExistsError(
            "One of names is already used by another pool."
        )

    # remove unwanted items
    for pool_name in pool.names[:]:
        if not _check_name_intersection([pool_name.name], names, True):
            pool.names.remove(pool_name)
    # add wanted items
    for name in names:
        if not _check_name_intersection(_get_names(pool), [name], True):
            pool.names.append(model.PoolName(name, -1))

    # set alias order to match the request
    for i, name in enumerate(names):
        for pool_name in pool.names:
            if pool_name.name.lower() == name.lower():
                pool_name.order = i


def update_pool_description(pool: model.Pool, description: str) -> None:
    assert pool
    if util.value_exceeds_column_size(description, model.Pool.description):
        raise InvalidPoolDescriptionError("Description is too long.")
    pool.description = description or None


def update_pool_posts(pool: model.Pool, post_ids: List[int]) -> None:
    assert pool
    dupes = _duplicates(post_ids)
    if len(dupes) > 0:
        dupes = ", ".join(list(str(x) for x in dupes))
        raise InvalidPoolDuplicateError("Duplicate post(s) in pool: " + dupes)
    ret = posts.get_posts_by_ids(post_ids)
    if len(post_ids) != len(ret):
        missing = set(post_ids) - set(post.post_id for post in ret)
        missing = ", ".join(list(str(x) for x in missing))
        raise InvalidPoolNonexistentPostError(
            "The following posts do not exist: " + missing
        )
    pool.posts.clear()
    for post in ret:
        pool.posts.append(post)

© 2015 - 2026 Jakob L. Kreuze