Skip to content

Commit

Permalink
Try to Fix: view preview and replay API are made for operate on singl…
Browse files Browse the repository at this point in the history
…e msg
  • Loading branch information
quentin on chickenita committed Oct 18, 2023
1 parent 0fd6e5a commit 0bff860
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 84 deletions.
36 changes: 24 additions & 12 deletions pypeman/plugins/remoteadmin/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,21 +129,24 @@ async def list_msgs(request, ws=None):

async def replay_msg(request, ws=None):
"""
Replay messages from message store.
Replay message from message store.
:params channel: The channel name.
:params msg_ids: The message ids list to replay.
:params msg_id: The message id to replay.
"""
channelname = request.match_info['channelname']
message_id = request.match_info['message_id']

chan = get_channel(channelname)
result = []
try:
msg_res = await chan.replay(message_id)
result.append(msg_res.to_dict())
result = msg_res.to_dict()
except IndexError:
message = f"Cannot replay msg, id {message_id} probably doesn't exists"
logger.error(message)
result = {'error': message}
except Exception as exc:
result.append({'error': str(exc)})
logger.exception(f"Cannot replay msg {message_id}")
result = {'error': str(exc)}

if ws is not None:
await ws.send_jsonrpcresp(result)
Expand All @@ -163,12 +166,17 @@ async def view_msg(request, ws=None):
message_id = request.match_info['message_id']

chan = get_channel(channelname)
result = []

try:
msg_res = await chan.message_store.get_msg_content(message_id)
result.append(msg_res.to_dict())
result = msg_res.to_dict()
except IndexError:
message = f"Cannot view msg, id {message_id} probably doesn't exists"
logger.error(message)
result = {'error': message}
except Exception as exc:
result.append({'error': str(exc)})
logger.exception(f"Cannot view msg {message_id}")
result = {'error': str(exc)}

if ws is not None:
await ws.send_jsonrpcresp(result)
Expand All @@ -187,12 +195,16 @@ async def preview_msg(request, ws=None):
message_id = request.match_info['message_id']

chan = get_channel(channelname)
result = []
try:
msg_res = await chan.message_store.get_preview_str(message_id)
result.append(msg_res.to_dict())
result = msg_res.to_dict()
except IndexError:
message = f"Cannot preview msg, id {message_id} probably doesn't exists"
logger.error(message)
result = {'error': message}
except Exception as exc:
result.append({'error': str(exc)})
logger.exception(f"Cannot preview msg {message_id}")
result = {'error': str(exc)}

if ws is not None:
await ws.send_jsonrpcresp(result)
Expand Down
4 changes: 2 additions & 2 deletions pypeman/plugins/tests/test_remoteadmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,15 @@ async def test_search_messages_with_rtext_flt(self, webremoteclient):
assert json_resp['messages'][0]['id'] == self.msg3.uuid

async def test_replay_message(self, webremoteclient):
assert await self.chan.message_store.total() == 4
resp = await webremoteclient.get(f"/channels/{self.chan_name}/messages/{self.msg3.uuid}/replay")
assert resp.status == 200

json_resp = json.loads(await resp.text())
assert len(json_resp) == 1
assert await self.chan.message_store.total() == 5

# Clean
await self.chan.message_store.delete(json_resp[0]["uuid"])
await self.chan.message_store.delete(json_resp["uuid"])

async def test_push_message(self, webremoteclient):
pass # actually not implemented
Expand Down
109 changes: 49 additions & 60 deletions pypeman/remoteadmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,59 +167,52 @@ async def list_msgs(self, channel, start=0, count=10, order_by='timestamp', star
return {'messages': messages, 'total': await chan.message_store.total()}

@method
async def replay_msg(self, channel, msg_ids):
async def replay_msg(self, channel, msg_id):
"""
Replay messages from message store.
:params channel: The channel name.
:params msg_ids: The message ids list to replay.
"""
chan = self.get_channel(channel)
result = []
for msg_id in msg_ids:
try:
msg_res = await chan.replay(msg_id)
result.append(msg_res.to_dict())
except Exception as exc:
result.append({'error': str(exc)})

try:
msg_res = await chan.replay(msg_id)
result = msg_res.to_dict()
except Exception as exc:
result = {'error': str(exc)}
return result

@method
async def view_msg(self, channel, msg_ids):
async def view_msg(self, channel, msg_id):
"""
Permit to get the content of a message
:params channel: The channel name.
:params msg_ids: The message ids list to replay.
"""
chan = self.get_channel(channel)
result = []
for msg_id in msg_ids:
try:
msg_res = await chan.message_store.get_msg_content(msg_id)
result.append(msg_res.to_dict())
except Exception as exc:
result.append({'error': str(exc)})
try:
msg_res = await chan.message_store.get_msg_content(msg_id)
result = msg_res.to_dict()
except Exception as exc:
result = {'error': str(exc)}

return result

@method
async def preview_msg(self, channel, msg_ids):
async def preview_msg(self, channel, msg_id):
"""
Permits to get the 1000 chars of a message payload
:params channel: The channel name.
:params msg_ids: The message ids list to replay.
"""
chan = self.get_channel(channel)
result = []
for msg_id in msg_ids:
try:
msg_res = await chan.message_store.get_preview_str(msg_id)
result.append(msg_res.to_dict())
except Exception as exc:
result.append({'error': str(exc)})
try:
msg_res = await chan.message_store.get_preview_str(msg_id)
result = msg_res.to_dict()
except Exception as exc:
result = {'error': str(exc)}
return result

@method
Expand Down Expand Up @@ -255,14 +248,16 @@ def send_command(self, command, args=None):
"""
if args is None:
args = []
if not isinstance(args, list):
args = [args]
return self.loop.run_until_complete(self._send_command(command, args))

async def _send_command(self, command, args):
"""
Asynchronous version of command sending
"""
async with websockets.connect(self.url) as ws:
await ws.send(request_json(command, [*args]))
await ws.send(request_json(command, args))
response = await ws.recv()
parsed_response = parse_json(response)
return parsed_response.result
Expand Down Expand Up @@ -321,30 +316,28 @@ def list_msgs(self, channel, start=0, count=10, order_by='timestamp', start_dt=N

return result

def replay_msg(self, channel, msg_ids):
def replay_msg(self, channel, msg_id):
"""
Replay specified message from id list of specified channel on remote instance.
:params channel: The channel name.
:params msg_ids: Message id list to replay
:params msg_id: Message id to replay
:returns: List of result for each message. Result
can be {'error': <msg_error>} for one id if error
occurs.
"""
request_result = self.send_command('replay_msg', [channel, msg_ids])
request_result = self.send_command('replay_msg', [channel, msg_id])

result = []
for msg in request_result:
if 'error' not in msg:
result.append(message.Message.from_dict(msg))
else:
result.append(msg)
if 'error' not in request_result:
result = message.Message.from_dict(request_result)
else:
result = request_result

return result

def view_msg(self, channel, msg_ids):
def view_msg(self, channel, msg_id):
"""
View content of the specified message from id list of specified
View content of the specified message from id of specified
channel on remote instance.
:params channel: The channel name.
Expand All @@ -353,20 +346,18 @@ def view_msg(self, channel, msg_ids):
can be {'error': <msg_error>} for one id if error
occurs.
"""
request_result = self.send_command('view_msg', [channel, msg_ids])
request_result = self.send_command('view_msg', [channel, msg_id])

result = []
for msg in request_result:
if 'error' not in msg:
result.append(message.Message.from_dict(msg))
else:
result.append(msg)
if 'error' not in request_result:
result = message.Message.from_dict(request_result)
else:
result = request_result

return result

def preview_msg(self, channel, msg_ids):
def preview_msg(self, channel, msg_id):
"""
Preview content of the specified message from id list of specified
Preview content of the specified message from id of specified
channel on remote instance.
:params channel: The channel name.
Expand All @@ -375,14 +366,12 @@ def preview_msg(self, channel, msg_ids):
can be {'error': <msg_error>} for one id if error
occurs.
"""
request_result = self.send_command('preview_msg', [channel, msg_ids])
request_result = self.send_command('preview_msg', [channel, msg_id])

result = []
for msg in request_result:
if 'error' not in msg:
result.append(message.Message.from_dict(msg))
else:
result.append(msg)
if 'error' not in request_result:
result = message.Message.from_dict(request_result)
else:
result = request_result

return result

Expand Down Expand Up @@ -520,9 +509,9 @@ def do_list(self, channel, arg):
@_with_current_channel
def do_replay(self, channel, arg):
"Replay a message list by their ids"
msg_ids = arg.split()
results = self.client.replay_msg(channel, msg_ids)
for msg_id, msg in zip(msg_ids, results):
msg_ids = str(arg).split()
for msg_id in msg_ids:
msg = self.client.replay_msg(channel, msg_id)
print("Result message for replaying message %s:" % msg_id)
if isinstance(msg, message.Message):
print(msg.to_print())
Expand All @@ -533,8 +522,8 @@ def do_replay(self, channel, arg):
def do_view(self, channel, arg):
"View content of a message list by their ids"
msg_ids = arg.split()
results = self.client.view_msg(channel, msg_ids)
for msg_id, msg in zip(msg_ids, results):
for msg_id in msg_ids:
msg = self.client.view_msg(channel, msg_id)
print("View of msg %s:" % msg_id)
if isinstance(msg, message.Message):
print(msg.to_print())
Expand All @@ -545,8 +534,8 @@ def do_view(self, channel, arg):
def do_preview(self, channel, arg):
"Preview content of a message list by their ids"
msg_ids = arg.split()
results = self.client.preview_msg(channel, msg_ids)
for msg_id, msg in zip(msg_ids, results):
for msg_id in msg_ids:
msg = self.client.preview_msg(channel, msg_id)
print("Preview of message %s:" % msg_id)
if isinstance(msg, message.Message):
print(msg.to_print())
Expand Down
18 changes: 8 additions & 10 deletions pypeman/tests/test_remoteadmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,11 @@ def test_remote_admin_list(self):
self.assertEqual(msg_list['messages'][0]['id'], idref_msg3, 'List channel messages broken')

# Replay message
result = client.replay_msg('test_remote050', [idref_msg3])
result = client.replay_msg('test_remote050', idref_msg3)

msg_list = client.list_msgs(channel='test_remote050', start=0, count=5, order_by='-timestamp')
self.assertEqual(msg_list['total'], 5, 'List channel messages broken')
self.assertEqual(msg_list['messages'][0]['id'], result[0].uuid, 'Replay messages broken')
self.assertEqual(msg_list['messages'][0]['id'], result.uuid, 'Replay messages broken')

# Push message
result = client.push_msg(channel='test_remote050', text="Yaaay")
Expand All @@ -159,15 +159,13 @@ def test_remote_admin_list(self):
self.assertEqual(msg_list['messages'][0]['id'], result.uuid, 'Push message broken')

# View message
msg_list = client.view_msg(channel='test_remote050', msg_ids=[idref_msg3])
print(msg_list)
msg_infos = client.view_msg(channel='test_remote050', msg_id=idref_msg3)
print(msg_infos)

self.assertEqual(len(msg_list), 1, 'View messages broken')
self.assertEqual(msg_list[0].payload, msg3.payload, 'View messages broken')
self.assertEqual(msg_infos.payload, msg3.payload, 'View messages broken')

# Preview message
msg_list = client.preview_msg(channel='test_remote050', msg_ids=[idref_msg3])
print(msg_list)
msg_infos = client.preview_msg(channel='test_remote050', msg_id=idref_msg3)
print(msg_infos)

self.assertEqual(len(msg_list), 1, 'Preview messages broken')
self.assertEqual(msg_list[0].payload, msg3.payload[:1000], 'Preview messages broken')
self.assertEqual(msg_infos.payload, msg3.payload[:1000], 'Preview messages broken')

0 comments on commit 0bff860

Please sign in to comment.