Esempio n. 1
0
    def doAttack(self, attackQueue):
        enemy = User.query(User.uid == attackQueue.attackTo).fetch()[0]
        enemy.updateValues()

        enemy.peopleAtAdministration = enemy.peopleAtAdministration - ((random.randint(39, 80)/100) * enemy.peopleAtAdministration)
        #Stolen resources
        res = { }
        res["wood"]  = enemy.wood  - (0.05 * enemy.storageLvl) * enemy.wood
        res["gold"]  = enemy.gold  - (0.05 * enemy.storageLvl) * enemy.gold
        res["food"]  = enemy.food  - (0.05 * enemy.storageLvl) * enemy.food
        res["stone"] = enemy.stone - (0.05 * enemy.storageLvl) * enemy.stone

        #Minus the attacked city
        enemy.wood  -= res["wood"]
        enemy.gold  -= res["gold"]
        enemy.food  -= res["food"]
        enemy.stone -= res["stone"]

        queueO          = Queue(queueType = Queue.TYPE_RETURN)
        queueO.attackTo = attackQueue.attackTo
        queueO.number   = attackQueue.number
        queueO.saveResources(res)
        self.addQueue(queueO, 20)
        queueO.put()
        enemy.put()

        Connection.sendMessageTo(enemy, 'attackResult', {
            "text" : "You were attacked",
            "lost" : res
        })
        Connection.sendMessageTo(self,  'attackResult', {
            "text" : "Your attack was successful",
            "gain" : res
        })
	def __init__(self, opts):
		super().__init__()

		# DEBUGGING 
		self.DEBUG = None

		self._handle = lambda err: self.emit('exception', err)
		on_exception = lambda err: self._log('Exception {}'.format(err))
		self.on('exception', on_exception)

		# self.id = opts['id'] # compatibility with five-bells-connector? 
		self.auth = opts['auth']
		self.store = opts['store']
		self.timers = dict() 

		self.transfer_log = Transfer_Log(opts['store'])

		self.connected = False 
		self.connection_config = opts['auth']
		self.connection = Connection(self.connection_config)
		on_receive = lambda obj: self._receive(obj).catch(self._handle)
		self.connection.on('receive', on_receive)

		self.balance = Balance({
				'store': opts['store'],
				'limit': opts['auth']['limit'],
				'balance': opts['auth']['balance']
			})
		self.balance.on('_balanceChanged', self.on_balance_change)
		self.balance.on('_settlement', self.on_settlement)

		self._log("Initialized Nerd Plugin Virtual: {}".format(self.auth))
Esempio n. 3
0
  def testInvalidConnectionTypeRaisesTypeError(self):
    """Test that a type error is raised when connection type is not passed in as a ConnectionType instance."""
    test_connection_dict = {
        'source_entity_guid': self.source_entity_guid,
        'target_entity_guid': self.target_entity_guid,
        'connection_type': 'FEEDS'
    }

    with self.assertRaises(TypeError):
      Connection.FromDict(test_connection_dict)
Esempio n. 4
0
    def load_entities(self):
        entities = super(ConnectionElasticsearch, self).load_entities()
        connections = []
        for item in entities:
            connection = Connection.create_from_log(
                item['_source']['message_payload'],
                item['_source']['timestamp'])
            if connection is not None:
                connections.append(connection)

        return connections
Esempio n. 5
0
    def save_connection(self):
        # Get all object that need be validated
        name = self.builder.get_object("txt_name")
        host = self.builder.get_object("txt_host")
        port = self.builder.get_object("txt_port")
        user = self.builder.get_object("txt_user")
        switch_key = self.builder.get_object("switch_use_key")
        password = self.builder.get_object("txt_password")
        file_chooser = self.builder.get_object("filechooser_key")

        # Create a new Connection
        if self.connection is None:
            self.connection = Connection()

        self.connection.name = name.get_text()
        self.connection.host = host.get_text()
        self.connection.port = port.get_text()
        self.connection.user = user.get_text()
        self.connection.use_key = switch_key.get_active()
        self.connection.key_path = file_chooser.get_filename()
        self.connection.password = password.get_text()

        # Save the connection
        saved = self.connection.save()

        # Delete the Tunnels
        self.connection.delete_tunnels()

        # Now saved the tunnels
        for tunnel in self.tunnels.get_tunnels():
            # Set the ID connection
            tunnel.id_connection = self.connection.id

            # Save the Tunnel
            tunnel.save()

        # return if is saved or not
        return saved
Esempio n. 6
0
  def testConnectionInitsFromDict(self):
    """Tests that a Connection instance is correctly initialized using the FromDict() class method."""
    test_connection_dict = {
        'source_entity_guid': self.source_entity_guid,
        'target_entity_guid': self.target_entity_guid,
        'connection_type': self.valid_connection_type
    }
    test_connection_instance = Connection.FromDict(test_connection_dict)

    self.assertIsInstance(test_connection_instance, Connection)
    self.assertEqual(self.valid_connection_type,
                     test_connection_instance.connection_type)
    self.assertEqual(self.source_entity_guid,
                     test_connection_instance.source_entity_guid)
    self.assertEqual(self.target_entity_guid,
                     test_connection_instance.target_entity_guid)
Esempio n. 7
0
    def load_connections(self):
        # Reset the List
        self.connections = []

        # Create the SQL
        sql = "select * from connections order by name"

        # Execute the sql
        results = self.dbconnection.select_query(sql)

        # Create a model for every connection
        for row in results:
            # Create new Connection
            connection = Connection()
            connection.id = row['id_connection']
            connection.name = row['name']
            connection.host = row['host']
            connection.user = row['user']
            connection.port = row['port']
            connection.use_key = True if row['use_key'] == 1 else False
            connection.key_path = row['key_path']

            # Add to the list
            self.connections.append(connection)
Esempio n. 8
0
class MessageModel():
    """class to create model message and connect to database """
    
    def __init__(self):
        self.db = Connection()
    
    
    def display_message(self):
        """method to display messages """
        self.db.initialize_connection()
        self.db.cursor.execute("SELECT * FROM message;")
        view=self.db.cursor.fetchall()
        self.db.close_connection()
        return view    
    
    def write_message(self,content, author):
        """ """ 
        self.db.initialize_connection()
        self.db.cursor.execute("INSERT INTO message(content, publishing_date, author) VALUES (%s, now(), %s);",(content,author))
        self.db.connection.commit() 
        self.db.close_connection() 
Esempio n. 9
0
    def on_btn_edit_clicked(self, btn):
        # Get the ID of selected Connection
        tree = self.builder.get_object("connections_tree")

        # Get the selection
        (model, treeiter) = tree.get_selection().get_selected_rows()

        # Get the connection ID
        if model is not None and len(treeiter) > 0:
            # Get the ID
            connection_id = model[treeiter][1]

            # Load the Connection
            connection = Connection()
            connection.id = connection_id
            connection.load()
            connection.load_tunnels()

            # Open the Window with the connection
            ConnectionWindow(self.refresh_connections_list, connection)
	def __init__(self, opts):
		self.DEBUG = None # for debugging 

		super().__init__()

		# self.id = opts.id 	
		# Compatibility with five bells connector; is this necessary? 

		self.auth = opts['auth']
		self.connected = False 
		self.connection_config = opts['auth']
		self.connection = Connection(self.connection_config)

		on_receive = lambda obj: self._receive(obj).catch(self._handle)
		self.connection.on('receive', on_receive)
		self.connection.on('disconnect', self.disconnect)

		self._expects = dict()
		self._seen = dict()
		self._fulfilled = dict()

		self._log("Initialized Noob Plugin Virtual: {}".format(self.auth))
    def delete_connection(self):
        # Instance the Connection Model
        connection = Connection()
        connection.id = self.id_connection

        # Delete the tunnels
        connection.delete_tunnels()

        # Delete the connection
        if connection.delete() is False:
            MessageBox("Fail to delete the connection, please try again")
        else:
            # Call the callback
            self.refresh_callback()

            # Close the Window
            self.window.destroy()
Esempio n. 12
0
    def on_btn_connect_clicked(self, btn):
        # Get the selected ID
        tree = self.builder.get_object("connections_tree")

        # Get the selection
        (model, treeiter) = tree.get_selection().get_selected_rows()

        # Get the connection ID
        if model is not None and len(treeiter) > 0:
            # Get the ID
            connection_id = model[treeiter][1]

            # Load the Model
            connection = Connection()
            connection.id = connection_id
            connection.load()

            # Get the SSH Command
            command = connection.generate_ssh_command()

            # Open the Shell
            shell = Shell(command, connection.name)
            shell.run()
Esempio n. 13
0
 def __init__(self):
     self.db = Connection()
Esempio n. 14
0
class Conference():
    def __init__(self):
        self.db = Connection()

    def add_conference(self, titre, resume, date, heure, date_creation,
                       id_conferencier):
        """method adding conference"""
        argument = (titre, resume, date, heure, date_creation, id_conferencier)
        sql = """INSERT INTO conferences (titre, resume, date, heure, date_creation, id_conferencier) VALUES (%s,%s,%s,%s,now(),%s);"""
        self.db.initialize_connection()
        self.db.cursor.execute(sql, argument)
        self.db.connection.commit()
        self.db.close_connection()

    def delete_conference(self, id):
        """method deleting conference"""
        sql = """DELETE FROM conferences WHERE id=%s;"""
        self.db.initialize_connection()
        self.db.cursor.execute(sql, (id, ))
        self.db.connection.commit()
        self.db.close_connection()

    def display_conference(self):
        '''method selecting all conferences with the nom prenom of conferencier having the id_conferencier valable'''
        SQL = " SELECT conferences.*, conferenciers.prenom, conferenciers.nom " \
              " FROM conferences INNER JOIN conferenciers" \
              " ON conferences.id_conferencier=conferenciers.id " \
              " ORDER BY conferences.date;"
        """SELECT a.*, b.prenom, b.prenom
        From conferences as a INNER JOIN conferenciers as b
        ON a.id_conferencier=b.id;"""

        self.db.initialize_connection()
        self.db.cursor.execute(SQL)
        all_conferences = self.db.cursor.fetchall()
        print(all_conferences)
        self.db.close_connection()
        for key, value in enumerate(all_conferences):
            all_conferences[key] = HydConference(value)
        return all_conferences
class Nerd_Plugin_Virtual(EventEmitter):
	'''
		### LedgerPlugin API ### 

		Create a Nerd plugin
	'''

	def __init__(self, opts):
		super().__init__()

		# DEBUGGING 
		self.DEBUG = None

		self._handle = lambda err: self.emit('exception', err)
		on_exception = lambda err: self._log('Exception {}'.format(err))
		self.on('exception', on_exception)

		# self.id = opts['id'] # compatibility with five-bells-connector? 
		self.auth = opts['auth']
		self.store = opts['store']
		self.timers = dict() 

		self.transfer_log = Transfer_Log(opts['store'])

		self.connected = False 
		self.connection_config = opts['auth']
		self.connection = Connection(self.connection_config)
		on_receive = lambda obj: self._receive(obj).catch(self._handle)
		self.connection.on('receive', on_receive)

		self.balance = Balance({
				'store': opts['store'],
				'limit': opts['auth']['limit'],
				'balance': opts['auth']['balance']
			})
		self.balance.on('_balanceChanged', self.on_balance_change)
		self.balance.on('_settlement', self.on_settlement)

		self._log("Initialized Nerd Plugin Virtual: {}".format(self.auth))

	def on_balance_change(self, balance):
		self._log('balance changed to ' + balance)
		self.emit('_balanceChanged')
		self._send_balance()

	def on_settlement(self, balance):
		self._log('you should settle your balance of ' + balance)
		self.emit('settlement', balance)
		self._send_settle()

	def get_account(self):
		return self.auth['account']

	def connect(self):
		self.connection.connect()

		def fulfill_connect(resolve, reject):
			def noob_connect():
				self.connected = True 
				self.emit('connect')
				resolve(None)
			self.connection.on('connect', noob_connect())

		return Promise(fulfill_connect)	

	def disconnect(self):

		def fulfill_disconnect():
			self.connected = False 
			self.emit('disconnect')
			return Promise.resolve(None)

		return self.connection.disconnect().then(success=fulfill_disconnect)

	def is_connected(self):
		return self.connected 

	def get_connectors(self):
		# Currently, only connections between two plugins are supported 
		# Thus, the list is empty 
		return Promise.resolve([])

	def send(self, outgoing_transfer):
		self._log("sending out a Transfer with tid: {}"
			.format(outgoing_transfer['id']))

		def send_then():
			self.connection.send({
					'type': 'transfer',
					'transfer': outgoing_transfer
				})

		return self.transfer_log.store_outgoing(outgoing_transfer) \
			.then(send_then()) \
				.catch(self._handle)

	def get_info(self):
		# Using placeholder values in promise resolution
		# TO-DO: What should these values be
		return Promise.resolve({
				'precision': '15',
				'scale': '15',
				'currencyCode': 'GBP',
				'currencySymbol': '$'
			})

	def fulfill_condition(self, transfer_id, fulfillment_buffer):
		fulfillment = str(fulfillment_buffer)
		transfer = None 
		self._log('fulfilling: ' + fulfillment)

		def fulfill_condition_then(stored_transfer):
			transfer = stored_transfer
			return self._fulfill_condition_local(transfer, fulfillment)

		return self.transfer_log.get_id(transfer_id) \
			.then(fulfill_condition_then) \
				.catch(self._handle)

	def _validate(self, fulfillment, condition):
		try:
			parsed_fulfillment = cc.Fulfillment.from_uri(fulfillment)
			is_valid = condition == parsed_fulfillment.condition_uri
			return is_valid
		except Exception:
			return False 

	def _fulfill_condition_local(self, transfer, fulfillment):
		if not transfer:
			raise Exception('got transfer ID for nonexistent transfer')
		elif not transfer['executionCondition']:
			raise Exception('got transfer ID for OTP transfer')

		def _fulfill_condition_local_then(fulfilled):
			if fulfilled:
				raise Exception('this transfer has already been fulfilled')
			else:
				return Promise.resolve(None)

		def _fulfill_transfer_then():
			execute = transfer['executionCondition']
			cancel = transfer['cancellationCondition']

			# FIX DATETIME ISSUES HERE 
			time = str(datetime.isoformat(datetime.now()))
			expires_at = str(datetime(transfer['expiresAt']))
			timed_out = time > expires_at
			
			if self._validate(fulfillment, execute) and not timed_out:
				return self._execute_transfer(transfer, fulfillment)	
			elif cancel and self._validate(fulfillment, cancel):
				return self._cancel_transfer(transfer, fulfillment)
			elif timed_out:
				return self._timeout_transfer(transfer)
			else:
				raise Exception('Invalid fulfillment')

		return self.transfer_log.is_fulfilled(transfer) \
			.then(_fulfill_condition_local_then) \
				.then(_fulfill_transfer_then) \
					.catch(self._handle)

	def _execute_transfer(self, transfer, fulfillment):
		fulfillment_buffer = fulfillment.encode('utf-8')
		self.emit('fulfill_execution_condition', transfer, fulfillment_buffer)
		# Because there is only one balance kept, 
		# money is not actually kept in escrow 
		# although it behaves as though it were 
		# So there is nothing to do for the execution condition 

		def _execute_transfer_then(type):
			if type == self.transfer_log.outgoing:
				return self.balance.add(transfer['amount'])
			elif type == self.transfer_log.incoming:
				return self.balance.sub(transfer['amount'])
			else:
				raise Exception("nonexistent transfer type")

		return self.transfer_log.get_type(transfer) \
			.then(_execute_transfer_then) \
				.then(lambda _: self.transfer_log.fulfill(transfer)) \
					.then(lambda _: self.connection.send({
							'type': 'fulfill_execution_condition',
							'transfer': transfer,
							'fulfillment': fulfillment
						})) \
						.catch(self._handle)

	def _cancel_transfer(self, transfer, fulfillment):
		fulfillment_buffer = fulfillment.encode('utf-8')
		self.emit('fulfill_cancellation_condition', transfer, fulfillment_buffer)
		# A cancellation on an outgoing transfer means nothing 
		# because balances aren't affected until it executes 

		def _cancel_transfer_then(type):
			if type == self.transfer_log.incoming:
				return self.balance.add(transfer['amount'])

		return self.transfer_log.get_type(transfer) \
			.then(_cancel_transfer_then) \
				.then(lambda _: self.transfer_log.fulfill(transfer)) \
					.then(lambda _: self.connection.send({
							'type': 'fulfill_cancellation_condition',
							'transfer': transfer,
							'fulfillment': fulfillment
						}))

	def _timeout_transfer(self, transfer):
		self.emit('reject', transfer, 'timed out')
		transaction_type = None 

		def _timeout_transfer_then(type):
			transaction_type = type 
			if type == self.transfer_log.incoming:
				return self.balance.add(transfer['amount'])

		def _fulfill_transfer_then():
			# potential problem here: figure out how to get transaction_type
			# into the scope of this callback 
			if transaction_type == self.transfer_log.incoming:
				return self.connection.send({
						'type': 'reject',
						'transfer': transfer,
						'message': 'timed out'
					})
			else:
				return Promise.resolve(None)

		return self.transfer_log.get_type(transfer) \
			.then(_timeout_transfer_then) \
				.then(lambda: self.transfer_log.fulfill(transfer)) \
					.then(_fulfill_transfer_then)

	def get_balance(self):
		return self.balance.get()

	def reply_to_transfer(self, transfer_id, reply_message):
		return self.transfer_log.get_id(transfer_id) \
			.then(lambda stored_transfer: self.connection.send({
					'type': 'reply',
					'transfer': stored_transfer,
					'message': reply_message
				}))

	def _receive(self, obj):
		'''
			Cases: 

			* obj.type == transfer
			* obj.type == acknowledge 
			* obj.type == reject 
			* obj.type == reply
			* obj.type == fulfillment
			* obj.type == balance 
			* obj.type == info 
		'''

		if obj['type'] == 'transfer':
			self._log('received a Transfer with tid: ' + obj['transfer']['id'])
			self.emit('receive', obj['transfer'])
			return self._handle_transfer(obj['transfer'])

		elif obj['type'] == 'acknowledge':
			self._log('received an ACK on tid: ' + obj['transfer']['id'])
			self.emit('accept', obj['transfer'], obj['message'].encode('utf-8'))
			return self._handle_acknowledge(obj['transfer'])

		elif obj['type'] == 'reject':
			self._log('received a reject on tid: ' + obj['transfer']['id'])
			self.emit('reject', obj['transfer'], obj['message'].encode('utf-8'))
			return self._handle_reject(obj['transfer'])

		elif obj['type'] == 'reply':
			self._log('received a reply on tid: ' + obj['transfer']['id'])
			def _receive_reply_then(transfer):
				self.emit('reply', transfer, obj['message'].encode('utf-8'))
				return Promise.resolve(None)
			return self.transfer_log.get_id(obj['transfer']['id']) \
				.then(_receive_reply_then)

		elif obj['type'] == 'fulfillment':
			self._log('received a fulfillment for tid: ' + obj['transfer']['id'])
			def _receive_fulfillment_then(transfer):
				self.emit('fulfillment', transfer, obj['fulfillment'].encode('utf-8'))
				return self._fulfill_condition_local(transfer, obj['fulfillment'])
			return self.transfer_log.get_id(obj['transfer']['id']) \
				.then(_receive_fulfillment_then)

		elif obj['type'] == 'balance':
			self._log('received a query for the balance...')
			return self._send_balance()

		elif obj['type'] == 'info':
			return self._send_info()

		else:
			self._handle(Exception('Invalid message received'))

	def _handle_reject(self, transfer):

		def _handle_reject_then(exists):
			if exists:
				print("_handle_reject_then exists")
				self._complete_transfer(transfer)
			else:
				self.emit('_falseReject', transfer) 
				# used for debugging purposes

		return self.transfer_log.exists(transfer) \
			.then(_handle_reject_then)

	def _send_balance(self):

		def _send_balance_then(balance):
			self._log('sending balance: ' + balance)
			return self.connection.send({
					'type': 'balance',
					'balance': balance 
				})

		return self.balance.get() \
			.then(_send_balance_then)

	def _send_settle(self):
	
		def _send_settle_then(balance):
			self._log('sending settlement notification: ' + balance)
			return self.connection.send({
					'type': 'settlement',
					'balance': balance
				})

		return self.balance.get() \
			.then(_send_settle_then)	

	def _send_info(self):
		return self.get_info() \
			.then(lambda info: self.connection.send({
					'type': 'info',
					'info': info
				}))

	def _handle_transfer(self, transfer):

		def _handle_transfer_then(stored_transfer):
			def _repeat_transfer():
				raise Exception('repeat transfer id')
			if stored_transfer:
				self.emit('_repeateTransfer', transfer)
				return self._reject_transfer(transfer, 'repeat transfer id') \
					.then(_repeat_transfer)
			else:
				return Promise.resolve(None)

		def is_valid_incoming_then(valid):
			def is_valid_then(_):
				self._handle_timer(transfer)
				self._accept_transfer(transfer)
			if valid:
				return self.balance.sub(transfer['amount']) \
					.then(is_valid_then)
			else:
				return self._reject_transfer(transfer, 'invalid transfer amount')

		return self.transfer_log.get(transfer) \
			.then(_handle_transfer_then) \
				.then(lambda _: self.transfer_log.store_incoming(transfer)) \
					.then(lambda _: self.balance.is_valid_incoming(transfer['amount'])) \
						.then(is_valid_incoming_then) \
							.catch(self._handle)

	def _handle_acknowledge(self, transfer):

		def _handle_acknowledge_then(stored_transfer):
			if equals(stored_transfer, transfer):
				return self.transfer_log.is_complete(transfer)
			else:
				self._false_acknowledge(transfer)

		def is_complete_transfer_then(is_complete):
			self.DEBUG = transfer
			if is_complete:
				self._false_acknowledge(transfer)
				# don't add to balance yet if it's UTP/ATP transfer 
			elif not transfer['executionCondition']:
				self.balance.add(transfer['amount'])

		def acknowledge_transfer_then(_):
			self._handle_timer(transfer)
			self._complete_transfer(transfer)

		return self.transfer_log.get(transfer) \
			.then(_handle_acknowledge_then) \
				.then(is_complete_transfer_then) \
					.then(acknowledge_transfer_then)

	def _false_acknowledge(self, transfer):
		self.emit('_falseAcknowledge', transfer)
		raise Exception("Received false acknowledge for tid: " + transfer['id'])

	def _handle_timer(self, transfer):
		if transfer['expiresAt']:
			now = datetime.now(pytz.utc)
			expiry = dateutil.parser.parse(transfer['expiresAt'])

			def timer():
				def timer_then(is_fulfilled):
					if not is_fulfilled:
						self._timeout_transfer(transfer)
						self._log('automatic timeout on tid: ' + transfer['id'])
				self.transfer_log.is_fulfilled(transfer) \
					.then(timer_then) \
						.catch(self._handle)

			self.timers[transfer['id']] = Timer(5, timer)
			self.timers[transfer['id']].start()
			# for debugging purposes 
			self.emit('_timing', transfer['id'])

	def _accept_transfer(self, transfer):
		self._log('sending out an ACK for tid: ' + transfer['id'])	
		return self.connection.send({
				'type': 'acknowledge',
				'transfer': transfer,
				'message': 'transfer accepted'
			})

	def _reject_transfer(self, transfer, reason):
		self._log('sending out a reject for tid: ' + transfer['id'])
		self._complete_transfer(transfer)
		return self.connection.send({
				'type': 'reject',
				'transfer': transfer,
				'message': reason
			})

	def _complete_transfer(self, transfer):
		promises = list(self.transfer_log.complete(transfer))
		if not transfer['executionCondition']:
			promises.append(self.transfer_log.fulfill(transfer))
		return Promise.all(promises)

	def _log(self, msg):
		log.log("{}: {}".format(self.auth['account'], msg))
class Noob_Plugin_Virtual(EventEmitter):

	'''
		Create a Noob plugin
		@param opts 

		@param opts.store 

		@param opts.auth
		@param opts.auth.account
		@param opts.auth.token
		@param opts.auth.host 
	'''

	def __init__(self, opts):
		self.DEBUG = None # for debugging 

		super().__init__()

		# self.id = opts.id 	
		# Compatibility with five bells connector; is this necessary? 

		self.auth = opts['auth']
		self.connected = False 
		self.connection_config = opts['auth']
		self.connection = Connection(self.connection_config)

		on_receive = lambda obj: self._receive(obj).catch(self._handle)
		self.connection.on('receive', on_receive)
		self.connection.on('disconnect', self.disconnect)

		self._expects = dict()
		self._seen = dict()
		self._fulfilled = dict()

		self._log("Initialized Noob Plugin Virtual: {}".format(self.auth))

	def _handle(self, err):
		self.emit('exception', err)
		raise err

	def can_connect_to_ledger(self, auth):
		implement()

	def _log(self, msg):
		log.log(self.auth['account'] + ': ' + msg)

	def _expect_response(self, tid):
		self._expects[tid] = True 

	def _expected_response(self, tid):
		if tid not in self._expects:
			self._expect_response(tid)
		return self._expects[tid]

	def _receive_response(self, tid):
		self._expects[tid] = False 

	def _see_transfer(self, tid):
		self._seen[tid] = True 

	def _seen_transfer(self, tid):
		return tid in self._seen

	def _fulfill_transfer(self, tid):
		self._fulfilled[tid] = True 

	def _fulfilled_transfer(self, tid):
		if tid not in self._fulfilled:
			self._fulfilled[tid] = False
		return self._fulfilled[tid]

	def _receive(self, obj):
		'''
			Cases:

			* obj.type == transfer && not seen_transfer(obj.transfer.id)
			* obj.type == acknowledge && expected_response(obj.transfer.id)
			* obj.type == fulfill_execution_condition && 
				not fulfilled_transfer(obj.transfer.id)
			* obj.type == fulfill_cancellation_condition &&
				not fulfilled_trasnfer(obj.transfer.id)
			* obj.type == reject && not fulfilled_transfer(obj.transfer.id) 
			* obj.type == reply
			* obj.type == balance 
			* obj.type == info 
			* obj.type == settlement
		'''
		print('_receive called with obj: {}, type: {}'.format(obj, type(obj))) # debugging

		if type(obj) is not dict:
			self._log("unexpected non-JSON message: '{}'".format(obj))
			return Promise.resolve(None)
		self.DEBUG = obj # debugging
		
		if obj['type'] == 'transfer' \
			and not self._seen_transfer(obj['transfer']['id']):
			self._see_transfer(obj['transfer']['id'])
			self._log('received a Transfer with tid {}'
				.format(obj['transfer']['id']))
			self.emit("receive", obj['transfer'])
			return self.connection.send({
					"type": "acknowledge",
					"transfer": obj['transfer'],
					"message": "transfer accepted"
				})

		elif obj['type'] == 'acknowledge' \
			and self._expected_response(obj['transfer']['id']):
			self._receive_response(obj['transfer']['id'])
			self._log('received an ACK on tid: {}'
				.format(obj['transfer']['id']))
			# TO-DO: Should accept be fulfill execution condition in OTP
			self.emit("accept", 
				obj['transfer'], 
				obj['message'].encode('utf-8')) 
			return Promise.resolve(None)

		elif obj['type'] == 'fulfill_execution_condition' \
			and not self._fulfilled_transfer(obj['transfer']['id']):
			self.emit("fulfill_execution_condition", 
				obj['transfer'], 
				obj['fulfillment'].encode('utf-8'))
			self._fulfill_transfer(obj['transfer']['id'])
			return Promise.resolve(None)

		elif obj['type'] == 'fulfill_cancellation_condtion' \
			and not self._fulfilled_transfer(obj['transfer']['id']):
			self.emit('fullfill_cancellation_condition',
				obj['transfer'],
				obj['fulfillment'].encode('utf-8'))
			self._fulfill_transfer(obj['transfer']['id'])
			return Promise.resolve(None)

		elif obj['type'] == 'reject' \
			and not self._fulfilled_transfer(obj['transfer']['id']):
			self._log('received a reject on tid: {}'
				.format(obj['transfer']['id']))
			self.emit('reject', 
				obj['transfer'], 
				obj['message'].encode('utf-8'))
			return Promise.resolve(None)

		elif obj['type'] == 'reply':
			self._log('received a reply on tid: {}'
				.format(obj['transfer']['id']))
			self.emit('reply', 
				obj['transfer'], 
				obj['message'].encode('utf-8'))
			return Promise.resolve(None)

		elif obj['type'] == 'balance':
			self._log('received balance: {}'.format(obj['balance']))
			self.emit('balance', obj['balance'])
			return Promise.resolve(None)

		elif obj['type'] == 'info':
			self.log('received info.')
			self.emit('_info', obj['info'])
			return Promise.resolve(None)

		elif obj['type'] == 'settlement':
			self._log('received settlement notification.')
			self.emit('settlement', obj['balance'])
			return Promise.resolve(None)

		else:
			raise Exception("Invalid message received")
			return Promise.resolve(None)

	def connect(self):
		self.connection.connect()

		def fulfill_connect(resolve, reject):
			def noob_connect():
				self.connected = True 
				self.emit('connect')
				resolve(None)
			self.connection.on('connect', noob_connect())

		return Promise(fulfill_connect)

	def disconnect(self):

		def fulfill_disconnect():
			self.connected = False 
			self.emit('disconnect')
			return Promise.resolve(None)

		return self.connection.disconnect().then(success=fulfill_disconnect)

	def is_connected(self):
		return self.connected

	def get_connectors(self):
		# Currently, only connections between two plugins are supported 
		# Thus, the list is empty
		return Promise.resolve([])

	def send(self, outgoing_transfer):
		self._log("Sending out a Transfer with tid: {}"
			.format(outgoing_transfer['id']))
		self._expect_response(outgoing_transfer['id'])
		return self.connection.send({
				"type": "transfer",
				"transfer": outgoing_transfer
			}).catch(self._handle)

	def get_balance(self):
		self._log("sending balance query...")
		self.connection.send({
				"type": "balance"
			})

		def fulfill_get_balance(resolve, reject):
			self.once("balance", lambda balance: resolve(balance))

		return Promise(fulfill_get_balance)

	def get_info(self):
		self._log("sending getInfo query...")
		self.connection.send({
				"type": "info"
			})

		def fulfill_get_info(resolve, reject):
			self.once("_info", lambda info: resolve(info))

		return Promise(fulfill_get_info)

	def get_account(self):
		return self.auth['account']

	def fulfill_condition(self, transfer_id, fulfillment):
		return self.connection.send({
				"type": "fulfillment",
				"transferId": transfer_id,
				"fulfillment": fulfillment
			})

	def reply_to_transfer(self, transfer_id, reply_message):
		return self.connection.send({
				"type": "reply",
				"transferId": transfer_id,
				"message": reply_message
			})
Esempio n. 17
0
 def __init__(self):
     # Create a instance of the connection class to acces the database
     self.db = Connection()
Esempio n. 18
0
 def sendMessage(self, call, data):
     Connection.sendMessageTo(self.user, call, data)
Esempio n. 19
0
class View_model():
    def __init__(self):
        self.db = Connection()

    def add_rdv(self, title, date, hour, description):
        sql = """INSERT INTO calendar (title, date, hour, description) VALUES (%s, %s, %s, %s );"""
        arguments = (title, date, hour, description)
        self.db.initialize_connection()
        self.db.cursor.execute(sql, arguments)
        self.db.connection.commit()
        self.db.close_connection()

    def del_rdv(self, date, hour):
        sql = "DELETE title, date, hour, description FROM calendar WHERE date = %s and hour = %s);"
        self.db.initialize_connection()
        self.db.cursor.execute(sql)
        self.db.connection.commit()
        self.db.close_connection()

    def get_all_rdv(self, date):
        sql = "SELECT * FROM calendar WHERE date = %s;"
        self.db.initialize_connection()
        self.db.cursor.execute(sql, (date, ))
        rdv = self.db.cursor.fetchall()
        self.db.close_connection()
        for key, value in enumerate(rdv):
            rdv[key] = Rdv(value)
            return rdv

    def get_rdv(self, date, hour):
        sql = "SELECT * FROM calendar WHERE date = %s and hour=%s;"
        self.db.initialize_connection()
        self.db.cursor.execute(sql, (date, hour))
        rdv = self.db.cursor.fetchone()
        self.db.close_connection()
        return rdv
Esempio n. 20
0
class ConnectionWindowEvents:

    window = None
    builder = None
    refresh_list_callback = None
    tunnels = None
    index_to_remove = None
    connection = None

    def __init__(self,
                 window,
                 builder,
                 refresh_list_callback,
                 connection=None):
        # Copy the parameters
        self.window = window
        self.builder = builder
        self.refresh_list_callback = refresh_list_callback
        self.tunnels = Tunnels()

        # If id_connection is not None, load the connection to Edit
        if connection is not None:
            self.connection = connection
            self.load_connection()

        # Connect the event notify::active of the switch key
        switch = self.builder.get_object("switch_use_key")
        switch.connect("notify::active", self.on_switch_use_key_activate)

    def on_switch_use_key_activate(self, switch, active):
        # Get the password fields
        password = self.builder.get_object("txt_password")
        confirm_password = self.builder.get_object("txt_password_confirm")
        file_chooser = self.builder.get_object("filechooser_key")

        if switch.get_active():
            # Disable them
            password.set_sensitive(False)
            confirm_password.set_sensitive(False)
            file_chooser.set_sensitive(True)
        else:
            # Enable them
            password.set_sensitive(True)
            confirm_password.set_sensitive(True)
            file_chooser.set_sensitive(False)

    def on_btn_add_clicked(self, btn):
        NewTunnelWindow(self.on_added_tunnel_callback)

    def on_tunnels_table_cursor_changed(self, treeview):
        # Get the Index
        (model, path) = treeview.get_selection().get_selected()
        if model is not None and path is not None:
            self.index_to_remove = model[path][3]

    def on_added_tunnel_callback(self, tunnel):
        # Add the tunnel on the list
        self.tunnels.add_tunnel(tunnel)

        # Add to the table the new model
        table = self.builder.get_object("tunnels_table")

        # Get and clean the model
        model = table.get_model()
        if model is not None:
            model.clear()

        # Set the new model
        table.set_model(self.tunnels.get_tunnels_model())

    def on_btn_remove_clicked(self, btn):
        # Remove the line tunnel from the collection and rebuild the table
        self.tunnels.remove_tunnel_at(self.index_to_remove)

        # Rebuild the table
        table = self.builder.get_object("tunnels_table")

        # Get and clean the model
        model = table.get_model()
        if model is not None:
            model.clear()

        # Set the new model
        table.set_model(self.tunnels.get_tunnels_model())

    def on_btn_save_clicked(self, btn):
        # First of all, validate the form
        if self.validate_form():
            # If OK, save the connection
            if self.save_connection():
                # Run the callback
                if self.refresh_list_callback is not None:
                    # Call the callback to refresh the connection list
                    self.refresh_list_callback()

                # Close the Window
                self.window.destroy()
            else:
                # Show a message Box telling the save fails
                MessageBox(
                    "Fail to save the connection. Check if have duplicate names. Try again"
                )

    def on_btn_cancel_clicked(self, btn):
        self.window.destroy()

    def load_connection(self):
        # Get all objects
        name = self.builder.get_object("txt_name")
        host = self.builder.get_object("txt_host")
        port = self.builder.get_object("txt_port")
        user = self.builder.get_object("txt_user")
        switch_key = self.builder.get_object("switch_use_key")
        password = self.builder.get_object("txt_password")
        confirm_password = self.builder.get_object("txt_password_confirm")
        file_chooser = self.builder.get_object("filechooser_key")
        table = self.builder.get_object("tunnels_table")

        # Set the values
        name.set_text(self.connection.name)
        host.set_text(self.connection.host)
        port.set_text(str(self.connection.port))
        user.set_text(self.connection.user)
        switch_key.set_active(self.connection.use_key)
        password.set_text(self.connection.password)
        confirm_password.set_text(self.connection.password)

        if self.connection.key_path != 'None':  # On SQLITE is saved as str 'None'
            file_chooser.set_filename(self.connection.key_path)

        # Check if use key is checked, and call the function to switch the fields
        if self.connection.use_key:
            self.on_switch_use_key_activate(switch_key,
                                            self.connection.use_key)

        # Also, load the tunnels
        self.tunnels = self.connection.get_tunnels()

        # Get and clean the model
        model = table.get_model()
        if model is not None:
            model.clear()

        # Set the new model
        table.set_model(self.tunnels.get_tunnels_model())

    def validate_form(self):
        # Get all object that need be validated
        name = self.builder.get_object("txt_name")
        host = self.builder.get_object("txt_host")
        port = self.builder.get_object("txt_port")
        user = self.builder.get_object("txt_user")
        switch_key = self.builder.get_object("switch_use_key")
        password = self.builder.get_object("txt_password")
        confirm_password = self.builder.get_object("txt_password_confirm")
        file_chooser = self.builder.get_object("filechooser_key")

        # Check for the name
        if len(name.get_text()) == 0:
            MessageBox("Name can't be empty!")
            return False

        # Check for the host
        if len(host.get_text()) == 0:
            MessageBox("Host can't be empty!")
            return False

        # Check for the port
        port_number = port.get_text()
        if len(port_number) == 0:
            MessageBox("Port can't be empty!")
            return False
        elif not port_number.isdigit() or int(port_number) <= 0 or int(
                port_number) > 65565:
            MessageBox("Port must be between 1 and 65565")
            return False

        # Check for the user
        if len(user.get_text()) == 0:
            MessageBox("User can't be empty!")
            return False

        # If switch key is On, the filechooser must have a file
        if switch_key.get_active():
            # If file chooser haven't any file, return error
            if file_chooser.get_filename() is None:
                MessageBox("You must select a key file")
                return False
        else:
            # Check if password is empty
            if len(password.get_text()) == 0:
                MessageBox("Password can't be empty!")
                return False

            # Check if the password are the same, if not, return error
            if password.get_text() != confirm_password.get_text():
                MessageBox("The passwords not match")
                return False

        # If all pass, return True
        return True

    def save_connection(self):
        # Get all object that need be validated
        name = self.builder.get_object("txt_name")
        host = self.builder.get_object("txt_host")
        port = self.builder.get_object("txt_port")
        user = self.builder.get_object("txt_user")
        switch_key = self.builder.get_object("switch_use_key")
        password = self.builder.get_object("txt_password")
        file_chooser = self.builder.get_object("filechooser_key")

        # Create a new Connection
        if self.connection is None:
            self.connection = Connection()

        self.connection.name = name.get_text()
        self.connection.host = host.get_text()
        self.connection.port = port.get_text()
        self.connection.user = user.get_text()
        self.connection.use_key = switch_key.get_active()
        self.connection.key_path = file_chooser.get_filename()
        self.connection.password = password.get_text()

        # Save the connection
        saved = self.connection.save()

        # Delete the Tunnels
        self.connection.delete_tunnels()

        # Now saved the tunnels
        for tunnel in self.tunnels.get_tunnels():
            # Set the ID connection
            tunnel.id_connection = self.connection.id

            # Save the Tunnel
            tunnel.save()

        # return if is saved or not
        return saved
Esempio n. 21
0
def main():
    """Program file for product substitution program, by 'Pur Beurre'."""
    try:
        parser = argparse.ArgumentParser(description="Launch the program !")
        parser.add_argument("-v",
                            "--verbose",
                            action="store_true",
                            help="add output verbosity")
        parser.add_argument("--install_database",
                            action="store_true",
                            help="install database")
        args = parser.parse_args()
        verbose = args.verbose

        if args.verbose:
            print("Running '{}'".format(__file__))

        if args.install_database:
            # Ask informations for sql server connection
            # and save them in 'conn_params.json'.
            Run = Ui()
            host, user, password = Run.connection_params()
            Json().save_connection_params(host, user, password)
            print("Installing...")
            # Server sql connection.
            Log = Connection(host, user, password)
            # Read sql.
            Sql = SqlRead(verbose)
            sql_readed = Sql.read_sql(SQL_FILE)
            # Write database name in 'database_name.json'.
            Sql.database_name(sql_readed)
            # Create database.
            Create(Log, sql_readed).create_db(verbose)
            # Retrieves the maximum number of characters for the fields.
            Fields_charmax = Fetch(Log).characters_max()
            # Retrives datas from Api and reject unsuitable datas.
            Api_data = ApiRequests().api_get_data(Fields_charmax, verbose)
            # Insertion in database.
            Insert(Log, verbose).insert_data(Api_data)
            print("Database installed.")

        else:
            try:
                with open("model/conn_params.json"):
                    pass
                with open("model/database_name.json"):
                    pass
            except IOError:
                print(
                    "\nInformations de connection manquantes.\n",
                    "Veuillez utiliser l'option : --install_database\n",
                )
                exit()
            # Load connection parameters from json.
            host, user, password = Json().read_connection_params()
            # Server connection.
            Log = Connection(host, user, password)
            # Database connection.
            Log_db = Log.database_log()
            # Booleans for loops.
            Loop = False
            log_choice = False
            # User account.
            user_name = False
            Run = Ui()
            while log_choice is False:
                log_choice = Run.log_menu()
            # User log.
            if log_choice == 1:
                logged = False
                while logged is False:
                    user_name = Run.log_user()
                    if isinstance(user_name, str):
                        try:
                            request_lists = RequestsLists().user_id(user_name)
                            user_id = Orm(Log_db).simple_request(
                                request_lists)[0]
                            logged = True
                        except IndexError:
                            print("\n- Ce nom d'utilisateur n'existe pas.")
                    else:
                        print("\n- Veuillez saisir un nom d'utilisateur.")
            # User create account.
            elif log_choice == 2:
                while user_name is False:
                    user_name = Run.create_user()
                    try:
                        request_lists = RequestsLists().user_id(user_name)
                        user = Orm(Log_db).simple_request(request_lists)
                        user_name = False
                        print("\nCe nom d'utilisateur existe déjà.")
                    except IndexError:
                        insert_lists = RequestsLists().user_insert(user_name)
                        Insert(Log_db, verbose).insert_user(insert_lists)
                        request_lists = RequestsLists().user_id(user_name)
                        user_id = Orm(Log_db).simple_request(request_lists)[0]

            while Loop is False:
                # Booleans for loops.
                menu_choice = False
                category = False
                product_id = False
                substitute_id = False
                save_choice = False
                # Display menu.
                while menu_choice is False:
                    menu_choice = Run.menu()
                # Launch search for substitute.
                if menu_choice == 1:
                    # Display categories
                    while category is False:
                        category = Run.categories()
                    # Display products.
                    while product_id is False:
                        product_id = Run.products(Log, category)
                    # Display substitute
                    while substitute_id is False:
                        substitute_id = Run.substitute(Log, product_id,
                                                       category)
                    # Save result, leave or loop.
                    while save_choice is False:
                        save_choice = Run.save_menu(Log)
                    if save_choice == 1:
                        insert_lists = RequestsLists().save_search(
                            product_id, substitute_id, user_id)
                        Insert(Log_db, verbose).insert_save(insert_lists)
                        print("\nRecherche sauvegardée.")
                    elif save_choice == 2:
                        pass
                    elif save_choice == 3:
                        exit(Ui().bye_message(user_name))

                # Display saved searches.
                elif menu_choice == 2:
                    Run.saves_display(Log_db, user_id)
                # Quit.
                elif menu_choice == 3:
                    exit(Ui().bye_message(user_name))

    except KeyboardInterrupt:
        Ui().bye_message(user_name)
Esempio n. 22
0
class Conferencier():
    def __init__(self):
        self.db = Connection()

    def add_conferencier(self, prenom, nom, description, profession):
        """method adding conferencier"""
        argument=(prenom, nom, description, profession)
        sql="""INSERT INTO conferenciers (prenom, nom, description, profession) VALUES (%s,%s,%s,%s);"""
        self.db.initialize_connection()
        self.db.cursor.execute(sql, argument)
        self.db.connection.commit()
        self.db.close_connection()

    def delete_conferencier(self, id):
        """method deleting conferencier"""
        sql="""DELETE FROM conferenciers WHERE id=%s;"""
        self.db.initialize_connection()
        self.db.cursor.execute(sql, (id,))
        self.db.connection.commit()
        self.db.close_connection()

    def display_conferencier(self):
        '''method selecting all conferenciers that have actif status'''
        self.db.initialize_connection()
        self.db.cursor.execute("SELECT * FROM conferenciers WHERE statut_actif=True ;")
        actif_conferenciers = self.db.cursor.fetchall()
        for key, value in enumerate(actif_conferenciers):
            actif_conferenciers[key]=HydConferencier(value)

        self.db.close_connection()

        return actif_conferenciers
Esempio n. 23
0
    def connect(self, fromVar, toVar):
        """
        Connect fromVar to toVar, add all modules of
        toVar-module-instrument to instrument of fromVar-module and
        sort modules list in the correct order for csound code
        generation.

        @type  fromVar: model.var.OutVar
        @param fromVar: Startpoint of connection.
        @type  toVar: model.var.InVar
        @param toVar: Endpoint of connection.
        @raise ConnectionError: If connection from module to itself.
        @rtype : model.Connection.connection
        @return: New connection.
        """
        if fromVar.module == toVar.module:
            raise ConnectionError, "Can\'t connect module with itself"

        if fromVar.type == "a" and toVar.type == "i":
            raise ConnectionError, \
                  "Can\'t connect audio rate output to initialisation rate input"

        if fromVar.type == "i" and toVar.type == "a":
            raise ConnectionError, \
                  "Can\'t connect initialisation rate output to audio rate input"

        if toVar.connection:
            raise ConnectionError, "There's already a connection to this input "

        newConnection = Connection(fromVar, toVar)

        targetInstr = fromVar.module.instrument
        leftInstr = toVar.module.instrument
        targetInstr.connections.append(newConnection)
        toVar.connection = newConnection

        # Append all modules and connections of leftInstr to
        # targetInstr and remove leftInstr from workspace
        if targetInstr != leftInstr:
            for m in leftInstr.modules:
                m.instrument = targetInstr
                targetInstr.modules.append(m)
            for c in leftInstr.connections:
                targetInstr.connections.append(c)
            self.instruments.remove(leftInstr)
        else:
            if targetInstr.modules.index(fromVar.module) \
               > targetInstr.modules.index(toVar.module):
                # Place toVar module behind fromVar module and close
                # the gap
                fromIdx = targetInstr.modules.index(fromVar.module)
                toIdx = targetInstr.modules.index(toVar.module)
                targetInstr.modules \
                                    = targetInstr.modules[:toIdx] \
                                    + targetInstr.modules[(toIdx+1):fromIdx] \
                                    + [targetInstr.modules[fromIdx], \
                                       targetInstr.modules[toIdx]] \
                                    + targetInstr.modules[(fromIdx+1):]
        self.setChanged()
        arg = ['connect', newConnection]
        self.notifyObservers(arg)

        return newConnection
Esempio n. 24
0
class EventModel():
    """Class to perform all queries related to the event table in the database"""
    def __init__(self):
        # Create a instance of the connection class to acces the database
        self.db = Connection()

    def show_events(self, date):
        """method to display all the events of the day """
        sql = "SELECT * FROM events WHERE date = %s;"
        self.db.initialize_connection()
        self.db.cursor.execute(sql, (date, ))
        events = self.db.cursor.fetchall()
        self.db.close_connection()
        for key, value in enumerate(events):
            events[key] = Event(value)
        return events

    def display_one_event(self, date, time):
        """method to dislay one event  """
        sql = "SELECT * FROM events WHERE date = %s AND time = %s;"
        self.db.initialize_connection()
        self.db.cursor.execute(sql, (date, time))
        event = self.db.cursor.fetchone()
        self.db.close_connection()
        if event:
            return Event(event)
        return False

    def add_event(self, event):
        """ """
        sql = "INSERT INTO events(title, date, time, description) VALUES(%s, %s, %s, %s);"
        percent_s = (event.title, event.date, event.time, event.description)
        self.db.initialize_connection()
        self.db.cursor.execute(sql, percent_s)
        self.db.connection.commit()
        self.db.close_connection()

    def delete_event(self, date, time):
        """ """
        sql = "DELETE FROM events WHERE date = %s AND time = %s;"
        percent_s = (date, time)
        self.db.initialize_connection()
        self.db.cursor.execute(sql, percent_s)
        self.db.connection.commit()
        self.db.close_connection()

    def update_event(self, title, date, time, description, actual_date,
                     actual_time):
        """ """
        sql = "UPDATE events SET title=%s, date=%s, time=%s, description = %s WHERE date = %s AND time = %s;"
        percent_s = (event.title, event.date, event.time, event.description,
                     actual_date, actual_time)
        self.db.initialize_connection()
        self.db.cursor.execute(sql, percent_s)
        self.db.connection.commit()
        self.db.close_connection()