Exemplo n.º 1
0
def conv_view(conv_id=None):
    if not g.user:
        return show_message('You need to be logged in to see this page.')

    conversation = database.query_db(
        "select * from conversation where conversation_id=?", [conv_id],
        one=True)

    # posting a draft
    if request.method == 'POST':
        database.replace_message(request.form["text"], conv_id,
                                 g.user["user_id"], conversation["user2_id"])
        return redirect('/conv_view/' + conv_id)

    messages = database.query_db(
        "select * from message where conversation_id=? order by message_timestamp desc",
        [conv_id])

    hide_editor = False
    if len(messages) > 0:
        if time.time() > messages[0]['message_timestamp'] + datetime.timedelta(
                days=7).total_seconds():
            database.add_message(conv_id, messages[0]['receiver_id'],
                                 messages[0]['sender_id'],
                                 "Put a cool message here", time.time(), 0)
        if messages[0]['sender_id'] != g.user[
                'user_id']:  #Hide draft post if use does not own it
            messages.pop(0)
            hide_editor = True

    return render_template('conv_view.html',
                           conversation=conversation,
                           messages=messages,
                           hide_editor=hide_editor)
Exemplo n.º 2
0
def add_database(username,post_time,payload):
    ip = str(request.remote_addr)
    if ip not in ids :
        ids.append(ip)
    username = "******".format(username,str(ids.index(ip)))
    add_message(username,post_time,payload)
    return ""
Exemplo n.º 3
0
    def rx_privatemessage(self):
        print("privatemessage api called")
        target_username = cherrypy.request.json["target_username"]
        print("received: " + target_username)
        print("actual: " + username)
        target_pubkey = cherrypy.request.json["target_pubkey"]
        print("received: " + target_pubkey)
        print("actual: " + pubkey_hex_str)
        time_str = str(time.time())

        if (username == target_username and pubkey_hex_str == target_pubkey):

            certificate = cherrypy.request.json["loginserver_record"]
            sender_username = certificate[0:7]
            try:
                private_key_curve = signing_key.to_curve25519_private_key()
                unseal_box = SealedBox(private_key_curve)
                message_encrypted = bytes(
                    cherrypy.request.json["encrypted_message"],
                    encoding='utf-8')
                message_decrypted = unseal_box.decrypt(
                    message_encrypted, encoder=nacl.encoding.HexEncoder)
                message = message_decrypted.decode('utf-8')
                print(message)
                database.add_message(username, sender_username, message,
                                     time_str)
                return {'response': 'ok'}
            except nacl.exceptions.CryptoError:
                return {'response': 'not decrypted'}

        return {'response': 'wrong target user'}
Exemplo n.º 4
0
async def on_message(message):
    """This method execute when a new message come"""

    # check if the message is from the bot itself, don't change this
    if message.author == client.user:
        return

    # print new incoming message
    print('Message from {0.author}: {0.content}'.format(message))

    time = datetime.datetime.now()
    time = time.strftime("%Y-%m-%d %I:%M %p")

    create_table()
    add_message(message.author.name, message.content,
                message.author.guild.name, str(time))
    all_messages = get_all_messages()
    df = pd.DataFrame(all_messages)  # this is your dataframe

    # check if the message content matches with any of the keywords
    if str(message.content).startswith("?"):
        if message.content in keywords:

            pdf_file = get_output(query=message.content)
            print("PDF:", pdf_file)
            with open(pdf_file, 'rb') as f:
                await message.channel.send(
                    file=File(f, os.path.basename(pdf_file)))
            # await message.channel.send("a = " + str(a) + " b = "+str(b))
        else:
            await message.channel.send("Ticker doesn't exist.")
Exemplo n.º 5
0
def echo(bot, update):

    reply_markup = InlineKeyboardMarkup([[
        InlineKeyboardButton(LIKE_TEXT, callback_data='1'),
        InlineKeyboardButton(DISLIKE_TEXT, callback_data='2')
    ]])

    if update.channel_post.photo:
        text = update.channel_post.caption
        bot_msg = bot.send_photo(chat_id=CHANN_ID,
                                 disable_web_page_preview=True,
                                 reply_markup=reply_markup,
                                 caption=text,
                                 photo=update.channel_post.photo[-1].file_id)
    elif update.channel_post.document:
        text = update.channel_post.caption
        bot_msg = bot.send_document(
            chat_id=CHANN_ID,
            disable_web_page_preview=True,
            reply_markup=reply_markup,
            caption=text,
            document=update.channel_post.document.file_id)
    else:
        text = update.channel_post.text
        bot_msg = bot.send_message(chat_id=CHANN_ID,
                                   disable_web_page_preview=True,
                                   reply_markup=reply_markup,
                                   text=text)

    database.add_message(bot_msg.message_id, CHANN_ID, USERBOT_ID)
    bot.delete_message(CHANN_ID, update.channel_post.message_id)
Exemplo n.º 6
0
async def on_message(message):
    if message.author == client.user:
        return

    content = (message.attachments[0].proxy_url
               if message.attachments else message.content)

    database.add_message(message.guild.id, message.id, message.created_at,
                         content, message.author.id, message.channel.id)

    logger.info("({0.guild} - #{0.channel}) {0.author}: {1}", message,
                content, feature="f-strings")
Exemplo n.º 7
0
def send_message(db):

    message = request.forms.get("message")
    recipient = request.query['username']
    sender_id = users.get_userID(db)
    recipient_id = users.return_userID(db, recipient)

    print(message)

    if ((sender_id != None) and (recipient_id != None)):
        database.add_message(db, sender_id, recipient_id, message)
    else:
        if sender_id == None:
            print('Please sign in to send a message!')
        elif recipient_id == None:
            print('Invalid recipient username')
Exemplo n.º 8
0
def post_message():
    arg = request.args.to_dict()
    token = arg.get('token', None)
    content = arg.get('content', None)
    fromEmail = logged_in_users.get(token, None)

    if fromEmail:
        toEmail = arg.get('toEmail', None)
        toEmail = toEmail if toEmail else fromEmail
        if database.get_user_data_by_email(toEmail):
            database.add_message(fromEmail, toEmail, content)
            response = {'success': True, 'message': 'Message posted.'}
        else:
            response = {'success': False, 'message': 'No such user.'}
    else:
        response = {'success': False, 'message': 'You are not signed in.'}

    return jsonify(response)
Exemplo n.º 9
0
def _add_msg_content(msg):
    def add_thread():
        user_id = msg['user']
        page_url = user_to_page[user_id]
        page_threads[page_url].append(msg["message_thread_id"])
        add_message_thread(db, {
            "x": msg["x"],
            "y": msg["y"],
            "id": msg["message_thread_id"]
        })

    thread_id = msg["message_thread_id"]
    if thread_id not in thread_messages:
        add_thread()

    new_msg = {
        "user": msg["user"],
        "body": msg["body"],
        "timestamp": msg["timestamp"]
    }
    thread_messages[msg["message_thread_id"]].append(new_msg)
    add_message(db, new_msg, msg["message_thread_id"])
Exemplo n.º 10
0
def conv_view(conv_id=None):
    if not g.user: return show_message('You need to be logged in to see this page.')

    conversation = database.query_db("select * from conversation where conversation_id=?",
                                     [conv_id], one=True)

    # posting a draft
    if request.method == 'POST':
        database.replace_message(request.form["text"],conv_id,g.user["user_id"],conversation["user2_id"])
        return redirect('/conv_view/'+conv_id)

    messages = database.query_db("select * from message where conversation_id=? order by message_timestamp desc",
                                 [conv_id])

    hide_editor=False
    if len(messages)>0:
        if time.time() > messages[0]['message_timestamp'] + datetime.timedelta(days=7).total_seconds():
            database.add_message(conv_id,messages[0]['receiver_id'],messages[0]['sender_id'],"Put a cool message here",time.time(),0)
        if messages[0]['sender_id'] != g.user['user_id']:#Hide draft post if use does not own it
            messages.pop(0)
            hide_editor = True

    return render_template('conv_view.html', conversation=conversation, messages=messages, hide_editor=hide_editor)
Exemplo n.º 11
0
    def lineReceived(self, line):
        message = line.decode()
        if self.login and not (message.startswith('/login')
                               or message.startswith('/register')
                               or message.startswith('/change_user_data')
                               or message.startswith('/get_users')
                               or message.startswith('/get_info')):
            login = message.split('::')[1]
            date_time = message.split('::')[2]
            date, time = date_time.split()[0], date_time.split()[1]

            message = message.replace(f'{login}::', '')
            message = message.replace(f'::{date_time}', '')
            print(f'got message from {login} -> {message}')
            database.add_message(message, self.login, date_time)
            message = f'[{date} {time}]      <{self.login}>: {message}'
            for user in self.factory.clients:
                user.sendLine(message.encode())
        elif self.login and message.startswith('/change_user_data'):
            message = message.replace('/change_user_data ', '')
            edit_field = message.split()[0].strip()
            new_val = message.replace(edit_field, '').strip()
            if edit_field == 'login':
                database.edit_user_info(self.login, new_login=new_val)
                self.login = new_val
                self.sendLine(f'nickname changed {self.login}'.encode())
            if edit_field == 'password':
                database.edit_user_info(self.login, password=new_val)
                self.sendLine('password changed'.encode())
            if edit_field == 'country':
                database.edit_user_info(self.login, country=new_val)
            if edit_field == 'phone':
                database.edit_user_info(self.login, phone=new_val)
            if edit_field == 'website':
                database.edit_user_info(self.login, website=new_val)
            if edit_field == 'author':
                database.edit_user_info(self.login, author=new_val)
            if edit_field == 'quote':
                database.edit_user_info(self.login, quote=new_val)
        elif message == '/get_users':
            users = database.get_names()
            self.sendLine('/logins\n'.encode() + '\n'.join(users).encode())
        elif message.startswith('/get_info'):
            login = message.replace('/get_info ', '')
            user = database.get_user(login)
            country = user.country if user.country else ''
            phone = user.phone_number if user.phone_number else ''
            website = user.website if user.website else ''
            author = user.favourite_book_author if user.favourite_book_author else ''
            quote = user.favourite_quote if user.favourite_quote else ''
            self.sendLine(
                f'/info {login}\t{country}\t{phone}\t{website}\t{author}\t{quote}'
                .encode())

        else:
            if message.startswith('/login '):
                login, password = message.replace(
                    '/login ', '').split()[0], message.replace('/login ',
                                                               '').split()[1]
                if database.check_auth(login, password):
                    self.login = login
                    print(f'user connected -> {login}')
                    self.sendLine(f'successful {login}'.encode())
                    self.sendLine(f'Welcome, {login}'.encode())
                else:
                    print('bad attempt to login')
                    self.sendLine('<login or password is incorrect>'.encode())
            elif message.startswith('/register '):
                login, password = message.replace('/register ', '').split()[0], \
                                  message.replace('/register ', '').split()[1]
                if not database.is_unique(login):
                    database.add_user(login, password.encode())
                    self.login = login
                    print(f'new user connected -> {login}')
                    self.sendLine(f'successful {login}'.encode())
                    self.sendLine('Welcome in our friendly community'.encode())
                else:
                    self.sendLine('<user already exists>'.encode())
Exemplo n.º 12
0
def privatemessage(message, signing_key, headers, target_username):
    time_str = str(time.time())
    target_ip = get_ip_from_username(target_username, headers)
    target_pubkey_str = get_pubkey_from_username(target_username, headers)
    print("inside report target ip: " + target_ip)

    url = "http://" + target_ip + "/api/rx_privatemessage"
    certificate = serverFunctions.get_loginserver_record(headers)

    #Turn the string of the target pubkey into an actual pubkey. Then convert it to curve.
    target_pubkey = nacl.signing.VerifyKey(target_pubkey_str,
                                           encoder=nacl.encoding.HexEncoder)
    target_pubkey_curve = target_pubkey.to_curve25519_public_key()

    #Create a sealed_box with the target public key
    sealed_box = nacl.public.SealedBox(target_pubkey_curve)
    encrypted = sealed_box.encrypt(bytes(message, encoding='utf-8'),
                                   encoder=nacl.encoding.HexEncoder)
    encrypted_str = encrypted.decode('utf-8')
    print("sent encrypted data: " + encrypted_str)

    signature_bytes = bytes(certificate + target_pubkey_str + target_username +
                            encrypted_str + time_str,
                            encoding='utf-8')

    signed = signing_key.sign(signature_bytes,
                              encoder=nacl.encoding.HexEncoder)
    signature_hex_str = signed.signature.decode('utf-8')

    payload = {
        "loginserver_record": certificate,
        "target_pubkey": target_pubkey_str,
        "target_username": target_username,
        "encrypted_message": encrypted_str,
        "sender_created_at": time_str,
        "signature": signature_hex_str
    }

    json_bytes = json.dumps(payload).encode('utf-8')

    try:
        req = urllib.request.Request(url, data=json_bytes, headers=headers)
        response = urllib.request.urlopen(req, timeout=2)
        data = response.read()  # read the received bytes
        encoding = response.info().get_content_charset(
            'utf-8')  #load encoding if possible (default to utf-8)
        response.close()
        print(str(data))
        JSON_object = json.loads(data.decode(encoding))
        print(JSON_object)
        if (JSON_object == {'response': 'ok'}):
            database.add_message(server.get_username(), target_username,
                                 message, time_str)
            print("added to the database")
            return "0"
    except urllib.error.HTTPError as error:
        print(error.read())
        return "1"
    except ConnectionResetError:
        print("connection reset error")
        return "1"
    except OSError as error:
        print("socket connection reset error")
        return "1"
    except socket.timeout as error:
        print("timed out")
        return "1"
    except json.decoder.JSONDecodeError as error:
        print("decode error")
        return "1"
    return "1"
Exemplo n.º 13
0
def send_message(sender, receiver, message_text):
    db.add_message(sender, receiver, message_text)
    return jsonify({"response": ["Success"]})
Exemplo n.º 14
0
def send_message(sender, receiver, message_text):
    db.add_message(sender, receiver, message_text)
    return jsonify({"response": ["Success"]})
Exemplo n.º 15
0
def send_message(sender, receiver, message_text):
    db.add_message(sender, receiver, message_text)
    return {"response": "Success"}