Skip to content

Commit 2409a60

Browse files
committed
change back to v0 posts
1 parent 0d10120 commit 2409a60

File tree

6 files changed

+94
-78
lines changed

6 files changed

+94
-78
lines changed

src/aleph/sdk/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -617,7 +617,7 @@ async def get_posts(
617617
end_date = end_date.timestamp()
618618
params["endDate"] = end_date
619619

620-
async with self.http_session.get("/api/v1/posts.json", params=params) as resp:
620+
async with self.http_session.get("/api/v0/posts.json", params=params) as resp:
621621
resp.raise_for_status()
622622
response_json = await resp.json()
623623
posts_raw = response_json["posts"]

src/aleph/sdk/models.py

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
from datetime import datetime
2-
from typing import Any, Dict, List, Optional
1+
from typing import Any, Dict, List, Optional, Union
32

4-
from aleph_message.models import AlephMessage, ItemHash
3+
from aleph_message.models import AlephMessage, ItemHash, ChainRef, ItemType, Chain, MessageConfirmation
54
from pydantic import BaseModel, Field
65

76

@@ -24,29 +23,24 @@ class Post(BaseModel):
2423
A post is a type of message that can be updated. Over the get_posts API
2524
we get the latest version of a post.
2625
"""
27-
28-
item_hash: ItemHash = Field(description="Hash of the content (sha256 by default)")
29-
content: Dict[str, Any] = Field(
30-
description="The content.content of the POST message"
31-
)
32-
original_item_hash: ItemHash = Field(
33-
description="Hash of the original content (sha256 by default)"
34-
)
35-
original_type: str = Field(
36-
description="The original, user-generated 'content-type' of the POST message"
37-
)
38-
address: str = Field(description="The address of the sender of the POST message")
39-
ref: Optional[str] = Field(description="Other message referenced by this one")
40-
channel: Optional[str] = Field(
41-
description="The channel where the POST message was published"
42-
)
43-
created: datetime = Field(description="The time when the POST message was created")
44-
last_updated: datetime = Field(
45-
description="The time when the POST message was last updated"
46-
)
47-
48-
class Config:
49-
allow_extra = False
26+
chain: Chain = Field(description="Blockchain this post is associated with")
27+
item_hash: ItemHash = Field(description="Unique hash for this post")
28+
sender: str = Field(description="Address of the sender")
29+
type: str = Field(description="Type of the POST message")
30+
channel: Optional[str] = Field(description="Channel this post is associated with")
31+
confirmed: bool = Field(description="Whether the post is confirmed or not")
32+
content: Dict[str, Any] = Field(description="The content of the POST message")
33+
item_content: Optional[str] = Field(description="The POSTs content field as serialized JSON, if of type inline")
34+
item_type: ItemType = Field(description="Type of the item content, usually 'inline' or 'storage' for POSTs")
35+
signature: Optional[str] = Field(description="Cryptographic signature of the message by the sender")
36+
size: int = Field(description="Size of the post")
37+
time: float = Field(description="Timestamp of the post")
38+
confirmations: List[MessageConfirmation] = Field(description="Number of confirmations")
39+
original_item_hash: ItemHash = Field(description="Hash of the original content")
40+
original_signature: Optional[str] = Field(description="Cryptographic signature of the original message")
41+
original_type: str = Field(description="The original type of the message")
42+
hash: ItemHash = Field(description="Hash of the original item")
43+
ref: Optional[Union[str, Any]] = Field(description="Other message referenced by this one")
5044

5145

5246
class PostsResponse(PaginationResponse):

src/aleph/sdk/node/__init__.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from ..types import GenericMessage, StorageEnum
3232
from .common import db
3333
from .message import MessageModel, get_message_query, message_to_model, model_to_message
34-
from .post import PostModel, get_post_query, message_to_post, model_to_post
34+
from .post import PostModel, get_post_query, message_to_post, model_to_post, post_to_model
3535

3636

3737
class MessageCache(BaseAlephClient):
@@ -112,9 +112,7 @@ def add(self, messages: Union[AlephMessage, Iterable[AlephMessage]]):
112112
if message.content.type == "amend":
113113
amend_messages.append(message)
114114
continue
115-
post = message_to_post(message).dict()
116-
post["chain"] = message.chain.value
117-
post["tags"] = message.content.content.get("tags", None)
115+
post = post_to_model(message_to_post(message))
118116
post_data.append(post)
119117
# Check if we can now add any amend messages that had missing refs
120118
if message.item_hash in self.missing_posts:

src/aleph/sdk/node/common.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,15 @@
55
from peewee import SqliteDatabase
66
from playhouse.sqlite_ext import JSONField
77
from pydantic import BaseModel
8+
from pydantic.json import pydantic_encoder
89

910
from aleph.sdk.conf import settings
1011

1112
db = SqliteDatabase(settings.CACHE_DATABASE_PATH)
1213
T = TypeVar("T", bound=BaseModel)
1314

1415

15-
class JSONDictEncoder(json.JSONEncoder):
16-
def default(self, obj):
17-
if isinstance(obj, BaseModel):
18-
return obj.dict()
19-
return json.JSONEncoder.default(self, obj)
20-
21-
22-
pydantic_json_dumps = partial(json.dumps, cls=JSONDictEncoder)
16+
pydantic_json_dumps = partial(json.dumps, default=pydantic_encoder)
2317

2418

2519
class PydanticField(JSONField, Generic[T]):
@@ -36,9 +30,9 @@ def __init__(self, *args, **kwargs):
3630
def db_value(self, value: Optional[T]) -> Optional[str]:
3731
if value is None:
3832
return None
39-
return value.json()
33+
return pydantic_json_dumps(value)
4034

4135
def python_value(self, value: Optional[str]) -> Optional[T]:
42-
if value is None:
36+
if not value:
4337
return None
4438
return self.type.parse_raw(value)

src/aleph/sdk/node/post.py

Lines changed: 64 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
from datetime import datetime
2-
from typing import Any, Dict, Iterable, Optional, Union
2+
from typing import Any, Dict, Iterable, Optional, Union, List
33

4-
from aleph_message.models import PostMessage
5-
from peewee import CharField, DateTimeField, Model
4+
from aleph_message.models import PostMessage, MessageConfirmation
5+
from peewee import CharField, Model, BooleanField, IntegerField, FloatField
66
from playhouse.shortcuts import model_to_dict
77
from playhouse.sqlite_ext import JSONField
88

99
from aleph.sdk.models import Post
10-
from aleph.sdk.node.common import db, pydantic_json_dumps
10+
from aleph.sdk.node.common import db, pydantic_json_dumps, PydanticField
1111

1212

1313
class PostModel(Model):
@@ -16,56 +16,84 @@ class PostModel(Model):
1616
"""
1717

1818
original_item_hash = CharField(primary_key=True)
19-
item_hash = CharField()
20-
content = JSONField(json_dumps=pydantic_json_dumps)
2119
original_type = CharField()
22-
address = CharField()
23-
ref = CharField(null=True)
20+
original_signature = CharField()
21+
item_hash = CharField()
22+
chain = CharField(5)
23+
type = CharField()
24+
sender = CharField()
2425
channel = CharField(null=True)
25-
created = DateTimeField()
26-
last_updated = DateTimeField()
26+
confirmations: PydanticField[MessageConfirmation] = PydanticField(
27+
type=MessageConfirmation, null=True
28+
)
29+
confirmed = BooleanField()
30+
signature = CharField()
31+
size = IntegerField(null=True)
32+
time = FloatField()
33+
item_type = CharField(7)
34+
item_content = CharField(null=True)
35+
content = JSONField(json_dumps=pydantic_json_dumps)
2736
tags = JSONField(json_dumps=pydantic_json_dumps, null=True)
28-
chain = CharField(5)
37+
key = CharField(null=True)
38+
ref = CharField(null=True)
39+
content_type = CharField(null=True)
2940

3041
class Meta:
3142
database = db
3243

3344

3445
def post_to_model(post: Post) -> Dict:
3546
return {
36-
"item_hash": str(post.item_hash),
37-
"content": post.content,
47+
"item_hash": str(post.original_item_hash),
48+
"chain": post.chain.value,
49+
"type": post.type,
50+
"sender": post.sender,
51+
"channel": post.channel,
52+
"confirmations": post.confirmations[0] if post.confirmations else None,
53+
"confirmed": post.confirmed,
54+
"signature": post.signature,
55+
"size": post.size,
56+
"time": post.time,
3857
"original_item_hash": str(post.original_item_hash),
39-
"original_type": post.original_type,
40-
"address": post.address,
58+
"original_type": post.original_type if post.original_type else post.type,
59+
"original_signature": post.original_signature if post.original_signature else post.signature,
60+
"item_type": post.item_type,
61+
"item_content": post.item_content,
62+
"content": post.content,
63+
"tags": post.content.content.get("tags", None) if hasattr(post.content, "content") else None,
4164
"ref": post.ref,
42-
"channel": post.channel,
43-
"created": post.created,
44-
"last_updated": post.last_updated,
4565
}
4666

4767

4868
def message_to_post(message: PostMessage) -> Post:
49-
return Post.parse_obj(
50-
{
51-
"item_hash": str(message.item_hash),
52-
"content": message.content,
53-
"original_item_hash": str(message.item_hash),
54-
"original_type": message.content.type
55-
if hasattr(message.content, "type")
56-
else None,
57-
"address": message.sender,
58-
"ref": message.content.ref if hasattr(message.content, "ref") else None,
59-
"channel": message.channel,
60-
"created": datetime.fromtimestamp(message.time),
61-
"last_updated": datetime.fromtimestamp(message.time),
62-
}
69+
return Post(
70+
chain=message.chain,
71+
item_hash=message.item_hash,
72+
sender=message.sender,
73+
type=message.content.type,
74+
channel=message.channel,
75+
confirmed=message.confirmed if message.confirmed else False,
76+
confirmations=message.confirmations if message.confirmations else [],
77+
content=message.content,
78+
item_content=message.item_content,
79+
item_type=message.item_type,
80+
signature=message.signature,
81+
size=message.size if message.size else len(message.content.json().encode()),
82+
time=message.time,
83+
original_item_hash=message.item_hash,
84+
original_signature=message.signature,
85+
original_type=message.content.type,
86+
hash=message.item_hash,
87+
ref=message.content.ref,
6388
)
6489

6590

6691
def model_to_post(item: Any) -> Post:
67-
to_exclude = [PostModel.tags, PostModel.chain]
68-
return Post.parse_obj(model_to_dict(item, exclude=to_exclude))
92+
to_exclude = [PostModel.tags]
93+
model_dict = model_to_dict(item, exclude=to_exclude)
94+
model_dict["confirmations"] = [model_dict["confirmations"]] if model_dict["confirmations"] else []
95+
model_dict["hash"] = model_dict["item_hash"]
96+
return Post.parse_obj(model_dict)
6997

7098

7199
def query_field(field_name, field_values: Iterable[str]):
@@ -88,14 +116,14 @@ def get_post_query(
88116
start_date: Optional[Union[datetime, float]] = None,
89117
end_date: Optional[Union[datetime, float]] = None,
90118
):
91-
query = PostModel.select().order_by(PostModel.created.desc())
119+
query = PostModel.select().order_by(PostModel.time.desc())
92120
conditions = []
93121
if types:
94122
conditions.append(query_field("original_type", types))
95123
if refs:
96124
conditions.append(query_field("ref", refs))
97125
if addresses:
98-
conditions.append(query_field("address", addresses))
126+
conditions.append(query_field("sender", addresses))
99127
if tags:
100128
for tag in tags:
101129
conditions.append(PostModel.tags.contains(tag))

tests/unit/test_node_get.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,15 +176,17 @@ async def mock_message_stream():
176176
address=get_fallback_account().get_address(),
177177
time=0,
178178
)
179+
item_hash = sha256(json.dumps(content.dict()).encode()).hexdigest()
179180
message = PostMessage(
180181
sender=get_fallback_account().get_address(),
181-
item_hash=sha256(json.dumps(content.dict()).encode()).hexdigest(),
182+
item_hash=item_hash,
182183
chain=Chain.ETH.value,
183184
type=MessageType.post.value,
184185
item_type="inline",
185186
time=0,
186187
content=content,
187188
item_content=json.dumps(content.dict()),
189+
signature="",
188190
)
189191
yield message
190192

0 commit comments

Comments
 (0)