Pārlūkot izejas kodu

Improve stability of WS connection with WXGF decoder app (#101)

* In case TYPE_LINK is missing a title, use url as title to avoid aborting

* Retry WS connection on broken pipe

* Update render.py

* Update wxgf.py

---------

Co-authored-by: Yuxin Wu <[email protected]>
Chang Qian (Fred) 8 mēneši atpakaļ
vecāks
revīzija
643bdd8984
2 mainītis faili ar 19 papildinājumiem un 3 dzēšanām
  1. 5 1
      wechat/render.py
  2. 14 2
      wechat/wxgf.py

+ 5 - 1
wechat/render.py

@@ -180,7 +180,11 @@ class HTMLRender(object):
             pq = PyQuery(msg.content_xml_ready)
             url = pq('url').text()
             if url:
-                title = pq('title')[0].text
+                try:
+                    title = pq('title')[0].text
+                except Exception as e:
+                    logger.warning('No title found in LINK message: ' + str(e))
+                    title = url
                 content = '<a target="_blank" href="{0}">{1}</a>'.format(url, title)
                 format_dict['content'] = content
                 return template.format(**format_dict)

+ 14 - 2
wechat/wxgf.py

@@ -17,6 +17,7 @@ class WxgfAndroidDecoder:
             if "://" not in server:
                 server = "ws://" + server
             logger.info(f"Connecting to {server} ...")
+            self.server = server
             self.ws = create_connection(server)
 
     def __del__(self):
@@ -28,8 +29,19 @@ class WxgfAndroidDecoder:
 
     def decode(self, data: bytes) -> bytes | None:
         assert data[:4] == WXGF_HEADER, data[:20]
-        self.ws.send(data, opcode=0x2)
-        res = self.ws.recv()
+        try:
+            self.ws.send(data, opcode=0x2)
+        except BrokenPipeError as e:
+            logger.warning(f'Failed to send data to wxgf service. {e}. Reconnecting ..')
+            self.ws = create_connection(self.server)
+            self.ws.send(data, opcode=0x2)
+        try:
+            res = self.ws.recv()
+        except Exception as e:
+            logger.warning(f'Failed to recv data to wxgf service. {e}. Reconnecting ..')
+            self.ws = create_connection(self.server)
+            self.ws.send(data, opcode=0x2)
+            res = self.ws.recv()
         if res == FAILURE_MESSAGE:
             return None
         return res