WU/app.py
2018-12-11 20:57:16 +01:00

651 lines
21 KiB
Python

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
#from flaskext.mysql import MySQL
#from pony.orm import *
import cv2
import logging as log
import datetime as dt
from time import sleep
from flask_socketio import SocketIO
from flask_socketio import emit, join_room, leave_room
import smtplib
from oauth2client import file, client, tools
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
main = Blueprint('main', __name__)
app = Flask(__name__)
app.secret_key = '523tvb6h3nio6r21cc4r1qx'
app.debug = True
socketio = SocketIO()
app.register_blueprint(main)
socketio.init_app(app)
# MySQL configurations
#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)
@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():
session['name'] = session["user"].split('@')[0] #form.name.data
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')
faces_list = []
testing_face = 0
service = None
SCOPES = "https://www.googleapis.com/auth/calendar.events"
@socketio.on('message')
def handleMessage(msg):
print('Message: ' + msg)
send(msg, broadcast=True)
@app.route("/")
def main():
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()))
return render_template('index.html', info="Witaj!")
@app.route("/indexENG")
def indexENG():
return render_template('indexENG.html', info="Hello!")
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/showSignUpENG')
def showSignUpENG():
return render_template('signupENG.html')
@app.route('/showSignIn')
def showSignIn():
return render_template('signin.html')
@app.route('/showSignInENG')
def showSignInENG():
return render_template('signinENG.html')
@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)
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()
@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()
@app.route('/validateLogin',methods=['POST'])
def validateLogin():
#con, cursor = None, None
#try:
#_username = request.form['inputLogin']
gmail_username = request.form['inputLogin']
#_password = request.form['inputPassword']
gmail_password = request.form['inputPassword']
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_username, gmail_password)
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"))
except:
return render_template('error.html',error = 'Zły email lub hasło!')
'''
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('/userHome', user=session['user'])
return render_template('userHome.html', user=session['user'])
else:
return render_template('error.html',error = 'Zły email lub hasło!')
else:
return render_template('error.html',error = 'Zły email lub hasło!')
except Exception as e:
return render_template('error.html',error = str(e))
finally:
if cursor:
cursor.close()
if con:
con.close()
'''
@app.route('/validateLoginENG',methods=['POST'])
def validateLoginENG():
#con, cursor = None, None
#try:
#_username = request.form['inputLogin']
gmail_username = request.form['inputLogin']
#_password = request.form['inputPassword']
gmail_password = request.form['inputPassword']
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_username, gmail_password)
session['user'] = gmail_username#.split('@')[0]
return render_template('userHomeENG.html', user=gmail_username.split('@')[0])
except:
return render_template('errorENG.html',error = 'Wrong email or password!')
'''
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:
if cursor:
cursor.close()
if con:
con.close()
'''
@app.route('/userHome')
def userHome():
if session.get('user'):
return render_template('userHome.html', user=session['user'].split('@')[0], calendar_src="https://calendar.google.com/calendar/embed?src=" + session.get("user"))
else:
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
@app.route('/userHomeENG')
def userHomeENG():
if session.get('user'):
return render_template('userHomeENG.html', user=session['user'].split('@')[0])
else:
return render_template('errorENG.html',error = 'Unauthorized access!')
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
@app.route('/logoutENG')
def logoutENG():
session.pop('user',None)
return redirect('/indexENG')
@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)
return render_template('index.html', info="Zapisano twarz")
@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)
return render_template('indexENG.html', info="A face has been saved")
@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()
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"))
@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()
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!')
if __name__ == "__main__":
#app.run(host='0.0.0.0')
# Port: 5000
#socketio.run(app, debug=True)
socketio.run(app, host="0.0.0.0")#, ssl_context=("cert.pem", "key.pem"))