91 lines
2.7 KiB
Python
91 lines
2.7 KiB
Python
|
|
import asyncio
|
||
|
|
import time
|
||
|
|
|
||
|
|
MAX_EDITS = 10
|
||
|
|
EDIT_THROTTLE_MS = 1500
|
||
|
|
|
||
|
|
|
||
|
|
class WebexEditStreamSession:
|
||
|
|
def __init__(self, outbound, room_id: str, *, parent_id: str | None = None):
|
||
|
|
self._outbound = outbound
|
||
|
|
self._room_id = room_id
|
||
|
|
self._parent_id = parent_id
|
||
|
|
self._message_id: str | None = None
|
||
|
|
self._edit_count = 0
|
||
|
|
self._cancelled = False
|
||
|
|
self._last_text = ""
|
||
|
|
self._last_update = 0.0
|
||
|
|
|
||
|
|
async def start(self) -> str:
|
||
|
|
sent_ids = await self._outbound.send_text(
|
||
|
|
self._room_id,
|
||
|
|
"\u23f3 _\u6b63\u5728\u751f\u6210\u56de\u590d..._",
|
||
|
|
parent_id=self._parent_id,
|
||
|
|
)
|
||
|
|
self._message_id = sent_ids[0]
|
||
|
|
self._edit_count = 0
|
||
|
|
self._last_text = "\u23f3 _\u6b63\u5728\u751f\u6210\u56de\u590d..._"
|
||
|
|
return self._message_id
|
||
|
|
|
||
|
|
async def update(self, text: str) -> bool:
|
||
|
|
if self._cancelled or self._edit_count >= MAX_EDITS - 1:
|
||
|
|
self._cancelled = True
|
||
|
|
return False
|
||
|
|
|
||
|
|
elapsed = (time.monotonic() - self._last_update) * 1000
|
||
|
|
if elapsed < EDIT_THROTTLE_MS:
|
||
|
|
await asyncio.sleep((EDIT_THROTTLE_MS - elapsed) / 1000.0)
|
||
|
|
|
||
|
|
try:
|
||
|
|
await self._outbound.edit_message(
|
||
|
|
self._message_id,
|
||
|
|
self._room_id,
|
||
|
|
text + "\n\n_\u751f\u6210\u4e2d..._",
|
||
|
|
)
|
||
|
|
self._edit_count += 1
|
||
|
|
self._last_text = text
|
||
|
|
self._last_update = time.monotonic()
|
||
|
|
return True
|
||
|
|
except Exception:
|
||
|
|
self._cancelled = True
|
||
|
|
return False
|
||
|
|
|
||
|
|
async def finish(self, final_text: str):
|
||
|
|
try:
|
||
|
|
await self._outbound.edit_message(
|
||
|
|
self._message_id,
|
||
|
|
self._room_id,
|
||
|
|
final_text,
|
||
|
|
)
|
||
|
|
except Exception:
|
||
|
|
try:
|
||
|
|
await self._outbound.delete_message(self._message_id)
|
||
|
|
except Exception:
|
||
|
|
pass
|
||
|
|
self._message_id = None
|
||
|
|
await self._outbound.send_text(
|
||
|
|
self._room_id,
|
||
|
|
final_text,
|
||
|
|
parent_id=self._parent_id,
|
||
|
|
)
|
||
|
|
|
||
|
|
async def cancel(self):
|
||
|
|
self._cancelled = True
|
||
|
|
if self._message_id:
|
||
|
|
try:
|
||
|
|
await self._outbound.edit_message(
|
||
|
|
self._message_id,
|
||
|
|
self._room_id,
|
||
|
|
self._last_text or "\u23f3 _\u56de\u590d\u4e2d\u65ad..._",
|
||
|
|
)
|
||
|
|
except Exception:
|
||
|
|
pass
|
||
|
|
|
||
|
|
@property
|
||
|
|
def is_cancelled(self) -> bool:
|
||
|
|
return self._cancelled
|
||
|
|
|
||
|
|
@property
|
||
|
|
def remaining_edits(self) -> int:
|
||
|
|
return max(0, MAX_EDITS - 1 - self._edit_count)
|