示例#1
0
    def sendString(self, string_msg):
        if not self.isConnected() and self.reopen:
            self.connect()

        self.trade_in_socket.send_unicode("REQ," + self.connection_id + ',' +
                                          string_msg)

        response_message = self.trade_in_socket.recv()
        raw_resp_message_header = response_message[:3]
        raw_resp_message = response_message[4:].strip()

        rep_msg = None
        if raw_resp_message:
            try:
                rep_msg = JsonMessage(raw_resp_message)
            except Exception:
                pass

        if raw_resp_message_header == 'CLS' and rep_msg and not rep_msg.isErrorMessage(
        ):
            self.close()
            if self.reopen:
                self.connect()
            return rep_msg

        if raw_resp_message_header != 'REP':
            self.close()
            if self.reopen:
                self.connect()

            if rep_msg and rep_msg.isErrorMessage():
                raise TradeClientException(rep_msg.get('Description'),
                                           rep_msg.get('Detail'))
            raise TradeClientException('Invalid request: ' + raw_resp_message)

        if rep_msg and rep_msg.isUserResponse():
            if rep_msg.get("UserStatus") == 1:
                self.user_id = rep_msg.get("UserID")
                self.is_logged = True

                if self.trade_pub_socket:
                    self.trade_pub_socket.setsockopt(
                        zmq.SUBSCRIBE, '^' + str(self.user_id) + '$')

        return rep_msg
示例#2
0
  def sendString(self, string_msg):
    if not self.isConnected() and self.reopen:
      self.connect()

    self.trade_in_socket.send_unicode( "REQ," +  self.connection_id + ',' + string_msg)

    response_message        = self.trade_in_socket.recv()
    raw_resp_message_header = response_message[:3]
    raw_resp_message        = response_message[4:].strip()

    rep_msg = None
    if raw_resp_message:
      try:
        rep_msg = JsonMessage(raw_resp_message)
      except Exception:
        pass

    if raw_resp_message_header == 'CLS' and rep_msg and not rep_msg.isErrorMessage():
      self.close()
      if self.reopen:
        self.connect()
      return rep_msg

    if raw_resp_message_header != 'REP':
      self.close()
      if self.reopen:
        self.connect()

      if rep_msg and rep_msg.isErrorMessage():
        raise TradeClientException(rep_msg.get('Description'), rep_msg.get('Detail'))
      raise TradeClientException('Invalid request: ' + raw_resp_message )


    if rep_msg and rep_msg.isUserResponse():
      if rep_msg.get("UserStatus") == 1:
        self.user_id = rep_msg.get("UserID")
        self.is_logged = True

        if self.trade_pub_socket:
          self.trade_pub_socket.setsockopt(zmq.SUBSCRIBE, str(self.user_id))

    return rep_msg
    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
            reactor.stop()
            return

        if self.factory.verbose:
            print 'rx:', payload

        msg = JsonMessage(payload.decode('utf8'))
        if msg.isHeartbeat():
            return

        if msg.isUserResponse():  # login response
            if msg.get('UserStatus') != 1:
                reactor.stop()
                raise RuntimeError('Wrong login')

            profile = msg.get('Profile')
            if profile['Type'] != 'BROKER':
                reactor.stop()
                raise RuntimeError('It is not a brokerage account')

            self.factory.broker_username = msg.get('Username')
            self.factory.broker_id = msg.get('UserID')
            self.factory.profile = profile
            return

        if msg.isWithdrawRefresh():
            if msg.get('BrokerID') != self.factory.broker_id:
                return  # received a message from a different broker

            msg.set('BrokerUsername', self.factory.broker_username)

            if msg.get('Status') == '1'\
              and (self.factory.methods[0] == '*' or msg.get('Method') in self.factory.methods) \
              and (self.factory.currencies[0] == '*' or  msg.get('Currency') in self.factory.currencies):
                withdraw_record = Withdraw.process_withdrawal_refresh_message(
                    self.factory.db_session, msg)
                if withdraw_record:
                    process_withdraw_message = MessageBuilder.processWithdraw(
                        action='PROGRESS',
                        withdrawId=msg.get('WithdrawID'),
                        data=msg.get('Data'),
                        percent_fee=msg.get('PercentFee'),
                        fixed_fee=msg.get('FixedFee'))

                    withdraw_record.process_req_id = process_withdraw_message[
                        'ProcessWithdrawReqID']

                    # sent a B6
                    self.sendJSON(process_withdraw_message)
                    self.factory.db_session.commit()

        if msg.isProcessWithdrawResponse():
            if not msg.get('Result'):
                return

            process_req_id = msg.get('ProcessWithdrawReqID')
            withdraw_record = Withdraw.get_withdraw_by_process_req_id(
                self.factory.db_session, process_req_id)

            should_transfer = False
            if withdraw_record:
                if withdraw_record.status == '1' and msg.get('Status') == '2'\
                  and (self.factory.methods[0] == '*' or withdraw_record.method  in self.factory.methods)\
                  and (self.factory.currencies[0] == '*' or  withdraw_record.currency in self.factory.currencies):

                    if withdraw_record.account_id not in self.factory.blocked_accounts:
                        should_transfer = True

                withdraw_record.status = msg.get('Status')
                withdraw_record.reason = msg.get('Reason')
                withdraw_record.reason_id = msg.get('ReasonID')

                self.factory.db_session.add(withdraw_record)
                self.factory.db_session.commit()

                if should_transfer:
                    self.factory.reactor.callLater(
                        0, partial(self.initiateTransfer, process_req_id))
示例#4
0
  def onMessage(self, payload, isBinary):
    if isBinary:
      print("Binary message received: {0} bytes".format(len(payload)))
      reactor.stop()
      return

    if self.factory.verbose:
      print 'rx:',payload

    msg = JsonMessage(payload.decode('utf8'))
    if msg.isHeartbeat():
      return

    if msg.isUserResponse(): # login response
      if msg.get('UserStatus') != 1:
        reactor.stop()
        raise RuntimeError('Wrong login')

      profile = msg.get('Profile')
      if profile['Type'] != 'BROKER':
        reactor.stop()
        raise RuntimeError('It is not a brokerage account')

      self.factory.broker_username = msg.get('Username')
      self.factory.broker_id = msg.get('UserID')
      self.factory.profile = profile
      return


    if msg.isVerifyCustomerRefresh():
      broker_id         = msg.get('BrokerID')
      if broker_id != self.factory.broker_id:
        return # received a message from a different broker

      verified          = msg.get('Verified')
      if verified != 1:
        return

      user_id           = msg.get('ClientID')
      username          = msg.get('Username')
      verification_data = msg.get('VerificationData')
      if verification_data:
        verification_data = json.loads(verification_data)

      edentiti_status = get_verification_data(verification_data, 'edentiti_status')
      if edentiti_status == "IN_PROGRESS":
        return

      street_address = get_verification_data(verification_data, 'address')['street1']
      flat_number = ''
      if '/' in street_address:
        flat_number = street_address[:street_address.find('/') ]
        street_address = street_address[street_address.find('/')+1: ]

      street_address_parts = street_address.split(" ")
      street_type = ""
      if len(street_address_parts) > 1:
        street_type = street_address_parts[-1]
        street_address = ' '.join(street_address_parts[:-1])

      street_address_parts = street_address.split(" ")
      street_number = ""
      if street_address_parts and street_address_parts[0].isdigit():
        street_number = street_address_parts[0]
        street_address = ' '.join(street_address_parts[1:])

      street_name = street_address

      try:
        res = self.factory.wsdl_client.registerUser(
            customerId=self.factory.edentiti_customer_id,
            password=self.factory.edentiti_password,
            ruleId='default',
            name={
              'givenName': get_verification_data(verification_data, 'name')['first'],
              'middleNames': get_verification_data(verification_data, 'name')['middle'],
              'surname': get_verification_data(verification_data, 'name')['last']
            },
            currentResidentialAddress={
              'country':get_verification_data(verification_data, 'address')['country_code'],
              'flatNumber': flat_number,
              'postcode': get_verification_data(verification_data, 'address')['postal_code'],
              'propertyName':'',
              'state':get_verification_data(verification_data, 'address')['state'],
              'streetName':street_name,
              'streetNumber': street_number ,
              'streetType': street_type.upper(),
              'suburb':get_verification_data(verification_data, 'address')['city']
            },
            homePhone=get_verification_data(verification_data, 'phone_number'),
            dob=datetime.datetime.strptime( get_verification_data(verification_data, 'date_of_birth') ,"%Y-%m-%d"))

        dt = datetime.datetime.now()
        createdAt = int(mktime(dt.timetuple()) + dt.microsecond/1000000.0)
        edentiti_verification_data = {
          "service_provider":"edentiti",
          "edentiti_status": res['return']['outcome'],
          "id": res['return']['transactionId'],
          "user_id": res['return']['userId'],
          "status": res['return']['outcome'],
          "created_at": createdAt,
          "updated_at": createdAt
        }
        if res['return']['outcome'] == "IN_PROGRESS":
          edentiti_verification_data["status"] = "progress"
          verified = 2

        if edentiti_verification_data["status"] == "valid":
          verified = 3

        self.sendJSON( MessageBuilder.verifyCustomer(user_id, verified, json.dumps(edentiti_verification_data)))

      except Exception:
        pass
示例#5
0
    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
            reactor.stop()
            return

        if self.factory.verbose:
            print 'rx:', payload

        msg = JsonMessage(payload.decode('utf8'))
        if msg.isHeartbeat():
            return

        if msg.isUserResponse():  # login response
            if msg.get('UserStatus') != 1:
                reactor.stop()
                raise RuntimeError('Wrong login')

            profile = msg.get('Profile')
            if profile['Type'] != 'BROKER':
                reactor.stop()
                raise RuntimeError('It is not a brokerage account')

            self.factory.broker_username = msg.get('Username')
            self.factory.broker_id = msg.get('UserID')
            self.factory.profile = profile
            return

        if msg.isVerifyCustomerRefresh():
            broker_id = msg.get('BrokerID')
            if broker_id != self.factory.broker_id:
                return  # received a message from a different broker

            verified = msg.get('Verified')
            if verified != 1:
                return

            user_id = msg.get('ClientID')
            username = msg.get('Username')
            verification_data = msg.get('VerificationData')
            if verification_data:
                verification_data = json.loads(verification_data)

            edentiti_status = get_verification_data(verification_data,
                                                    'edentiti_status')
            if edentiti_status == "IN_PROGRESS":
                return

            street_address = get_verification_data(verification_data,
                                                   'address')['street1']
            flat_number = ''
            if '/' in street_address:
                flat_number = street_address[:street_address.find('/')]
                street_address = street_address[street_address.find('/') + 1:]

            street_address_parts = street_address.split(" ")
            street_type = ""
            if len(street_address_parts) > 1:
                street_type = street_address_parts[-1]
                street_address = ' '.join(street_address_parts[:-1])

            street_address_parts = street_address.split(" ")
            street_number = ""
            if street_address_parts and street_address_parts[0].isdigit():
                street_number = street_address_parts[0]
                street_address = ' '.join(street_address_parts[1:])

            street_name = street_address

            try:
                res = self.factory.wsdl_client.registerUser(
                    customerId=self.factory.edentiti_customer_id,
                    password=self.factory.edentiti_password,
                    ruleId='default',
                    name={
                        'givenName':
                        get_verification_data(verification_data,
                                              'name')['first'],
                        'middleNames':
                        get_verification_data(verification_data,
                                              'name')['middle'],
                        'surname':
                        get_verification_data(verification_data,
                                              'name')['last']
                    },
                    currentResidentialAddress={
                        'country':
                        get_verification_data(verification_data,
                                              'address')['country_code'],
                        'flatNumber':
                        flat_number,
                        'postcode':
                        get_verification_data(verification_data,
                                              'address')['postal_code'],
                        'propertyName':
                        '',
                        'state':
                        get_verification_data(verification_data,
                                              'address')['state'],
                        'streetName':
                        street_name,
                        'streetNumber':
                        street_number,
                        'streetType':
                        street_type.upper(),
                        'suburb':
                        get_verification_data(verification_data,
                                              'address')['city']
                    },
                    homePhone=get_verification_data(verification_data,
                                                    'phone_number'),
                    dob=datetime.datetime.strptime(
                        get_verification_data(verification_data,
                                              'date_of_birth'), "%Y-%m-%d"))

                dt = datetime.datetime.now()
                createdAt = int(
                    mktime(dt.timetuple()) + dt.microsecond / 1000000.0)
                edentiti_verification_data = {
                    "service_provider": "edentiti",
                    "edentiti_status": res['return']['outcome'],
                    "id": res['return']['transactionId'],
                    "user_id": res['return']['userId'],
                    "status": res['return']['outcome'],
                    "created_at": createdAt,
                    "updated_at": createdAt
                }
                if res['return']['outcome'] == "IN_PROGRESS":
                    edentiti_verification_data["status"] = "progress"
                    verified = 2

                if edentiti_verification_data["status"] == "valid":
                    verified = 3

                self.sendJSON(
                    MessageBuilder.verifyCustomer(
                        user_id, verified,
                        json.dumps(edentiti_verification_data)))

            except Exception:
                pass
    def onMessage(self, payload, isBinary):
        if isBinary:
            print ("Binary message received: {0} bytes".format(len(payload)))
            reactor.stop()
            return

        if self.factory.verbose:
            print "rx:", payload

        msg = JsonMessage(payload.decode("utf8"))
        if msg.isHeartbeat():
            return

        if msg.isUserResponse():  # login response
            if msg.get("UserStatus") != 1:
                reactor.stop()
                raise RuntimeError("Wrong login")

            profile = msg.get("Profile")
            if profile["Type"] != "BROKER":
                reactor.stop()
                raise RuntimeError("It is not a brokerage account")

            self.factory.broker_username = msg.get("Username")
            self.factory.broker_id = msg.get("UserID")
            self.factory.profile = profile
            return

        if msg.isWithdrawRefresh():
            if msg.get("BrokerID") != self.factory.broker_id:
                return  # received a message from a different broker

            msg.set("BrokerUsername", self.factory.broker_username)

            if (
                msg.get("Status") == "1"
                and (self.factory.methods[0] == "*" or msg.get("Method") in self.factory.methods)
                and (self.factory.currencies[0] == "*" or msg.get("Currency") in self.factory.currencies)
            ):
                withdraw_record = Withdraw.process_withdrawal_refresh_message(self.factory.db_session, msg)
                if withdraw_record:
                    process_withdraw_message = MessageBuilder.processWithdraw(
                        action="PROGRESS",
                        withdrawId=msg.get("WithdrawID"),
                        data=msg.get("Data"),
                        percent_fee=msg.get("PercentFee"),
                        fixed_fee=msg.get("FixedFee"),
                    )

                    withdraw_record.process_req_id = process_withdraw_message["ProcessWithdrawReqID"]

                    # sent a B6
                    self.sendJSON(process_withdraw_message)
                    self.factory.db_session.commit()

        if msg.isProcessWithdrawResponse():
            if not msg.get("Result"):
                return

            process_req_id = msg.get("ProcessWithdrawReqID")
            withdraw_record = Withdraw.get_withdraw_by_process_req_id(self.factory.db_session, process_req_id)

            should_transfer = False
            if withdraw_record:
                if (
                    withdraw_record.status == "1"
                    and msg.get("Status") == "2"
                    and (self.factory.methods[0] == "*" or withdraw_record.method in self.factory.methods)
                    and (self.factory.currencies[0] == "*" or withdraw_record.currency in self.factory.currencies)
                ):

                    if withdraw_record.account_id not in self.factory.blocked_accounts:
                        should_transfer = True

                withdraw_record.status = msg.get("Status")
                withdraw_record.reason = msg.get("Reason")
                withdraw_record.reason_id = msg.get("ReasonID")

                self.factory.db_session.add(withdraw_record)
                self.factory.db_session.commit()

                if should_transfer:
                    self.factory.reactor.callLater(0, partial(self.initiateTransfer, process_req_id))
  def onMessage(self, payload, isBinary):
    if isBinary:
      print("Binary message received: {0} bytes".format(len(payload)))
      reactor.stop()
      return

    if self.factory.verbose:
      print 'rx:',payload

    msg = JsonMessage(payload.decode('utf8'))
    if msg.isHeartbeat():
      return

    if msg.isUserResponse(): # login response
      if msg.get('UserStatus') != 1:
        reactor.stop()
        raise RuntimeError('Wrong login')

      profile = msg.get('Profile')
      if profile['Type'] != 'BROKER':
        reactor.stop()
        raise RuntimeError('It is not a brokerage account')

      self.factory.broker_username = msg.get('Username')
      self.factory.broker_id = msg.get('UserID')
      self.factory.profile = profile
      return

    if msg.isWithdrawRefresh():
      if msg.get('BrokerID') != self.factory.broker_id:
        return # received a message from a different broker

      msg.set('BrokerUsername', self.factory.broker_username )

      if msg.get('Status') == '1'\
        and (self.factory.methods[0] == '*' or msg.get('Method') in self.factory.methods) \
        and (self.factory.currencies[0] == '*' or  msg.get('Currency') in self.factory.currencies):
        withdraw_record = Withdraw.process_withdrawal_refresh_message( self.factory.db_session , msg)
        if withdraw_record:
          process_withdraw_message = MessageBuilder.processWithdraw(action      = 'PROGRESS',
                                                                    withdrawId  = msg.get('WithdrawID'),
                                                                    data        = msg.get('Data') ,
                                                                    percent_fee = msg.get('PercentFee'),
                                                                    fixed_fee   = msg.get('FixedFee') )

          withdraw_record.process_req_id = process_withdraw_message['ProcessWithdrawReqID']

          # sent a B6
          self.sendJSON( process_withdraw_message )
          self.factory.db_session.commit()

    if msg.isProcessWithdrawResponse():
      if not msg.get('Result'):
        return

      process_req_id = msg.get('ProcessWithdrawReqID')
      withdraw_record = Withdraw.get_withdraw_by_process_req_id(self.factory.db_session, process_req_id)



      should_transfer = False
      if withdraw_record:
        if withdraw_record.status == '1' and msg.get('Status') == '2'\
          and (self.factory.methods[0] == '*' or withdraw_record.method  in self.factory.methods)\
          and (self.factory.currencies[0] == '*' or  withdraw_record.currency in self.factory.currencies):

          if withdraw_record.account_id not in self.factory.blocked_accounts:
            should_transfer = True

        withdraw_record.status = msg.get('Status')
        withdraw_record.reason = msg.get('Reason')
        withdraw_record.reason_id = msg.get('ReasonID')

        self.factory.db_session.add(withdraw_record)
        self.factory.db_session.commit()

        if should_transfer:
          self.factory.reactor.callLater(0, partial(self.initiateTransfer, process_req_id) )