def message_user(self, reddit_user, subject, message, sender_email): # TODO: CREATE MODULE TO ENCAPSULATE REDDIT FUNCTIONALITY """ SEND A REDDIT USER A MESSAGE :param reddit: REDDIT INSTANCE :param reddit_user: USERS NAME (STR) :param subject: MESSAGE SUBJECT (STR) :param message: MESSAGE TO SEND (STR) :return: """ try: self.reddit_conn.redditor(reddit_user).message(subject, message) except Exception: logger.critical('----------Error encountered----------') tb = traceback.format_exc() logger.critical(tb) logger.critical('-------------------------------------') return False message = Messages(sender=sender_email, recipient=reddit_user, body=message, subject=subject, date_sent=datetime.datetime.now(), has_been_sent_for_processing=0, ca_user_id_assoc='parent') Messages.add_record(message) db.session.commit() return True
def order_product(): morder_form = MakeOrderForm() sites = Site.query.all() categories = Category.query.all() if request.method == "POST": site = Site.query.get(int(request.form['site'])) message = Messages() message.time = int(time.time()) addition = { 'name': request.form['name'], 'site': int(request.form['site']), 'link': request.form['url'], 'category': int(request.form['category']) } message.addition = dumps(addition, ensure_ascii=False) message.from_user = current_user.id message.recepient_id = site.manager_id message.m_text = request.form['additional'] message.type = 1 db.session.add(message) db.session.commit() return redirect(url_for("index")) return render_template("order_product.html", title="Заказать товар", morder_form=morder_form, sites=sites, categories=categories)
def guestbook_save(request): if request.method=="POST": form=guestbook_check(request.POST) if form.is_valid(): nickname=form.cleaned_data['nickname'] email=form.cleaned_data['email'] content=form.cleaned_data['content'] c=Messages(nickname=nickname,email=email,content=content) c.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form=guestbook_check() some="发表失败!" return render(request,'waring.html',{'string':some})
def messages(): try: current_username = current_user.email except AttributeError: current_username = '******' if request.method == 'POST': to_username = request.form.get('to_username') from_username = current_username message = request.form.get('message') new_message = Messages(to_username=to_username, from_username=from_username, message=message) db.session.add(new_message) db.session.commit() message_query_results = Messages.query.filter_by( to_username=current_username) messages = [] for message_row in message_query_results: # Add dict to list for each message messages.append({ 'to_username': message_row.to_username, 'from_username': message_row.from_username, 'message': message_row.message }) return render_template('messages.html', page_title='Messages', page_description='This is to demonstrate basic XSS', messages=messages)
def approved(): form = ApproveForm() if request.method == 'POST': messages = Messages.query.filter_by(message_to=current_user.id).all() user = User.query.filter_by(username=current_user.username).first() courses = user.courser_coordinator course = Course.query.filter_by(course_name=courses).first() question = Question.query.filter_by(course_id=course.id).first() approved = form.approve.data if approved == 'Approved': data = True question.approved = data print(question.approved) db.session.commit() elif approved == 'Not Approved': data = False question.approved = data print(question.approved) db.session.commit() message_to = User.query.filter_by( username=request.form['name']).first() message = Messages(message=form.message.data, message_to=message_to.id) db.session.add(message) db.session.commit() flash('Message sent successful', 'success') return redirect(url_for('coordinator')) lectures = User.query.filter_by(is_a_lecture=True).all() return render_template('approved.html', form=form, lectures=lectures)
def handleMessage(msg): temp_chat = session['chat_session'][ 0] #Hold value of session at this stage, for use down below if (temp_chat == 'None'): # no chat is allocated, so create a new chat this_chat = Chats(user1=current_user.id, user2=session['chat_session'][1]) session['chat_session'][0] == this_chat.id db.session.add(this_chat) else: # if chat was already there, load the chat this_chat = Chats.query.get(session['chat_session'][0]) msg = Messages(author=current_user, recipient=this_chat.other(current_user.id), body=msg, chat_session=this_chat) reciever = User.query.get(session['chat_session'][1]) reciever.add_notification('unread_chats', reciever.unread_chats()) db.session.add(msg) db.session.commit() if (temp_chat == 'None' ): #if first message, refresh the page to load chat session properly socketio.emit('refresh') json_msg = {'body': msg.body, 'author': current_user.username} socketio.emit('recieve message', json_msg, room=session['chat_session'][0])
def contact(): header = { "title": 'Contact me', "subtitle": 'We are just one click away!', "image_path": "contact_bg.jpg", "needed": True } #if form is submited ==> post request if request.method == 'POST': name = request.form['name'] email = request.form['email'] message = request.form['message'] #write to DB message = Messages(name=name, email=email, message=message) db.session.add(message) db.session.commit() #redirect to index return redirect(url_for('index')) return render_template('contact.html', header=header)
def request_page(request): if request.method == 'POST': json_data = request.read().decode('utf-8') data = json.loads( json_data) # json_data contains the data uploaded in request message = data['message'] stopid = data['stopid'] new_message = Messages(message_text=message, pub_date=datetime.datetime.now(), stop_id=stopid, votes=0) new_message.save() return StreamingHttpResponse('Your message was sent successfully!') else: return StreamingHttpResponse( '..............It was GET request............................')
def handle_message(message): print('received message: ' + str(message)) status = "Pending" msg = Messages(message=message["message"], username=message["user_name"], user_id=message["user_id"], ticket_id=message["ticket_id"]) db.session.add(msg) db.session.commit() socketio.emit('my response', message)
def send_messages(): if not g.user: return 'Bad request!' if not request.json.get('recipient'): return 'Bad request!' if not request.json.get('message'): return '' channel = Channels.objects(sender=g.user, recipient=Users.objects( id=request.json.get('recipient')).first()).first() if not channel: channel = Channels(sender=g.user, recipient=Users.objects( id=request.json.get('recipient')).first(), not_read=True).save() msg = Messages(channel=channel, spam=False, content=request.json.get('message'), status=Messages.STATUSES['NOT_READ'], cr_tm=datetime.datetime.now()) msg.save() return dumps(msg.object_to_dict())
def client_send_message_to_server(message): user_id = str(request.cookies.get('user_id')) friend_id = redis_store.hget('active_chat', user_id).decode('utf-8') room_id = '-'.join([friend_id, user_id]) message = Messages(body=message['data'], receiver=friend_id, sender=user_id) db.session.add(message) db.session.commit() emit('server_send_message_to_client', {'message': message.body}, room=room_id)
def contact(): form = ContactForm() if form.validate_on_submit(): message = Messages(name=form.name.data, email=form.email.data, subject=form.subject.data, message=form.message.data) db.session.add(message) db.session.commit() flash('Thank you for contacting us!') return redirect(url_for('index')) return render_template('contact.html', title='Denver Breakfast Burrito Reviews', form=form)
def for_review(): try: message_to = request.form['message-to'] user = User.query.filter_by(username=message_to).first() message = request.form['message'] message1 = Messages(message=message, message_to=user.id) db.session.add(message1) db.session.commit() flash( 'You have successfuly submited your exam paper to ansurance board') return redirect(url_for('find_question')) except: db.session.close() finally: db.session.close()
def send_message(user): user = Users.query.filter_by(username=user).first_or_404() form = MessageForm() if form.validate_on_submit(): message = Messages(author=current_user, recipient=user, body=form.message.data) db.session.add(message) db.session.commit() flash('Your message was sent.') return redirect(url_for('main.profile', username=user.username)) return render_template('main/send_message.html', title='Send a Message', form=form, user=user)
def contact(): # Generate Contact Form form = ContactForm() if form.validate_on_submit(): # Create message object with the neccesary details message = Messages(name=form.name.data, email=form.email.data, phone=form.phone.data, message=form.message.data) # 'Send' to me (add message to db) db.session.add(message) db.session.commit() flash('Message sent!') return redirect(url_for('index')) return render_template('contact.html', form=form, title='Contact')
def home(): """ Create a home page for the message board. Display a form for users to post messages under their name. Post all messages for all visitors to see. Parameters ---------- GET Method to request data. POST Method to send data. Returns ------- Render the home.html template. """ form = MessageForm() if form.validate_on_submit(): # check if user exists in database # Determine who to link the message to user = User.query.filter_by(author=form.author.data).first() if user is None: # if not create user and add to database # Allow new users to post messages as well user = User(author=form.author.data) db.session.add(user) db.session.commit() # create row in Message table with user (created/found) add to the database message = Messages(message=form.message.data, user_id=user.id) db.session.add(message) db.session.commit() posts = [] # output all messages # create a list of dictionaries with the following structure # [{'author':'carlos', 'message':'Yo! Where you at?!'}, # {'author':'Jerry', 'message':'Home. You?'}] # Follow format for collecting author name and message specified in the home.html template list = Messages.query.all() for m in list: posts.append({ 'author': User.query.get(m.user_id).author, 'message': m.message }) return render_template('home.html', posts=posts, form=form)
def get_chats(): if not g.user: return 'Bad request!' users = Users.objects(id__ne=g.user.id).all() res_user = [] not_read_messages = None for user in users: channel = Channels.objects(sender=user, recipient=g.user).first() if channel: not_read_messages = Messages.objects( channel=channel, status=Messages.STATUSES['NOT_READ']).count() dict_user = user.object_to_dict() if not_read_messages: dict_user['not_read'] = not_read_messages res_user.append(dict_user) return dumps({'data': res_user, 'g_user': g.user.object_to_dict()})
def home(): form=MessageForm() if form.validate_on_submit(): # check if user exits in database # if not create user and add to database # create row in Message table with user (created/found) add to ta database user = User.query.filter_by(author= form.author.data).first() if user is None: new_user = User(author = form.author.data) db.session.add(new_user) new_message = Messages(message =form.message.data, user_id = User.query.filter_by(author = form.author.data).first().id) db.session.add(new_message) db.session.commit() posts = [ { 'author':'Carlos', 'message': 'Yo! Where you at?!' }, { 'author':'Jerry', 'message':'Home. You?' } ] # output all messages # create a list of dictionaries with the following structure # [{'author':'Carlos', 'message':'Yo! Where you at?!'}, # {'author':'Jerry', 'message':'Home. You?'}] every_message = Messages.query.all() if every_message is not None: for a_message in every_message: posts = posts + [ { 'author': f'{User.query.filter_by(id = a_message.user_id).first().author}', 'message': f'{a_message.message}' } ] return render_template('home.html', posts=posts, form=form)
def message(): try: date_sent = request.headers.get('date_sent') user_id = request.headers.get('user_id') reciever_id = request.headers.get('reciever_id') message = request.headers.get('message') message = Messages(date_sent=date_sent, user_id=user_id, reciever_id=reciever_id, message=message) db.session.add(message) db.session.commit() return jsonify({'message': 'success'}) except: return jsonify({'message': 'Was unable to send a message.'})
def home(): form = MessageForm() if form.validate_on_submit(): # check if user exits in database '''checks db by authors name to see if they exist or not''' user = User.query.filter_by(author=form.author.data).first() # if not create user and add to database if user is None: '''creates user and adds them to db''' user = User(author=form.author.data) db.session.add(user) db.session.commit() # create row in Message table with user (created/found) add to ta database '''creates row based on user id''' row = Messages(message=form.message.data, user_id=user.id) db.session.add(row) db.session.commit() posts = [{ 'author': 'Carlos', 'message': 'Yo! Where you at?!' }, { 'author': 'Jerry', 'message': 'Home. You?' }] # output all messages # create a list of dictionaries with the following structure # [{'author':'carlos', 'message':'Yo! Where you at?!'}, # {'author':'Jerry', 'message':'Home. You?'}] '''saves all messages in a variable to be used later''' messages = Messages.query.all() '''for all the messages that have been posted, adds them to dictionary and is visible to user''' for currentMessage in messages: posts = posts + [{ 'author': User.query.filter_by(id=currentMessage.id).first().author, 'message': currentMessage.message }] return render_template('home.html', posts=posts, form=form)
def moderation_board(): form = ApproveForm() if request.method == 'POST': message_to = User.query.filter_by( username=request.form['name']).first() message = Messages(message=form.message.data, message_to=message_to.id) db.session.add(message) db.session.commit() flash('Message sent successful', 'success') messages = Messages.query.filter_by(message_to=current_user.id).all() user = User.query.filter_by(username=current_user.username).first() courses = user.courser_assurance_board course = Course.query.filter_by(course_name=courses).first() question = Question.query.filter_by(course_id=course.id).first() users = User.query.filter_by(is_a_coordinator=True) return render_template('moderation_board.html', form=form, messages=messages, courses=courses, question=question, users=users)
def home(): form = MessageForm() if form.validate_on_submit(): # check if user exists in database # if not, create user and add to database user = User.query.filter_by(author=form.author.data).first() if user is None: create_user = User(author=form.author.data) db.session.add(create_user) # create row in Message table with user (created/found) add to database message_row = Messages( message=form.message.data, user_id=User.query.filter_by(author=form.author.data).first().id) db.session.add(message_row) db.session.commit() # output all messages # create a list of dictionaries with the following structure # [{'author':'carlos', 'message':'Yo! Where you at?!'}, # {'author':'Jerry', 'message':'Home. You?'}] posts = [{ 'author': 'Carlos', 'message': 'Yo! Where you at?!' }, { 'author': 'Jerry', 'message': 'Home. You?' }] list_dict = Messages.query.all() for m in list_dict: posts = posts + [{ 'author': ' {}'.format(User.query.filter_by(id=m.user_id).first().author), 'message': ' {}'.format(m.message) }] return render_template('home.html', posts=posts, form=form)
def home(): form = MessageForm() if form.validate_on_submit(): # If the form submit # check if user exits in database # if not create user and add to database # create row in Message table with user (created/found) add to ta database user = User.query.filter_by(author=form.author.data).first() if user is None or not user.check_author(form.author.data): user = User(author=form.author.data) db.session.add(user) db.session.commit() #db.session.refresh(user) message = Messages(user_id=user.id, message=form.message.data) db.session.add(message) db.session.commit() #db.session.refresh(message) #create the list of messages with the Users messageList = (db.session.query(User, Messages).join(User)).all() posts = [] for item in messageList: #Add the item in the message list into the posts posts.append({ "author": item.User.author, "message": item.Messages.message }) # output all messages # create a list of dictionaries with the following structure # [{'author':'carlos', 'message':'Yo! Where you at?!'}, # {'author':'Jerry', 'message':'Home. You?'}] return render_template('home.html', posts=posts, form=form)
def run(self): """ :return: """ logger.info("ENTERED EMAIL INBOX SCRAPER") while True: # CONNECT TO EMAIL SERVER try: # TRY TO LOGIN self.server = imaplib.IMAP4_SSL(self.imap_ssl_host, self.imap_ssl_port) self.server.login(self.username, self.password) except Exception: logger.critical( "FAILED TO LOGIN TO EMAIL SERVER. KILLING THREAD") # exit(1) self.server.select('INBOX') (retcode, messages) = self.server.search(None, '(UNSEEN)') if retcode == 'OK': for num in messages[0].split(): typ, data = self.server.fetch(num, '(RFC822)') for response_part in data: if isinstance(response_part, tuple): message = email.message_from_bytes( response_part[1]) _from = message['Reply-to'] _subject = message['Subject'] if 're' in _subject.lower(): _subject = re.split("Re:", _subject)[1].strip() _subject = json.loads(_subject) mesage_id = _subject['message_id'] # EXTRACT REDDIT USERNAME reddit_user = _subject['username'] body = EmailReader.get_first_text_block(message) try: # MESSAGE HAS A SIGNATURE, ALSO A POSSIBLE REPLY W SIGNATURE body_without_signature = body.split( "=E2=80=94")[1] except IndexError: # MESSAGE IS A REPLY body_without_signature = body.split( "=EF=BB=BF")[0] # parent_message = Messages.query.filter_by( # recipient=reddit_user).filter_by( # ca_user_id_assoc='parent').first() self.reddit.reddit_conn.inbox.message( mesage_id).reply(body_without_signature) self.server.store(num, '+FLAGS', '\\Seen') message = Messages( sender=_from, recipient=reddit_user, subject=_subject['subject'], body=body_without_signature, date_sent=datetime.datetime.now(), has_been_sent_for_processing=1, ca_user_id_assoc=mesage_id) Messages.add_record(message) db.session.commit() self.server.logout() # logger.info("NOTHING NEW IN EMAIL INBOX--SLEEPING") time.sleep(20)
def socket_message(data): Messages.update_messages_daemon(data, emit, request.sid)
def message_delete(message_id): msg = Messages.objects(id=message_id).first() msg.delete() return 'success'
def reply_checker(self): """ METHOD THAT CONSTANTLY CHECKS FOR NEW MESSAGES IN REDDIT INBOX :return: """ logger.info("ENTERED REDDIT INBOX SCRAPER") while True: try: # TODO: CHANGE TO STREAM FOR PROD # PULL REDDIT INBOX STREAM new_reddit_messages = self.reddit.reddit_conn.inbox.unread() # LOOP THROUGH REDDIT MESSAGES for message in new_reddit_messages: # GET REDDIT USERNAME / ID OF NEW MESSAGE reddit_username_of_new_message = message.author.name message_id = message.id # CHECK TO SEE IF MESSAGE IS ALREADY IN MESSAGE QUEUE message_exists = Messages.query.filter_by( recipient=reddit_username_of_new_message).filter_by( ca_user_id_assoc=message_id).first() if not message_exists: # FIND PARENT COMMENT, SO WE CAN IDENTIFY WHO REACHED OUT parent_message = Messages.query.filter_by( recipient=reddit_username_of_new_message ).filter_by(ca_user_id_assoc='parent').first() if parent_message: # GET THE SENDERS EMAIL sender = parent_message.sender # GET THE BODY TEXT OF THE NEW MESSAGE body = message.body parent_message_subect = parent_message.subject # THE IDEA IS TO CODE THE REDDIT-EMAIL LINK IN JSON: reddit_user_email_id = "\"username\": \"{reddit_username_of_new_message}\", " \ "\"message_id\": \"{message_id}\", " \ "\"subject\": \"{subject}\"".format( reddit_username_of_new_message=reddit_username_of_new_message, message_id=message_id, subject=message.subject) subject = "{" + reddit_user_email_id + "}" # STORE MESSAGE IN DATABASE ca_message = Messages( sender=reddit_username_of_new_message, recipient=sender, body=body, subject=subject, date_sent=datetime.datetime.now(), has_been_sent_for_processing=0, ca_user_id_assoc=message.parent_id) # WE HAVE ADDED NEW MESSAGE TO DB, TIME TO EMAIL THE COMPLAINING ABOUT USER WHO STARTED CONVO # We want to notify the user that they received a response Messages.add_record(ca_message) # TODO: UPDATE FOR PROD self.send_email(sender, "*****@*****.**", body, subject) ca_message.has_been_sent_for_processing = 1 self.reddit.reddit_conn.inbox.mark_read([message]) db.session.commit() else: # IF PARENT MESSAGE DOESNT EXIST, MARK AS READ self.reddit.reddit_conn.inbox.mark_read([message]) except Exception as e: logger.info("EXCEPTION IN REDDIT READER") traceback.print_exc() # logger.info("NOTHING NEW IN INBOX STREAM--SLEEPING") time.sleep(100)
def send_msg(sender, receiver, msg_text): msg = Messages(sender=sender, receiver=receiver, msg_text=msg_text) db.session.add(msg) db.session.commit()