aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/models/utils.py
blob: e961088f2fea2e5db9787d31acb649e0e41598f1 (plain) (blame)
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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""URL fingerprints and UUID timestamp utilities."""

import json
from datetime import UTC, datetime
from hashlib import sha256
from uuid import UUID


def uuid7_to_datetime(identifier: UUID) -> datetime:
    """Convert a UUID version 7 timestamp to a datetime.

    :param identifier: UUID whose embedded timestamp should be converted.
    :returns: Timestamp as a timezone-aware UTC datetime.
    """
    return datetime.fromtimestamp(identifier.time / 1000, tz=UTC)


def source_target_digest(source: str, target: str) -> str:
    """Fingerprint an unambiguous, ordered source/target pair.

    :param source: Webmention source URL.
    :param target: Webmention target URL.
    :returns: SHA-256 hexadecimal digest of the ordered URL pair.
    """
    encoded = json.dumps(
        [source, target], ensure_ascii=False, separators=(",", ":")
    ).encode("utf-8")
    return sha256(encoded).hexdigest()


def target_digest(target: str) -> str:
    """Fingerprint an outgoing target (unique within each source ID).

    :param target: Outgoing Webmention target URL.
    :returns: SHA-256 hexadecimal digest of the target URL.
    """
    return sha256(target.encode("utf-8")).hexdigest()