Esempio n. 1
0
    async def handle_DATA(self, server, session, envelope):
        """Handles the content of a mail
        """
        print('handle_DATA')

        message = envelope.content.decode('utf8', errors='replace')
        message = decrypt(message)

        job_id = message.split("|")[0].strip()
        database.update_state(database.open_db(), 20, job_id)
        segments = json.loads(message.split("|")[1].strip())

        print('segments', segments)

        new_segments = []
        for (x1, y1), (x2, y2) in segments:
            new_segments.append(split.Segment(split.Vect(x1, y1),
                                              split.Vect(x2, y2)))
        database.update_state(database.open_db(), 21, job_id)
        cut_segments = split.cut(new_segments)
        database.update_state(database.open_db(), 22, job_id)

        print('job_id: ', job_id)

        sk1, pk1 = ensicoin.generate_keys()
        database.open_db().write("/{}/address".format(job_id), pk1)
        sk2, pk2 = ensicoin.generate_keys()

        print('connecting to solidator')

        solidator_socket = socket.create_connection((SOLIDATOR_ADDRESS,
                                                     SOLIDATOR_PORT))
        
        print('sending pk2')

        solidator_socket.send(pk2.encode())
        database.update_state(database.open_db(), 23, job_id)
        
        print('waiting for payment')
        
        hashtx, _ = ensicoin.wait_for_pubkey(pk1)

        print('hashtx: ', hashtx)

        ensicoin.send_to(10,
                         hashtx,
                         0,
                         sk1,
                         42,
                         pk2,
                         [job_id,
                          "'" + json.dumps(split.generate_id_tuple(cut_segments)) + "'"], job_id)

        print('payment sent')

        database.update_state(database.open_db(), 24, job_id)

        return '250 Message accepted for delivery'
Esempio n. 2
0
def send_menu_message(message):
	user = database.get_user(message.chat.id)
	delete_menu(message.chat.id)
	text = user['user_name'] + ', ви хочете знайти найближчий пункт переробки чи залишити заявку на вивіз сміття?'
	kb = types.InlineKeyboardMarkup()
	kb.row(types.InlineKeyboardButton(text='Найближчий пункт', callback_data='find_closest_init'))
	kb.row(types.InlineKeyboardButton(text='Заявка на вивіз', callback_data='leave_request_init'))
	m = bot.send_message(message.chat.id, text, reply_markup=kb)
	database.update_state(message.chat.id, 'menu')
	database.update_user(message.chat.id, 'menu_message', m.message_id)
Esempio n. 3
0
def translation(segments, job_id, gpg):
    """Creates replicas of the segments in the eight directions
    """
    print('translating')

    segments = translator.translate_segments(segments, True)

    database.update_state(database.open_db(), 16, job_id)

    send(SMTP_ADDR, segments, job_id, gpg)
Esempio n. 4
0
    def on_post():
        """Fetches segments and job_id from POST
        """

        job_id = request.form['job']
        segments = json.loads(request.form['message'])

        print('new job', job_id, segments)

        database.update_state(database.open_db(), 14, request.form['job'])

        translation(segments, job_id, gpg)

        return ""
Esempio n. 5
0
def listen():
    listener = socket.socket()
    listener.bind((TCP_IP, TCP_PORT))
    listener.listen()

    while True:
        conn, _ = listener.accept()

        print("connection accepted")

        data = conn.recv(66).decode()

        print("data:", data)

        _, flags = ensicoin.wait_for_pubkey(data)

        print("flags: ", flags)

        segments = None
        job_id = None

        if flags[0][0] == "[":
            segments = json.loads(flags[0])
            job_id = flags[1]

        if flags[1][0] == "[":
            segments = json.loads(flags[1])
            job_id = flags[0]

        print("segments: ", segments)
        print("job_id: ", job_id)

        database.update_state(database.open_db(), 26, job_id)

        print("saving results")

        points = solidator.create_points(segments)
        os.mkdir(job_id)
        os.chdir(job_id)
        solidator.remove_deg_1(points, job_id, True)

        result = open("result.svg", "r")
        svg_data = result.read()
        result.close()

        os.chdir("..")
        shutil.rmtree(job_id)

        database.open_db().write("/{}/result".format(job_id), svg_data)
        database.update_state(database.open_db(), 31, job_id)
Esempio n. 6
0
def query_handler(c):
	m_id = c.message.chat.id
	user = database.get_user(m_id)
	if not user:
		return
	if c.data == 'find_closest_init':
		database.update_state(m_id, 'find_closest_init')
		delete_menu(m_id)
		bot.send_message(m_id, 'Надішли мені свою геопозицію за допомогою скріпки знизу.')
		return
	elif c.data == 'leave_request_init':
		types = recyclers.get_types()
		delete_menu(m_id)
		bot.send_message(m_id, '\n'.join(types))
		bot.send_message(m_id, 'Вибери тип сміття зі списку вище.')
		database.update_state(m_id, 'leave_request_type')
Esempio n. 7
0
def terminate(db, job_id, mill_stub):
    """Finishes the job *job_id* and forwards it to the *mill_stub*
    """
    database.update_state(database.open_db(), 2, job_id)

    segments = json.loads(db.read("/a_pi/{}/segments".format(job_id)).value)

    segments = [
        mill_pb2.Segment(a=mill_pb2.Point(x=s[0], y=s[1]),
                         b=mill_pb2.Point(x=s[2], y=s[3])) for s in segments
    ]

    mill_stub.Turn(mill_pb2.Job(id=job_id, segments=segments))
    database.update_state(database.open_db(), 3, job_id)

    db.delete("/a_pi/{}/segments".format(job_id))
    db.delete("/a_pi/{}/digit".format(job_id))
Esempio n. 8
0
def listen():
    """Start a Unitator server listening for notifications of
    a golfer server
    """
    notifier = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    notifier.bind((TCP_IP, TCP_PORT))

    notifier.listen()

    print('listening')

    while True:
        conn, _ = notifier.accept()
        print('accepted')

        data = conn.recv(19)
        if data == b'pssssst want some ?':
            data = b""
            while True:
                new_data = conn.recv(1)
                if not new_data or new_data == b'#':
                    break
                data += new_data
            conn.close()

            data = data.decode()
            data = data.split('|')

            if len(data) == 2:
                host, ip = data[0].split(":")
                job_selector = data[1]

                print('>', host, ip, job_selector)

                job_conn = send(job_selector.encode() + b'\n', host, ip)
                raw = recv_data(job_conn)
                segments = json.loads(raw)

                print(raw, segments)

                send(b'!/delete ' + job_selector.encode() + b'\n', host, ip)

                job_id = job_selector.split("/")[1]
                database.update_state(database.open_db(), 9, job_id)
                unit(segments, job_id)
Esempio n. 9
0
def write(job_id, text):
    """Writes a *text* by an html form
    """
    print(text)

    database.update_state(database.open_db(), 11, job_id)
    display = Display(visible=0, size=(1024, 768))
    display.start()

    browser = webdriver.Firefox()
    actions = webdriver.ActionChains(browser)
    browser.get("file:///app/test.html")
    message = browser.find_element_by_name("message")
    message.send_keys(text)
    job = browser.find_element_by_name("job")
    job.send_keys(job_id)
    job.submit()
    database.update_state(database.open_db(), 12, job_id)
Esempio n. 10
0
def location_handler(message):
	if not user_check_routine(message):
		return
	user = database.get_user(message.chat.id)
	if user['state'] == 'find_closest_init':
		database.update_state(message.chat.id, 'find_closest_type')
		print(message.location.longitude, message.location.latitude)
		database.update_user(message.chat.id, 'pos_lon', message.location.longitude)
		database.update_user(message.chat.id, 'pos_lat', message.location.latitude)
		types = recyclers.get_types()
		bot.send_message(message.chat.id, '\n'.join(types))
		bot.send_message(message.chat.id, 'Вибери тип сміття зі списку вище. Можеш вибирати скільки завгодно, а потім просто повернутися в /menu.')
	if user['state'] == 'leave_request_location':
		database.update_state(message.chat.id, 'menu')
		print(message.location.longitude, message.location.latitude)
		database.update_request(message.chat.id, 'pos_lon', message.location.longitude)
		database.update_request(message.chat.id, 'pos_lat', message.location.latitude)
		bot.send_message(message.chat.id, 'Чудово! Оператор зв\'яжеться й домовиться з ваи про усе інше. Список ваших заявок можна побачити за допомогою /current_requests.')
		send_menu_message(message)
Esempio n. 11
0
def unit(segments, job_id):
    """Clip *segments* of the job *job_id* into a unit square and forwards them
    """
    print("segments:", segments)

    segments = [
        clipping.segment(clipping.p(segment[0][0], segment[0][1]),
                         clipping.p(segment[1][0], segment[1][1]))
        for segment in segments
    ]

    print("segments1:", segments)

    clipped_segments = clipping.clip_unit_square(segments)
    database.update_state(database.open_db(), 10, job_id)

    print("clipped_segments:", clipped_segments)

    tuple_segments = [((segment.a.x, segment.a.y), (segment.b.x, segment.b.y))
                      for segment in clipped_segments]

    print("tuple_segments:", tuple_segments)

    write(job_id, json.dumps(tuple_segments, indent=4))
Esempio n. 12
0
    def Turn(self, request, context):
        """Turns segments contained in the RPC message *request*
        """
        print("DEEEEEEEEEE")
        status_db = database.open_db()
        database.update_state(status_db, 4, request.id)

        segments = MessageToDict(request)["segments"]
        segments = list(map(segment_to_tuple, segments))

        database.update_state(status_db, 5, request.id)
        rotated_segments = rotate.mirror_and_turn_segments(segments, True)
        database.update_state(status_db, 6, request.id)

        write(json.dumps(list(rotated_segments)), request.id)
        database.update_state(status_db, 7, request.id)

        return mill_pb2.Response()
Esempio n. 13
0
def send(host, segments, job_id, gpg):
    """Sends the encoded *segments* to the next service by smtp
    throught *host* encrypted using the *gpg* context
    """
    import smtplib

    print('sending')

    sender = "*****@*****.**"
    receivers = ["*****@*****.**"]
    message = """{}|""".format(job_id)

    message += json.dumps(segments) + "\n"
    database.update_state(database.open_db(), 17, job_id)

    message = encrypt(message, gpg)
    database.update_state(database.open_db(), 18, job_id)

    smtpObj = smtplib.SMTP(host)
    print(smtpObj.sendmail(sender, receivers, message.encode()))
    database.update_state(database.open_db(), 19, job_id)
Esempio n. 14
0
def change_name(message):
	if not user_check_routine(message):
		return
	bot.send_message(message.chat.id, 'Як ти хочеш, щоб я тебе називав?')
	database.update_state(message.chat.id, 'change_name')
Esempio n. 15
0
def index():

    # contains json object that telegram sent
    msg = request.get_json()
    with open('request.json', 'w', encoding='utf-8') as file:
        json.dump(msg, file, ensure_ascii=False, indent=4)  

    # admins = bot_functions.get_admins()
    admins = bot_functions.get_admins()

    if 'message' in msg.keys():
        if 'contact' in msg['message'].keys():
            user_id, phone_number, firstname, lastname, username = bot_functions.proces_contact(msg)
            state = db.get_state(user_id)
            response_state = db.add_user(user_id=user_id, phone_number=phone_number, firstname=firstname, lastname=lastname, username=username)
            db.update_state(user_id=user_id, state=int(response_state))
            bot_functions.menu(user_id)
        elif 'photo' in msg['message'].keys():
            user_id, message_id, file_id, caption = bot_functions.parse_image_message(msg)
            state = db.get_state(user_id)
            if len(state) == 0:
                print("\n\n not enter in key part \n\n")
                state = 0
            else:
                print("\n\n enter in key part \n\n")
                state, = state[0]
            
            ligal = Semaphore.is_ligal(caption, user_id, state)
            if ligal:
                returned_state = bot_functions.photoMessageHandler(user_id, file_id, caption, message_id)
                db.update_state(user_id, returned_state)
            else:
                bot_functions.send_message(chat_id=user_id, text=bot_texts.get_illigalText())

        elif 'video' in msg['message'].keys():
            user_id, message_id, file_id, caption = bot_functions.parse_video_message(msg)
            state = db.get_state(user_id)
            if len(state) == 0:
                print("\n\n not enter in key part \n\n")
                state = 0
            else:
                print("\n\n enter in key part \n\n")
                state, = state[0]
            
            ligal = Semaphore.is_ligal(caption, user_id, state)
            if ligal:
                returned_state = bot_functions.videoMessageHandler(user_id, file_id, caption, message_id)
                db.update_state(user_id, returned_state)
            else:
                bot_functions.send_message(chat_id=user_id, text=bot_texts.get_illigalText())
            
        else:
            # parsing the message
            user_id, type, content, username, message_id = bot_functions.parse_message(msg)
            state = db.get_state(user_id)  
            if user_id in admins:
                admin_mesage = AdminMessage(user_id)
                if type == 1:
                    returned_state = admin_mesage.commandHandler(content)
            else:
                if len(state) == 0:
                    print("\n\n\n state = 0\n\n\n")
                    state = 0
                else:
                    state, = state[0]
                print(" \n\n type = ", state, " \n\n")
                # bot_functions.send_message(chat_id=chat_id, text=state)    
                ligal = Semaphore.is_ligal(content, user_id, state)
                if ligal:
                    if type == 1:
                        returned_state = bot_functions.commandHandler(user_id, content)
                        db.update_state(user_id, returned_state)
                        print("\n\n\n state updated : {} \n\n\n".format(returned_state))
                    else:
                        returned_state = bot_functions.regularTextHandler(user_id, content, message_id)
                        db.update_state(user_id, returned_state)
                else:
                    bot_functions.send_message(chat_id=user_id, text=bot_texts.get_illigalText())
    elif 'callback_query' in msg.keys():
        handler = InLineKeyboardHandler(msg)
        handler.execute()
    return Response('ok', status=200)
Esempio n. 16
0
def text_handler(message):
	if message.chat.type != 'private':
		bot.send_message(message.chat.id, 'Я працюю лише в особистих повідомленнях!')
		return
	user = database.get_user(message.chat.id)
	if not user:
		bot.send_message(message.chat.id, 'Натисни /start, щоб почати.')
		return
	if user['state'] == 'init':
		database.update_user(message.chat.id, 'user_name', message.text)
		database.update_state(message.chat.id, 'waiting_for_phone')
		bot.send_message(message.chat.id, 'Приємно познайомитись, ' + message.text + '! Тепер надішли мені свій номер телефону (або 0, якщо не хочеш давати його) щоб наші оператори могли з тобою зв\'язатися.')
		return
	elif user['state'] == 'waiting_for_phone':
		if message.text == '0':
			database.update_state(message.chat.id, 'menu')
			bot.send_message(message.chat.id, 'Не проблема. Список команд знайдеш за допомогою /help.')
			send_menu_message(message)
			return
		if not check_number(message.text):
			bot.send_message(message.chat.id, 'Формат номеру має відповідати одному з двох:\n1. +380XXXXXXXXX\n2. 0XXXXXXXXX')
			return
		database.update_user(message.chat.id, 'user_phone', message.text) # TODO валидация
		database.update_state(message.chat.id, 'menu')
		bot.send_message(message.chat.id, 'Дякую! Список команд ти можеш знайти за допомогою /help.')
		send_menu_message(message)
		return
	elif user['state'] == 'change_name':
		text = 'Дуже добре, ' + message.text + '.'
		database.update_state(message.chat.id, 'menu')
		database.update_user(message.chat.id, 'user_name', message.text)
		bot.send_message(message.chat.id, text)
		send_menu_message(message)
		return
	elif user['state'] == 'change_phone':
		if message.text == '0':
			database.update_state(message.chat.id, 'menu')
			database.update_user(message.chat.id, 'user_phone', '0')
			bot.send_message(message.chat.id, 'Не проблема. Твій номер видалено з бази. Список команд знайдеш за допомогою /help.')
			send_menu_message(message)
			return
		if not check_number(message.text):
			bot.send_message(message.chat.id, 'Формат номеру має відповідати одному з двох:\n1. +380XXXXXXXXX\n2. 0XXXXXXXXX')
			return
		text = 'Тепер твій номер - ' + message.text + '.'
		database.update_state(message.chat.id, 'menu')
		database.update_user(message.chat.id, 'user_phone', message.text) # TODO валидация
		bot.send_message(message.chat.id, text)
		send_menu_message(message)
		return
	elif user['state'] == 'find_closest_type':
		types = recyclers.get_types()
		if message.text not in types:
			bot.send_message(message.chat.id, 'Вибери тип зі списку вище, будь-ласка.')
			return
		closest = recyclers.get_closest((user['pos_lon'], user['pos_lat']), message.text, 10)
		text = '\n'.join([str(elem[0]) + ', ' + str(elem[1]) for elem in closest])
		bot.send_message(message.chat.id, 'Найближчі до вас пункти:\n' + text)
		return
	elif user['state'] == 'leave_request_type':
		types = recyclers.get_types()
		if message.text not in types:
			bot.send_message(message.chat.id, 'Вибери тип зі списку вище, будь-ласка.')
			return
		database.init_request(message.chat.id)
		database.update_request(message.chat.id, 'type', message.text)
		database.update_state(message.chat.id, 'leave_request_amount')
		bot.send_message(message.chat.id, 'Чудово! Тепер назви обсяги разом із одиницями вимірювання. Наприклад, 12кг.')
		return
	elif user['state'] == 'leave_request_amount':
		database.update_request(message.chat.id, 'amount', message.text)
		database.update_state(message.chat.id, 'leave_request_location')
		bot.send_message(message.chat.id, 'А тепер надішли мені свою геопозицію за допомогою скріпки знизу.')
		return
	else:
		bot.send_message(message.chat.id, 'Натисни /menu для того, щоб почати, або /help, щоб побачити всі доступні команди.')
		return
Esempio n. 17
0
def change_phone(message):
	if not user_check_routine(message):
		return
	bot.send_message(message.chat.id, 'Надішли мені новий номер телефону або 0, якщо не хочеш давати його.')
	database.update_state(message.chat.id, 'change_phone')