IEEE.org     |     IEEE Xplore Digital Library     |     IEEE Standards     |     IEEE Spectrum     |     More Sites

Commit 0697fb90 authored by Bilal KABAŞ's avatar Bilal KABAŞ
Browse files

Project files added

parent 2a7c23b1
from flask import Flask
from datetime import timedelta
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = '9e7d0c31d2ee6da88b76f7cc0b2bf0df'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=60)
from app import routes
\ No newline at end of file
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=100)])
confirm_password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=100), EqualTo('password', message= 'Password do not match!')])
submit = SubmitField('Sign Up')
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember me')
submit = SubmitField('Login')
from flask import render_template, flash, redirect, url_for, request, session, logging
from app import app
from app.forms import RegistrationForm, LoginForm
from flask_mysqldb import MySQL
from functools import wraps
from passlib.hash import sha256_crypt
import uuid
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'rtqa'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# init MYSQL
mysql = MySQL(app)
# Login Control
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
return redirect(url_for('login'))
return wrap
# HOME *****
@app.route('/')
@app.route('/home')
def home():
return render_template('home.html')
# ABOUT *****
@app.route('/about')
def about():
return render_template('about.html', title='About')
# REGISTER *****
@app.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate_on_submit():
# Validate
cur = mysql.connection.cursor()
username_val = cur.execute("SELECT * FROM users WHERE username = %s", [form.username.data])
email_val = cur.execute("SELECT * FROM users WHERE email = %s", [form.email.data])
if username_val > 0:
flash(f'This username was already taken!', 'danger')
elif email_val > 0:
flash(f'Somebody has already used this email address!', 'danger')
else:
username = form.username.data
email = form.email.data
password = sha256_crypt.hash(str(form.password.data))
# DB stuff
cur = mysql.connection.cursor()
cur.execute("INSERT INTO users(username, email, password) VALUES(%s, %s, %s)", (username, email, password))
mysql.connection.commit()
cur.close()
flash(f'Account created for {form.username.data}!', 'success')
return redirect(url_for('home'))
return render_template('register.html', title='Register', form=form)
available = {}
# LOGIN *****
@app.route("/login", methods=['GET', 'POST'])
def login():
print (session)
form = LoginForm()
if request.method == 'POST' and form.validate_on_submit():
#DB stuff
cur = mysql.connection.cursor()
result = cur.execute("SELECT * FROM users WHERE username = %s", [form.username.data])
if result > 0:
data = cur.fetchone()
password = data['password']
if sha256_crypt.verify(form.password.data, password):
session['logged_in'] = True
session['username'] = form.username.data
# Set room id
session['room'] = str(uuid.uuid4()) + '-' + form.username.data
# Register user to the available list
available[form.username.data] = None
flash('You have been logged in!', 'success')
return redirect(url_for('home'))
else:
flash('Login unsuccessful. Please check username and password.', 'danger')
return render_template('login.html', title='Login', form=form)
# Close connection
cur.close()
else:
flash('Login unsuccessful. Please check username and password.', 'danger')
return render_template('login.html', title='Login', form=form)
return render_template('login.html', title='Login', form=form)
# LOGOUT *****
@app.route('/logout')
@is_logged_in
def logout():
available.pop(session['username'], None)
# Clear the session
session.clear()
flash('You are now logged out', 'success')
return redirect(url_for('login'))
# ASK *****
@app.route('/ask')
@is_logged_in
def ask():
return render_template('ask.html', title='Ask', users=available)
from app import app
from flask import request, session, flash, redirect, url_for
from flask_session import Session
from flask_socketio import SocketIO, send, emit, join_room, leave_room, close_room
from app.routes import is_logged_in, mysql, available
import uuid
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)
socketio = SocketIO(app, manage_sessions=False)
# Join the personal room / It is mandatory that for every single request user will join the same room
@socketio.on('join', namespace='/session')
@is_logged_in
def on_join(data):
join_room(session['room'])
if available.get(session['username']) is None:
available[session['username']] = session['room']
emit('update available users', available, broadcast=True)
# Send chat request to the respondent
@socketio.on('send request', namespace='/session')
@is_logged_in
def on_request(data):
room = data['room']
questioner = session['username']
respondent = [username for username, room_id in available.items() if room_id == room][0]
room_id = str(uuid.uuid4()) + questioner + '-to-' + respondent
leave_room(session['room'])
close_room(session['room'])
available.pop(session['username'], None)
available.pop(respondent, None)
join_room(room_id)
emit('incoming request', {'questioner': questioner, 'respondent': respondent, 'room': room_id}, room=room, include_self=False)
emit('receive room id', {'room': room_id}, room=room_id, broadcast=False)
emit('update available users', available, broadcast=True)
# Join the chat room
@socketio.on('join chat room', namespace='/session')
@is_logged_in
def join_chat_room(data):
room = data['room']
join_room(room)
emit('message', {'username': session['username'], 'message': session['username'] + ' joined the chat'}, room=room, include_self=False)
# Send messages
@socketio.on('send message', namespace='/session')
@is_logged_in
def send_message(data):
emit('message', {'username': session['username'], 'message': data['message']}, room=data['room'], include_self=False)
# Decline the chat request
@socketio.on('decline chat request', namespace='/session')
@is_logged_in
def decline_chat_request(data):
session['room'] = str(uuid.uuid4()) + '-' + session['username']
join_room(session['room'])
available[session['username']] = session['room']
emit('request declined', {}, room=data['room'])
emit('update available users', available, broadcast=True)
# Logout
@socketio.on('logout', namespace='/session')
@is_logged_in
def logout_socket(data):
leave_room(session['room'])
close_room(session['room'])
available.pop(session['username'], None)
emit('update available users', available, broadcast=True)
\ No newline at end of file
.form-control {
margin-top: 20px;
margin-bottom: 7px;
height: 42px !important;
font-size: 17px;
}
.people {
margin-right: 7px;
margin-bottom: 13px;
}
#log {
height: 60vh !important;
max-height: 60vh !important;
overflow-y: scroll;
}
.input-group {
width: 100% !important;
}
#send {
margin-top: 5px !important;
}
.request-box {
display: flex;
justify-content: space-between;
align-items: center;
}
.btn-request {
margin-left: 15px;
}
#logout {
cursor: pointer;
}
/*/////////////////////////////////*/
.chat-container{display: none; max-width:1170px; margin:auto; padding-top: 10px;}
img{ max-width:100%;}
.inbox_people {
background: #f8f8f8 none repeat scroll 0 0;
float: left;
overflow: hidden;
width: 40%; border-right:1px solid #c4c4c4;
}
.inbox_msg {
border: 1px solid #c4c4c4;
clear: both;
overflow: hidden;
}
.top_spac{ margin: 20px 0 0;}
.recent_heading {float: left; width:40%;}
.headind_srch{ padding:10px 29px 10px 20px; overflow:hidden; border-bottom:1px solid #c4c4c4;}
.recent_heading h4 {
color: #05728f;
font-size: 21px;
margin: auto;
}
.srch_bar input{ border:1px solid #cdcdcd; border-width:0 0 1px 0; width:80%; padding:2px 0 4px 6px; background:none;}
.srch_bar .input-group-addon button {
background: rgba(0, 0, 0, 0) none repeat scroll 0 0;
border: medium none;
padding: 0;
color: #707070;
font-size: 18px;
}
.srch_bar .input-group-addon { margin: 0 0 0 -27px;}
.chat_ib h5{ font-size:15px; color:#464646; margin:0 0 8px 0;}
.chat_ib h5 span{ font-size:13px; float:right;}
.chat_ib p{ font-size:14px; color:#989898; margin:auto}
.chat_img {
float: left;
width: 11%;
}
.chat_ib {
float: left;
padding: 0 0 0 15px;
width: 88%;
}
.chat_people{ overflow:hidden; clear:both;}
.chat_list {
border-bottom: 1px solid #c4c4c4;
margin: 0;
padding: 18px 16px 10px;
}
.inbox_chat { height: 550px; overflow-y: scroll;}
.active_chat{ background:#ebebeb;}
.incoming_msg_img {
display: inline-block;
width: 6%;
}
.received_msg {
display: inline-block;
padding: 0 0 0 10px;
vertical-align: top;
width: 92%;
}
.received_withd_msg p {
background: #ebebeb none repeat scroll 0 0 !important;
border-bottom-right-radius: 0 !important;
border-bottom-left-radius: 20px !important;
color: #646464 !important;
font-size: 14px;
}
.time_date {
color: #747474;
display: block;
font-size: 12px;
margin: 8px 0 0;
}
.received_withd_msg { max-width: 50%; min-width: 120px;}
.mesgs {
padding: 30px 15px 0 25px;
}
.sent_msg p, .sent_message p {
border-radius: 3px;
font-size: 14px;
margin: 0; color:#fff;
padding: 5px 10px 5px 12px;
width:100%;
}
.sent_message p, .received_withd_msg p {
display: flex;
align-items: center;
background: #2196F3 none repeat scroll 0 0;
font-size: 14px;
margin: 0; color:#fff;
padding: 5px 10px 5px 12px;
min-width: 100px;
min-height: 40px;
border-bottom-right-radius: 20px;
}
.sent_message {
box-sizing: border-box;
float: right;
}
.outgoing_msg{ overflow:hidden; margin:26px 0 26px;}
.sent_msg {
margin: auto !important;
box-sizing: border-box;
padding: 7px;
width: 46%;
}
.input_msg_write input {
background: rgba(0, 0, 0, 0) none repeat scroll 0 0;
border: medium none;
color: #4c4c4c;
font-size: 15px;
min-height: 48px;
width: 100%;
outline: none;
}
.type_msg {border-top: 1px solid #c4c4c4;position: relative;}
.msg_send_btn {
background: #2196F3 none repeat scroll 0 0;
border: medium none;
border-radius: 5px;
color: #fff;
cursor: pointer;
font-size: 17px;
height: 33px;
position: absolute;
right: 0;
top: 11px;
}
.messaging { padding: 0 0 50px 0;}
.msg_history {
height: 516px;
overflow-y: auto;
}
\ No newline at end of file
$(document).ready(function() {
//Connect to the socket
let socket = io.connect('http://127.0.0.1:5000/session');
//Everyone joins the personal room
socket.emit('join', {})
//Questioner sends the chat request and joins the chat room
$('.people').on('click', function(e) {
let room = this.dataset.room
socket.emit('send request', {'room': room})
//Open the chat window
$('.request-box').remove();
$('.main-container').hide();
$('.chat-container').show();
});
socket.on('receive room id', function(data) {
//Send message
$('#send_message').on('click', function() {
let message = $('#message_input').val();
socket.emit('send message', {'message': message, 'room': data.room});
$('.msg_history').append('<div class="outgoing_msg"><div class="sent_message"><p>' + message + '</p></div></div>');
$('#message_input').val('');
scrollDown();
});
});
//Show incoming request
socket.on('incoming request', function(data) {
$('#messages').append('<div class="alert alert-success request-box"><p>Hey ' + data.respondent + '! ' + data.questioner + ' want to ask a question.</p><div><button id="accept_request" class="btn btn-success btn-request">Accept</button><button id="decline_request" class="btn btn-danger btn-request">Decline</button></div></div>')
//Respondent accepts the request
$('#accept_request').on('click', function() {
//Respondent joins the chat room
socket.emit('join chat room', {'room': data.room});
//Open the chat window
$('.request-box').remove();
$('.main-container').hide();
$('.chat-container').show();
//Send message
$('#send_message').on('click', function() {
let message = $('#message_input').val();
socket.emit('send message', {'message': message, 'room': data.room})
$('.msg_history').append('<div class="outgoing_msg"><div class="sent_message"><p>' + message + '</p></div></div>');
$('#message_input').val('');
scrollDown();
});
});
//Decline the request
$('#decline_request').on('click', function() {
socket.emit('decline chat request', {'room': data.room});
$('.request-box').remove();
});
});
//Get messages
socket.on('message', function(data) {
$('.msg_history').append('<div class="incoming_msg"><div class="received_msg"><div class="received_withd_msg"><p>' + data.message + '</p><span class="time_date">' + data.username + '</span></div></div></div>');
});
//The request is declined
socket.on('request declined', function() {
alert('Your request has been declined.')
window.location.replace("http://127.0.0.1:5000/ask");
});
//Update available users
socket.on('update available users', function(data) {
$('.people-container').html('')
Object.keys(data).forEach(function(user) {
$('.people-container').append('<button data-room="' + data[user] + '" class="btn btn-success people"><b style="font-size: 20px !important;">' + user + '</b><br>Available !</button>');
//Questioner sends the chat request and joins the chat room
$('.people').on('click', function(e) {
let room = this.dataset.room
socket.emit('send request', {'room': room})
//Open the chat window
$('.request-box').remove();
$('.main-container').hide();
$('.chat-container').show();
});
});
});
//Logout
$('#logout').on('click', function() {
socket.emit('logout', {});
window.location.replace("http://127.0.0.1:5000/logout");
});
//Set enter key to send message
$('#message_input').on('keyup', function(event) {
if (event.keyCode === 13) {
$("#send_message").click();
}
});
//Scroll down
function scrollDown() {
$('.msg_history').stop().animate({
scrollTop: $('.msg_history')[0].scrollHeight
}, 800);
}
});
\ No newline at end of file
{% extends 'layout.html' %}
{% block content %}
<h1>About Us</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum a fugiat cumque culpa magni voluptatibus consequatur numquam beatae tenetur quod esse necessitatibus recusandae odio officiis, voluptas deleniti vel adipisci fuga.</p>
{% endblock %}
\ No newline at end of file
{% extends 'layout.html' %}
{% block content %}
<h2>Find somebody to ask a question</h2>
<input class="form-control" type="text" placeholder="Add the topics related to your question" aria-label="Search">
<button type="button" class="btn btn-warning btn-sm">JavaScript</button>
<button type="button" class="btn btn-primary btn-sm">CSS</button>
<button type="button" class="btn btn-info btn-sm">HTML</button>
<br><br><br>
<div class="people-container">
{% for username, room_id in users.items() %}
<button data-room="{{ room_id }}" class="btn btn-success people">
<b style="font-size: 20px !important;">{{ username }}</b>
<br>Available !
</button>
{% endfor %}
</div>
{% endblock %}
\ No newline at end of file
{% extends 'layout.html' %}
{% block content %}
<h1>Dashboard <small> Welcome {{session.username}}</small></h1>
<a class="btn btn-success" href="/add_article"> Add Article</a>
<hr>
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Date</th>
<th></th>
<th></th>
</tr>
{% for article in articles %}
<tr>
<td>{{article.id}}</td>
<td>{{article.title}}</td>
<td>{{article.author}}</td>
<td>{{article.create_date}}</td>
<td><a href="edit_article/{{article.id}}" class="btn btn-default pull-right">Edit</a></td>
<td>
<form action="{{url_for('delete_article', id=article.id)}}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="Delete" class="btn btn-danger">
</form>
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
\ No newline at end of file
{% extends 'layout.html' %}
{% block content %}
<div class="jumbotron text-center">
<h1>Welcome To FlaskApp</h1>
<p class="lead">This application is built on the Python Flask framework and is the focus for the "Python Flask From Scratch" YouTube series</p>
{% if session.logged_in == NULL %}
<a href="/register" class="btn btn-primary btn-lg">Register</a>
<a href="/login" class="btn btn-success btn-lg">Login</a>
{% endif %}
</div>
{% endblock %}
\ No newline at end of file
<div class="chat-container">
<h3 class="text-center">Chat Room</h3>
<div class="messaging">
<div class="inbox_msg">