Example #1
0
def send_message_request(sock, current_user):
    '''
    Method is executed once a user has indicated that they wish to
    send a message to another user.
    Prompts user for details of this message, and sends it.

    :param sock: Socket object of connection to client.
    :param current_user: string, sending user's username.
    '''
    while True:
        print '''
        Enter the username of the user who you would like to send a
        message to. Usernames are five characters long.
        '''
        receiving_user = raw_input()
        if len(receiving_user) == 5:
            break

    print(
        "Enter the message you'd like to send to this user. "
        "Messages are limited to 1008 characters.")
    message = raw_input("you to %s:" % receiving_user)
    while len(message) > 1008:
        message = raw_input("you to %s:" % receiving_user)

    payload_len = (2 * config.username_length) + len(message)
    fmt_str = config.request_body_fmt['\x30'] % len(message)
    send_message(
        '\x01' + pack('!I', payload_len) + '\x30' +
        pack(fmt_str, current_user, receiving_user, message), sock)
Example #2
0
def on_vote():
    print(request.headers)
    if request.headers.get('Authorization') == tok.WEBHOOKTOKEN:
        data = request.json

        try:
            user = int(data['user'])

        except Exception as E:
            return jsonify({'success': False})
        try:
            member = db.get_user(user)
            db.inc_user(user, "xp", 70)
            db.inc_user(user, "votes", 1)
            if "voter" not in member["badges"]:
                db.add_badge(user, "voter")
                config.send_message(
                    config.VOTECHANNEL, member["name"] +
                    " voted and got 70 tokens plus the voter badge!")
            else:
                config.send_message(
                    config.VOTECHANNEL,
                    member["name"] + " voted and got 70 tokens!")
        except Exception as E:
            pass

        return jsonify({'success': True})
    else:
        return jsonify({'success': False})
Example #3
0
def deliver_request_success(conn, username):
    '''
    Message sent from the client to the server indicating that a
    chat message has successfully been recvd by the client and displayed.

    :param conn: Socket object representing connection to server.
    :param username: current user logged in, to whom delivery succeeded.
    '''
    send_message(
        '\x01' + pack('!I', 5) + '\x81' +
        pack(config.request_body_fmt['\x81'], username), conn)
Example #4
0
def logout_request(conn, username):
    '''
    Sends logout request to the server containing the username to be
    removed from the active_clients list

    :param conn: connection to server
    :param username: current_user variable to be removed from active_clients
    list
    '''
    print "\nLOGGING OUT \n"
    send_message(
        '\x01' + pack('!I', 5) + '\x60' +
        pack(config.request_body_fmt['\x60'], username), conn)
Example #5
0
def deliver_request_failure(conn, reason):
    '''
    Message sent from the client to the server indicating that a
    chat message has not successfully been recvd by the client and displayed.

    :param conn: Socket object representing connection to server.
    :param reason: A string indicating why the delivery might have failed, for
    example the user logged in is not the one for whom the message was
    intended.
    '''
    send_message(
        '\x01' + pack('!I', len(reason)) + '\x82' +
        pack(config.request_body_fmt['\x82'] % len(reason), reason), conn)
Example #6
0
def delete_request(conn, username):
    '''
    If the user is logged in, then indicate that they are deleting their
    own account by setting own = "T". Otherwise, retrieve the input of which
    account they want to delete. Pack and send to server.

    :param username: current_id from client side
    '''
    if username:
        print "\nDELETING YOUR ACCOUNT \n"
        own = "T"
    else:
        username = raw_input(
            'Enter the username of the account to be deleted: ')
        own = "F"
    username += own
    print "here"
    send_message(
        '\x01' + pack('!I', 6) + '\x70' +
        pack(config.request_body_fmt['\x70'], username), conn)
Example #7
0
def login_request(conn):
    '''
    Prompts user to input an existing username. Repeats prompt if username
    does not follow the specs of being alphanumeric and exactly 5 characters
    long. Packs and send the message to the server.

    :param conn: connection to the server
    '''
    print "\nLOGGING IN \n"
    print "Enter your username"
    while True:
        userInput = raw_input('>> ')
        if (userInput.isalnum() and len(userInput) == 5):
            username = userInput
            break
        print "We only support usernames that are alphanumeric and exactly 5 characters long. \nPlease try again."

    send_message(
        '\x01' + pack('!I', 5) + '\x20' +
        pack(config.request_body_fmt['\x20'], username), conn)
Example #8
0
def create_request(conn):
    '''
    Prompts user to input an original username. Repeats prompt if username
    does not follow the specs of being alphanumeric and exactly 5 characters
    long. Packs and send the message to the server.

    :param conn: connection to the server
    '''
    print "\nCREATING AN ACCOUNT \n"
    print "enter a an alphanumeric username five characters long:"
    while True:
        userInput = raw_input('>> ')
        if (userInput.isalnum() and len(userInput) == 5):
            username = userInput
            break
        print "We only support usernames that are alphanumeric and exactly 5 characters long. \nPlease try again."

    send_message(
        '\x01' + pack('!I', 5) + '\x10' +
        pack(config.request_body_fmt['\x10'], username), conn)
Example #9
0
def list_request(conn):
    '''
    Requests user to make a selection from functions. Set the
    regular expression accordingly. Pack and send to server
    '''
    raw = raw_input('''
        Choose from the following options:
        0) List all users
        1) List users whose username match a specified regular expression.

        Please enter your choice below.
        ''')
    if raw == str(0):
        print "\nLISTING ALL ACCOUNTS \n"
        regexp = ".*"
    else:
        regexp = raw_input("Enter the regexp used to search the user list.")

    send_message(
        '\x01' + pack('!I', len(regexp)) + '\x50' +
        pack(config.request_body_fmt['\x50'] % len(regexp), regexp), conn)
Example #10
0
    def deliver_pending_messages(self, receiving_username, lock, sock):
        '''
        Delivers all pending messages for a given user to a client.
        Fails if the account does not exist, or if delivery to the client
        is responded to with an error message.

        :param receiving_username: username of the user whose pending messages
        should be dequeued and sent over the socket.
        :param lock: lock object that should be acquired before any
        messages are sent over the socket.
        :param sock: socket object over which to send messages,

        :return: tuple of (boolean, String).
                 Returns (True, "") if the request succeeds, and
                 (False, failure-reason) if the request fails.
        '''
        if not self.account_exists(receiving_username):
            return (False, "account %s does not exist." % receiving_username)
        logging.info("waiting for lock on pending messages for %s" %
                     receiving_username)
        with self.__pending_messages[receiving_username][0]:
            logging.info("waiting for lock on client thread")
            with lock:
                dq = self.__pending_messages[receiving_username][1]
                while dq:
                    config.send_message(dq[0], sock)
                    client_message = get_client_message(sock)
                    if not client_message:
                        print "connection with client dropped"
                        thread.exit()
                    _, payload_len, opcode, buf = client_message

                    if opcode != '\x81':
                        return (False, "Delivery failed." + reason_string(buf))
                    dq.popleft()

        return True, ""
        update_id, chat_id, chat_user, command, update_time = parse_message(
            last_msg)  #tra ve chat_id va lenh sau khi nhan duoc chuoi json
        chat_id = str(chat_id)
        #check time : neu thoi gian nhan tin nhan va thoi gian thuc te khong bang nhau thi khong gui tin nua
        # kiem tra so giay tu 01-01-1970 tu telegram va he thong
        ticks = round(time.time())
        if (ticks - update_time) < TIME_OFFSET:
            if update_id != update_id_readed:
                # neu message da doc roi thi ko lam gi ca
                update_id_readed = update_id

                print(chat_id, chat_user, command)
                list_commands = ('start', 'stop', 'help', 'status', 'quit')

                if command not in list_commands:
                    config.send_message(chat_id, 'Wrong command')
                    # return Response('ok',status=200)

                elif command == 'start':
                    write_user(chat_id, chat_user, 'No')
                    if var_status:  # if bot disable send other message
                        mes_send = mes_start
                    else:
                        mes_send = mes_status_dis

                    config.send_message(chat_id, mes_send)
                    #message to admin to ask to add an user to list people, these  will receive notification
                    mess_admin = '  There is a person, who wants to receive \
notification from the climate camera.\n - User_name : {} \n - Id : {}.'\
.format(chat_user,  chat_id )
                    if len(chat_id_admin) > 0: