Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions MIGRATION_v7_to_v8.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Migration Guide: v7 → v8

v8 regenerates the client from the current Stream API. Most of the changes add new methods, models and optional parameters. This guide lists the changes that can break code written for stream-py 7.1.0.

```bash
pip install "getstream==8.*"
```

## Pass optional parameters by keyword

Generated method parameters are positional-or-keyword, and v8 adds new optional parameters in the middle of many signatures. A call that passes optional arguments by position can now send a value to the wrong parameter. Calls that pass them by keyword work unchanged.

```python
# v7: the fourth positional argument was `user_id`
client.feeds.get_activity(activity_id, "first", 10, "jane")

# v8: "jane" would go to the new `skip_own_followings`, so pass it by keyword
client.feeds.get_activity(activity_id, comment_sort="first", comment_limit=10, user_id="jane")
```

These methods have new parameters before existing ones. Each async client has the same changes.

| Method | New parameters | First moved parameter |
|---|---|---|
| `Channel.get_or_create`, `chat.get_or_create_channel`, `chat.get_or_create_distinct_channel` | `include_scheduled_messages` | `state` |
| `Channel.send_message`, `chat.send_message` | `scheduled_at` | `skip_enrich_url` |
| `chat.query_channels` | `include_active_member_count` | `limit` |
| `chat.grouped_query_channels` | `sort` | `groups` |
| `chat.channel_batch_update` | `synchronous` | `custom_unset` |
| `chat.create_channel_type` | `quotes`, `reminders`, `automod_thresholds` | `reactions` |
| `chat.create_reminder`, `chat.update_reminder` | `expires_at` | `remind_at` |
| `chat.cast_poll_vote`, `feeds.cast_poll_vote` | `config_key`, `config_team` | `user_id` |
| `create_poll` | `config_key`, `config_team`, `team` | `description` |
| `update_poll` | `config_key`, `config_team` | `description` |
| `update_poll_partial`, `create_poll_option`, `update_poll_option` | `config_key`, `config_team` | `user_id` |
| `update_app` | `two_way_block_effect_enabled` | `user_response_time_enabled` |
| `Feed.get_or_create`, `feeds.get_or_create_feed` | `discard_actors` | `data` |
| `Feed.query_pinned_activities`, `feeds.query_pinned_activities` | `include_expired_activities`, `include_moderated_activities`, `include_soft_deleted_activities`, `user_id` | `limit` |
| `feeds.add_activity` | `skip_existing` | `skip_push` |
| `feeds.get_activity` | `skip_own_followings` | `user_id` |
| `feeds.query_activities` | `include_moderated_activities` | `include_private_activities` |
| `feeds.query_comments` | `include_soft_deleted_comments` | `limit` |
| `feeds.query_follows` | `include_group_counts` | `limit` |
| `feeds.follow_batch`, `feeds.get_or_create_follows` | `_async` | `create_users` |
| `feeds.unfollow_batch`, `feeds.get_or_create_unfollows` | `_async` | `delete_notification_activity` |
| `moderation.analyze` | `country_code`, `country_codes` | `entity_creator_id` |
| `moderation.check` | `country_code`, `country_codes` | `test_mode` |
| `moderation.appeal` | `channel_cid` | `review_queue_item_id` |
| `moderation.ban` | `ban_from_future_channels`, `delete_reactions` | `banned_by_id` |
| `moderation.unban` | `remove_future_channels_ban` | `unbanned_by_id` |
| `moderation.submit_action` | `delete_poll`, `delete_poll_answer`, `delete_poll_option` | `delete_reaction` |
| `moderation.upsert_config` | `engine`, `intent_config` | `flood_config` |

## Parameters that are now optional

These parameters are now optional, so they moved behind the required ones. Pass them by keyword.

- `chat.update_channel_type`: `automod`, `automod_behavior` and `max_message_length`. `max_message_length` now comes after `mark_messages_pending`.
- `moderation.submit_moderation_feedback`: `message`, `published_at` and `reference`. They now come after `channel_id` and the new `confidence`, `entity_creator_id`, `entity_id`, `entity_type`, `false_positive` and `feedback_type` parameters, and before the new `review_queue_item_id` and `user_id`.

The matching request models, `UpdateChannelTypeRequest` and `SubmitModerationFeedbackRequest`, give these fields a `None` default, so they also moved in the dataclass field order.

## Campaign responses

`update_campaign` returns `UpdateCampaignResponse` and `stop_campaign` returns `StopCampaignResponse`. v7 decoded both into `CampaignResponse`, whose fields came back as `None` because the API returns the campaign inside a `campaign` field. Read the campaign from that field.

```python
# v7
resp = client.chat.stop_campaign(id=campaign_id)
status = resp.data.status # None

# v8
resp = client.chat.stop_campaign(id=campaign_id)
status = resp.data.campaign.status
```

## Removed models

These request models had no fields, because their endpoints take no request body. The methods that call those endpoints keep their signatures.

- `CancelImportV2TaskRequest`
- `CommitMessageRequest`
- `EndCallRequest`
- `ExportFeedUserDataRequest`
- `RestoreFeedGroupRequest`
- `StartHLSBroadcastingRequest`
- `StartPolicyTestRunRequest`
- `StopAllRTMPBroadcastsRequest`
- `StopCampaignRequest`
- `StopFrameRecordingRequest`
- `StopHLSBroadcastingRequest`
- `VideoEndCallRequestPayload`
- `VideoKickUserRequestPayload`

`Time` was also removed. `EnrichedReaction.created_at` and `EnrichedReaction.updated_at` are now `Optional[str]`.

## Removed field

`AIVideoConfig.provider` was removed. Drop it from `AIVideoConfig(...)` calls in your moderation config.

## Type annotation changes

These changes affect only type checkers. Runtime values are unchanged.
Comment thread
mogita marked this conversation as resolved.
Resolved

- `own_capabilities` on call, channel and feed responses is annotated as `List[str]`. The constants classes `OwnCapability`, `ChannelOwnCapability` and `FeedOwnCapability` still exist, and their values are strings.
- `CampaignResponse.sender_mode` and `CampaignResponse.sender_visibility` are now `Optional[str]`.

## Required response fields

`ChannelMemberResponse.user_id` and `OwnUserResponse.blocked_user_ids` are now required and have no default. Responses the SDK decodes are unaffected, but code that builds these models itself, such as test fixtures, must pass both fields, or the constructor raises `TypeError` and a direct `from_dict` without `infer_missing=True` raises `KeyError`.

## Uploads

`upload_file`, `upload_image`, `upload_channel_file` and `upload_channel_image` keep their signatures and still send `multipart/form-data`. `file` is a keyword with a `None` default in the signature, but the upload raises `ValueError` without it.
32 changes: 19 additions & 13 deletions getstream/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import uuid
import warnings
import asyncio
from typing import Any, Dict, List, Optional, Tuple, Type, cast, get_origin
from typing import Any, Dict, Optional, Tuple, Type, cast, get_origin

from getstream.exceptions import (
StreamApiException,
Expand Down Expand Up @@ -143,6 +143,20 @@ def _read_file_bytes(file_path: str) -> bytes:
return f.read()


def _multipart_form(body: Dict[str, Any]) -> Tuple[str, Dict[str, str]]:
"""Split an upload body into the file path and the other set fields as form
values: strings as-is, anything else JSON-encoded, which is how the API reads
"user" and "upload_sizes"."""
fields = _strip_none(body)
file_path = fields.pop("file", None)
if not file_path:
raise ValueError("file path must be provided")
return file_path, {
name: value if isinstance(value, str) else json.dumps(value)
for name, value in fields.items()
}


def _strip_none(obj):
"""Recursively remove None values from dicts so unset optional fields
are omitted from the JSON body instead of being sent as null. ``NULL``
Expand Down Expand Up @@ -569,23 +583,19 @@ def _upload_multipart(
self,
path: str,
data_type: Type[T],
file_path: str,
*,
path_params: Optional[Dict[str, str]] = None,
query_params: Optional[Dict[str, str]] = None,
form_fields: Optional[List[Tuple[str, str]]] = None,
json: Dict[str, Any],
) -> StreamResponse[T]:
"""Send a multipart/form-data upload request, matching Go/PHP SDK behavior."""
file_path, data = _multipart_form(json)
file_name = os.path.basename(file_path)
content_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
with open(file_path, "rb") as f:
file_content = f.read()

files = {"file": (file_name, file_content, content_type)}
data: Dict[str, str] = {}
for field_name, field_value in form_fields or []:
data[field_name] = field_value

kwargs: Dict[str, Any] = {"files": files}
if data:
kwargs["data"] = data
Expand Down Expand Up @@ -700,23 +710,19 @@ async def _upload_multipart(
self,
path: str,
data_type: Type[T],
file_path: str,
*,
path_params: Optional[Dict[str, str]] = None,
query_params: Optional[Dict[str, str]] = None,
form_fields: Optional[List[Tuple[str, str]]] = None,
json: Dict[str, Any],
) -> StreamResponse[T]:
"""Send a multipart/form-data upload request, matching Go/PHP SDK behavior."""
file_path, data = _multipart_form(json)
file_name = os.path.basename(file_path)
content_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"

file_content = await asyncio.to_thread(_read_file_bytes, file_path)

files = {"file": (file_name, file_content, content_type)}
data: Dict[str, str] = {}
for field_name, field_value in form_fields or []:
data[field_name] = field_value

kwargs: Dict[str, Any] = {"files": files}
if data:
kwargs["data"] = data
Expand Down
97 changes: 96 additions & 1 deletion getstream/chat/async_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ def __init__(
self.custom_data = custom_data or {}

def _sync_from_response(self, data):
if hasattr(data, "channel") and isinstance(data.channel, ChannelResponse):
# A fork's response carries the new channel, not this one.
if (
hasattr(data, "channel")
and isinstance(data.channel, ChannelResponse)
and data.channel.cid == f"{self.channel_type}:{self.channel_id}"
):
self.custom_data = data.channel.custom

@attach_channel_cid_async
Expand Down Expand Up @@ -131,6 +136,33 @@ async def update(
self._sync_from_response(response.data)
return response

@attach_channel_cid_async
async def query_channel_bans(
self,
exclude_expired_bans: Optional[bool] = None,
include_total: Optional[bool] = None,
limit: Optional[int] = None,
next: Optional[str] = None,
prev: Optional[str] = None,
user_id: Optional[str] = None,
filter_conditions: Optional[Dict[str, object]] = None,
user: Optional[UserRequest] = None,
) -> StreamResponse[QueryChannelBansResponse]:
response = await self.client.query_channel_bans(
type=self.channel_type,
id=self.channel_id,
exclude_expired_bans=exclude_expired_bans,
include_total=include_total,
limit=limit,
next=next,
prev=prev,
user_id=user_id,
filter_conditions=filter_conditions,
user=user,
)
self._sync_from_response(response.data)
return response

@attach_channel_cid_async
async def delete_draft(
self, parent_id: Optional[str] = None, user_id: Optional[str] = None
Expand Down Expand Up @@ -185,6 +217,44 @@ async def upload_channel_file(
self._sync_from_response(response.data)
return response

@attach_channel_cid_async
async def fork(
self,
message_id: str,
channel: ForkChannelTarget,
exclude_attachments: Optional[bool] = None,
user_id: Optional[str] = None,
user: Optional[UserRequest] = None,
) -> StreamResponse[ForkChannelResponse]:
response = await self.client.fork_channel(
type=self.channel_type,
id=self.channel_id,
message_id=message_id,
channel=channel,
exclude_attachments=exclude_attachments,
user_id=user_id,
user=user,
)
self._sync_from_response(response.data)
return response

@attach_channel_cid_async
async def fork_message_ids(
self,
source_message_ids: List[str],
user_id: Optional[str] = None,
user: Optional[UserRequest] = None,
) -> StreamResponse[ForkMessageIDsResponse]:
response = await self.client.fork_message_ids(
type=self.channel_type,
id=self.channel_id,
source_message_ids=source_message_ids,
user_id=user_id,
user=user,
)
self._sync_from_response(response.data)
return response

@attach_channel_cid_async
async def hide(
self,
Expand Down Expand Up @@ -255,6 +325,7 @@ async def send_message(
include_mentioned_members: Optional[bool] = None,
keep_channel_hidden: Optional[bool] = None,
pending: Optional[bool] = None,
scheduled_at: Optional[datetime] = None,
skip_enrich_url: Optional[bool] = None,
skip_push: Optional[bool] = None,
pending_message_metadata: Optional[Dict[str, str]] = None,
Expand All @@ -268,6 +339,7 @@ async def send_message(
include_mentioned_members=include_mentioned_members,
keep_channel_hidden=keep_channel_hidden,
pending=pending,
scheduled_at=scheduled_at,
skip_enrich_url=skip_enrich_url,
skip_push=skip_push,
pending_message_metadata=pending_message_metadata,
Expand Down Expand Up @@ -333,6 +405,7 @@ async def get_pinned_messages(
async def get_or_create(
self,
hide_for_creator: Optional[bool] = None,
include_scheduled_messages: Optional[bool] = None,
state: Optional[bool] = None,
thread_unread_counts: Optional[bool] = None,
member_custom_include: Optional[List[str]] = None,
Expand All @@ -345,6 +418,7 @@ async def get_or_create(
type=self.channel_type,
id=self.channel_id,
hide_for_creator=hide_for_creator,
include_scheduled_messages=include_scheduled_messages,
state=state,
thread_unread_counts=thread_unread_counts,
member_custom_include=member_custom_include,
Expand Down Expand Up @@ -375,6 +449,27 @@ async def mark_read(
self._sync_from_response(response.data)
return response

@attach_channel_cid_async
async def rewind(
self,
expected_last_message_id: str,
message_id: str,
inclusive: Optional[bool] = None,
user_id: Optional[str] = None,
user: Optional[UserRequest] = None,
) -> StreamResponse[RewindChannelResponse]:
response = await self.client.rewind_channel(
type=self.channel_type,
id=self.channel_id,
expected_last_message_id=expected_last_message_id,
message_id=message_id,
inclusive=inclusive,
user_id=user_id,
user=user,
)
self._sync_from_response(response.data)
return response

@attach_channel_cid_async
async def show(
self, user_id: Optional[str] = None, user: Optional[UserRequest] = None
Expand Down
Loading
Loading