Exemplo n.º 1
0
    def __genNetworkPostRequest(self, path, body, auth_token=""):

        # transfer obj => json string
        body_in_json = json.dumps(body)

        # generate robot's auth token
        if auth_token == "":
            token = self.genPOSTJwtToken(path, body_in_json, str(uuid.uuid4()))
            auth_token = token.decode('utf8')

        headers = {
            'Content-Type'  : 'application/json',
            'Authorization' : 'Bearer ' + auth_token,
        }
        # generate url
        url = self.__genUrl(path)

        r = requests.post(url, json=body, headers=headers)
        # {'error': {'status': 202, 'code': 20118, 'description': 'Invalid PIN format.'}}

        # r = requests.post(url, data=body, headers=headers)
        # {'error': {'status': 202, 'code': 401, 'description': 'Unauthorized, maybe invalid token.'}}
        result_obj = r.json()
        myPrint(result_obj)
        return result_obj
Exemplo n.º 2
0
def get_auth_token():
    get_auth_token_url = 'https://api.mixin.one/oauth/token'

    # 从 url 中取到 code
    auth_code = request.args.get('code')

    post_data = {
        "client_id": robot_config.client_id,
        "code": auth_code,
        "client_secret": robot_config.client_secret,
    }

    r = requests.post(get_auth_token_url, json=post_data)
    r_json = r.json()
    myPrint(r_json)
    logUserAuth.info( r_json )

    auth_token = ""
    if r_json is None:
        return auth_token

    if "data" in r_json and "access_token" in r_json[ 'data' ]:
            auth_token = r_json['data']['access_token']

    return auth_token
Exemplo n.º 3
0
def user():

    # 2. 取得 Authorization Token
    auth_token = get_auth_token()
    if auth_token in ( "", None ):
        strTmp = "<b>Failed</b> to do authorization, or you have already authorized. Please try again later. Thanks!"
        myPrint( strTmp )
        logUserAuth.critical( strTmp )
        return strTmp

    data = mixin_api.getMyProfile(auth_token)

    data_friends = mixin_api.getMyFriends(auth_token)

    data_asset = mixin_api.getMyAssets(auth_token)

    # 返回数据中没有 conversationId.
    if 'user_id' in data:
        print( data[ 'user_id'], data[ 'full_name' ], data[ 'identity_number'] )
        logUserAuth.info( data )
    else:
        str = "read user info failed: {}".format( data )
        myPrint( str )
        logError.critical( str )
        return "<b>Failed</b> to authorization. Try again. Later. Thanks."

    welcome = '<html>Welcome back, <b>{}</b><br><p></p></html>'.format( data['full_name'] )
    return welcome
Exemplo n.º 4
0
 def __on_close(ws):
     str = "###### on close ######. \n traceback deatails: {}".format(
         traceback.format_exc())
     myPrint(str)
     logError.error(str)
     # for long-lived connection. on_close(). just a print.
     # refers to: https://github.com/websocket-client/websocket-client#long-lived-connection
     return
Exemplo n.º 5
0
    def createAddress(self, asset_id, public_key = "", label = "", account_name = "", account_tag = ""):

        body = {
            "asset_id": asset_id,
            "pin": self.genEncrypedPin().decode(),
            "public_key": public_key,
            "label": label,
            "account_name": account_name,
            "account_tag": account_tag,
        }
        myPrint(body)
        return self.__genNetworkPostRequest('/addresses', body)
Exemplo n.º 6
0
        def run(*args):
            myPrint("###### ws open ######")
            Message = {
                "id": str(uuid.uuid1()),
                "action": "LIST_PENDING_MESSAGES"
            }
            Message_instring = json.dumps(Message)

            fgz = BytesIO()
            gzip_obj = gzip.GzipFile(mode='wb', fileobj=fgz)
            gzip_obj.write(Message_instring.encode())
            gzip_obj.close()
            # https: // github.com / websocket - client / websocket - client  # long-lived-connection
            ws.send(fgz.getvalue(), opcode=websocket.ABNF.OPCODE_BINARY)
            while True:
                time.sleep(1)
Exemplo n.º 7
0
    def __genPostRequest(self, path, body, auth_token=""):

        # generate url
        url = self.__genUrl(path)

        # transfer obj => json string
        body_in_json = json.dumps(body)

        if auth_token == "":
            r = requests.post(url, json=body_in_json)
        else:
            r = requests.post(url, json=body_in_json, headers={ "Authorization": "Bearer " + auth_token, "Content-Type": "application/json" })

        result_obj = r.json()
        myPrint(result_obj)
        return result_obj
Exemplo n.º 8
0
    def __genGetRequest(self, path, auth_token=""):

        url = self.__genUrl(path)

        if auth_token == "":
            r = requests.get(url)
        else:
            headerJson = { "Authorization": "Bearer " + auth_token, "Content-Type": "application/json" }
            r = requests.get(url, headers = headerJson  )

        result_obj = r.json()
        myPrint( result_obj )
        if "data" in result_obj:
            return result_obj['data']
        else:
            return ""
Exemplo n.º 9
0
    def writeMessage(websocketInstance, action, params):

        message = {"id": str(uuid.uuid1()), "action": action, "params": params}
        message_instring = json.dumps(message)

        fgz = BytesIO()
        gzip_obj = gzip.GzipFile(mode='wb', fileobj=fgz)
        gzip_obj.write(message_instring.encode())
        gzip_obj.close()
        try:
            s = "value: {}, size: {}".format(fgz.getvalue(),
                                             len(fgz.getvalue()))
            myPrint(s)
            websocketInstance.send(fgz.getvalue(),
                                   opcode=websocket.ABNF.OPCODE_BINARY)
        except Exception as e:
            myPrintErrorAndLog2File(e)
Exemplo n.º 10
0
 def run(self):
     myPrint(" run ")
     while True:
         try:
             # reconnect server logic
             self.ws = self.initAWebSocket()
             # ping/pong logic.
             self.ws.run_forever(ping_interval=30, ping_timeout=10)
             str3 = "running, or reconnected server."
             myPrint(str3)
             logMixin.info(str3)
         except Exception as e:
             # refers to: https://github.com/websocket-client/websocket-client/issues/95
             excepStr = "Try reconnect to the server. exception: {}".format(
                 e)
             myPrint(excepStr)
             logError.error(excepStr)
             pass
Exemplo n.º 11
0
 def __on_error(ws, error):
     strErr = " ###### on error ######: {}. \ntraceback details: {}".format(
         error, traceback.format_exc())
     myPrint(strErr)
     logError.error(strErr)
     return
Exemplo n.º 12
0
 def on_exit(ws):
     myPrint("###### on exit ###### ws!")
     ws.close()
     thread.exit()
     return
Exemplo n.º 13
0
 def __on_data(ws, readableString, dataType, continueFlag):
     myPrint("###### on data ######")
     return
Exemplo n.º 14
0
def on_message(ws, message):

    inbuffer = BytesIO(message)

    f = gzip.GzipFile(mode="rb", fileobj=inbuffer)
    rdata_injson = f.read()
    rdata_obj = json.loads(rdata_injson)
    action = rdata_obj["action"]

    myPrint( action )
    if action not in ["ACKNOWLEDGE_MESSAGE_RECEIPT", "CREATE_MESSAGE", "LIST_PENDING_MESSAGES"]:
        myPrint("unknow action", action  )
        return

    if action == "ACKNOWLEDGE_MESSAGE_RECEIPT":
        myPrint( "ACKNOWLEDGE_MESSAGE_RECEIPT, return"  )
        return

    if action == "CREATE_MESSAGE":
        data = rdata_obj["data"]
        msgid = data["message_id"]
        typeindata = data["type"]
        categoryindata = data["category"]
        userId = data["user_id"]
        conversationId = data["conversation_id"]
        dataindata = data["data"]
        created_at = data["created_at"]
        updated_at = data["updated_at"]

        realData = base64.b64decode(dataindata)
        MIXIN_WS_API.replayMessage(ws, msgid)

        message_instring = json.dumps( data )
        myPrint( message_instring )

        if 'error' in rdata_obj:
            err = "".format( "error occcur: {}", rdata_obj[ 'error'] )
            myPrint( err )
            return

        if categoryindata not in ["SYSTEM_ACCOUNT_SNAPSHOT", "PLAIN_TEXT", "SYSTEM_CONVERSATION", "PLAIN_STICKER", "PLAIN_IMAGE", "PLAIN_CONTACT"]:
            info = "".format( "unknow category: {}", categoryindata )
            myPrint( info  )
            return

        if categoryindata == "PLAIN_TEXT" and typeindata == "message":
            realData = realData.lower().decode('utf-8')

            if realData in [ "hi", "?", "help" ]:
                introductionContent = 'welcome.\n[hihi] reply n times text\n[c] send a contact card\n[b] send a link button\n[p] you need to pay\n[t] transfer to you'
                MIXIN_WS_API.sendUserText(ws, conversationId, userId, introductionContent)
                return

            if 'hihi' == realData:
                introductionContent = '你好呀 '
                for i in range(3):
                    MIXIN_WS_API.sendUserText(ws, conversationId, userId, introductionContent + str(i))
                    time.sleep(1)
                return

            if 'c' == realData:
                myPrint('send a contact card')
                MIXIN_WS_API.sendUserContactCard(ws, conversationId, userId, get_admin_mixin_id() )
                return

            if 'b' == realData:
                myPrint('send a link button')
                MIXIN_WS_API.sendUserAppButton(ws, conversationId, userId, mixin_api.getRobotHrefLink( 'JinLab' ), mixin_api.getRobotDesc( 'JinLab' ) )
                return

            if 'p' == realData:
                myPrint('you need to pay')
                money = random.randint( 5, 23 ) / 100000
                toPay = "打赏作者: {}".format( money )
                MIXIN_WS_API.sendUserPayAppButton(ws, conversationId, userId, "打赏机器人", mixin_asset_lists.CNB_ASSET_ID,  money, userId )
                return

            if 't' == realData:
                # 机器人 转给 userId
                myPrint('transfer to you')
                myPrint( "userId: %s, jinId: %s" % ( userId, get_admin_mixin_id() ) )
                money = random.randint( 1, 5 ) / 100000
                mxUuid =  "mixin://users/{}".format( robot_config.client_id )
                mixin_api.transferTo( userId, mixin_asset_lists.CNB_ASSET_ID, money, mxUuid )
                txt = "{} 打赏你 {} ".format( mxUuid, money )
                MIXIN_WS_API.sendUserText( ws, conversationId, userId, txt )
                return

        elif categoryindata == "PLAIN_TEXT":
            myPrint("PLAIN_TEXT but unkonw:")
Exemplo n.º 15
0
                return

            if 'p' == realData:
                myPrint('you need to pay')
                money = random.randint( 5, 23 ) / 100000
                toPay = "打赏作者: {}".format( money )
                MIXIN_WS_API.sendUserPayAppButton(ws, conversationId, userId, "打赏机器人", mixin_asset_lists.CNB_ASSET_ID,  money, userId )
                return

            if 't' == realData:
                # 机器人 转给 userId
                myPrint('transfer to you')
                myPrint( "userId: %s, jinId: %s" % ( userId, get_admin_mixin_id() ) )
                money = random.randint( 1, 5 ) / 100000
                mxUuid =  "mixin://users/{}".format( robot_config.client_id )
                mixin_api.transferTo( userId, mixin_asset_lists.CNB_ASSET_ID, money, mxUuid )
                txt = "{} 打赏你 {} ".format( mxUuid, money )
                MIXIN_WS_API.sendUserText( ws, conversationId, userId, txt )
                return

        elif categoryindata == "PLAIN_TEXT":
            myPrint("PLAIN_TEXT but unkonw:")


if __name__ == "__main__":
    myPrint("main")
    mixin_api = MIXIN_API(robot_config)
    mixin_ws = MIXIN_WS_API( on_message=on_message )
    mixin_ws.run()

Exemplo n.º 16
0
def run_server():
    myPrint("main")
    app.run( host="0.0.0.0", port=5000, debug = True )