This commit is contained in:
Micik2 2018-12-19 01:54:56 +01:00
parent 3470662318
commit 5186c2e54c
5 changed files with 290 additions and 30 deletions

194
app.py
View File

@ -1,4 +1,4 @@
from flask import Flask, render_template, request, json, session, redirect, Blueprint, url_for
from flask import Flask, render_template, request, json, session, redirect, Blueprint, url_for, flash, Response, send_from_directory
from flask_wtf import Form
from wtforms.fields import StringField, SubmitField
from wtforms.validators import Required
@ -13,8 +13,12 @@ from flask_socketio import emit, join_room, leave_room
import smtplib
from oauth2client import file, client, tools
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
import os
from werkzeug.utils import secure_filename
from camera import VideoCamera
@ -35,6 +39,13 @@ socketio.init_app(app)
#mysql = MySQL()
#mysql.init_app(app)
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/groupChat', methods=['GET', 'POST'])
def indexChat():
@ -99,7 +110,10 @@ class LoginForm(Form):
faces_list = []
testing_face = 0
service = None
SCOPES = "https://www.googleapis.com/auth/calendar.events"
drive_service = None
CALENDAR_SCOPES = "https://www.googleapis.com/auth/calendar.events"
DRIVE_SCOPES = "https://www.googleapis.com/auth/drive"
@socketio.on('message')
def handleMessage(msg):
@ -111,9 +125,15 @@ def main():
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
flow = client.flow_from_clientsecrets('credentials.json', CALENDAR_SCOPES)
creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', DRIVE_SCOPES)
creds = tools.run_flow(flow, store)
drive_service = build('drive', 'v3', http=creds.authorize(Http()))
return render_template('index.html', info="Witaj!")
@app.route("/indexENG")
@ -636,6 +656,10 @@ def addEvent():
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('/streaming')
def streaming():
return render_template('streaming.html')
@app.route('/toAddEvent')
def toAddEvent():
if session.get('user'):
@ -643,6 +667,170 @@ def toAddEvent():
else:
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/stream')
def stream():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
def make_tree(path=app.config['UPLOAD_FOLDER']):
tree = dict(name=path, children=[])
try: lst = os.listdir(path)
except OSError:
pass #ignore errors
else:
for name in lst:
fn = os.path.join(path, name)
if os.path.isdir(fn):
tree['children'].append(make_tree(fn))
else:
tree['children'].append(dict(name=fn))
return tree
@app.route('/uploads/<filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename, as_attachment=True)
@app.route('/toResources')
def toResources():
if session.get('user'):
files = make_tree()
# list_of_files = {}
# path = app.config['UPLOAD_FOLDER']
# for filename in os.listdir(path):
# print (filename)
# print ()
# list_of_files[filename] = filename.file.name
print (files)
# items_keys = []
# for key, value in files.items():
# if key == "children":
# for k, v in value[0].items():
# items_keys.append(v)
# items_values = []
# for item in items_keys:
# items_values.append(item.indexOf("\\"))
return render_template('resources.html', items=files)
else:
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
@app.route('/resources', methods=['POST'])
def resources():
if request.method == 'POST':
# check if the post request has the file part
#if 'file' not in request.files:
# flash('No file part')
# return redirect(request.url)
file = request.files['fileToUpload']
#file = request.form["fileToUpload"]
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return render_template('userHome.html', user=session['user'].split('@')[0], calendar_src="https://calendar.google.com/calendar/embed?src=" + session.get("user"))
@app.route('/showResources')
def showResources():
path = app.config['UPLOAD_FOLDER']
for filename in os.listdir(path):
list_of_files[filename] = filename
#return render_template("")
#input_file = UPLOAD_FOLDER + filename
#uploads = []
#uploads.append(input_file)
#return render_template('resources.html', resources = uploads)
# if user does not select file, browser also
# submit an empty part without filename
#if file.filename == '':
# flash('No selected file')
# return redirect(request.url)
#if file and allowed_file(file.filename):
#filename = secure_filename(file.filename)
#filename = app.config['UPLOAD_FOLDER'] + file.filename
#file.save(filename) #os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
#return redirect(url_for('uploaded_file', filename=filename))
'''if request.method == 'GET':
uploads = app.config['UPLOAD_FOLDER'] #os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
return render_template('resources.html', resources = os.getcwd() + os.listdir(uploads))
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
''' '''
@app.route('/addResources', methods=['GET', 'POST'])
def addResources():
if request.method == 'POST':
# check if the post request has the file part
#if 'file' not in request.files:
# flash('No file part')
# return redirect(request.url)
file = request.files['fileToUpload']
file_metadata = {'name': file}
path = request.files['fileToUpload'].file.name
print (os.path.basename(file.filename))
media = MediaFileUpload(path)
file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
results = drive_service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
return render_template('allResources.html', resources = items)
# file = request.files['fileToUpload']
# file = request.form["fileToUpload"]
# filename = secure_filename(file.filename)
# file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# input_file = UPLOAD_FOLDER + filename
# uploads = []
# uploads.append(input_file)
# return render_template('addResources.html', resources = uploads)
@app.route('/allResources')
def allResources():
results = drive_service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
return render_template('allResources.html', resources = items)
@app.route('/toAllResources')
def toAllResources():
if session.get('user'):
uploads = app.config['UPLOAD_FOLDER'] #os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
path = os.getcwd()
return render_template('allResources.html', resources = os.path.join(path, uploads))
#return render_template('resources.html')
else:
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
@app.route('/toAddResources')
def toAddResources():
if session.get('user'):
uploads = app.config['UPLOAD_FOLDER'] #os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
path = os.getcwd()
return render_template('addResources.html', resources = os.path.join(path, uploads))
#return render_template('resources.html')
else:
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
@app.route('/downloadResource')
def downloadResource():
if session.get('user'):
file_id = request.files["files"]
return render_template('addResources.html', resources = os.path.join(path, uploads))
#return render_template('resources.html')
else:
return render_template('error.html',error = 'Nieautoryzowany dostęp!')
'''
if __name__ == "__main__":
#app.run(host='0.0.0.0')
# Port: 5000

93
templates/resources.html Normal file
View File

@ -0,0 +1,93 @@
<!DOCTYPE html>
<!--<html lang="en">-->
<html lang="pl-PL">
<head>
<meta charset="UTF-8">
<title>Python Flask App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="signup.css">
<!-- <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"> -->
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<link href="../static/css/signup.css" rel="stylesheet">
<link rel="stylesheet" href="../static/css/calendar.css">
</head>
<body>
<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-left">
<!--<form><input type="button" value="Back" onClick="history.go(-1);return true;"></form>-->
<!--<li role="presentation" class="active"><input type="button" value="Back" onClick="history.go(-1);return true;">
</li>-->
<!--<li role="presentation" class="active"><form action="http://google.com"><input type="button" value="Wstecz" onClick="history.go(-1);return true;"></form></li>-->
<!-- <li role="presentation" class="active"><a href="userHomeENG">ENG</a> -->
<!-- </li> -->
<li role="presentation" class="active"><a href="userHome">Wróć do strony domowej</a>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active"><a href="/logout">Wyloguj</a>
</li>
</ul>
</nav>
<h3 class="text-muted"><center>Python Flask</center></h3>
</div>
<div class="jumbotron" style="height: 550px;">
<h1>Wszystkie materiały uczelni</h1>
<div class="col-xs-6">
<h2>Materiały do pobrania:</h2>
<!-- <form action="downloadResource" method="get" enctype="multipart/form-data"> -->
{% for key, value in items.items() %}
{% if key == "children" %}
{% for val in value %}
{% for k, v in val.items() %}
<h3><ul><a href="{{ v }}">{{ v[v.index('\\')+1:] }}</a></ul></h3>
<!-- <ul>{{ value }}</ul> -->
<!-- <h2>Value: {{value}}</h2> -->
{% endfor %}
{% endfor %}
{% endif %}
{% endfor %}
<!-- {% for item in items %} -->
<!-- item.children -->
<!-- <ul><a href="{{ item.children }}">{{ item.children }}</a></ul> -->
<!-- {% endfor %} -->
<!-- {% for file in files %} -->
<!-- file</br> -->
<!-- <ol><a href="{{ resource }}" download>Plik</a></ol> -->
<!-- {% endfor %} -->
<!-- </form> -->
</div>
<div class="col-xs-6">
<h3>Wrzuć materiał</h3>
<form action="resources" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Przekaż plik" name="submit">
</form>
</div>
</div>
<footer class="footer">
<p>&copy; UAM 2018</p>
</footer>
</div>
</body>
</html>

View File

@ -140,36 +140,13 @@ body {font-family: Verdana, sans-serif;}
<!-- <a class="btn btn-lg btn-success" href="#" role="button">Wyniki</a> -->
<a class="btn btn-lg btn-success" href="toAddEvent" role="button">Dodaj wydarzenie</a>
<a class="btn btn-lg btn-success" href="chat" role="button" style="margin-top: 5px;">Czat grupowy</a>
<!-- <a class="btn btn-lg btn-success" href="toResources" role="button" style="margin-top: 5px;">Dodaj materiały</a> -->
<a class="btn btn-lg btn-success" href="toResources" role="button" style="margin-top: 5px;">Podejrzyj materiały</a>
<a class="btn btn-lg btn-success" href="stream" role="button" style="margin-top: 5px;">Uruchom testowy stream</a>
<!-- <form action="ch"> -->
<!-- <input type="submit" value="Wejdź na czat grupowy" /> -->
<!-- </form> -->
</p>
<table>
<tr>
<th>Czas</th>
<th>Jaka aktywność</th>
</tr>
<tr>
<td>8:00</td>
<td>brak</td>
</tr>
<tr>
<td>9:00</td>
<td>brak</td>
</tr>
<tr>
<td>10:00</td>
<td>brak</td>
</tr>
<tr>
<td>11:00</td>
<td>brak</td>
</tr>
<tr>
<td>12:00</td>
<td>brak</td>
</tr>
</table>
</div>

1
uploads/test.txt Normal file
View File

@ -0,0 +1 @@
test uploadu

1
uploads/test_2.txt Normal file
View File

@ -0,0 +1 @@
test downloadu