-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclient.py
1421 lines (1265 loc) · 48.1 KB
/
client.py
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import hashlib
import json
import logging
import queue
import threading
import time
import warnings
from datetime import datetime
from io import BytesIO
from pathlib import Path
from typing import (
Any,
AsyncIterable,
Awaitable,
Callable,
Dict,
Iterable,
List,
Mapping,
NoReturn,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
import aiohttp
from aleph_message.models import (
AggregateContent,
AggregateMessage,
AlephMessage,
ForgetContent,
ForgetMessage,
ItemHash,
ItemType,
MessageType,
PostContent,
PostMessage,
ProgramContent,
ProgramMessage,
StoreContent,
StoreMessage,
parse_message,
)
from aleph_message.models.execution.base import Encoding
from aleph_message.status import MessageStatus
from pydantic import ValidationError
from aleph.sdk.types import Account, GenericMessage, StorageEnum
from aleph.sdk.utils import Writable, copy_async_readable_to_buffer
from .base import BaseAlephClient, BaseAuthenticatedAlephClient
from .conf import settings
from .exceptions import (
BroadcastError,
FileTooLarge,
InvalidMessageError,
MessageNotFoundError,
MultipleMessagesError,
)
from .models import MessagesResponse, Post, PostsResponse
from .utils import check_unix_socket_valid, get_message_type_value
logger = logging.getLogger(__name__)
try:
import magic
except ImportError:
logger.info("Could not import library 'magic', MIME type detection disabled")
magic = None # type:ignore
T = TypeVar("T")
def async_wrapper(f):
"""
Copies the docstring of wrapped functions.
"""
wrapped = getattr(AuthenticatedAlephClient, f.__name__)
f.__doc__ = wrapped.__doc__
def wrap_async(func: Callable[..., Awaitable[T]]) -> Callable[..., T]:
"""Wrap an asynchronous function into a synchronous one,
for easy use in synchronous code.
"""
def func_caller(*args, **kwargs):
loop = asyncio.get_event_loop()
return loop.run_until_complete(func(*args, **kwargs))
# Copy wrapped function interface:
func_caller.__doc__ = func.__doc__
func_caller.__annotations__ = func.__annotations__
func_caller.__defaults__ = func.__defaults__
func_caller.__kwdefaults__ = func.__kwdefaults__
return func_caller
async def run_async_watcher(
*args, output_queue: queue.Queue, api_server: Optional[str], **kwargs
):
async with AlephClient(api_server=api_server) as session:
async for message in session.watch_messages(*args, **kwargs):
output_queue.put(message)
def watcher_thread(output_queue: queue.Queue, api_server: Optional[str], args, kwargs):
asyncio.run(
run_async_watcher(
output_queue=output_queue, api_server=api_server, *args, **kwargs
)
)
class UserSessionSync:
"""
A sync version of `UserSession`, used in sync code.
This class is returned by the context manager of `UserSession` and is
intended as a wrapper around the methods of `UserSession` and not as a public class.
The methods are fully typed to enable static type checking, but most (all) methods
should look like this (using args and kwargs for brevity, but the functions should
be fully typed):
>>> def func(self, *args, **kwargs):
>>> return self._wrap(self.async_session.func)(*args, **kwargs)
"""
def __init__(self, async_session: "AlephClient"):
self.async_session = async_session
def _wrap(self, method: Callable[..., Awaitable[T]], *args, **kwargs):
return wrap_async(method)(*args, **kwargs)
def get_messages(
self,
pagination: int = 200,
page: int = 1,
message_type: Optional[MessageType] = None,
message_types: Optional[List[MessageType]] = None,
content_types: Optional[Iterable[str]] = None,
content_keys: Optional[Iterable[str]] = None,
refs: Optional[Iterable[str]] = None,
addresses: Optional[Iterable[str]] = None,
tags: Optional[Iterable[str]] = None,
hashes: Optional[Iterable[str]] = None,
channels: Optional[Iterable[str]] = None,
chains: Optional[Iterable[str]] = None,
start_date: Optional[Union[datetime, float]] = None,
end_date: Optional[Union[datetime, float]] = None,
ignore_invalid_messages: bool = True,
invalid_messages_log_level: int = logging.NOTSET,
) -> MessagesResponse:
return self._wrap(
self.async_session.get_messages,
pagination=pagination,
page=page,
message_type=message_type,
message_types=message_types,
content_types=content_types,
content_keys=content_keys,
refs=refs,
addresses=addresses,
tags=tags,
hashes=hashes,
channels=channels,
chains=chains,
start_date=start_date,
end_date=end_date,
ignore_invalid_messages=ignore_invalid_messages,
invalid_messages_log_level=invalid_messages_log_level,
)
# @async_wrapper
def get_message(
self,
item_hash: str,
message_type: Optional[Type[GenericMessage]] = None,
channel: Optional[str] = None,
) -> GenericMessage:
return self._wrap(
self.async_session.get_message,
item_hash=item_hash,
message_type=message_type,
channel=channel,
)
def fetch_aggregate(
self,
address: str,
key: str,
limit: int = 100,
) -> Dict[str, Dict]:
return self._wrap(self.async_session.fetch_aggregate, address, key, limit)
def fetch_aggregates(
self,
address: str,
keys: Optional[Iterable[str]] = None,
limit: int = 100,
) -> Dict[str, Dict]:
return self._wrap(self.async_session.fetch_aggregates, address, keys, limit)
def get_posts(
self,
pagination: int = 200,
page: int = 1,
types: Optional[Iterable[str]] = None,
refs: Optional[Iterable[str]] = None,
addresses: Optional[Iterable[str]] = None,
tags: Optional[Iterable[str]] = None,
hashes: Optional[Iterable[str]] = None,
channels: Optional[Iterable[str]] = None,
chains: Optional[Iterable[str]] = None,
start_date: Optional[Union[datetime, float]] = None,
end_date: Optional[Union[datetime, float]] = None,
) -> PostsResponse:
return self._wrap(
self.async_session.get_posts,
pagination=pagination,
page=page,
types=types,
refs=refs,
addresses=addresses,
tags=tags,
hashes=hashes,
channels=channels,
chains=chains,
start_date=start_date,
end_date=end_date,
)
def download_file(self, file_hash: str) -> bytes:
return self._wrap(self.async_session.download_file, file_hash=file_hash)
def download_file_ipfs(self, file_hash: str) -> bytes:
return self._wrap(
self.async_session.download_file_ipfs,
file_hash=file_hash,
)
def download_file_to_buffer(
self, file_hash: str, output_buffer: Writable[bytes]
) -> bytes:
return self._wrap(
self.async_session.download_file_to_buffer,
file_hash=file_hash,
output_buffer=output_buffer,
)
def download_file_ipfs_to_buffer(
self, file_hash: str, output_buffer: Writable[bytes]
) -> bytes:
return self._wrap(
self.async_session.download_file_ipfs_to_buffer,
file_hash=file_hash,
output_buffer=output_buffer,
)
def watch_messages(
self,
message_type: Optional[MessageType] = None,
content_types: Optional[Iterable[str]] = None,
refs: Optional[Iterable[str]] = None,
addresses: Optional[Iterable[str]] = None,
tags: Optional[Iterable[str]] = None,
hashes: Optional[Iterable[str]] = None,
channels: Optional[Iterable[str]] = None,
chains: Optional[Iterable[str]] = None,
start_date: Optional[Union[datetime, float]] = None,
end_date: Optional[Union[datetime, float]] = None,
) -> Iterable[AlephMessage]:
"""
Iterate over current and future matching messages synchronously.
Runs the `watch_messages` asynchronous generator in a thread.
"""
output_queue: queue.Queue[AlephMessage] = queue.Queue()
thread = threading.Thread(
target=watcher_thread,
args=(
output_queue,
self.async_session.api_server,
(
message_type,
content_types,
refs,
addresses,
tags,
hashes,
channels,
chains,
start_date,
end_date,
),
{},
),
)
thread.start()
while True:
yield output_queue.get()
class AuthenticatedUserSessionSync(UserSessionSync):
async_session: "AuthenticatedAlephClient"
def __init__(self, async_session: "AuthenticatedAlephClient"):
super().__init__(async_session=async_session)
def ipfs_push(self, content: Mapping) -> str:
return self._wrap(self.async_session.ipfs_push, content=content)
def storage_push(self, content: Mapping) -> str:
return self._wrap(self.async_session.storage_push, content=content)
def ipfs_push_file(self, file_content: Union[str, bytes]) -> str:
return self._wrap(self.async_session.ipfs_push_file, file_content=file_content)
def storage_push_file(self, file_content: Union[str, bytes]) -> str:
return self._wrap(
self.async_session.storage_push_file, file_content=file_content
)
def create_post(
self,
post_content,
post_type: str,
ref: Optional[str] = None,
address: Optional[str] = None,
channel: Optional[str] = None,
inline: bool = True,
storage_engine: StorageEnum = StorageEnum.storage,
sync: bool = False,
) -> Tuple[PostMessage, MessageStatus]:
return self._wrap(
self.async_session.create_post,
post_content=post_content,
post_type=post_type,
ref=ref,
address=address,
channel=channel,
inline=inline,
storage_engine=storage_engine,
sync=sync,
)
def create_aggregate(
self,
key: str,
content: Mapping[str, Any],
address: Optional[str] = None,
channel: Optional[str] = None,
inline: bool = True,
sync: bool = False,
) -> Tuple[AggregateMessage, MessageStatus]:
return self._wrap(
self.async_session.create_aggregate,
key=key,
content=content,
address=address,
channel=channel,
inline=inline,
sync=sync,
)
def create_store(
self,
address: Optional[str] = None,
file_content: Optional[bytes] = None,
file_path: Optional[Union[str, Path]] = None,
file_hash: Optional[str] = None,
guess_mime_type: bool = False,
ref: Optional[str] = None,
storage_engine: StorageEnum = StorageEnum.storage,
extra_fields: Optional[dict] = None,
channel: Optional[str] = None,
sync: bool = False,
) -> Tuple[StoreMessage, MessageStatus]:
return self._wrap(
self.async_session.create_store,
address=address,
file_content=file_content,
file_path=file_path,
file_hash=file_hash,
guess_mime_type=guess_mime_type,
ref=ref,
storage_engine=storage_engine,
extra_fields=extra_fields,
channel=channel,
sync=sync,
)
def create_program(
self,
program_ref: str,
entrypoint: str,
runtime: str,
environment_variables: Optional[Mapping[str, str]] = None,
storage_engine: StorageEnum = StorageEnum.storage,
channel: Optional[str] = None,
address: Optional[str] = None,
sync: bool = False,
memory: Optional[int] = None,
vcpus: Optional[int] = None,
timeout_seconds: Optional[float] = None,
persistent: bool = False,
encoding: Encoding = Encoding.zip,
volumes: Optional[List[Mapping]] = None,
subscriptions: Optional[List[Mapping]] = None,
metadata: Optional[Mapping[str, Any]] = None,
) -> Tuple[ProgramMessage, MessageStatus]:
return self._wrap(
self.async_session.create_program,
program_ref=program_ref,
entrypoint=entrypoint,
runtime=runtime,
environment_variables=environment_variables,
storage_engine=storage_engine,
channel=channel,
address=address,
sync=sync,
memory=memory,
vcpus=vcpus,
timeout_seconds=timeout_seconds,
persistent=persistent,
encoding=encoding,
volumes=volumes,
subscriptions=subscriptions,
metadata=metadata,
)
def forget(
self,
hashes: List[str],
reason: Optional[str],
storage_engine: StorageEnum = StorageEnum.storage,
channel: Optional[str] = None,
address: Optional[str] = None,
sync: bool = False,
) -> Tuple[ForgetMessage, MessageStatus]:
return self._wrap(
self.async_session.forget,
hashes=hashes,
reason=reason,
storage_engine=storage_engine,
channel=channel,
address=address,
sync=sync,
)
def submit(
self,
content: Dict[str, Any],
message_type: MessageType,
channel: Optional[str] = None,
storage_engine: StorageEnum = StorageEnum.storage,
allow_inlining: bool = True,
sync: bool = False,
) -> Tuple[AlephMessage, MessageStatus]:
return self._wrap(
self.async_session.submit,
content=content,
message_type=message_type,
channel=channel,
storage_engine=storage_engine,
allow_inlining=allow_inlining,
sync=sync,
)
class AlephClient(BaseAlephClient):
api_server: str
http_session: aiohttp.ClientSession
def __init__(
self,
api_server: Optional[str] = None,
api_unix_socket: Optional[str] = None,
allow_unix_sockets: bool = True,
timeout: Optional[aiohttp.ClientTimeout] = None,
):
"""AlephClient can use HTTP(S) or HTTP over Unix sockets.
Unix sockets are used when running inside a virtual machine,
and can be shared across containers in a more secure way than TCP ports.
"""
self.api_server = api_server or settings.API_HOST
if not self.api_server:
raise ValueError("Missing API host")
unix_socket_path = api_unix_socket or settings.API_UNIX_SOCKET
if unix_socket_path and allow_unix_sockets:
check_unix_socket_valid(unix_socket_path)
connector = aiohttp.UnixConnector(path=unix_socket_path)
else:
connector = None
# ClientSession timeout defaults to a private sentinel object and may not be None.
self.http_session = (
aiohttp.ClientSession(
base_url=self.api_server, connector=connector, timeout=timeout
)
if timeout
else aiohttp.ClientSession(
base_url=self.api_server,
connector=connector,
)
)
def __enter__(self) -> UserSessionSync:
return UserSessionSync(async_session=self)
def __exit__(self, exc_type, exc_val, exc_tb):
close_fut = self.http_session.close()
try:
loop = asyncio.get_running_loop()
loop.run_until_complete(close_fut)
except RuntimeError:
asyncio.run(close_fut)
async def __aenter__(self) -> "AlephClient":
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.http_session.close()
async def fetch_aggregate(
self,
address: str,
key: str,
limit: int = 100,
) -> Dict[str, Dict]:
params: Dict[str, Any] = {"keys": key}
if limit:
params["limit"] = limit
async with self.http_session.get(
f"/api/v0/aggregates/{address}.json", params=params
) as resp:
result = await resp.json()
data = result.get("data", dict())
return data.get(key)
async def fetch_aggregates(
self,
address: str,
keys: Optional[Iterable[str]] = None,
limit: int = 100,
) -> Dict[str, Dict]:
keys_str = ",".join(keys) if keys else ""
params: Dict[str, Any] = {}
if keys_str:
params["keys"] = keys_str
if limit:
params["limit"] = limit
async with self.http_session.get(
f"/api/v0/aggregates/{address}.json",
params=params,
) as resp:
result = await resp.json()
data = result.get("data", dict())
return data
async def get_posts(
self,
pagination: int = 200,
page: int = 1,
types: Optional[Iterable[str]] = None,
refs: Optional[Iterable[str]] = None,
addresses: Optional[Iterable[str]] = None,
tags: Optional[Iterable[str]] = None,
hashes: Optional[Iterable[str]] = None,
channels: Optional[Iterable[str]] = None,
chains: Optional[Iterable[str]] = None,
start_date: Optional[Union[datetime, float]] = None,
end_date: Optional[Union[datetime, float]] = None,
ignore_invalid_messages: Optional[bool] = True,
invalid_messages_log_level: Optional[int] = logging.NOTSET,
) -> PostsResponse:
ignore_invalid_messages = (
True if ignore_invalid_messages is None else ignore_invalid_messages
)
invalid_messages_log_level = (
logging.NOTSET
if invalid_messages_log_level is None
else invalid_messages_log_level
)
params: Dict[str, Any] = dict(pagination=pagination, page=page)
if types is not None:
params["types"] = ",".join(types)
if refs is not None:
params["refs"] = ",".join(refs)
if addresses is not None:
params["addresses"] = ",".join(addresses)
if tags is not None:
params["tags"] = ",".join(tags)
if hashes is not None:
params["hashes"] = ",".join(hashes)
if channels is not None:
params["channels"] = ",".join(channels)
if chains is not None:
params["chains"] = ",".join(chains)
if start_date is not None:
if not isinstance(start_date, float) and hasattr(start_date, "timestamp"):
start_date = start_date.timestamp()
params["startDate"] = start_date
if end_date is not None:
if not isinstance(end_date, float) and hasattr(start_date, "timestamp"):
end_date = end_date.timestamp()
params["endDate"] = end_date
async with self.http_session.get("/api/v0/posts.json", params=params) as resp:
resp.raise_for_status()
response_json = await resp.json()
posts_raw = response_json["posts"]
posts: List[Post] = []
for post_raw in posts_raw:
try:
posts.append(Post.parse_obj(post_raw))
except ValidationError as e:
if not ignore_invalid_messages:
raise e
if invalid_messages_log_level:
logger.log(level=invalid_messages_log_level, msg=e)
return PostsResponse(
posts=posts,
pagination_page=response_json["pagination_page"],
pagination_total=response_json["pagination_total"],
pagination_per_page=response_json["pagination_per_page"],
pagination_item=response_json["pagination_item"],
)
async def download_file_to_buffer(
self,
file_hash: str,
output_buffer: Writable[bytes],
) -> None:
"""
Download a file from the storage engine and write it to the specified output buffer.
:param file_hash: The hash of the file to retrieve.
:param output_buffer: Writable binary buffer. The file will be written to this buffer.
"""
async with self.http_session.get(
f"/api/v0/storage/raw/{file_hash}"
) as response:
if response.status == 200:
await copy_async_readable_to_buffer(
response.content, output_buffer, chunk_size=16 * 1024
)
if response.status == 413:
ipfs_hash = ItemHash(file_hash)
if ipfs_hash.item_type == ItemType.ipfs:
return await self.download_file_ipfs_to_buffer(
file_hash, output_buffer
)
else:
raise FileTooLarge(f"The file from {file_hash} is too large")
async def download_file_ipfs_to_buffer(
self,
file_hash: str,
output_buffer: Writable[bytes],
) -> None:
"""
Download a file from the storage engine and write it to the specified output buffer.
:param file_hash: The hash of the file to retrieve.
:param output_buffer: The binary output buffer to write the file data to.
"""
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://ipfs.aleph.im/ipfs/{file_hash}"
) as response:
if response.status == 200:
await copy_async_readable_to_buffer(
response.content, output_buffer, chunk_size=16 * 1024
)
else:
response.raise_for_status()
async def download_file(
self,
file_hash: str,
) -> bytes:
"""
Get a file from the storage engine as raw bytes.
Warning: Downloading large files can be slow and memory intensive.
:param file_hash: The hash of the file to retrieve.
"""
buffer = BytesIO()
await self.download_file_to_buffer(file_hash, output_buffer=buffer)
return buffer.getvalue()
async def download_file_ipfs(
self,
file_hash: str,
) -> bytes:
"""
Get a file from the ipfs storage engine as raw bytes.
Warning: Downloading large files can be slow.
:param file_hash: The hash of the file to retrieve.
"""
buffer = BytesIO()
await self.download_file_ipfs_to_buffer(file_hash, output_buffer=buffer)
return buffer.getvalue()
async def get_messages(
self,
pagination: int = 200,
page: int = 1,
message_type: Optional[MessageType] = None,
message_types: Optional[Iterable[MessageType]] = None,
content_types: Optional[Iterable[str]] = None,
content_keys: Optional[Iterable[str]] = None,
refs: Optional[Iterable[str]] = None,
addresses: Optional[Iterable[str]] = None,
tags: Optional[Iterable[str]] = None,
hashes: Optional[Iterable[str]] = None,
channels: Optional[Iterable[str]] = None,
chains: Optional[Iterable[str]] = None,
start_date: Optional[Union[datetime, float]] = None,
end_date: Optional[Union[datetime, float]] = None,
ignore_invalid_messages: Optional[bool] = True,
invalid_messages_log_level: Optional[int] = logging.NOTSET,
) -> MessagesResponse:
ignore_invalid_messages = (
True if ignore_invalid_messages is None else ignore_invalid_messages
)
invalid_messages_log_level = (
logging.NOTSET
if invalid_messages_log_level is None
else invalid_messages_log_level
)
params: Dict[str, Any] = dict(pagination=pagination, page=page)
if message_type is not None:
warnings.warn(
"The message_type parameter is deprecated, please use message_types instead.",
DeprecationWarning,
)
params["msgType"] = message_type.value
if message_types is not None:
params["msgTypes"] = ",".join([t.value for t in message_types])
print(params["msgTypes"])
if content_types is not None:
params["contentTypes"] = ",".join(content_types)
if content_keys is not None:
params["contentKeys"] = ",".join(content_keys)
if refs is not None:
params["refs"] = ",".join(refs)
if addresses is not None:
params["addresses"] = ",".join(addresses)
if tags is not None:
params["tags"] = ",".join(tags)
if hashes is not None:
params["hashes"] = ",".join(hashes)
if channels is not None:
params["channels"] = ",".join(channels)
if chains is not None:
params["chains"] = ",".join(chains)
if start_date is not None:
if not isinstance(start_date, float) and hasattr(start_date, "timestamp"):
start_date = start_date.timestamp()
params["startDate"] = start_date
if end_date is not None:
if not isinstance(end_date, float) and hasattr(start_date, "timestamp"):
end_date = end_date.timestamp()
params["endDate"] = end_date
async with self.http_session.get(
"/api/v0/messages.json", params=params
) as resp:
resp.raise_for_status()
response_json = await resp.json()
messages_raw = response_json["messages"]
# All messages may not be valid according to the latest specification in
# aleph-message. This allows the user to specify how errors should be handled.
messages: List[AlephMessage] = []
for message_raw in messages_raw:
try:
message = parse_message(message_raw)
messages.append(message)
except KeyError as e:
if not ignore_invalid_messages:
raise e
logger.log(
level=invalid_messages_log_level,
msg=f"KeyError: Field '{e.args[0]}' not found",
)
except ValidationError as e:
if not ignore_invalid_messages:
raise e
if invalid_messages_log_level:
logger.log(level=invalid_messages_log_level, msg=e)
return MessagesResponse(
messages=messages,
pagination_page=response_json["pagination_page"],
pagination_total=response_json["pagination_total"],
pagination_per_page=response_json["pagination_per_page"],
pagination_item=response_json["pagination_item"],
)
async def get_message(
self,
item_hash: str,
message_type: Optional[Type[GenericMessage]] = None,
channel: Optional[str] = None,
) -> GenericMessage:
messages_response = await self.get_messages(
hashes=[item_hash],
channels=[channel] if channel else None,
)
if len(messages_response.messages) < 1:
raise MessageNotFoundError(f"No such hash {item_hash}")
if len(messages_response.messages) != 1:
raise MultipleMessagesError(
f"Multiple messages found for the same item_hash `{item_hash}`"
)
message: GenericMessage = messages_response.messages[0]
if message_type:
expected_type = get_message_type_value(message_type)
if message.type != expected_type:
raise TypeError(
f"The message type '{message.type}' "
f"does not match the expected type '{expected_type}'"
)
return message
async def watch_messages(
self,
message_type: Optional[MessageType] = None,
message_types: Optional[Iterable[MessageType]] = None,
content_types: Optional[Iterable[str]] = None,
content_keys: Optional[Iterable[str]] = None,
refs: Optional[Iterable[str]] = None,
addresses: Optional[Iterable[str]] = None,
tags: Optional[Iterable[str]] = None,
hashes: Optional[Iterable[str]] = None,
channels: Optional[Iterable[str]] = None,
chains: Optional[Iterable[str]] = None,
start_date: Optional[Union[datetime, float]] = None,
end_date: Optional[Union[datetime, float]] = None,
) -> AsyncIterable[AlephMessage]:
params: Dict[str, Any] = dict()
if message_type is not None:
warnings.warn(
"The message_type parameter is deprecated, please use message_types instead.",
DeprecationWarning,
)
params["msgType"] = message_type.value
if message_types is not None:
params["msgTypes"] = ",".join([t.value for t in message_types])
if content_types is not None:
params["contentTypes"] = ",".join(content_types)
if content_keys is not None:
params["contentKeys"] = ",".join(content_keys)
if refs is not None:
params["refs"] = ",".join(refs)
if addresses is not None:
params["addresses"] = ",".join(addresses)
if tags is not None:
params["tags"] = ",".join(tags)
if hashes is not None:
params["hashes"] = ",".join(hashes)
if channels is not None:
params["channels"] = ",".join(channels)
if chains is not None:
params["chains"] = ",".join(chains)
if start_date is not None:
if not isinstance(start_date, float) and hasattr(start_date, "timestamp"):
start_date = start_date.timestamp()
params["startDate"] = start_date
if end_date is not None:
if not isinstance(end_date, float) and hasattr(start_date, "timestamp"):
end_date = end_date.timestamp()
params["endDate"] = end_date
async with self.http_session.ws_connect(
"/api/ws0/messages", params=params
) as ws:
logger.debug("Websocket connected")
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == "close cmd":
await ws.close()
break
else:
data = json.loads(msg.data)
yield parse_message(data)
elif msg.type == aiohttp.WSMsgType.ERROR:
break
class AuthenticatedAlephClient(AlephClient, BaseAuthenticatedAlephClient):
account: Account
BROADCAST_MESSAGE_FIELDS = {
"sender",
"chain",
"signature",
"type",
"item_hash",
"item_type",
"item_content",
"time",
"channel",
}
def __init__(
self,
account: Account,
api_server: Optional[str],
api_unix_socket: Optional[str] = None,
allow_unix_sockets: bool = True,
timeout: Optional[aiohttp.ClientTimeout] = None,
):
super().__init__(
api_server=api_server,
api_unix_socket=api_unix_socket,
allow_unix_sockets=allow_unix_sockets,
timeout=timeout,
)
self.account = account
def __enter__(self) -> "AuthenticatedUserSessionSync":
return AuthenticatedUserSessionSync(async_session=self)
async def __aenter__(self) -> "AuthenticatedAlephClient":
return self
async def ipfs_push(self, content: Mapping) -> str:
"""
Push arbitrary content as JSON to the IPFS service.
:param content: The dict-like content to upload
"""
url = "/api/v0/ipfs/add_json"
logger.debug(f"Pushing to IPFS on {url}")
async with self.http_session.post(url, json=content) as resp:
resp.raise_for_status()
return (await resp.json()).get("hash")
async def storage_push(self, content: Mapping) -> str:
"""
Push arbitrary content as JSON to the storage service.
:param content: The dict-like content to upload
"""
url = "/api/v0/storage/add_json"
logger.debug(f"Pushing to storage on {url}")
async with self.http_session.post(url, json=content) as resp:
resp.raise_for_status()
return (await resp.json()).get("hash")
async def ipfs_push_file(self, file_content: Union[str, bytes]) -> str:
"""
Push a file to the IPFS service.
:param file_content: The file content to upload
"""
data = aiohttp.FormData()
data.add_field("file", file_content)
url = "/api/v0/ipfs/add_file"
logger.debug(f"Pushing file to IPFS on {url}")
async with self.http_session.post(url, data=data) as resp:
resp.raise_for_status()
return (await resp.json()).get("hash")
async def storage_push_file(self, file_content) -> str:
"""
Push a file to the storage service.
"""
data = aiohttp.FormData()
data.add_field("file", file_content)
url = "/api/v0/storage/add_file"
logger.debug(f"Posting file on {url}")