def removeItem(c, r, name):
    try:
        lock.acquire()
        #print("thread %s locking" % name)
        with open(filepath, "r") as f:
            lines = f.readlines()
        #time.sleep(3)
        lock.release()
        #print("thread %s released lock" % name)

        if len(lines) > r:
            lock.acquire()
            #print("thread %s locking" % name)
            with open(filepath, "w") as f:
                for idx, line in enumerate(lines):
                    if idx != r:
                        f.write(line)
                    else:
                        print("Removed task: %s" % line)
            #time.sleep(3)
            lock.release()
            #print("thread %s released lock" % name)
            response = protocol.Message("SUCCESS", 0, "")
            return response
        else:
            error_response = protocol.Message("ERROR",
                                              protocol.ERROR_ITEMNOTFOUND, "")
            return error_response

    except Exception as e:
        print(e)
        error_response = protocol.Message("ERROR", protocol.ERROR_ITEMNOTFOUND,
                                          "")
        return error_response
예제 #2
0
def handle_request(request, client):
	if request.method == "LIST":
	
		with open("D:\\testi.txt") as f:
			f = f.read().splitlines()
			body = "\r\n".join(f)
			response = protocol.Message("LISTRESPONSE", len(f), body)
			return response

	elif request.method == "DOWNLOAD":
		filename = request.methodparams[0]
		print filename
		try:
			with open("D:\\testi.txt", "a") as myfile:
				myfile.write(filename+'\n')
            # inefficient, but works for now
			body = "Ok"
			response = protocol.Message("FILE", filename, body)
			return response

		except Exception as e:
			print e
			error_response = protocol.Message("ERROR", protocol.ERROR_FILENOTFOUND, "") 
			return error_response
	elif request.method == "DELETE":
		filename = request.methodparams[0]
		numero = int(filename)
		print numero
		try:
			
			with open("D:\\testi.txt") as f:
				lines = f.read().splitlines()
				
			print lines
			numero = numero -1
			lines.pop(numero)
			print lines
			#split() splittina \n, parseta 
			
			
			x = open("D:\\testi.txt", 'w')
			for item in lines: 
				x.write(item + "\n")
			x.close()
            # inefficient, but works for now
			body = "Ok"
			response = protocol.Message("DELETERESPONSE", filename, body)
			return response

		except Exception as e:
			print e
			error_response = protocol.Message("ERROR", protocol.ERROR_FILENOTFOUND, "") 
			return error_response
	else:
		raise protocol.UnexpectedMethodException(request.header)
예제 #3
0
def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((server_addr, server_port))
    s.listen(10)

    while True:
        client, (client_addr, client_port) = s.accept()
        print("Client connected from %s") % client_addr

        try:
            (method, bodylen, methodparams) = protocol.read_firstpart(client)
            body = ""
            if method == "LIST" and bodylen > 0:
                print("malformed bodylength")
                client.close()
            else:
                if bodylen > 0:
                    body = protocol.read_body(client, bodylen)
                re = protocol.Message(method, methodparams, body)
                response = handle_request(re, client)
                protocol.send_message(client, response)
        except protocol.InvalidMethodException:
            print("received malformed header from the client")

        client.close()
예제 #4
0
파일: link.py 프로젝트: liulunet/pycarplay
 def _read_thread(self):
     while self._run:
         try:
             data = self._ep_in.read(protocol.Message.headersize)
         except usb.core.USBError as e:
             if e.errno != 110:  # Timeout
                 self.on_error(e)
             continue
         if len(data) == protocol.Message.headersize:
             header = protocol.Message()
             header.deserialise(data)
             needlen = len(header._data())
             if needlen:
                 try:
                     msg = header.upgrade(self._ep_in.read(needlen))
                 except usb.core.USBError as e:
                     self._threaderror(e)
                     continue
             else:
                 msg = header
             try:
                 self.on_message(msg)
             except Exception as e:
                 self.on_error(e)
                 continue
         else:
             print(f"R> Bad data: {data}")
예제 #5
0
def main():

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((server_addr, server_port))
    s.listen(5)

    def clean_exit(signal, frame):
        print "ctrl+c pressed"
        s.close()
        sys.exit()

    # when ctrl+c is pressed, call clean_exit function
    signal.signal(signal.SIGINT, clean_exit)

    while True:
        client, (client_addr, client_port) = s.accept()
        print "client connected from %s" % client_addr

        try:
            (method, bodylen, methodparams) = protocol.read_header(client)
            body = ""
            if bodylen > 0:
                body = protocol.read_body(client, bodylen)
            request = protocol.Message(method, methodparams, body)
            response = handle_request(request, client)
            protocol.send_message(response, client)
        except protocol.InvalidMethodException:
            print "received invalid method from %s, disconnecting the client..." % (client_addr)
        except protocol.MalformedHeaderException:
            print "received malformed header the %s, disconnecting the client" % (client_addr)

        client.close()
예제 #6
0
def main():
    if len(sys.argv) < 2:
        print("not enough parameters")
        print("syntax: ADDRESS [PORT]")
        sys.exit()

    server_addr = sys.argv[1]
    server_port = 0

    if len(sys.argv) == 2:
        server_port = 65432
    else:
        server_port = int(sys.argv[2])

    while True:
        choice = main_menu()
        print("Connecting to %s %d") % (server_addr, server_port)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((server_addr, server_port))

        if choice == MAIN_MENU_CHOICE_DOWNLOAD:
            filename = raw_input("Filename: ")
            request = protocol.Message("DOWNLOAD", filename, "")
            protocol.send_message(s, request)

            (method, bodylen, methodparams) = protocol.read_firstpart(s)

            if method == "FILE":
                f = open(filename, "w")
                shutil.copyfileobj(s.makefile(), f)
                f.close()
                print("File downloaded succesfully!!")
            else:
                print("An error occured")

        if choice == MAIN_MENU_CHOICE_LIST:
            filepath = raw_input("Filepath: ")
            request = protocol.Message("LIST", filepath, "")
            protocol.send_message(s, request)

            (method, bodylen, methodparams) = protocol.read_firstpart(s)

            if method == "LISTRESPONSE":
                print(s.recv(1024))
            else:
                print("An error occured")
예제 #7
0
def handle_request(re, client):
    if re.method == "DOWNLOAD":
        filename = re.methodparams[0]
        print(filename)
        try:
            f = open(server_datadir + filename, "r")
            body = "".join(f.readlines())
            print(body)
            #body = f.read()
            response = protocol.Message("FILE", filename, body)
            return response
        except Exception as e:
            print(e)
            error_response = protocol.Message("ERROR",
                                              protocol.ERROR_FILENOTFOUND, "")
            return error_response
    elif re.method == "LIST":
        filepath = resolve_path(server_datadir + re.methodparams[0])
        #filepath = server_datadir + re.methodparams[0]
        try:
            if os.path.isdir(filepath):
                files = os.listdir(filepath)
                filesLen = 0
                if len(files) > 0:
                    body = '\r\n'.join(files)
                    filesLen = len(files)
                else:
                    body = 0
                print(body)
                response = protocol.Message("LISTRESPONSE", filesLen, body)
                return response
            else:
                print("error")
                error_response = protocol.Message("ERROR",
                                                  protocol.ERROR_BADFOLDER, "")
                return error_response
        except Exception as e:
            print(e)
            error_response = protocol.Message("ERROR",
                                              protocol.ERROR_FILENOTFOUND, "")
            return error_response
    else:
        print("something went wrong!")
def addItem(c, data, name):
    try:
        lock.acquire()
        #print("thread %s locking" % name)
        with open(filepath, "a+") as f:
            f.write("%s\n" % data)
        #time.sleep(3)
        lock.release()
        #print("thread %s released lock" % name)

        #print("Added task: %s" % data)
        response = protocol.Message("SUCCESS", 0, "")
        return response

    except Exception as e:
        print(e)
        error_response = protocol.Message("ERROR", protocol.ERROR_ADDFAILED,
                                          "")
        return error_response
예제 #9
0
def serialReceive(ser, event):
    parser = protocol.Parser()
    msg = protocol.Message()

    while not event.is_set():
        byte = ser.read(size=1)
        if len(byte) > 0 and parser.parseByte(byte[0], msg):
            if msg.id == protocol.Heartbeat.id():
                handleHeartbeat(msg.getHeartbeat())
            elif msg.id == protocol.Response.id():
                handleResponse(msg.getResponse())
    def send_chat_message(self, text: str) -> None:
        """
        Sends a chat message to the other party in the chat.
        :param text: text of the text message
        :return: None
        """
        message = protocol.Message(protocol.Message.CHAT_MESSAGE, text,
                                   self.user_name, self.other_user)
        serialized_message = protocol.serialize_message(message)
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.connect(self.server_address)
                s.sendall(serialized_message)

        finally:
            s.close()
def table_row_to_msg(row: typing.Tuple[str, str, str]) -> protocol.Message:
    """
    Translates a row of the chat messages table into a Message object.
    :param row: the row that should be translated
    :return: the row as a Message object.
    """
    message_identifier = row[0]
    content = row[1]
    sender = row[2]
    first_user, second_user = message_identifier.split(":")[:2]
    if first_user != sender:
        receiver = first_user
    else:
        receiver = second_user

    message = protocol.Message(protocol.Message.CHAT_MESSAGE, content, sender,
                               receiver)
    return message
예제 #12
0
 def run(self):
     chat_identifier = database.create_chat_identifier(self.user_name,
                                              self.other_user)
     while not self.kill_flag.kill:
         con = self.db_handler.open_connection()
         last_message = self.db_handler.total_message_amount(
             con,
             chat_identifier)
         query_msg = protocol.Message(protocol.Message.REQUEST_NEW_MESSAGES,
                             last_message,
                             self.user_name,
                             self.other_user)
         con.close()
         ser_msg = protocol.serialize_message(query_msg)
         with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
             try:
                 s.connect(self.server_address)
                 s.sendall(ser_msg)
                 buffer = b''
                 while True:
                     data = s.recv(4096)
                     if not data:
                         if len(buffer) == 0:
                             raise NoMessageReceived
                         break
                     buffer += data
                 des_msg = protocol.reassemble_message(
                     protocol.deserialize_json_object(buffer[2:]))
                 
                 if len(buffer) > 0:
                     con = self.db_handler.open_connection()
                     list_of_msgs = json.loads(des_msg.content)
                     for each in list_of_msgs:
                         msg_cont = protocol.deserialize_json_object(each)
                         rec_msg = protocol.reassemble_message(msg_cont)
                         self.db_handler.add_chat_message_to_database(con, rec_msg)
                     # tell observers that new messages have been fetched and added
                     self.update_observers()
                     con.close()
             except NoMessageReceived:
                 pass
             finally:
                 s.close()
         time.sleep(2)
    def get_new_messages(self, message: protocol.Message) -> protocol.Message:
        """
        Returns any messages in the database newer than the message specified.
        :raises database.NotPresentInDatabase: when no newer messages exist.
        :param message: message with type REQUEST_NEW_MESSAGES and its content
                        contains the number of the last message it has
        :return: a message containing serialized messages in its content
        """
        protocol.validate_request_message_format(message)
        clients_last_message = int(message.content)
        chat_identifier = database.create_chat_identifier(
            message.sender, message.receiver)
        messages_available_in_db = self.total_message_amount(
            self.connection, chat_identifier)

        message_list = []

        if clients_last_message >= messages_available_in_db:
            raise database.NotPresentInDatabase(
                "There are no new messages in the database.")

        # send maximum of 50 messages per request message
        if clients_last_message + 50 + 1 < messages_available_in_db:
            messages_available_in_db = clients_last_message + 50 + 1

        for i in range(clients_last_message + 1, messages_available_in_db + 1):
            message_identifier = database.create_message_identifier(
                chat_identifier, i)
            msg_row = self._get_chat_message(self.connection,
                                             message_identifier)
            msg = database.table_row_to_msg(msg_row)
            msg_serialized = protocol.serialize_message_content(msg)
            message_list.append(msg_serialized)

        ser_msg_list = json.dumps(message_list)
        return_message = protocol.Message(protocol.Message.NEW_MESSAGES,
                                          ser_msg_list)
        return return_message
def listItems(c, name):
    lock.acquire()
    #print("thread %s locking" % name)
    with open(filepath, "r") as f:
        todo = f.readlines()
    # sleep to test locks
    #time.sleep(3)
    lock.release()
    #print("thread %s released lock" % name)
    # add numbers 1) etc to todo list items
    if len(todo) > 0:
        list = []
        for idx, listitem in enumerate(todo):
            list.append(str(idx) + ") " + listitem)

        body = '\r\n'.join(list)
        listLen = len(todo)
    else:
        listLen = 0
        body = ""

    response = protocol.Message("LISTRESPONSE", listLen, body)
    return response
예제 #15
0
def message(cmd):
    s = cmd.split(' ')
    room = s[0]
    msg = ' '.join(s[1:])
    send(protocol.Message(USERNAME, msg, room))
예제 #16
0
def main():
	if len(sys.argv) < 2:
		print "not enough parameters."
		print "usage: %s ADDRESS [PORT]"
		sys.exit(1)

	server_addr = sys.argv[1]
	server_port = 0

	if len(sys.argv) == 2:
		server_port = 1234
	else:
		server_port = int(sys.argv[2])

	while True:
		choice = main_menu()
		print "Connecting to %s:%d..." % (server_addr, server_port)
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((server_addr, server_port))

		if choice == MAIN_MENU_CHOICE_LIST:
			folder = "."
			request = protocol.Message("LIST", folder, "")
			protocol.send_message(request, s)

			(method, bodylen, methodparams) = protocol.read_header(s)

			if method == "LISTRESPONSE":
				body = ""
				if bodylen > 0:
					body = protocol.read_body(s, bodylen)

				files = body.split("\r\n")
				print "files:"
				i = 1;
				for file in files:
					print i , " %s" % file
					i=i+1
			else:
				print "an error occured: %s" % methodparams[0]

		elif choice == MAIN_MENU_CHOICE_DOWNLOAD:
			filename = raw_input("filename: ")
			request = protocol.Message("DOWNLOAD", filename, "")
			protocol.send_message(request, s)

			(method, bodylen, methodparams) = protocol.read_header(s)

			if method == "FILE":
				# write the body to a file of the same name
				print "Sana lisatty"
			else:
				print "an error occured: %s" % methodparams[0]
		elif choice == MAIN_MENU_CHOICE_DELETE:
			filename = raw_input("filename: ")
			request = protocol.Message("DELETE", filename, "")
			protocol.send_message(request, s)

			(method, bodylen, methodparams) = protocol.read_header(s)

			if method == "DELETERESPONSE":
				# write the body to a file of the same name
				print "Sana poistettu"
			else:
				print "an error occured: %s" % methodparams[0]

		s.close()