Ejemplo n.º 1
0
    def on_enter_future_date(self, event):
        text = event.message.text
        split_date = text.split('~')
        start = check_date_format(split_date[0])[1]
        end = check_date_format(split_date[1])[1]
        s = start[4]
        start = datetime.strptime(start, f'%Y{s}%m{s}%d')
        end = datetime.strptime(end, f'%Y{s}%m{s}%d')
        if (end - start).days < 5:
            df = querl_sql(start, end, False)
            isday = False
        else:
            df = querl_sql(start, end, True)
            isday = True
        if df.empty:
            content = '查無資料請重新輸入'
            send_message(event, TextSendMessage(text=content))
            self.go_back_future(event)
        else:
            # plot
            plot_kbar(df, True, fig_path, isday)
            # -- upload
            # imgur with account: [email protected]

            client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
            print("Uploading image... ")
            image = client.upload_from_path(fig_path, anon=True)
            print("Done")

            url = image['link']
            image_message = ImageSendMessage(original_content_url=url,
                                             preview_image_url=url)
            send_message(event, image_message)
            print('查詢結束回到初始狀態')
            self.go_init(event)
Ejemplo n.º 2
0
def handle_question_answer(update, context, is_free_choice):
    current_question = context.user_data["current_question"]
    is_correct = utils.is_correct(utils.message_to_text(update, context),
                                  current_question.answers,
                                  no_answer_options=is_free_choice)
    if is_correct is None:
        send_message(texts.common.FAILED_TO_PARSE, update, context)
        return
    if is_correct:
        send_message(current_question.right_text, update, context)
        case = random.choice(data.cases)
        context.user_data["current_case"] = case

        body_text = case.body
        answers_text = "\n".join(
            f"{letter}. {answer}" for letter, answer in zip(
                answer_numbers, [a.text for a in case.choices]))
        text = f"{body_text}\n{answers_text}\nЧто ты выберешь?"
        send_message(text, update, context)
        return states.DECISION_CHOICE_STATE
    else:
        send_message(current_question.wrong_text, update, context)
        if utils.has_more_questions(update, context):
            send_message(texts.question.HAS_MORE_QUESTIONS, update, context)
            state = send_question(update, context)
            return state
        else:
            return states.NO_MORE_QUESTIONS_STATE
Ejemplo n.º 3
0
def process_image(messaging_event):
    user = get_user_or_signup(messaging_event)
    ans = model.predict_by_url(
        messaging_event["message"]["attachments"][0]["payload"]["url"])
    print(json.dumps(ans, indent=4))
    product_type = str(ans["outputs"][0]["data"]["concepts"][0]["name"])
    if product_type != "food":
        value = get_price(product_type)
    else:
        food_ans = model_food.predict_by_url(
            messaging_event["message"]["attachments"][0]["payload"]["url"])
        product_type = get_food_type(
            food_ans["outputs"][0]["data"]["concepts"])
        value = get_food_price(product_type)
        print(json.dumps(food_ans, indent=4))

    utils.send_message(
        messaging_event["sender"]["id"],
        "You sent me {} and I think it is worth {}".format(
            product_type, value))
    save_trash_to_database(user, product_type, value)

    if (value >= 30):
        if (user.kijiji_email != ""
                and user.kijiji_email) and (user.kijiji_password
                                            and user.kijiji_password != ""):
            suggest_kijiji(messaging_event)
        else:
            suggest_kijiji_link(messaging_event)
    else:
        utils.send_message(user.fb_id, "Waste is now saved")
Ejemplo n.º 4
0
def request_chunk_from_storage(storage_ip, chunk_path):
    sock = socket.socket()
    sock.connect((storage_ip, 9005))
    send_message(sock, chunk_path)
    response = recv_message(sock)
    sock.close()
    return response
Ejemplo n.º 5
0
    def on_enter_strategy_date(self, event):
        text = event.message.text
        split_date = text.split('~')
        start = check_date_format(split_date[0])[1]
        end = check_date_format(split_date[1])[1]
        s = start[4]
        start = datetime.strptime(start, f'%Y{s}%m{s}%d')
        end = datetime.strptime(end, f'%Y{s}%m{s}%d')
        num = user_strategy_num[event.source.user_id]
        df = pd.read_pickle(f'./strategy/strategy_{num}.pkl')
        df = df[(df.Date >= start) & (df.Date <= end)]
        df['ROI'] -= df['ROI'][0]
        if df.empty:
            content = '查無資料請重新輸入'
            send_message(event, TextSendMessage(text=content))
            self.go_back_future(event)
        else:
            # plot
            plot_roi(df, True, fig_path)
            # -- upload
            # imgur with account: [email protected]

            client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
            print("Uploading image... ")
            image = client.upload_from_path(fig_path, anon=True)
            print("Done")

            url = image['link']
            image_message = ImageSendMessage(original_content_url=url,
                                             preview_image_url=url)
            send_message(event, image_message)
            print('查詢結束回到初始狀態')
            self.go_init(event)
Ejemplo n.º 6
0
def book_uber(user, fare_id, **args):
    s = {}
    if "start_place_id" in args:
        s["start_place_id"] = args["start_place_id"]
        if "end_place_id" in args:
            s["end_place_id"] = args["end_place_id"]
        else:
            s["end_latitude"] = args["end_latitude"]
            s["end_longitude"] = args["end_longitude"]
    else:
        if "end_place_id" in args:
            s = {
                "start_latitude": args['start_latitude'],
                "start_longitude": args["start_longitude"],
                "end_place_id": args["end_place_id"]
            }
        else:
            s = {
                "start_latitude": args['start_latitude'],
                "start_longitude": args["start_longitude"],
                "end_latitude": args["end_latitude"],
                "end_longitude": args["end_longitude"]
            }
    s["fare_id"] = fare_id
    res = base_service.authorized_curl(
        "-X POST -H 'Content-Type: application/json' 'https://sandbox-api.uber.com/v1.2/requests' -d '{}'"
        .format(json.dumps(s)), user)
    if "status" in res:
        return utils.send_message(
            "Uber booked!\nStatus:{}\nDriver:{}\nVehicle:{}".format(
                res['status'], res["driver"], res["vehicle"]))
    elif "errors" in res:
        return utils.send_message("Title:{}".format(res["errors"][0]["title"]))
Ejemplo n.º 7
0
def send_email(user, **args):
    reply = False
    if "message_id" in args:
        reply = True
        message = get_message(args["message_id"], user)
        args["to_email"] = get_from(message)
        args["subject"] = "Re: " + get_subject(message)
    draft_message = "To: " + args["to_email"] + "\r\n" + "From: <" + get_user_email(
        user
    ) + ">\r\n" + "Subject: " + args[
        "subject"] + "\r\n" + "Content-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n" + args[
            "body"] + "\r\n"
    print("=====")
    print(draft_message)
    print("=====")
    encodedMail = base64.b64encode(draft_message).replace("+", "-").replace(
        "//", "_")
    url = "https://www.googleapis.com/gmail/v1/users/me/messages/send"
    res = base_service.authorized_curl(
        "'{}' --data '{}' -H 'Content-Type: application/json'".format(
            url, json.dumps({"raw": encodedMail})), user)

    if "id" in res:
        return utils.send_message("{}!\n{}".format(
            "Replied" if reply else "Message sent",
            format_gmail_message(get_message(res["id"], user))))
    else:
        return utils.send_message("Email sending failed")
Ejemplo n.º 8
0
    def test_serialized_data_length_in_header(self):
        """
        The data header is formed by:
        <serialized data digest> <serialized data length>\n
        """
        mock_digest = self.mocker.mock()
        mock_pickle = self.mocker.mock()
        mock_digest(mocker.ANY)
        self.mocker.result('e5fcf4f4606df6368779205e29b22e5851355de3')

        mock_pickle.HIGHEST_PROTOCOL
        self.mocker.result('foo')

        mock_pickle.dumps(mocker.ANY, mocker.ANY)
        self.mocker.result('serialized-data-byte-string')

        self.mocker.replay()

        stream = StringIO()

        utils.send_message(stream, 'message', mock_digest, pickle_dep=mock_pickle)

        self.assertEqual(
            int(stream.getvalue().split('\n')[0].split(' ')[1]),
            len('serialized-data-byte-string')
        )
Ejemplo n.º 9
0
def choose_name_state_callback(update, context):
    company_name = utils.message_to_text(update, context)
    context.user_data["company_name"] = company_name
    send_message(texts.onboarding.CHOSE_NAME.format(name=company_name), update,
                 context)
    state = handlers.question.send_question(update, context)
    return state
Ejemplo n.º 10
0
def miss_event(update, context):
    chat_id = update.effective_chat.id
    event_args = context.args
    db_connector, events_col = db_handler('event')
    if len(event_args) != 1:
        message = f"Invalid message, the only parameter should be the event name."
        return send_message(context, chat_id, message)
    event_name = event_args[0]
    query = {"name": event_name.lower(), "chat_id": chat_id}
    event = events_col.find_one(query)
    if not event:
        message = f"Event {event_name} not found."
        return send_message(context, chat_id, message)
    not_assisting_users = event['not_assisting']
    participants = event['participants']

    not_assisting_user = create_participant(update.message.from_user)

    if not_assisting_user['id'] not in [not_assisting_user['id'] for not_assisting_user in not_assisting_users]:
        events_col.update_one(query, {"$push": {'not_assisting': not_assisting_user}}, upsert=False)

    if not_assisting_user['id'] in [participant['id'] for participant in participants]:
        events_col.update_one(query, {"$pull": {'participants': not_assisting_user}}, upsert=False)

    message = f"{not_assisting_user['name']} will not assist {event['name'].capitalize()}"
    return send_message(context, chat_id, message)
Ejemplo n.º 11
0
def conversation(username):
    if request.method == "GET":
        conversations = session['conversations']
        now_read = conversations[username]['unread_count'] #newly read messages
        
        conversations[username]['unread_count'] = 0 #this conversation now has all conversations read
        for message in conversations[username]['messages']:
            message['unread'] = False
        
        count_unread = session['count_unread'] - now_read

        if session['type'] == "tutor":
            update_tutor(session['email'], {'conversations':conversations, 'count_unread':count_unread}, db)
        else:
            update_tutee(session['email'], {'conversations':conversations, 'count_unread':count_unread}, db)
        session['count_unread'] = count_unread
        session['conversations'] = conversations

        convo = conversations[username]['messages']
        return render_template("inbox.html", username = username, convo = convo)
    if request.method == "POST":
        if request.form['s'] == "Log Out":
            return logout()
        if request.form['s'] == "Send Message":
            message = send_message(request.form, session, db)
            flash(message)
            return redirect("inbox/%s"%username)
        if request.form['s'] == "Reply":
            print request.form
            message = send_message(request.form, session, db)
            flash(message)
            return redirect("inbox/%s"%username)
Ejemplo n.º 12
0
def play_spotify_intent(user, event):
    slots = event["currentIntent"]["slots"]
    song = slots["song"]
    album = slots["album"]
    artist = slots["artist"]
    if song != None:
        if artist != None:
            searched_song = search_song_by_artist(user, song, artist)
        else:
            searched_song = search_song(user, song)
        if searched_song:
            return play_tracks_intent(user, [searched_song["uri"]],
                                      get_track_info(searched_song))
        else:
            #todo remove no result json
            return utils.send_message("No results found!")
    elif album != None:
        searched_album = search_album(user, album)
        if searched_album:
            return play_context_intent(
                user, searched_album["uri"],
                "Playing album {}".format(searched_album["name"]))
        else:
            return utils.send_message("No results found!")
    elif artist != None:
        searched_artist = search_artist(user, artist)
        if searched_artist:
            return play_context_intent(
                user, searched_artist["uri"],
                "Playing artist {}".format(searched_artist["name"]))
        else:
            return utils.send_message("No results found!")
    return play_intent_spotify(user)
Ejemplo n.º 13
0
    def create_message(self):
        to = input('Введите получателя сообщения: ')
        message = input('Введите сообщение для отправки: ')

        # Проверим, что получатель существует
        with database_lock:
            if not self.database.check_user(to):
                logger.error(
                    f'Попытка отправить сообщение незарегистрированому получателю: {to}'
                )
                return
        message_dict = {
            'action': 'message',
            'from': self.account_name,
            'to': to,
            'time': time.strftime("%d-%m-%Y %H:%M:%S", time.localtime()),
            'mess_text': message
        }
        logger.debug(f'Сформирован словарь сообщения: {message_dict}')
        # Сохраняем сообщения для истории
        with database_lock:
            self.database.save_message(self.account_name, to, message)

        # Необходимо дождаться освобождения сокета для отправки сообщения
        with sock_lock:
            try:
                send_message(self.sock, message_dict)
                logger.info(f'Отправлено сообщение для пользователя {to}')
            except OSError as err:
                if err.errno:
                    logger.critical('Потеряно соединение с сервером.')
                    exit(1)
                else:
                    logger.error(
                        'Не удалось передать сообщение. Таймаут соединения')
Ejemplo n.º 14
0
 def test_send_message(self):
     test_socket = TestSocket(self.test_message_send)
     send_message(test_socket, self.test_message_send, self.CONFIGS)
     self.assertEqual(test_socket.encoded_message,
                      test_socket.received_message)
     with self.assertRaises(Exception):
         send_message(test_socket, test_socket, self.CONFIGS)
Ejemplo n.º 15
0
def clients_commands(conn):
    while True:
        request = recv_message(conn)
        print request
        sys.stdout.flush()
        req = request.split()
        client_pwd = req[0]
        command = req[1]
        args = req[2:]
        response = "nothing"

        if command == "quit":
            conn.close()
            break
        elif command == "pwd":
            response = pwd(client_pwd)
        elif command == "ls":
            response = ls(client_pwd, args)
        elif command == "cd":
            response = cd(client_pwd, args)
        elif command == "mkdir":
            response = mkdir(client_pwd, args)
        elif command == "cp":
            response = cp(client_pwd, list(connected_storages), args)
        elif command == "rm":
            response = rm(client_pwd, args)
        elif command == "stat":
            response = stat(client_pwd, args)
        elif command == "cat":
            response = cat(client_pwd, connected_storages, args)
        elif command == "init":
            response = init(client_pwd, args)

        send_message(conn, response)
Ejemplo n.º 16
0
def main():
    global CONFIGS
    CONFIGS = load_configs(is_server=False)
    try:
        server_address = sys.argv[1]
        server_port = int(sys.argv[2])
        if not 65535 >= server_port >= 1024:
            raise ValueError
    except IndexError:
        server_address = CONFIGS.get('DEFAULT_IP_ADDRESS')
        server_port = CONFIGS.get('DEFAULT_PORT')
    except ValueError:
        print('The port should be in the range of 1024 and 65535')
        sys.exit(1)

    transport = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    transport.connect((server_address, server_port))
    presence_message = create_presence_message('Guest')
    send_message(transport, presence_message, CONFIGS)
    try:
        response = get_message(transport, CONFIGS)
        handled_response = handle_response(response)
        print(f'The response from the server: {response}')
        print(handled_response)
    except (ValueError, json.JSONDecodeError):
        print('Error message decoding ')
Ejemplo n.º 17
0
 def reset(self):
     utils.send_message(self.sock,
                        gym_uds_pb2.Request(type=gym_uds_pb2.Request.RESET))
     state_pb = utils.recv_message(self.sock, gym_uds_pb2.State)
     observation = np.asarray(state_pb.observation.data).reshape(
         state_pb.observation.shape)
     return observation
Ejemplo n.º 18
0
def main():
    global CONFIGS
    CONFIGS = load_configs(is_server=False)
    try:
        server_address = sys.argv[1]
        server_port = int(sys.argv[2])
        if not 65535 >= server_port >= 1024:
            raise ValueError
    except IndexError:
        server_address = CONFIGS.get('DEFAULT_IP_ADDRESS')
        server_port = CONFIGS.get('DEFAULT_PORT')
    except ValueError:
        CLIENT_LOGGER.critical(
            f'The port should be specified in the range of (1024, 65535)')
        print('The port should be in the range of 1024 and 65535')
        sys.exit(1)

    transport = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    transport.connect((server_address, server_port))
    presence_message = create_presence_message('Guest', CONFIGS)
    CLIENT_LOGGER.info(f'Sending a message to the server')
    send_message(transport, presence_message, CONFIGS)
    try:
        response = get_message(transport, CONFIGS)
        handled_response = handle_response(response, CONFIGS)
        CLIENT_LOGGER.debug(f'The response were handled: {response}')
        CLIENT_LOGGER.info(f'The response were handled: {handled_response}')
        print(f'The response from the server: {response}')
        print(handled_response)
    except (ValueError, json.JSONDecodeError):
        CLIENT_LOGGER.critical(f'An error during decoding of server message')
        print('Error message decoding ')
Ejemplo n.º 19
0
def process_location(messaging_event):
    user = get_user_or_signup(messaging_event)
    coord = messaging_event["message"].get("attachments",
                                           [])[0]["payload"]["coordinates"]
    lat = coord["lat"]
    lng = coord["long"]
    if (utils.is_near_store(lat, lng)):
        after_time = datetime.utcnow() - timedelta(hours=30 * 24)
        transactions = DisposalTransaction.query.filter(
            DisposalTransaction.user_id == user.id).filter(
                DisposalTransaction.category != "electronics").filter(
                    DisposalTransaction.datetime >= after_time).all()
        cats = {}
        for t in transactions:
            cats.update({t.category: cats.get(t.category, 0) + t.value})
        catsList = sorted(cats.items(), key=lambda c: c[1], reverse=True)
        top3Cats = catsList[:min(len(catsList), 3)]
        utils.send_message(
            user.fb_id,
            "During the next grocery trip, consider your top three waste categories in your last month"
        )
        [
            utils.send_message(user.fb_id, "{}: ${}".format(c[0], c[1]))
            for c in top3Cats
        ]
Ejemplo n.º 20
0
def send(request):
	'''
	'''
	form = MessageSendForm()
	from_user = request.user
	to_user = None
	contact = None
	if request.method == 'GET':
		if 'to' in request.GET and request.GET['to']:
			username = request.GET['to']
			try:
				to_user = User.objects.get(username__iexact=username)
			except:
				pass
			else:
				if to_user == from_user:
					return HttpResponseRedirect(reverse('message_inbox'))
				try:
					contact = from_user.contact_list.filter(to_user=to_user)[0]
				except:
					contact = None
			
	elif request.method == "POST":
		form = MessageSendForm(request.POST)
		if form.is_valid():
			data = form.cleaned_data
			try:
				to_user = User.objects.get(username__iexact=data['send_to'])
			except:
				messages.error(request, u'用户不存在')
			else:
				if to_user == from_user:
					messages.error(request, u'不可以给自己发送私信')
					to_user = None
				else:
					message = data['message']
					send_message(from_user, to_user, message)
					contact = from_user.contact_list.filter(to_user=to_user)[0]
					return HttpResponseRedirect(reverse(conversation, 
					               kwargs={'contact_id': contact.id}))
		else:
			messages.error(request, u'发送失败')
			try:
				from_url = request.META['HTTP_REFERER']
				return HttpResponseRedirect(from_url)
			except KeyError:
				pass
	else:
		pass
	try:
		from_url = request.META['HTTP_REFERER']
	except:
		from_url = "/"
	return render_to_response('messages/send.html',
	                         {'form': form,
	                          'to_user': to_user,
	                          'from_url': from_url,
	                          'contact': contact,},
	                          context_instance=RequestContext(request))
Ejemplo n.º 21
0
    def on_enter_state5(self, event):
        print("I'm entering state5")

        reply_token = event.reply_token
        # reply_arr = []
        # reply_arr.append(TextSendMessage("https://www.thsrc.com.tw/"))
        # reply_arr.append(canmessage)
        send_message(reply_token, canmessage1)
Ejemplo n.º 22
0
 def on_enter_init(self, event):
     content = '基本功能:'
     content += '\n1.請先選擇你想知道的訊息,如果想知道台指期走勢請輸入期貨或future,如果想知道期貨機器人的交易表現請輸入策略或strategy\n'
     content += '\nVIP功能:'
     content += '\n1.每天晚上8點推播告知使用者明天期貨機器人的預測結果'
     content += '\n2.每天自動化爬蟲會到期交所爬近30日內的期貨tick資料,成功完成後會告知使用者'
     content += '\n3.監測自動化交易程式,當停損停利或建倉成功時以及有任何異常交易都會發訊息告知使用者'
     send_message(event, TextSendMessage(text=content))
Ejemplo n.º 23
0
def send_temperature_debug(temperature_reader):
    names = temperature_reader.sensor_names()
    values = temperature_reader.temperatures()
    lines = []
    for n, v in zip(names, values):
        lines.append("{0:16} {1:.2f}".format(n, v))
    message = "testshow \"" + "<br>".join(lines) + "\""
    send_message(message)
Ejemplo n.º 24
0
 def step(self, action):
     utils.send_message(self.sock,
                        gym_uds_pb2.Request(type=gym_uds_pb2.Request.STEP))
     utils.send_message(self.sock, gym_uds_pb2.Action(value=action))
     state_pb = utils.recv_message(self.sock, gym_uds_pb2.State)
     observation = np.asarray(state_pb.observation.data).reshape(
         state_pb.observation.shape)
     return observation, state_pb.reward, state_pb.done
Ejemplo n.º 25
0
def naming_commands(conn):
    request = recv_message(conn)
    filepath = request
    chunk_name = os.path.normpath(fake_root + filepath)
    chunk_data = ''
    with open(chunk_name, 'r') as chunk:
        chunk_data += chunk.read()
    send_message(conn, chunk_data)
Ejemplo n.º 26
0
 def go_to_idle():
     nonlocal activity, state_logger
     all_off()
     activity = Idle(logger)
     state_logger = None
     send_splash()
     send_message("ok")
     leave_test_mode()
Ejemplo n.º 27
0
def write_messages(client):
    while True:
        # Вводим сообщение с клавиатуры
        text = input('Отправить сообщение>')
        # Создаем jim сообщение
        message = create_message('Всем в чате: ', text)
        # отправляем на сервер
        send_message(client, message)
Ejemplo n.º 28
0
 def test_process_ans(self):
     server_address, server_port = DEFAULT_IP_ADDRESS, DEFAULT_PORT
     self.transport.connect((server_address, server_port))
     self.message_to_server = create_presence()
     send_message(self.transport, self.message_to_server)
     self.answer = get_message(self.transport)
     self.assertEqual(self.answer[RESPONSE], 200)
     self.transport.close()
Ejemplo n.º 29
0
 def set_temperatures(self, temperatures):
     if len(temperatures) > 0:
         ave = average(temperatures)
         send_message("temp " + str(ave))
         if self.temperature_log is not None:
             self.temperature_log.log_temperatures(temperatures, ave)
         return ave
     return math.nan
def decode_last_char(c_text, block_size):
    """
    Toma un texto cifrado, y tamaño de bloque
    Retorna el último byte del mensaje original del texto cifrado
    :param c_text: byte-like message
    """
    error_mssg = "pkcs7"                                    # Prefijo de error típico de padding
    blocks_array = utils.split_blocks(c_text, block_size//8)# Get cyphered text as an bytearray
    n = len(blocks_array)                                   # Cantidad n de bloques
    b = block_size//8                                       # Cantidad b de bytes por bloque
    
    m_n1 = bytearray(b)                                     # Crea bytearray de largo 128//8 = 16 bytes
    for i in range(0, b - 1):                               # Copia del byte 0 al 15
        m_n1[i] = blocks_array[n-2][i]                      # Obtener M[n-1] copiando de C[n-1]

    i = 1                                                   # De 0 a 256
    # print("Decode last char", flush = True)
    ant_mn1 = m_n1[b-1] 
    while True:
        if (ant_mn1 == i):
            pass
        else:
            #print(i, flush=True)
            m_n1[b-1] = i                                       # M[n-1][BlockSize-1] = i
            blocks_array[n-2] = m_n1                            # Sobrescribimos el blocks_Array[n-2] por el M[n-1]
            modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array)) # Joinblocks and then cast to hex
            resp = utils.send_message(sock_B_input, sock_B_output, modified_c_text) # Send to sock_B
            #print(resp, flush=True)
            if not resp.startswith(error_mssg):                 # Check if there is not a padding error, we have a candidate
                                                                  # Validar: Asegurar que texto plano termina en 0x01
                #print("Validando... ")
                ant = m_n1[b-2]                                 # M[n-1][b-2] penúltimo valor antiguo
                m_n1[b-2] = (ant+125) % 256                       # Cambiar a otro valor
                blocks_array[n-2] = m_n1                        # Modificamos M[n-2]
                modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))   # Joinblocks and then cast to hex
                resp = utils.send_message(sock_B_input, sock_B_output, modified_c_text) # Acá tenemos que el texto descifrado es del estilo [.....[0xfe][0x01]]

                if resp.startswith(error_mssg):                          # Si no validó estamos en un caso donde podríamos haber encontrado un falso positivo, ej: que el último byte descifrado fuera [0x02] y el byte anterior cifrado [0x02]. Ahora da [...[0xfe][0x02]] y no pasa
                    #print("No valida, falso positivo encontrado, valor encontrado para M[n-1][b-1] incosistente, buscando otro valor ...")
                    m_n1[b-2] = ant                             # Always Revert al valor C[n-1][b-2] original
                    blocks_array[n-2] = m_n1
                    modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
                else:
                    m_n1[b-2] = ant                             # Always Revert
                    blocks_array[n-2] = m_n1
                    modified_c_text = utils.bytes_to_hex(utils.join_blocks(blocks_array))
                    break                                       # Pasó validación, encontramos M[n-1][b-1]
        
        if(i == 0):
            print("Se han probado los 256 valores de padding sin éxito")
            exit(1)

        i = (i+1)%256
    
    i_n = i^1 # XOR para obtener I_[n][b-1]. i = M[n-1][b-1], 1 = 0x01
    c_n1_b1 = utils.split_blocks(c_text, block_size//8)[n-2][b-1] # Get clean C[n-2][b-1]
    #print(i_n^c_n1_b1)
    return i_n, i_n^c_n1_b1 # XOR para obtener B_[n][b-1]
Ejemplo n.º 31
0
 def process_message(self, message, listen_socks):
     if message['to'] in self.names and self.names[message['to']] in listen_socks:
         send_message(self.names[message['to']], message)
         logger.info(f'Отправлено сообщение пользователю {message["to"]} от пользователя {message["from"]}.')
     elif message['to'] in self.names and self.names[message['to']] not in listen_socks:
         raise ConnectionError
     else:
         logger.error(
             f'Пользователь {message["to"]} не зарегистрирован на сервере, отправка сообщения невозможна.')
Ejemplo n.º 32
0
 def reset(self):
     observation = self.env.reset()
     observation_pb = gym_uds_pb2.Observation(data=observation.ravel(),
                                              shape=observation.shape)
     utils.send_message(
         self.sock,
         gym_uds_pb2.State(observation=observation_pb,
                           reward=0.0,
                           done=False))
Ejemplo n.º 33
0
 def test_send_mes(self):
     # подменяем настоящий сокет нашим классом заглушкой
     # зоздаем сокет, он уже был подменен
     sock = ClientSocket()
     # т.к. возвращаемого значения нету, можно просто проверить, что метод отрабатывает без ошибок
     self.assert_(send_message(sock, {'test': 'test'}) is None)
     # и проверяем, чтобы обязательно передавали словарь на всякий пожарный
     with self.assertRaises(TypeError):
         send_message(sock, 'test')
Ejemplo n.º 34
0
def message_view(request):
    patient = Patient.objects.get(pk=request.user.doctor.current_patient_id)
    if (request.method == "POST"):
        doctor_email = request.user.email
        send_message(doctor_email, request.POST['body'], patient)
        messages.success(request, 'Message sent!')
        return redirect('patients_app:message')

    message = 'Hi Dr. {0}, \n\n\n\nBest Regards,\n{1} {2}'.format(
        request.user.last_name, patient.first_name, patient.last_name
    )
    return render(request, 'patients_app/message.html', {'message': message})
Ejemplo n.º 35
0
 def form_valid(self, form):
     self.object = form.save(commit=False)
     self.object.application = self.application
     self.object.event = AUDIT_EVENT_MESSAGE
     self.object.user = self.request.user
     self.object.save()
     if not self.application.user == self.request.user:
         try:
             send_message(self.application, 'message', note=self.object.text)
         except:
             pass
     return HttpResponseRedirect(self.get_success_url())
Ejemplo n.º 36
0
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.application = self.application
        self.object.user = self.request.user
        self.object.event = self.audit_event_type
        self.object.save()

        self.object.application.status = self.application_change_status
        self.object.application.save(user=self.request.user)

        try:
            send_message(self.object.application, self.message_template_name, note=self.object.text)
        except:
            pass
        return HttpResponseRedirect(self.get_success_url())
Ejemplo n.º 37
0
    def test_serialized_data_digest_in_header(self):
        """
        The data header is formed by:
        <serialized data digest> <serialized data length>\n
        """
        mock_digest = self.mocker.mock()
        mock_digest(mocker.ANY)
        self.mocker.result('e5fcf4f4606df6368779205e29b22e5851355de3')
        self.mocker.replay()

        stream = StringIO()

        utils.send_message(stream, 'message', mock_digest)
        self.assertEqual(
            stream.getvalue().split('\n')[0].split(' ')[0],
            'e5fcf4f4606df6368779205e29b22e5851355de3'
        )
Ejemplo n.º 38
0
    def handle_events(self, job_queue):
        while True:
            filepath = job_queue.get()
            logger.debug('Started handling event for %s' % filepath)

            try:
                attempt = checkin.get_attempt(filepath)

            except ValueError as e:
                try:
                    utils.mark_as_failed(filepath)
                except OSError as e:
                    logger.debug('The file is gone before marked as failed. %s' % e)

                logger.debug('Failed during checkin: %s: %s' % (filepath, e))

            except excepts.DuplicatedPackage as e:
                try:
                    utils.mark_as_duplicated(filepath)
                except OSError as e:
                    logger.debug('The file is gone before marked as duplicated. %s' % e)

            else:
                # Create a notification to keep track of the checkin process
                session = models.Session()
                checkin_notifier = self.CheckinNotifier(attempt, session)
                checkin_notifier.start()

                if attempt.is_valid:
                    notification_msg = 'Attempt ready to be validated'
                    notification_status = models.Status.ok
                else:
                    notification_msg = 'Attempt cannot be validated'
                    notification_status = models.Status.error

                checkin_notifier.tell(notification_msg, notification_status, 'Checkin')
                checkin_notifier.end()

                transaction.commit()

                #Send stream
                utils.send_message(self.stream, attempt, utils.make_digest)
                logging.debug('Message sent for %s: %s, %s' % (filepath,
                    repr(attempt), repr(utils.make_digest)))
Ejemplo n.º 39
0
    def test_stream_is_flushed(self):
        mock_stream = self.mocker.mock()

        mock_stream.write(mocker.ANY)
        self.mocker.result(None)
        self.mocker.count(2)

        mock_stream.flush()
        self.mocker.result(None)

        self.mocker.replay()

        self.assertIsNone(
            utils.send_message(mock_stream, 'message', utils.make_digest))
Ejemplo n.º 40
0
def profile(username):
    if request.method == "GET":
        user = find_user(username, db)
        flasher = {}
        for key in user:
            ##print(user[key].encode())
            flasher[key] = str(user[key]).decode('utf-8')   
        flash(flasher)
        #print 'username' + user['username']
        return render_template("profile.html", courses=user["courses"], subjects=user["subjects"])
    if request.method == "POST":
        if request.form['s'] == "Log Out":
            return logout()
        if request.form['s'] == "Send Message":
            message = send_message(request.form, session, db)
            flash(message)
            return redirect("inbox")
Ejemplo n.º 41
0
def homepage():
    user = find_user(session["username"], db)
    appts = user["appts"]
    print(appts)
    if request.method == "GET":
        return render_template("homepage.html", appts=appts)
    else:
        if 'b' in request.form:
            if request.form['b'] == 'Complete':
                appt = appts.pop(int(request.form['index']))
                flash("You have completed an appointment! Congrats")
                db.tutees.update( {'username' : appt['tutee'] }, { '$set' : {'appts' : appts} })
                db.tutors.update( {'username' : appt['tutor'] }, { '$set' : {'appts' : appts} })
                return render_template("homepage.html", appts=appts)
        if 's' in request.form:
            if request.form['s'] == "Log Out":
                return logout()
            if request.form['s'] == "Send":
                message = send_message(request.form, session, db)
                flash(message)
                return redirect("inbox")
Ejemplo n.º 42
0
def search():
        if request.method == "GET":
            return render_template("search.html") 
        else:
            print request.form
            if request.form['s'] == "Log Out":
                return logout() 
            if request.form['s'] == "Submit":
                print request.form

                if request.form['0-day'] == "":
                    print "You must select a day"
                if len(request.form.getlist("0-address")) == 0:
                    print "You must select at least one location"
                if (request.form['0-start_hour'] == "") | (request.form['0-end_hour'] == ""):
                    print "You must select an hour for starting and ending times"
                if (request.form['0-start_minute'] == "") | (request.form['0-end_minute'] == ""):
                    print "You must select a minute for starting and ending times"
                if (request.form['0-start_type'] == "") | (request.form['0-end_type'] == ""):
                    print "You must select a type for starting and ending times"
                    
                tutor_list = search_operation(request.form, db, session)
                tutor_list.reverse() #to put highest score at top
                return render_template("search_results.html", tutor_list=tutor_list)
            if request.form['s'] == "Send Message":
                message = send_message(request.form, session, db)
                flash(message)
                return redirect("inbox")

            if request.form['s'] == "Make Appointment":
                print(request.form)
                tutor_username = request.form['username']
                ## create_appointment    (tutor,          tutee,               subject,                 course)
                appt = create_appointment(tutor_username, session['username'], request.form["subject"], request.form["class"], request.form)
                ## print(appt)
                db.tutees.update( {'username' : session['username'] }, { '$addToSet' : {'appts' : appt} })
                db.tutors.update( {'username' : tutor_username      }, { '$addToSet' : {'appts' : appt} })
                flash("You have succesfully added your appt!")
                return redirect(url_for("homepage"))
Ejemplo n.º 43
0
 def process_IN_CLOSE_WRITE(self, event):
     attempt = checkin.get_attempt(event.pathname)
     utils.send_message(sys.stdout, attempt, utils.make_digest)
Ejemplo n.º 44
0
#
# Usage: python test_send_message.py username password <message>
#
# Example: python test_send_message.py laurinda laurinda "help me please"
#

from sys import argv
from utils import send_message

script, username, password, message = argv
response = send_message(username, password, message)
# print(response.json())
Ejemplo n.º 45
0
def start_collect(ip, remote_dir, local_dir, interval=30):
  try:
    cycle_run(lambda: FileCollector(ip, remote_dir, local_dir).run(), interval)
  except Exception:
    print traceback.format_exc()
    send_message('file_collector failed ...', TEL_LIST)