shellzapy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shellzapy-0.1.0.dist-info/METADATA +112 -0
- shellzapy-0.1.0.dist-info/RECORD +345 -0
- shellzapy-0.1.0.dist-info/WHEEL +4 -0
- shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
- shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
- zapy/__init__.py +58 -0
- zapy/_appstate/__init__.py +59 -0
- zapy/_appstate/constants.py +82 -0
- zapy/_appstate/crypto/__init__.py +17 -0
- zapy/_appstate/crypto/app_state_crypto.py +401 -0
- zapy/_appstate/parsers/__init__.py +23 -0
- zapy/_appstate/parsers/encoding.py +157 -0
- zapy/_appstate/parsers/response_parser.py +135 -0
- zapy/_appstate/sync/__init__.py +11 -0
- zapy/_appstate/sync/sync_client.py +1559 -0
- zapy/_appstate/types.py +137 -0
- zapy/_appstate/utils.py +100 -0
- zapy/_auth/__init__.py +3 -0
- zapy/_auth/auth_client.py +618 -0
- zapy/_auth/credentials_flow.py +290 -0
- zapy/_auth/pairing/__init__.py +3 -0
- zapy/_auth/pairing/companion_host.py +239 -0
- zapy/_auth/pairing/flow.py +808 -0
- zapy/_auth/pairing/pairing_code_crypto.py +143 -0
- zapy/_auth/pairing/qr_flow.py +123 -0
- zapy/_auth/pairing/shortcake_crypto.py +122 -0
- zapy/_auth/pairing/shortcake_flow.py +393 -0
- zapy/_auth/types.py +110 -0
- zapy/_client/__init__.py +26 -0
- zapy/_client/client.py +972 -0
- zapy/_client/connection/__init__.py +6 -0
- zapy/_client/connection/manager.py +525 -0
- zapy/_client/connection/receipt_queue.py +74 -0
- zapy/_client/coordinators/__init__.py +81 -0
- zapy/_client/coordinators/ab_props.py +260 -0
- zapy/_client/coordinators/app_state_mutation.py +2538 -0
- zapy/_client/coordinators/bot.py +830 -0
- zapy/_client/coordinators/broadcast_list.py +101 -0
- zapy/_client/coordinators/business.py +247 -0
- zapy/_client/coordinators/email.py +158 -0
- zapy/_client/coordinators/group.py +1478 -0
- zapy/_client/coordinators/incoming_node.py +758 -0
- zapy/_client/coordinators/low_level.py +119 -0
- zapy/_client/coordinators/message.py +1153 -0
- zapy/_client/coordinators/message_dispatch.py +1637 -0
- zapy/_client/coordinators/newsletter.py +110 -0
- zapy/_client/coordinators/offline_resume.py +271 -0
- zapy/_client/coordinators/passive_tasks.py +447 -0
- zapy/_client/coordinators/presence.py +103 -0
- zapy/_client/coordinators/privacy.py +623 -0
- zapy/_client/coordinators/profile.py +1024 -0
- zapy/_client/coordinators/retry.py +1878 -0
- zapy/_client/coordinators/status.py +132 -0
- zapy/_client/coordinators/stream_control.py +260 -0
- zapy/_client/coordinators/trusted_contact_token.py +417 -0
- zapy/_client/events/__init__.py +266 -0
- zapy/_client/events/abprops.py +58 -0
- zapy/_client/events/appstate_mutation.py +248 -0
- zapy/_client/events/business.py +565 -0
- zapy/_client/events/call.py +144 -0
- zapy/_client/events/chatstate.py +41 -0
- zapy/_client/events/devices.py +122 -0
- zapy/_client/events/dirty.py +384 -0
- zapy/_client/events/group.py +655 -0
- zapy/_client/events/identity.py +40 -0
- zapy/_client/events/incoming.py +1079 -0
- zapy/_client/events/mex_notification.py +317 -0
- zapy/_client/events/offline.py +123 -0
- zapy/_client/events/picture.py +67 -0
- zapy/_client/events/presence.py +74 -0
- zapy/_client/events/privacy.py +187 -0
- zapy/_client/events/privacy_token.py +72 -0
- zapy/_client/events/receipt.py +109 -0
- zapy/_client/events/registration.py +70 -0
- zapy/_client/events/username.py +76 -0
- zapy/_client/factory.py +2020 -0
- zapy/_client/media.py +829 -0
- zapy/_client/newsletter/__init__.py +90 -0
- zapy/_client/newsletter/admin.py +323 -0
- zapy/_client/newsletter/content.py +499 -0
- zapy/_client/newsletter/discovery.py +233 -0
- zapy/_client/newsletter/messaging.py +396 -0
- zapy/_client/newsletter/mex.py +99 -0
- zapy/_client/newsletter/parse.py +406 -0
- zapy/_client/newsletter/types.py +393 -0
- zapy/_client/persistence/__init__.py +89 -0
- zapy/_client/persistence/companion_host.py +133 -0
- zapy/_client/persistence/ephemeral_setting.py +245 -0
- zapy/_client/persistence/group_history.py +361 -0
- zapy/_client/persistence/history_blob.py +169 -0
- zapy/_client/persistence/history_sync.py +646 -0
- zapy/_client/persistence/mailbox.py +232 -0
- zapy/_client/persistence/write_behind_persistence.py +368 -0
- zapy/_client/plugins/__init__.py +23 -0
- zapy/_client/plugins/define.py +44 -0
- zapy/_client/plugins/install.py +254 -0
- zapy/_client/plugins/types.py +64 -0
- zapy/_client/tokens/__init__.py +21 -0
- zapy/_client/tokens/cs_token.py +47 -0
- zapy/_client/tokens/tc_token.py +43 -0
- zapy/_client/types.py +988 -0
- zapy/_crypto/__init__.py +65 -0
- zapy/_crypto/core/__init__.py +62 -0
- zapy/_crypto/core/hkdf.py +41 -0
- zapy/_crypto/core/keys.py +51 -0
- zapy/_crypto/core/nonce.py +25 -0
- zapy/_crypto/core/primitives.py +179 -0
- zapy/_crypto/core/random.py +32 -0
- zapy/_crypto/core/xeddsa.py +72 -0
- zapy/_crypto/curves/__init__.py +3 -0
- zapy/_crypto/curves/constants.py +10 -0
- zapy/_crypto/curves/ed25519.py +61 -0
- zapy/_crypto/curves/types.py +18 -0
- zapy/_crypto/curves/x25519.py +117 -0
- zapy/_crypto/math/__init__.py +3 -0
- zapy/_crypto/math/constants.py +35 -0
- zapy/_crypto/math/edwards.py +174 -0
- zapy/_crypto/math/fe.py +120 -0
- zapy/_crypto/math/le.py +13 -0
- zapy/_crypto/math/mod.py +15 -0
- zapy/_crypto/math/prime.py +11 -0
- zapy/_crypto/math/types.py +25 -0
- zapy/_crypto/native_backend.py +40 -0
- zapy/_infra/__init__.py +3 -0
- zapy/_infra/log.py +142 -0
- zapy/_infra/perf.py +77 -0
- zapy/_media/__init__.py +64 -0
- zapy/_media/constants.py +133 -0
- zapy/_media/container.py +110 -0
- zapy/_media/crypto/__init__.py +19 -0
- zapy/_media/crypto/crypto.py +633 -0
- zapy/_media/crypto/media_retry.py +107 -0
- zapy/_media/processor.py +100 -0
- zapy/_media/sticker/__init__.py +8 -0
- zapy/_media/sticker/pack.py +188 -0
- zapy/_media/transfer/__init__.py +15 -0
- zapy/_media/transfer/client.py +635 -0
- zapy/_media/transfer/conn.py +48 -0
- zapy/_media/types.py +169 -0
- zapy/_message/__init__.py +121 -0
- zapy/_message/addons/__init__.py +5 -0
- zapy/_message/addons/link_preview/__init__.py +54 -0
- zapy/_message/addons/link_preview/builder.py +56 -0
- zapy/_message/addons/link_preview/detect.py +72 -0
- zapy/_message/addons/link_preview/fetcher.py +553 -0
- zapy/_message/addons/link_preview/types.py +100 -0
- zapy/_message/client.py +486 -0
- zapy/_message/context_info.py +424 -0
- zapy/_message/crypto/__init__.py +71 -0
- zapy/_message/crypto/addon_crypto.py +656 -0
- zapy/_message/crypto/icdc.py +138 -0
- zapy/_message/crypto/phash.py +87 -0
- zapy/_message/crypto/reporting_token.py +498 -0
- zapy/_message/crypto/use_case_secret.py +113 -0
- zapy/_message/encode/__init__.py +84 -0
- zapy/_message/encode/content.py +636 -0
- zapy/_message/encode/device_sent.py +88 -0
- zapy/_message/encode/media_payload.py +122 -0
- zapy/_message/encode/padding.py +27 -0
- zapy/_message/kinds/__init__.py +1 -0
- zapy/_message/kinds/bot.py +179 -0
- zapy/_message/kinds/group_history.py +206 -0
- zapy/_message/kinds/newsletter.py +388 -0
- zapy/_message/kinds/sticker_pack.py +74 -0
- zapy/_message/messaging/__init__.py +336 -0
- zapy/_message/messaging/companion_host.py +117 -0
- zapy/_message/messaging/fanout.py +311 -0
- zapy/_message/messaging/group_metadata.py +444 -0
- zapy/_message/messaging/ignore_key.py +264 -0
- zapy/_message/messaging/key_protocol.py +217 -0
- zapy/_message/messaging/link_preview.py +448 -0
- zapy/_message/messaging/messages.py +1429 -0
- zapy/_message/primitives/__init__.py +1 -0
- zapy/_message/primitives/ack.py +232 -0
- zapy/_message/primitives/incoming.py +1141 -0
- zapy/_message/primitives/media_retry.py +451 -0
- zapy/_message/primitives/peer_data_operation.py +271 -0
- zapy/_message/types.py +434 -0
- zapy/_proto/WAProto_pb2.py +2584 -0
- zapy/_proto/__init__.py +1 -0
- zapy/_protocol/__init__.py +3 -0
- zapy/_protocol/abprops_spec.py +6216 -0
- zapy/_protocol/auth.py +17 -0
- zapy/_protocol/browser.py +57 -0
- zapy/_protocol/defaults.py +38 -0
- zapy/_protocol/device_identity.py +54 -0
- zapy/_protocol/jid.py +241 -0
- zapy/_protocol/message.py +127 -0
- zapy/_protocol/nodes.py +144 -0
- zapy/_protocol/notification.py +18 -0
- zapy/_retry/__init__.py +77 -0
- zapy/_retry/codec.py +209 -0
- zapy/_retry/constants.py +28 -0
- zapy/_retry/parse.py +132 -0
- zapy/_retry/reason.py +65 -0
- zapy/_retry/replay.py +483 -0
- zapy/_retry/tracker.py +161 -0
- zapy/_retry/types.py +122 -0
- zapy/_signal/__init__.py +171 -0
- zapy/_signal/api/__init__.py +133 -0
- zapy/_signal/api/codec.py +164 -0
- zapy/_signal/api/constants.py +14 -0
- zapy/_signal/api/device_sync.py +915 -0
- zapy/_signal/api/digest_sync.py +363 -0
- zapy/_signal/api/identity_sync.py +250 -0
- zapy/_signal/api/missing_pre_keys_sync.py +267 -0
- zapy/_signal/api/prekeys.py +191 -0
- zapy/_signal/api/result_map.py +40 -0
- zapy/_signal/api/rotate_key.py +111 -0
- zapy/_signal/api/session_sync.py +297 -0
- zapy/_signal/attestation.py +145 -0
- zapy/_signal/constants.py +22 -0
- zapy/_signal/encoding.py +78 -0
- zapy/_signal/group/__init__.py +35 -0
- zapy/_signal/group/chain.py +139 -0
- zapy/_signal/group/codec.py +78 -0
- zapy/_signal/group/encoding.py +166 -0
- zapy/_signal/group/manager.py +361 -0
- zapy/_signal/registration/__init__.py +44 -0
- zapy/_signal/registration/keygen.py +46 -0
- zapy/_signal/registration/reg_encoding.py +66 -0
- zapy/_signal/registration/reg_utils.py +52 -0
- zapy/_signal/session/__init__.py +114 -0
- zapy/_signal/session/encoding.py +385 -0
- zapy/_signal/session/protocol.py +590 -0
- zapy/_signal/session/ratchet.py +381 -0
- zapy/_signal/session/resolver.py +630 -0
- zapy/_signal/session/serializer.py +96 -0
- zapy/_signal/session/session.py +272 -0
- zapy/_signal/types.py +214 -0
- zapy/_store/__init__.py +118 -0
- zapy/_store/cache/__init__.py +166 -0
- zapy/_store/cache/identity.py +130 -0
- zapy/_store/cache/privacy_token.py +116 -0
- zapy/_store/cache/sender_key.py +168 -0
- zapy/_store/cache/session.py +142 -0
- zapy/_store/contracts/__init__.py +84 -0
- zapy/_store/contracts/appstate.py +82 -0
- zapy/_store/contracts/auth.py +16 -0
- zapy/_store/contracts/chat_metadata.py +29 -0
- zapy/_store/contracts/contact.py +31 -0
- zapy/_store/contracts/device_list.py +35 -0
- zapy/_store/contracts/group_metadata.py +33 -0
- zapy/_store/contracts/identity.py +18 -0
- zapy/_store/contracts/message.py +36 -0
- zapy/_store/contracts/message_secret.py +41 -0
- zapy/_store/contracts/pre_key.py +32 -0
- zapy/_store/contracts/privacy_token.py +32 -0
- zapy/_store/contracts/retry.py +47 -0
- zapy/_store/contracts/sender_key.py +37 -0
- zapy/_store/contracts/session.py +21 -0
- zapy/_store/contracts/signal.py +23 -0
- zapy/_store/contracts/thread.py +35 -0
- zapy/_store/create_store.py +890 -0
- zapy/_store/locks.py +1154 -0
- zapy/_store/memory/__init__.py +40 -0
- zapy/_store/memory/appstate.py +200 -0
- zapy/_store/memory/auth.py +24 -0
- zapy/_store/memory/chat_metadata.py +124 -0
- zapy/_store/memory/contact.py +125 -0
- zapy/_store/memory/device_list.py +161 -0
- zapy/_store/memory/group_metadata.py +125 -0
- zapy/_store/memory/identity.py +86 -0
- zapy/_store/memory/message.py +85 -0
- zapy/_store/memory/message_secret.py +145 -0
- zapy/_store/memory/pre_key.py +112 -0
- zapy/_store/memory/privacy_token.py +103 -0
- zapy/_store/memory/retry.py +250 -0
- zapy/_store/memory/sender_key.py +162 -0
- zapy/_store/memory/session.py +111 -0
- zapy/_store/memory/signal.py +45 -0
- zapy/_store/memory/thread.py +66 -0
- zapy/_store/noop.py +279 -0
- zapy/_transport/__init__.py +3 -0
- zapy/_transport/binary/__init__.py +77 -0
- zapy/_transport/binary/constants.py +80 -0
- zapy/_transport/binary/decoder.py +260 -0
- zapy/_transport/binary/encoder.py +279 -0
- zapy/_transport/binary/tokens.py +1289 -0
- zapy/_transport/comms.py +759 -0
- zapy/_transport/keepalive/__init__.py +3 -0
- zapy/_transport/keepalive/keep_alive.py +252 -0
- zapy/_transport/node/__init__.py +3 -0
- zapy/_transport/node/builders/__init__.py +9 -0
- zapy/_transport/node/builders/abprops.py +33 -0
- zapy/_transport/node/builders/account_sync.py +120 -0
- zapy/_transport/node/builders/bot.py +56 -0
- zapy/_transport/node/builders/business.py +261 -0
- zapy/_transport/node/builders/chatstate.py +74 -0
- zapy/_transport/node/builders/community.py +116 -0
- zapy/_transport/node/builders/device.py +30 -0
- zapy/_transport/node/builders/email.py +181 -0
- zapy/_transport/node/builders/global_.py +74 -0
- zapy/_transport/node/builders/group.py +279 -0
- zapy/_transport/node/builders/media.py +21 -0
- zapy/_transport/node/builders/message.py +436 -0
- zapy/_transport/node/builders/mobile.py +227 -0
- zapy/_transport/node/builders/newsletter.py +293 -0
- zapy/_transport/node/builders/offline.py +20 -0
- zapy/_transport/node/builders/pairing.py +130 -0
- zapy/_transport/node/builders/passive.py +28 -0
- zapy/_transport/node/builders/prekeys.py +215 -0
- zapy/_transport/node/builders/presence.py +100 -0
- zapy/_transport/node/builders/privacy.py +243 -0
- zapy/_transport/node/builders/privacy_token.py +94 -0
- zapy/_transport/node/builders/profile.py +176 -0
- zapy/_transport/node/builders/retry.py +156 -0
- zapy/_transport/node/builders/shortcake.py +87 -0
- zapy/_transport/node/builders/tos.py +92 -0
- zapy/_transport/node/builders/usync.py +185 -0
- zapy/_transport/node/helpers.py +201 -0
- zapy/_transport/node/orchestrator.py +210 -0
- zapy/_transport/node/query.py +82 -0
- zapy/_transport/node/transport.py +105 -0
- zapy/_transport/node/usync.py +33 -0
- zapy/_transport/node/xml.py +38 -0
- zapy/_transport/noise/__init__.py +7 -0
- zapy/_transport/noise/cert.py +85 -0
- zapy/_transport/noise/client_payload.py +344 -0
- zapy/_transport/noise/constants.py +12 -0
- zapy/_transport/noise/frame_codec.py +120 -0
- zapy/_transport/noise/handshake.py +92 -0
- zapy/_transport/noise/session.py +493 -0
- zapy/_transport/noise/socket.py +45 -0
- zapy/_transport/noise/types.py +66 -0
- zapy/_transport/noise/version.json +3 -0
- zapy/_transport/proxy.py +35 -0
- zapy/_transport/types.py +19 -0
- zapy/_transport/wa_version_fetcher.py +159 -0
- zapy/_transport/web_socket.py +602 -0
- zapy/_util/__init__.py +3 -0
- zapy/_util/bytes.py +131 -0
- zapy/_util/coercion.py +29 -0
- zapy/_util/collections.py +45 -0
- zapy/_util/primitives.py +49 -0
- zapy/client.py +840 -0
- zapy/errors.py +148 -0
- zapy/events.py +564 -0
- zapy/jid.py +140 -0
- zapy/py.typed +0 -0
- zapy/stores/__init__.py +50 -0
- zapy/stores/base.py +1627 -0
- zapy/stores/json_file.py +359 -0
- zapy/stores/memory.py +322 -0
- zapy/stores/sqlite.py +343 -0
zapy/_client/media.py
ADDED
|
@@ -0,0 +1,829 @@
|
|
|
1
|
+
"""Client media helpers (mirrors ``src/client/media.ts``).
|
|
2
|
+
|
|
3
|
+
The media transfer client (``src/media``) belongs to another worker, so this
|
|
4
|
+
module works against the structural :class:`WaClientMediaTransfer` protocol.
|
|
5
|
+
``download_media_message`` returns the decrypted bytes (the oracle returns a
|
|
6
|
+
live ``Readable``); pass ``stream=True``-style callers should use the transfer
|
|
7
|
+
client directly.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import base64
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
import random
|
|
19
|
+
import tempfile
|
|
20
|
+
import urllib.parse
|
|
21
|
+
import weakref
|
|
22
|
+
from collections.abc import Awaitable, Callable
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Any, BinaryIO, Protocol, cast
|
|
25
|
+
|
|
26
|
+
from zapy._infra.log import Logger
|
|
27
|
+
from zapy._message.encode.content import MessageDict
|
|
28
|
+
from zapy._message.encode.media_payload import resolve_media_payload
|
|
29
|
+
from zapy._util.primitives import to_error
|
|
30
|
+
|
|
31
|
+
_logger = logging.getLogger("zapy._client.media")
|
|
32
|
+
|
|
33
|
+
IMAGE_THUMB_MAX_EDGE: int = 100
|
|
34
|
+
VIDEO_THUMB_MAX_EDGE: int = 100
|
|
35
|
+
STICKER_THUMB_MAX_EDGE: int = 100
|
|
36
|
+
|
|
37
|
+
MEDIA_UPLOAD_ID_MAX: int = 281_474_976_710_655
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class ProcessedMediaFields:
|
|
42
|
+
"""Derived media fields (mirrors ``ProcessedMediaFields``)."""
|
|
43
|
+
|
|
44
|
+
jpeg_thumbnail: bytes | None = None
|
|
45
|
+
png_thumbnail: bytes | None = None
|
|
46
|
+
width: int | None = None
|
|
47
|
+
height: int | None = None
|
|
48
|
+
seconds: int | None = None
|
|
49
|
+
waveform: bytes | None = None
|
|
50
|
+
is_animated: bool | None = None
|
|
51
|
+
first_frame_length: int | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True)
|
|
55
|
+
class WebpAnimInfo:
|
|
56
|
+
"""WebP animation probe result."""
|
|
57
|
+
|
|
58
|
+
is_animated: bool = True
|
|
59
|
+
first_frame_length: int = 0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, slots=True)
|
|
63
|
+
class StreamFileMetrics:
|
|
64
|
+
"""SHA-256 + length of an uploaded stream."""
|
|
65
|
+
|
|
66
|
+
file_sha256: bytes
|
|
67
|
+
byte_length: int
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True, slots=True)
|
|
71
|
+
class WaMediaProcessorCallContext:
|
|
72
|
+
"""Per-call processor context (mirrors ``WaMediaProcessorCallContext``)."""
|
|
73
|
+
|
|
74
|
+
logger: Any = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class WaMediaProcessor(Protocol):
|
|
78
|
+
"""Structural media processor (mirrors ``WaMediaProcessor``)."""
|
|
79
|
+
|
|
80
|
+
async def generate_image_thumbnail(
|
|
81
|
+
self, input: Any, max_edge: int, ctx: Any = None
|
|
82
|
+
) -> Any | None: ...
|
|
83
|
+
async def generate_video_thumbnail(
|
|
84
|
+
self, input: Any, max_edge: int, ctx: Any = None
|
|
85
|
+
) -> Any | None: ...
|
|
86
|
+
async def probe_media(self, input: Any, ctx: Any = None) -> Any | None: ...
|
|
87
|
+
async def compute_waveform(self, input: Any, ctx: Any = None) -> Any | None: ...
|
|
88
|
+
async def generate_sticker_thumbnail(
|
|
89
|
+
self, input: Any, max_edge: int, ctx: Any = None
|
|
90
|
+
) -> Any | None: ...
|
|
91
|
+
async def normalize_voice_note(self, input: Any, ctx: Any = None) -> Any | None: ...
|
|
92
|
+
async def detect_mimetype(self, input: Any, ctx: Any = None) -> str | None: ...
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True, slots=True)
|
|
96
|
+
class WaMediaOptions:
|
|
97
|
+
"""Media handling tuning (mirrors ``WaMediaOptions``)."""
|
|
98
|
+
|
|
99
|
+
processor: WaMediaProcessor | None = None
|
|
100
|
+
generate_thumbnail: bool | None = None
|
|
101
|
+
generate_probe: bool | None = None
|
|
102
|
+
generate_waveform: bool | None = None
|
|
103
|
+
generate_sticker_thumbnail: bool | None = None
|
|
104
|
+
normalize_voice_note: bool | None = None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True, slots=True)
|
|
108
|
+
class WaDownloadMediaOptions:
|
|
109
|
+
"""Download tuning (mirrors ``WaDownloadMediaOptions``)."""
|
|
110
|
+
|
|
111
|
+
max_bytes: int | None = None
|
|
112
|
+
timeout_ms: int | None = None
|
|
113
|
+
signal: Any | None = None
|
|
114
|
+
transfer: Any | None = None
|
|
115
|
+
proxy: Any | None = None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class WaClientMediaTransfer(Protocol):
|
|
119
|
+
"""Transfer leg used by the client media helpers."""
|
|
120
|
+
|
|
121
|
+
async def upload_stream(
|
|
122
|
+
self,
|
|
123
|
+
*,
|
|
124
|
+
url: str,
|
|
125
|
+
body: Any,
|
|
126
|
+
content_length: int,
|
|
127
|
+
content_type: str | None = None,
|
|
128
|
+
) -> Any: ...
|
|
129
|
+
|
|
130
|
+
async def read_response_bytes(self, response: Any) -> bytes: ...
|
|
131
|
+
|
|
132
|
+
async def download_and_decrypt(
|
|
133
|
+
self,
|
|
134
|
+
*,
|
|
135
|
+
direct_path: str,
|
|
136
|
+
media_type: str,
|
|
137
|
+
media_key: bytes,
|
|
138
|
+
file_sha256: bytes | None = None,
|
|
139
|
+
file_enc_sha256: bytes | None = None,
|
|
140
|
+
timeout_ms: int | None = None,
|
|
141
|
+
max_bytes: int | None = None,
|
|
142
|
+
) -> bytes: ...
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
async def read_file_head(file_path: str, byte_count: int) -> bytes:
|
|
146
|
+
"""Read the first ``byte_count`` bytes of ``file_path``."""
|
|
147
|
+
|
|
148
|
+
def _read() -> bytes:
|
|
149
|
+
with open(file_path, "rb") as handle:
|
|
150
|
+
return handle.read(byte_count)
|
|
151
|
+
|
|
152
|
+
return await asyncio.to_thread(_read)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def parse_webp_animation(data: bytes | bytearray) -> WebpAnimInfo | None:
|
|
156
|
+
"""Detect an animated WebP and the length of its first frame."""
|
|
157
|
+
raw = bytes(data)
|
|
158
|
+
RIFF_HEADER_SIZE = 12
|
|
159
|
+
CHUNK_HEADER_SIZE = 8
|
|
160
|
+
if len(raw) < RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE:
|
|
161
|
+
return None
|
|
162
|
+
offset = RIFF_HEADER_SIZE
|
|
163
|
+
if raw[offset : offset + 4] != b"VP8X":
|
|
164
|
+
return None
|
|
165
|
+
offset += CHUNK_HEADER_SIZE + 10
|
|
166
|
+
|
|
167
|
+
while offset + CHUNK_HEADER_SIZE <= len(raw):
|
|
168
|
+
is_anmf = raw[offset : offset + 4] == b"ANMF"
|
|
169
|
+
size_offset = offset + 4
|
|
170
|
+
if size_offset + 4 > len(raw):
|
|
171
|
+
return None
|
|
172
|
+
chunk_size = int.from_bytes(raw[size_offset : size_offset + 4], "little")
|
|
173
|
+
if chunk_size % 2 != 0:
|
|
174
|
+
chunk_size += 1
|
|
175
|
+
next_offset = offset + CHUNK_HEADER_SIZE + chunk_size
|
|
176
|
+
if next_offset <= offset or next_offset > len(raw):
|
|
177
|
+
return None
|
|
178
|
+
if is_anmf:
|
|
179
|
+
return WebpAnimInfo(is_animated=True, first_frame_length=next_offset)
|
|
180
|
+
offset = next_offset
|
|
181
|
+
return None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def is_readable_stream(value: Any) -> bool:
|
|
185
|
+
"""Return whether ``value`` behaves like a binary read stream."""
|
|
186
|
+
return hasattr(value, "read") and callable(value.read)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
async def stream_to_temp_file(source: BinaryIO) -> str:
|
|
190
|
+
"""Spill ``source`` to a temp file; returns its path."""
|
|
191
|
+
|
|
192
|
+
def _spill() -> str:
|
|
193
|
+
fd, path = tempfile.mkstemp(prefix="zapy-media-")
|
|
194
|
+
try:
|
|
195
|
+
with os.fdopen(fd, "wb") as handle:
|
|
196
|
+
while True:
|
|
197
|
+
chunk = source.read(65536)
|
|
198
|
+
if not chunk:
|
|
199
|
+
break
|
|
200
|
+
handle.write(chunk)
|
|
201
|
+
except BaseException:
|
|
202
|
+
try:
|
|
203
|
+
os.unlink(path)
|
|
204
|
+
except OSError:
|
|
205
|
+
pass
|
|
206
|
+
raise
|
|
207
|
+
return path
|
|
208
|
+
|
|
209
|
+
return await asyncio.to_thread(_spill)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
async def cleanup_temp_file(file_path: str) -> None:
|
|
213
|
+
"""Remove a temp file, ignoring missing paths."""
|
|
214
|
+
try:
|
|
215
|
+
await asyncio.to_thread(os.unlink, file_path)
|
|
216
|
+
except OSError:
|
|
217
|
+
pass
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _close_quietly(handle: BinaryIO) -> None:
|
|
221
|
+
try:
|
|
222
|
+
handle.close()
|
|
223
|
+
except OSError:
|
|
224
|
+
pass
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _sha256_size(body: bytes) -> StreamFileMetrics:
|
|
228
|
+
return StreamFileMetrics(
|
|
229
|
+
file_sha256=hashlib.sha256(body).digest(), byte_length=len(body)
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
async def stream_to_temp_file_with_sha256(
|
|
234
|
+
source: BinaryIO,
|
|
235
|
+
) -> tuple[str, StreamFileMetrics]:
|
|
236
|
+
"""Spill ``source`` to a temp file while hashing it."""
|
|
237
|
+
|
|
238
|
+
def _spill() -> tuple[str, StreamFileMetrics]:
|
|
239
|
+
digest = hashlib.sha256()
|
|
240
|
+
byte_length = 0
|
|
241
|
+
fd, path = tempfile.mkstemp(prefix="zapy-media-")
|
|
242
|
+
try:
|
|
243
|
+
with os.fdopen(fd, "wb") as handle:
|
|
244
|
+
while True:
|
|
245
|
+
chunk = source.read(65536)
|
|
246
|
+
if not chunk:
|
|
247
|
+
break
|
|
248
|
+
digest.update(bytes(chunk))
|
|
249
|
+
byte_length += len(chunk)
|
|
250
|
+
handle.write(chunk)
|
|
251
|
+
except BaseException:
|
|
252
|
+
try:
|
|
253
|
+
os.unlink(path)
|
|
254
|
+
except OSError:
|
|
255
|
+
pass
|
|
256
|
+
raise
|
|
257
|
+
return path, StreamFileMetrics(
|
|
258
|
+
file_sha256=digest.digest(), byte_length=byte_length
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
return await asyncio.to_thread(_spill)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
WaUploadMediaSource = bytes | str | BinaryIO
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _host_name(host: Any) -> str | None:
|
|
268
|
+
name = (
|
|
269
|
+
host.get("hostname")
|
|
270
|
+
if isinstance(host, dict)
|
|
271
|
+
else getattr(host, "hostname", None)
|
|
272
|
+
)
|
|
273
|
+
return name if isinstance(name, str) else None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _host_fallback(host: Any) -> bool:
|
|
277
|
+
if isinstance(host, dict):
|
|
278
|
+
return bool(host.get("is_fallback", False))
|
|
279
|
+
return bool(getattr(host, "is_fallback", False))
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def select_media_upload_host(media_conn: Any) -> str:
|
|
283
|
+
"""Pick the first non-fallback upload host (mirrors the TS helper)."""
|
|
284
|
+
hosts = getattr(media_conn, "hosts", [])
|
|
285
|
+
for host in hosts:
|
|
286
|
+
hostname = _host_name(host)
|
|
287
|
+
if hostname and not _host_fallback(host):
|
|
288
|
+
return hostname
|
|
289
|
+
if hosts:
|
|
290
|
+
hostname = _host_name(hosts[0])
|
|
291
|
+
if hostname:
|
|
292
|
+
return hostname
|
|
293
|
+
raise ValueError("media conn has no upload hosts")
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def build_media_upload_url(
|
|
297
|
+
host: str,
|
|
298
|
+
path: str,
|
|
299
|
+
auth: str,
|
|
300
|
+
file_sha256: bytes,
|
|
301
|
+
media_id: str | None = None,
|
|
302
|
+
) -> str:
|
|
303
|
+
"""Build the plaintext upload URL (mirrors ``buildMediaUploadUrl``)."""
|
|
304
|
+
hash_token = base64.urlsafe_b64encode(bytes(file_sha256)).decode("ascii")
|
|
305
|
+
base = (
|
|
306
|
+
f"https://{host}{path}/{hash_token}"
|
|
307
|
+
f"?auth={urllib.parse.quote(auth, safe='')}"
|
|
308
|
+
f"&token={urllib.parse.quote(hash_token, safe='')}"
|
|
309
|
+
)
|
|
310
|
+
return base if media_id is None else f"{base}&media_id={media_id}"
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def assert_media_upload_status(status: int, label: str) -> None:
|
|
314
|
+
"""Throw unless the upload status is 2xx (mirrors the TS helper)."""
|
|
315
|
+
if status < 200 or status >= 300:
|
|
316
|
+
raise ValueError(f"{label} failed with status {status}")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def parse_media_upload_json_body(body: bytes, label: str) -> Any:
|
|
320
|
+
"""Parse an upload JSON body (mirrors ``parseMediaUploadJsonBody``)."""
|
|
321
|
+
try:
|
|
322
|
+
return json.loads(bytes(body).decode("utf-8"))
|
|
323
|
+
except (ValueError, UnicodeDecodeError) as error:
|
|
324
|
+
raise ValueError(f"{label} returned invalid json: {to_error(error)}") from error
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
async def perform_plaintext_media_upload(
|
|
328
|
+
media_transfer: WaClientMediaTransfer,
|
|
329
|
+
media_conn: Any,
|
|
330
|
+
source: WaUploadMediaSource,
|
|
331
|
+
path: str,
|
|
332
|
+
mimetype: str | None = None,
|
|
333
|
+
log_label: str = "sending media upload",
|
|
334
|
+
logger: Any = None,
|
|
335
|
+
) -> dict[str, Any]:
|
|
336
|
+
"""Upload plaintext media; returns response bytes plus file metrics."""
|
|
337
|
+
metrics: StreamFileMetrics | None = None
|
|
338
|
+
body: bytes | BinaryIO
|
|
339
|
+
cleanup: Callable[[], Awaitable[None]] | None = None
|
|
340
|
+
if isinstance(source, (bytes, bytearray)):
|
|
341
|
+
raw = bytes(source)
|
|
342
|
+
metrics = _sha256_size(raw)
|
|
343
|
+
body = raw
|
|
344
|
+
elif isinstance(source, str):
|
|
345
|
+
await assert_readable_file(source)
|
|
346
|
+
handle = open(source, "rb")
|
|
347
|
+
temp_path, metrics = await stream_to_temp_file_with_sha256(handle)
|
|
348
|
+
handle.close()
|
|
349
|
+
|
|
350
|
+
def _open_temp() -> BinaryIO:
|
|
351
|
+
return open(temp_path, "rb")
|
|
352
|
+
|
|
353
|
+
temp_handle: BinaryIO = await asyncio.to_thread(_open_temp)
|
|
354
|
+
body = temp_handle
|
|
355
|
+
|
|
356
|
+
async def _cleanup_temp() -> None:
|
|
357
|
+
_close_quietly(temp_handle)
|
|
358
|
+
await cleanup_temp_file(temp_path)
|
|
359
|
+
|
|
360
|
+
cleanup = _cleanup_temp
|
|
361
|
+
elif is_readable_stream(source):
|
|
362
|
+
temp_path, metrics = await stream_to_temp_file_with_sha256(source)
|
|
363
|
+
stream_handle: BinaryIO = await asyncio.to_thread(open, temp_path, "rb")
|
|
364
|
+
body = stream_handle
|
|
365
|
+
|
|
366
|
+
async def _cleanup_stream() -> None:
|
|
367
|
+
_close_quietly(stream_handle)
|
|
368
|
+
await cleanup_temp_file(temp_path)
|
|
369
|
+
|
|
370
|
+
cleanup = _cleanup_stream
|
|
371
|
+
else:
|
|
372
|
+
raise ValueError("media upload received unsupported source type")
|
|
373
|
+
try:
|
|
374
|
+
assert metrics is not None
|
|
375
|
+
host = select_media_upload_host(media_conn)
|
|
376
|
+
media_id = str(random.randint(0, MEDIA_UPLOAD_ID_MAX))
|
|
377
|
+
raw_auth = (
|
|
378
|
+
media_conn.get("auth")
|
|
379
|
+
if isinstance(media_conn, dict)
|
|
380
|
+
else getattr(media_conn, "auth", "")
|
|
381
|
+
)
|
|
382
|
+
auth = raw_auth if isinstance(raw_auth, str) else ""
|
|
383
|
+
url = build_media_upload_url(host, path, auth, metrics.file_sha256, media_id)
|
|
384
|
+
if logger is None:
|
|
385
|
+
_logger.debug("%s to %s (%d bytes)", log_label, host, metrics.byte_length)
|
|
386
|
+
else:
|
|
387
|
+
_log_debug(
|
|
388
|
+
logger,
|
|
389
|
+
log_label,
|
|
390
|
+
{"host": host, "path": path, "size": metrics.byte_length},
|
|
391
|
+
)
|
|
392
|
+
response = await media_transfer.upload_stream(
|
|
393
|
+
url=url,
|
|
394
|
+
body=body,
|
|
395
|
+
content_length=metrics.byte_length,
|
|
396
|
+
content_type=mimetype,
|
|
397
|
+
)
|
|
398
|
+
response_bytes = await media_transfer.read_response_bytes(response)
|
|
399
|
+
return {
|
|
400
|
+
"response_bytes": response_bytes,
|
|
401
|
+
"status": getattr(response, "status", 200),
|
|
402
|
+
"file_sha256": metrics.file_sha256,
|
|
403
|
+
"byte_length": metrics.byte_length,
|
|
404
|
+
"media_id": media_id,
|
|
405
|
+
}
|
|
406
|
+
finally:
|
|
407
|
+
if cleanup is not None:
|
|
408
|
+
await cleanup()
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _log_debug(logger: Any, message: str, context: dict[str, Any]) -> None:
|
|
412
|
+
debug = getattr(logger, "debug", None)
|
|
413
|
+
if callable(debug):
|
|
414
|
+
try:
|
|
415
|
+
debug(message, context)
|
|
416
|
+
return
|
|
417
|
+
except TypeError:
|
|
418
|
+
pass
|
|
419
|
+
_logger.debug("%s %s", message, context)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
async def assert_readable_file(file_path: str) -> None:
|
|
423
|
+
"""Throw unless ``file_path`` is a readable regular file."""
|
|
424
|
+
|
|
425
|
+
def _check() -> None:
|
|
426
|
+
if not os.path.isfile(file_path):
|
|
427
|
+
if not os.path.exists(file_path):
|
|
428
|
+
raise ValueError(f"media file not found: {file_path}")
|
|
429
|
+
raise ValueError(f"media path is not a regular file: {file_path}")
|
|
430
|
+
|
|
431
|
+
await asyncio.to_thread(_check)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
async def resolve_media_inputs(
|
|
435
|
+
should_process: bool, raw: bytes | BinaryIO | str
|
|
436
|
+
) -> dict[str, Any]:
|
|
437
|
+
"""Resolve upload/processor inputs (mirrors ``resolveMediaInputs``)."""
|
|
438
|
+
if isinstance(raw, str):
|
|
439
|
+
await assert_readable_file(raw)
|
|
440
|
+
|
|
441
|
+
def _open() -> BinaryIO:
|
|
442
|
+
return open(raw, "rb")
|
|
443
|
+
|
|
444
|
+
return {
|
|
445
|
+
"processor_input": raw,
|
|
446
|
+
"upload_media": await asyncio.to_thread(_open),
|
|
447
|
+
}
|
|
448
|
+
if isinstance(raw, (bytes, bytearray)):
|
|
449
|
+
raw_bytes = bytes(raw)
|
|
450
|
+
return {"processor_input": raw_bytes, "upload_media": raw_bytes}
|
|
451
|
+
if is_readable_stream(raw):
|
|
452
|
+
stream = raw
|
|
453
|
+
if should_process:
|
|
454
|
+
temp_file_path = await stream_to_temp_file(stream)
|
|
455
|
+
|
|
456
|
+
def _open_temp() -> BinaryIO:
|
|
457
|
+
return open(temp_file_path, "rb")
|
|
458
|
+
|
|
459
|
+
return {
|
|
460
|
+
"processor_input": temp_file_path,
|
|
461
|
+
"upload_media": await asyncio.to_thread(_open_temp),
|
|
462
|
+
"temp_file_path": temp_file_path,
|
|
463
|
+
}
|
|
464
|
+
return {"upload_media": stream}
|
|
465
|
+
raise ValueError("media resolve received unsupported source type")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _content_type(content: Any) -> str | None:
|
|
469
|
+
raw = (
|
|
470
|
+
content.get("type")
|
|
471
|
+
if isinstance(content, dict)
|
|
472
|
+
else getattr(content, "type", None)
|
|
473
|
+
)
|
|
474
|
+
return raw if isinstance(raw, str) else None
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _processor_fn(
|
|
478
|
+
processor: WaMediaProcessor, name: str
|
|
479
|
+
) -> Callable[..., Awaitable[Any]] | None:
|
|
480
|
+
"""Fetch an optional processor hook as a typed callable."""
|
|
481
|
+
fn = getattr(processor, name, None)
|
|
482
|
+
if callable(fn):
|
|
483
|
+
return cast(Callable[..., Awaitable[Any]], fn)
|
|
484
|
+
return None
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _read_field(source: Any, name: str) -> Any:
|
|
488
|
+
"""Read a result field off a dict or an object (calling zero-arg methods)."""
|
|
489
|
+
raw = source.get(name) if isinstance(source, dict) else getattr(source, name, None)
|
|
490
|
+
if callable(raw):
|
|
491
|
+
return cast(Callable[[], Any], raw)()
|
|
492
|
+
return raw
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _content_field(content: Any, name: str) -> Any:
|
|
496
|
+
if isinstance(content, dict):
|
|
497
|
+
return content.get(name)
|
|
498
|
+
return getattr(content, name, None)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def should_generate_thumbnail(media: WaMediaOptions | None, content: Any) -> bool:
|
|
502
|
+
"""Mirror the TS ``shouldGenerateThumbnail`` predicate."""
|
|
503
|
+
if media is None or media.processor is None or media.generate_thumbnail is False:
|
|
504
|
+
return False
|
|
505
|
+
content_type = _content_type(content)
|
|
506
|
+
processor = media.processor
|
|
507
|
+
if content_type == "image":
|
|
508
|
+
return (
|
|
509
|
+
_content_field(content, "jpeg_thumbnail") is None
|
|
510
|
+
and _processor_fn(processor, "generate_image_thumbnail") is not None
|
|
511
|
+
)
|
|
512
|
+
if content_type in ("video", "ptv"):
|
|
513
|
+
return (
|
|
514
|
+
_content_field(content, "jpeg_thumbnail") is None
|
|
515
|
+
and _processor_fn(processor, "generate_video_thumbnail") is not None
|
|
516
|
+
)
|
|
517
|
+
if content_type == "document":
|
|
518
|
+
return _processor_fn(processor, "generate_image_thumbnail") is not None
|
|
519
|
+
return False
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def should_probe_media(media: WaMediaOptions | None, content: Any) -> bool:
|
|
523
|
+
"""Mirror the TS ``shouldProbeMedia`` predicate."""
|
|
524
|
+
if media is None or media.processor is None or media.generate_probe is False:
|
|
525
|
+
return False
|
|
526
|
+
processor = media.processor
|
|
527
|
+
if _processor_fn(processor, "probe_media") is None:
|
|
528
|
+
return False
|
|
529
|
+
content_type = _content_type(content)
|
|
530
|
+
if content_type in ("video", "ptv"):
|
|
531
|
+
return (
|
|
532
|
+
_content_field(content, "seconds") is None
|
|
533
|
+
or _content_field(content, "width") is None
|
|
534
|
+
or _content_field(content, "height") is None
|
|
535
|
+
)
|
|
536
|
+
if content_type == "audio":
|
|
537
|
+
return _content_field(content, "seconds") is None
|
|
538
|
+
return False
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def should_generate_waveform(media: WaMediaOptions | None, content: Any) -> bool:
|
|
542
|
+
"""Mirror the TS ``shouldGenerateWaveform`` predicate."""
|
|
543
|
+
if media is None or media.processor is None or media.generate_waveform is False:
|
|
544
|
+
return False
|
|
545
|
+
return (
|
|
546
|
+
_processor_fn(media.processor, "compute_waveform") is not None
|
|
547
|
+
and _content_type(content) == "audio"
|
|
548
|
+
and _content_field(content, "waveform") is None
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def should_normalize_voice_note(media: WaMediaOptions | None, content: Any) -> bool:
|
|
553
|
+
"""Mirror the TS ``shouldNormalizeVoiceNote`` guard."""
|
|
554
|
+
return (
|
|
555
|
+
media is not None
|
|
556
|
+
and media.processor is not None
|
|
557
|
+
and _processor_fn(media.processor, "normalize_voice_note") is not None
|
|
558
|
+
and media.normalize_voice_note is True
|
|
559
|
+
and _content_type(content) == "audio"
|
|
560
|
+
and _content_field(content, "ptt") is True
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def should_generate_sticker_thumbnail(
|
|
565
|
+
media: WaMediaOptions | None, content: Any
|
|
566
|
+
) -> bool:
|
|
567
|
+
"""Mirror the TS sticker-thumbnail predicate."""
|
|
568
|
+
if media is None or media.processor is None:
|
|
569
|
+
return False
|
|
570
|
+
if media.generate_sticker_thumbnail is False:
|
|
571
|
+
return False
|
|
572
|
+
return (
|
|
573
|
+
_content_type(content) == "sticker"
|
|
574
|
+
and _content_field(content, "png_thumbnail") is None
|
|
575
|
+
and _processor_fn(media.processor, "generate_sticker_thumbnail") is not None
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def has_media_processing_tasks(media: WaMediaOptions | None, content: Any) -> bool:
|
|
580
|
+
"""Return whether any processor step applies (mirrors the TS helper)."""
|
|
581
|
+
return (
|
|
582
|
+
should_generate_thumbnail(media, content)
|
|
583
|
+
or should_probe_media(media, content)
|
|
584
|
+
or should_generate_waveform(media, content)
|
|
585
|
+
or should_generate_sticker_thumbnail(media, content)
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
_scoped_media_logger_cache: weakref.WeakKeyDictionary[Any, Logger] = (
|
|
590
|
+
weakref.WeakKeyDictionary()
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def get_scoped_media_logger(parent: Logger) -> Logger:
|
|
595
|
+
"""Return the cached ``scope=media-utils`` child logger for ``parent``."""
|
|
596
|
+
cached = _scoped_media_logger_cache.get(parent)
|
|
597
|
+
if cached is not None:
|
|
598
|
+
return cached
|
|
599
|
+
scoped = parent.child({"scope": "media-utils"})
|
|
600
|
+
_scoped_media_logger_cache[parent] = scoped
|
|
601
|
+
return scoped
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
async def _run_processor_step(
|
|
605
|
+
step: str, content: Any, logger: Logger, fn: Callable[[], Awaitable[Any]]
|
|
606
|
+
) -> Any | None:
|
|
607
|
+
try:
|
|
608
|
+
return await fn()
|
|
609
|
+
except Exception as error:
|
|
610
|
+
logger.error(
|
|
611
|
+
"media processor step failed, skipping step",
|
|
612
|
+
{
|
|
613
|
+
"type": _content_type(content),
|
|
614
|
+
"step": step,
|
|
615
|
+
"message": str(to_error(error)),
|
|
616
|
+
},
|
|
617
|
+
)
|
|
618
|
+
return None
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
async def run_media_processor(
|
|
622
|
+
media: WaMediaOptions | None,
|
|
623
|
+
input: bytes | str | None,
|
|
624
|
+
content: Any,
|
|
625
|
+
logger: Logger,
|
|
626
|
+
) -> ProcessedMediaFields:
|
|
627
|
+
"""Run thumbnail/probe/waveform/sticker steps (mirrors ``runMediaProcessor``)."""
|
|
628
|
+
processor = media.processor if media is not None else None
|
|
629
|
+
if (
|
|
630
|
+
processor is None
|
|
631
|
+
or not has_media_processing_tasks(media, content)
|
|
632
|
+
or input is None
|
|
633
|
+
):
|
|
634
|
+
return ProcessedMediaFields()
|
|
635
|
+
|
|
636
|
+
result: dict[str, Any] = {
|
|
637
|
+
"jpeg_thumbnail": None,
|
|
638
|
+
"png_thumbnail": None,
|
|
639
|
+
"width": None,
|
|
640
|
+
"height": None,
|
|
641
|
+
"seconds": None,
|
|
642
|
+
"waveform": None,
|
|
643
|
+
"is_animated": None,
|
|
644
|
+
"first_frame_length": None,
|
|
645
|
+
}
|
|
646
|
+
ctx = WaMediaProcessorCallContext(logger=get_scoped_media_logger(logger))
|
|
647
|
+
|
|
648
|
+
content_type = _content_type(content)
|
|
649
|
+
is_video = content_type in ("video", "ptv")
|
|
650
|
+
thumb_max_edge = VIDEO_THUMB_MAX_EDGE if is_video else IMAGE_THUMB_MAX_EDGE
|
|
651
|
+
thumb_fn = _processor_fn(
|
|
652
|
+
processor,
|
|
653
|
+
"generate_video_thumbnail" if is_video else "generate_image_thumbnail",
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
async def _run_thumb() -> Any | None:
|
|
657
|
+
assert thumb_fn is not None
|
|
658
|
+
return await thumb_fn(input, thumb_max_edge, ctx)
|
|
659
|
+
|
|
660
|
+
async def _run_probe() -> Any | None:
|
|
661
|
+
assert probe_fn is not None
|
|
662
|
+
return await probe_fn(input, ctx)
|
|
663
|
+
|
|
664
|
+
thumb_task = (
|
|
665
|
+
_run_processor_step("thumbnail", content, logger, _run_thumb)
|
|
666
|
+
if should_generate_thumbnail(media, content) and thumb_fn is not None
|
|
667
|
+
else None
|
|
668
|
+
)
|
|
669
|
+
probe_fn = _processor_fn(processor, "probe_media")
|
|
670
|
+
probe_task = (
|
|
671
|
+
_run_processor_step("probe", content, logger, _run_probe)
|
|
672
|
+
if should_probe_media(media, content) and probe_fn is not None
|
|
673
|
+
else None
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
thumb, probe = None, None
|
|
677
|
+
if thumb_task is not None or probe_task is not None:
|
|
678
|
+
thumb, probe = await asyncio.gather(
|
|
679
|
+
thumb_task or asyncio.sleep(0, result=None),
|
|
680
|
+
probe_task or asyncio.sleep(0, result=None),
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
if thumb:
|
|
684
|
+
result["jpeg_thumbnail"] = _read_field(thumb, "jpeg_thumbnail")
|
|
685
|
+
if not is_video and not probe:
|
|
686
|
+
result["width"] = _read_field(thumb, "width")
|
|
687
|
+
result["height"] = _read_field(thumb, "height")
|
|
688
|
+
|
|
689
|
+
if probe:
|
|
690
|
+
duration = _read_field(probe, "duration_seconds") or _read_field(
|
|
691
|
+
probe, "durationSeconds"
|
|
692
|
+
)
|
|
693
|
+
if duration is not None and _content_field(content, "seconds") is None:
|
|
694
|
+
result["seconds"] = int(duration)
|
|
695
|
+
if _content_field(content, "width") is None:
|
|
696
|
+
width = _read_field(probe, "width")
|
|
697
|
+
if width is not None:
|
|
698
|
+
result["width"] = width
|
|
699
|
+
if _content_field(content, "height") is None:
|
|
700
|
+
height = _read_field(probe, "height")
|
|
701
|
+
if height is not None:
|
|
702
|
+
result["height"] = height
|
|
703
|
+
|
|
704
|
+
if should_generate_waveform(media, content):
|
|
705
|
+
waveform_fn = _processor_fn(processor, "compute_waveform")
|
|
706
|
+
|
|
707
|
+
async def _run_waveform() -> Any | None:
|
|
708
|
+
assert waveform_fn is not None
|
|
709
|
+
return await waveform_fn(input, ctx)
|
|
710
|
+
|
|
711
|
+
waveform_result = (
|
|
712
|
+
await _run_processor_step("waveform", content, logger, _run_waveform)
|
|
713
|
+
if waveform_fn is not None
|
|
714
|
+
else None
|
|
715
|
+
)
|
|
716
|
+
if waveform_result:
|
|
717
|
+
result["waveform"] = _read_field(waveform_result, "waveform")
|
|
718
|
+
duration = _read_field(waveform_result, "duration_seconds") or _read_field(
|
|
719
|
+
waveform_result, "durationSeconds"
|
|
720
|
+
)
|
|
721
|
+
if (
|
|
722
|
+
result["seconds"] is None
|
|
723
|
+
and _content_field(content, "seconds") is None
|
|
724
|
+
and duration is not None
|
|
725
|
+
):
|
|
726
|
+
result["seconds"] = int(duration)
|
|
727
|
+
|
|
728
|
+
if content_type == "sticker":
|
|
729
|
+
if should_generate_sticker_thumbnail(media, content):
|
|
730
|
+
sticker_fn = _processor_fn(processor, "generate_sticker_thumbnail")
|
|
731
|
+
|
|
732
|
+
async def _run_sticker_thumb() -> Any | None:
|
|
733
|
+
assert sticker_fn is not None
|
|
734
|
+
return await sticker_fn(input, STICKER_THUMB_MAX_EDGE, ctx)
|
|
735
|
+
|
|
736
|
+
sticker_thumb = (
|
|
737
|
+
await _run_processor_step(
|
|
738
|
+
"stickerThumbnail", content, logger, _run_sticker_thumb
|
|
739
|
+
)
|
|
740
|
+
if sticker_fn is not None
|
|
741
|
+
else None
|
|
742
|
+
)
|
|
743
|
+
if sticker_thumb:
|
|
744
|
+
result["png_thumbnail"] = _read_field(sticker_thumb, "png_thumbnail")
|
|
745
|
+
result["width"] = _read_field(sticker_thumb, "width")
|
|
746
|
+
result["height"] = _read_field(sticker_thumb, "height")
|
|
747
|
+
if _content_field(content, "is_animated") is None:
|
|
748
|
+
header = (
|
|
749
|
+
await read_file_head(input, 100) if isinstance(input, str) else input
|
|
750
|
+
)
|
|
751
|
+
anim = parse_webp_animation(header)
|
|
752
|
+
if anim is not None:
|
|
753
|
+
result["is_animated"] = True
|
|
754
|
+
result["first_frame_length"] = anim.first_frame_length
|
|
755
|
+
else:
|
|
756
|
+
result["is_animated"] = False
|
|
757
|
+
|
|
758
|
+
return ProcessedMediaFields(**result)
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
async def download_media_message(
|
|
762
|
+
source: MessageDict | dict[str, Any],
|
|
763
|
+
options: WaDownloadMediaOptions | None = None,
|
|
764
|
+
transfer: WaClientMediaTransfer | None = None,
|
|
765
|
+
) -> bytes:
|
|
766
|
+
"""Download and decrypt message media (mirrors ``downloadMediaMessage``).
|
|
767
|
+
|
|
768
|
+
Returns the decrypted bytes; ``options.transfer`` (or ``transfer``)
|
|
769
|
+
supplies the transfer leg.
|
|
770
|
+
"""
|
|
771
|
+
opts = options or WaDownloadMediaOptions()
|
|
772
|
+
if isinstance(source, dict):
|
|
773
|
+
message: MessageDict | None = source
|
|
774
|
+
else:
|
|
775
|
+
message = getattr(source, "message", None)
|
|
776
|
+
payload = resolve_media_payload(message)
|
|
777
|
+
if payload is None:
|
|
778
|
+
raise ValueError("message has no downloadable media")
|
|
779
|
+
active = transfer or opts.transfer
|
|
780
|
+
if active is None:
|
|
781
|
+
raise ValueError("download_media_message requires a transfer client")
|
|
782
|
+
return await active.download_and_decrypt(
|
|
783
|
+
direct_path=payload.direct_path,
|
|
784
|
+
media_type=str(payload.media_type),
|
|
785
|
+
media_key=bytes(payload.media_key),
|
|
786
|
+
file_sha256=payload.file_sha256,
|
|
787
|
+
file_enc_sha256=payload.file_enc_sha256,
|
|
788
|
+
timeout_ms=opts.timeout_ms,
|
|
789
|
+
max_bytes=opts.max_bytes,
|
|
790
|
+
)
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
__all__: list[str] = [
|
|
794
|
+
"IMAGE_THUMB_MAX_EDGE",
|
|
795
|
+
"MEDIA_UPLOAD_ID_MAX",
|
|
796
|
+
"STICKER_THUMB_MAX_EDGE",
|
|
797
|
+
"VIDEO_THUMB_MAX_EDGE",
|
|
798
|
+
"ProcessedMediaFields",
|
|
799
|
+
"StreamFileMetrics",
|
|
800
|
+
"WaClientMediaTransfer",
|
|
801
|
+
"WaDownloadMediaOptions",
|
|
802
|
+
"WaMediaOptions",
|
|
803
|
+
"WaMediaProcessor",
|
|
804
|
+
"WaMediaProcessorCallContext",
|
|
805
|
+
"WaUploadMediaSource",
|
|
806
|
+
"WebpAnimInfo",
|
|
807
|
+
"assert_media_upload_status",
|
|
808
|
+
"assert_readable_file",
|
|
809
|
+
"build_media_upload_url",
|
|
810
|
+
"cleanup_temp_file",
|
|
811
|
+
"download_media_message",
|
|
812
|
+
"get_scoped_media_logger",
|
|
813
|
+
"has_media_processing_tasks",
|
|
814
|
+
"is_readable_stream",
|
|
815
|
+
"parse_media_upload_json_body",
|
|
816
|
+
"parse_webp_animation",
|
|
817
|
+
"perform_plaintext_media_upload",
|
|
818
|
+
"read_file_head",
|
|
819
|
+
"resolve_media_inputs",
|
|
820
|
+
"run_media_processor",
|
|
821
|
+
"select_media_upload_host",
|
|
822
|
+
"should_generate_sticker_thumbnail",
|
|
823
|
+
"should_generate_thumbnail",
|
|
824
|
+
"should_generate_waveform",
|
|
825
|
+
"should_normalize_voice_note",
|
|
826
|
+
"should_probe_media",
|
|
827
|
+
"stream_to_temp_file",
|
|
828
|
+
"stream_to_temp_file_with_sha256",
|
|
829
|
+
]
|