Skip to content

Commit

Permalink
优化receiver模块
Browse files Browse the repository at this point in the history
  • Loading branch information
Mooling0602 committed Nov 6, 2024
1 parent 7c38bf0 commit 2a7e50f
Showing 1 changed file with 13 additions and 17 deletions.
30 changes: 13 additions & 17 deletions matrix_sync/sync/receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
refresh = True
next_batch = None
client = None
transfer = False

class RoomMessageEvent(PluginEvent):
def __init__(self, message: str, sender: str, room: Optional[str] = None):
Expand All @@ -22,38 +23,30 @@ def __init__(self, message: str, sender: str, room: Optional[str] = None):
self.room = room

async def message_callback(room: MatrixRoom, event: RoomMessageText) -> None:
global transfer
user_id = matrix_sync.config.user_id
room_name = matrix_sync.config.room_name
roomMsg = f"[MSync|{room.display_name}] {room.user_name(event.sender)}: {event.body}"
transfer = True
# Avoid echo messages.
if event.sender == user_id:
transfer = False
if not event.sender == user_id:
transfer = True
# Apply settings config
if not matrix_sync.config.settings["allow_all_rooms_msg"]:
roomMsg = f"[MSync] {room.user_name(event.sender)}: {event.body}"
if not room.display_name == room_name:
transfer = False
else:
if room.display_name == room_name:
transfer = True
psi.dispatch_event(RoomMessageEvent(event.body, room.user_name(event.sender)), (event.body, room.user_name(event.sender)))
else:
psi.dispatch_event(RoomMessageEvent(event.body, room.user_name(event.sender), room.display_name), (event.body, room.user_name(event.sender), room.display_name))
if transfer:
psi.broadcast(f"{roomMsg}")

def sync_cache(data):
TOKEN_FILE = matrix_sync.config.TOKEN_FILE
with open(TOKEN_FILE, "r") as f:
existing_data = json.load(f)
existing_data["next_batch"] = data
with open(TOKEN_FILE, "w") as f:
json.dump(existing_data, f)


def on_sync_response(response: SyncResponse):
global refresh
global refresh, next_batch
if refresh:
next_batch = response.next_batch
sync_cache(next_batch)
refresh = False
else:
pass
Expand Down Expand Up @@ -86,8 +79,11 @@ async def getMsg() -> None:
if sync_old_msg is True:
await client.sync_forever(timeout=5)
else:
next_batch = await get_next_batch()
await client.sync_forever(timeout=5, since=next_batch)
if next_batch is not None:
next_batch = await get_next_batch()
await client.sync_forever(timeout=5, since=next_batch)
else:
psi.logger.error("Sync failed: can't get 'next_batch' when sync.")
else:
psi.logger.error("Sync failed: homeserver is down or your network disconnected with it.")
psi.logger.info("Use !!msync start after homeserver is running or your network restored.")
Expand Down

0 comments on commit 2a7e50f

Please sign in to comment.