XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
"""Private native instrumentation worker; JSON IPC with the C# desktop host."""
import argparse
import hashlib
import json
import pathlib
import sys
import threading

parser = argparse.ArgumentParser()
parser.add_argument('configuration')
args = parser.parse_args()
config = json.loads(pathlib.Path(args.configuration).read_text(encoding='utf-8'))
if sys.stdout.encoding.lower().replace('-', '') != 'utf8':
    sys.stdout.reconfigure(encoding='utf-8')
sys.stdin.reconfigure(encoding='utf-8')
write_lock = threading.Lock()
def emit(value):
    with write_lock:
        print(json.dumps(value, ensure_ascii=False), flush=True)

session = script = None
closing = False
try:
    with open(config['executablePath'], 'rb') as stream:
        digest = hashlib.file_digest(stream, 'sha256').hexdigest().upper()
    if digest != 'F46DBFB0059D4527B76B8DD3DFCD1DD45604C5BA257AF80C064E4896E02CF50E':
        raise RuntimeError('企业微信二进制已变化,请停止使用本适配器。')
    if config.get('developmentDependencyPath'):
        sys.path.insert(0, config['developmentDependencyPath'])
    import frida
    source = pathlib.Path(__file__).with_name('agent.js').read_text(encoding='utf-8')
    source += '\n' + pathlib.Path(__file__).with_name('quote.js').read_text(encoding='utf-8')
    source = source.replace('__PROFILE__', json.dumps(config))
    session = frida.attach(config['pid'])
    def detached(reason, crash):
        if not closing:
            emit({'event': 'fatal', 'detail': '企业微信连接已断开:' + str(reason)})
    session.on('detached', detached)
    script = session.create_script(source, name='WeComNativeReply')
    def message_received(message, data):
        if message['type'] == 'send':
            emit(message['payload'])
        else:
            emit({'event': 'fatal', 'detail': message.get('description', str(message))})
    script.on('message', message_received)
    script.load()
    emit({'event': 'ready', **script.exports_sync.initialize()})
    for line in sys.stdin:
        request = json.loads(line)
        request_id = request['id']
        try:
            operation = request['operation']
            if operation == 'watch':
                result = script.exports_sync.watch(request['since'], request.get('baselineIds', []))
            elif operation == 'unwatch':
                result = script.exports_sync.unwatch()
            elif operation == 'send':
                reference = {'messageId': request['triggerMessageId'], 'localId': request.get('triggerLocalId'),
                             'senderId': request.get('triggerSenderId'), 'quoteOriginal': request.get('quoteOriginal', False)}
                result = script.exports_sync.sendtext(request['conversationId'], request['content'], reference)
            elif operation == 'sendSelfTest':
                result = script.exports_sync.sendselftest()
            elif operation == 'stop':
                result = script.exports_sync.stop()
                emit({'id': request_id, 'result': result})
                break
            else:
                raise ValueError('Unknown native operation')
            emit({'id': request_id, 'result': result})
        except Exception as error:
            # No automatic retries, especially after a possibly accepted send.
            emit({'id': request_id, 'error': str(error)})
except Exception as error:
    emit({'event': 'fatal', 'detail': str(error)})
finally:
    closing = True
    if script is not None:
        try:
            script.exports_sync.stop()
            script.unload()
        except Exception:
            pass
    if session is not None:
        try:
            session.detach()
        except Exception:
            pass