WU/app.py

651 lines
21 KiB
Python
Raw Normal View History

2018-12-03 01:52:04 +01:00
from flask import Flask, render_template, request, json, session, redirect, Blueprint, url_for
from flask_wtf import Form
from wtforms.fields import StringField, SubmitField
from wtforms.validators import Required
2018-12-03 00:31:48 +01:00
#from flaskext.mysql import MySQL
#from pony.orm import *
2018-11-27 15:48:22 +01:00
import cv2
import logging as log
import datetime as dt
from time import sleep
2018-12-03 00:31:48 +01:00
from flask_socketio import SocketIO
2018-12-03 01:52:04 +01:00
from flask_socketio import emit, join_room, leave_room
2018-12-03 00:31:48 +01:00
import smtplib
2018-12-11 20:57:16 +01:00
from oauth2client import file, client, tools
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
2018-12-03 00:31:48 +01:00
2018-11-27 15:48:22 +01:00
2018-12-03 01:52:04 +01:00
main = Blueprint('main', __name__)
2018-11-27 15:48:22 +01:00
app = Flask(__name__)
app.secret_key = '523tvb6h3nio6r21cc4r1qx'
2018-12-03 01:52:04 +01:00
app.debug = True
socketio = SocketIO()
app.register_blueprint(main)
socketio.init_app(app)
2018-11-27 15:48:22 +01:00
# MySQL configurations
2018-12-03 00:31:48 +01:00
#app.config['MYSQL_DATABASE_USER'] = 'root'
#app.config['MYSQL_DATABASE_PASSWORD'] = 'localhost'
#app.config['MYSQL_DATABASE_DB'] = 'wu'
#app.config['MYSQL_DATABASE_HOST'] = 'localhost'
#mysql = MySQL()
#mysql.init_app(app)
2018-11-27 15:48:22 +01:00
2018-12-03 01:52:04 +01:00
@app.route('/groupChat', methods=['GET', 'POST'])
def indexChat():
if "user" in session:
"""Login form to enter a room."""
form = LoginForm()
if form.validate_on_submit():
2018-12-11 20:57:16 +01:00
session['name'] = session["user"].split('@')[0] #form.name.data
2018-12-03 01:52:04 +01:00
session['room'] = "Czat grupowy" #form.room.data
return redirect(url_for('.chat'))
elif request.method == 'GET':
form.name.data = session.get('name', '')
form.room.data = session.get('room', '')
return render_template('indexChat.html', form=form)
else:
return render_template("error.html", error = "Brak dostępu!")
@app.route('/chat')
def chat():
if "user" in session:
"""Chat room. The user's name and room must be stored in
the session."""
name = session["user"] #session.get('name', '')
room = "Czat grupowy" #session.get('room', '')
if name == '' or room == '' or name == None:
return redirect("index.html")
return render_template('chat.html', name=name, room=room)
else:
return render_template("error.html", error = "Brak dostępu!")
@socketio.on('joined', namespace='/chat')
def joined(message):
"""Sent by clients when they enter a room.
A status message is broadcast to all people in the room."""
room = "Czat grupowy" #session.get('room')
join_room(room)
emit('status', {'msg': session.get('user').split('@')[0] + ' wszedł na czat'}, room=room)
@socketio.on('text', namespace='/chat')
def text(message):
"""Sent by a client when the user entered a new message.
The message is sent to all people in the room."""
room = "Czat grupowy" #session.get('room')
emit('message', {'msg': session.get('user').split('@')[0] + ':' + message['msg']}, room=room)
@socketio.on('left', namespace='/chat')
def left(message):
"""Sent by clients when they leave a room.
A status message is broadcast to all people in the room."""
room = "Czat grupowy" #session.get('room')
leave_room(room)
emit('status', {'msg': session.get('user').split('@')[0] + ' opuścił czat'}, room=room)
class LoginForm(Form):
"""Accepts a nickname and a room."""
name = StringField('Name', validators=[Required()])
room = StringField('Room', validators=[Required()])
submit = SubmitField('Wejdź na czat')
2018-11-27 15:48:22 +01:00
faces_list = []
testing_face = 0
2018-12-11 20:57:16 +01:00
service = None
SCOPES = "https://www.googleapis.com/auth/calendar.events"
2018-11-27 15:48:22 +01:00
2018-12-03 00:31:48 +01:00
@socketio.on('message')
def handleMessage(msg):
print('Message: ' + msg)
send(msg, broadcast=True)
2018-11-27 15:48:22 +01:00
@app.route("/")
def main():
2018-12-11 20:57:16 +01:00
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))
2018-11-27 15:48:22 +01:00
return render_template('index.html', info="Witaj!")
2018-11-28 01:38:57 +01:00
@app.route("/indexENG")
def indexENG():
return render_template('indexENG.html', info="Hello!")
2018-11-27 15:48:22 +01:00
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
2018-11-28 01:38:57 +01:00
@app.route('/showSignUpENG')
def showSignUpENG():
return render_template('signupENG.html')
2018-11-27 15:48:22 +01:00
@app.route('/showSignIn')
def showSignIn():
return render_template('signin.html')
2018-11-28 01:38:57 +01:00
@app.route('/showSignInENG')
def showSignInENG():
return render_template('signinENG.html')
2018-11-27 15:48:22 +01:00
@app.route('/signUp',methods=['POST','GET'])
def signUp():
try:
_login = request.form['inputLogin']
_password = request.form['inputPassword']
if _login and _password:
conn = mysql.connect()
cursor = conn.cursor()
#_hashed_password = generate_password_hash(_password)
2018-12-03 00:31:48 +01:00
2018-11-27 15:48:22 +01:00
args = (_login, _password)
cursor.execute("INSERT into Users(login, password) values(%s, %s)", args)
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return render_template("index.html", info="Pomyślnie zarejestrowano!")
#return json.dumps({'message':'User created successfully !'})
else:
return render_template("error.html", error="Użytkownik już istnieje!")
#return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
#except Exception as e:
# return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
2018-11-28 01:38:57 +01:00
@app.route('/signUpENG',methods=['POST','GET'])
def signUpENG():
try:
_login = request.form['inputLogin']
_password = request.form['inputPassword']
if _login and _password:
conn = mysql.connect()
cursor = conn.cursor()
#_hashed_password = generate_password_hash(_password)
args = (_login, _password)
cursor.execute("INSERT into Users(login, password) values(%s, %s)", args)
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return render_template("indexENG.html", info="Successfully registered!")
#return json.dumps({'message':'User created successfully !'})
else:
return render_template("errorENG.html", error="The user already exists!")
#return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
#except Exception as e:
# return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
2018-11-27 15:48:22 +01:00
@app.route('/validateLogin',methods=['POST'])
def validateLogin():
2018-12-03 00:31:48 +01:00
#con, cursor = None, None
#try:
#_username = request.form['inputLogin']
gmail_username = request.form['inputLogin']
#_password = request.form['inputPassword']
gmail_password = request.form['inputPassword']
2018-11-27 15:48:22 +01:00
try:
2018-12-03 00:31:48 +01:00
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_username, gmail_password)
2018-12-11 20:57:16 +01:00
if "@gmail.com" not in gmail_username:
session['user'] = gmail_username + "@gmail.com" #.split('@')[0]
else:
session["user"] = gmail_username
return render_template('userHome.html', user=session['user'].split('@')[0], calendar_src="https://calendar.google.com/calendar/embed?src=" + session.get("user"))
2018-12-03 00:31:48 +01:00
except:
return render_template('error.html',error = 'Zły email lub hasło!')
2018-11-27 15:48:22 +01:00
2018-12-03 00:31:48 +01:00
'''
2018-11-27 15:48:22 +01:00
con = mysql.connect()
cursor = con.cursor()
#cursor.callproc('logowanie',(_username,))
args = (_username, _password)
query = "SELECT * from Users where login = %s and password = %s"
cursor.execute(query, args)
data = cursor.fetchall()
if len(data) > 0:
#if check_password_hash(str(data[0][3]),_password):
#if str(data[0][3]) == _password:
if str(data[0][1]) == _password:
session['user'] = data[0][0]
2018-11-28 01:38:57 +01:00
#return redirect('/userHome', user=session['user'])
return render_template('userHome.html', user=session['user'])
2018-11-27 15:48:22 +01:00
else:
2018-12-03 00:31:48 +01:00
return render_template('error.html',error = 'Zły email lub hasło!')
2018-11-27 15:48:22 +01:00
else:
2018-12-03 00:31:48 +01:00
return render_template('error.html',error = 'Zły email lub hasło!')
2018-11-27 15:48:22 +01:00
except Exception as e:
return render_template('error.html',error = str(e))
finally:
2018-12-03 00:31:48 +01:00
if cursor:
cursor.close()
if con:
con.close()
'''
2018-11-28 01:38:57 +01:00
@app.route('/validateLoginENG',methods=['POST'])
def validateLoginENG():
2018-12-03 00:31:48 +01:00
#con, cursor = None, None
#try:
#_username = request.form['inputLogin']
gmail_username = request.form['inputLogin']
#_password = request.form['inputPassword']
gmail_password = request.form['inputPassword']
2018-11-28 01:38:57 +01:00
try:
2018-12-03 00:31:48 +01:00
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_username, gmail_password)
2018-12-11 20:57:16 +01:00
session['user'] = gmail_username#.split('@')[0]
2018-12-03 00:31:48 +01:00
return render_template('userHomeENG.html', user=gmail_username.split('@')[0])
except:
return render_template('errorENG.html',error = 'Wrong email or password!')
2018-11-28 01:38:57 +01:00
2018-12-03 00:31:48 +01:00
'''
2018-11-28 01:38:57 +01:00
con = mysql.connect()
cursor = con.cursor()
#cursor.callproc('logowanie',(_username,))
args = (_username, _password)
query = "SELECT * from Users where login = %s and password = %s"
cursor.execute(query, args)
data = cursor.fetchall()
if len(data) > 0:
#if check_password_hash(str(data[0][3]),_password):
#if str(data[0][3]) == _password:
if str(data[0][1]) == _password:
session['user'] = data[0][0]
#return redirect('/userHomeENG', user=session['user'])
return render_template('userHomeENG.html', user=session['user'])
else:
return render_template('errorENG.html',error = 'Wrong email or password!')
else:
return render_template('errorENG.html',error = 'Wrong email or password!')
except Exception as e:
return render_template('errorENG.html', error = str(e))
finally:
2018-12-03 00:31:48 +01:00
if cursor:
cursor.close()
if con:
con.close()
'''
2018-11-27 15:48:22 +01:00
@app.route('/userHome')
def userHome():
if session.get('user'):
2018-12-11 20:57:16 +01:00
return render_template('userHome.html', user=session['user'].split('@')[0], calendar_src="https://calendar.google.com/calendar/embed?src=" + session.get("user"))
2018-11-27 15:48:22 +01:00
else:
2018-12-03 00:31:48 +01:00
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
2018-11-28 01:38:57 +01:00
@app.route('/userHomeENG')
def userHomeENG():
if session.get('user'):
2018-12-11 20:57:16 +01:00
return render_template('userHomeENG.html', user=session['user'].split('@')[0])
2018-11-28 01:38:57 +01:00
else:
return render_template('errorENG.html',error = 'Unauthorized access!')
2018-11-27 15:48:22 +01:00
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
2018-11-28 01:38:57 +01:00
@app.route('/logoutENG')
def logoutENG():
session.pop('user',None)
return redirect('/indexENG')
2018-11-27 15:48:22 +01:00
@app.route('/signUpWithFace')
def signUpWithFace():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
if type(faces) is not tuple:
i += 1
face = 0
for f in faces[0]:
face += f
faces_list.append(face)
if i == 5:
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
print (faces_list)
2018-12-03 00:31:48 +01:00
return render_template('index.html', info="Zapisano twarz")
2018-11-27 15:48:22 +01:00
2018-11-28 01:38:57 +01:00
@app.route('/signUpWithFaceENG')
def signUpWithFaceENG():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
if type(faces) is not tuple:
i += 1
face = 0
for f in faces[0]:
face += f
faces_list.append(face)
if i == 5:
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
print (faces_list)
2018-12-03 00:31:48 +01:00
return render_template('indexENG.html', info="A face has been saved")
2018-11-28 01:38:57 +01:00
2018-11-27 15:48:22 +01:00
@app.route('/signInWithFace')
def signInWithFace():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
testing_face = 825
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
#print (faces_list)
if type(faces) is not tuple:
face = 0
i += 1
for f in faces[0]:
face += f
if face in faces_list:
break
elif i == 20:
return render_template("error.html", error="Brak dostępu!")
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
2018-12-11 20:57:16 +01:00
return render_template('userHome.html', info="Zapisano twarz", user=session.get('user').split('@')[0], calendar_src="https://calendar.google.com/calendar/embed?src=" + session.get("user"))
2018-11-28 01:38:57 +01:00
@app.route('/signInWithFaceENG')
def signInWithFaceENG():
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
faces = None
testing_face = 825
i = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Display the resulting frame
cv2.imshow('Video', frame)
#print (faces_list)
if type(faces) is not tuple:
face = 0
i += 1
for f in faces[0]:
face += f
if face in faces_list:
break
elif i == 20:
return render_template("errorENG.html", error="Lack of access!")
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
2018-12-11 20:57:16 +01:00
return render_template('userHomeENG.html', info="A face has been saved", user=session.get('user').split('@')[0])
@app.route('/addEvent', methods=['POST'])
def addEvent():
summary = request.form["inputSummary"]
location = request.form["inputLocation"]
description = request.form["inputDescription"]
description = request.form["inputDescription"]
description = request.form["inputDescription"]
start = request.form["inputStart"]
end = request.form["inputEnd"]
attendees = request.form["inputAttendees"].split(',')
processed_attendees = []
for attendee in attendees:
attendee = attendee.strip()
if "@gmail.com" not in attendee:
attendee += "@gmail.com"
processed_attendees.append({'email': attendee})
event = { 'summary': summary,
'location': location,
'description': description,
'start': {
'dateTime': start + ":00+01:00",
'timeZone': 'Europe/Warsaw'
},
'end': {
'dateTime': end + ":00+01:00",
'timeZone': 'Europe/Warsaw'
},
'attendees': processed_attendees
}
#credentials = ServiceAccountCredentials.from_json_keyfile_name(
# 'credentials.json',
# scopes="https://www.googleapis.com/auth/calendar.events")
#http = httplib2.Http()
#http = credentials.authorize(http)
#service = build("calendar", "v3", http=http)
#store = file.Storage('token.json')
#creds = store.get()
#if not creds or creds.invalid:
# flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
# creds = tools.run_flow(flow, store)
#service = build('calendar', 'v3', http=creds.authorize(Http()))
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', "https://www.googleapis.com/auth/calendar.events")
creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))
service.events().insert(calendarId='primary', body=event).execute()
return render_template('userHome.html', user=session['user'].split('@')[0], calendar_src="https://calendar.google.com/calendar/embed?src=" + session.get("user"))
@app.route('/toAddEvent')
def toAddEvent():
if session.get('user'):
return render_template('addEvent.html')
else:
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
2018-11-27 15:48:22 +01:00
if __name__ == "__main__":
2018-12-03 00:31:48 +01:00
#app.run(host='0.0.0.0')
# Port: 5000
2018-12-03 01:52:04 +01:00
#socketio.run(app, debug=True)
2018-12-11 20:57:16 +01:00
socketio.run(app, host="0.0.0.0")#, ssl_context=("cert.pem", "key.pem"))