Private Study
Code
from flask import Flask, request, jsonify , redirect
import datetime
import json
import urllib.parse
from discord_webhook import DiscordWebhook
from time import sleep
from dotenv import load_dotenv
import os
load_dotenv()
from google_auth_oauthlib.flow import Flow
app = Flask(__name__)
@app.after_request
def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
return response
def getContent():
content = ""
file = open("log.txt","r")
for line in file:
name = line.split(",")[0].strip()
register = line.split(",")[1].strip()
date = line.split(",")[2].strip()
time = line.split(",")[3].strip()
content += f"{name},{register},{date},{time}\n"
content = f"```{content}```"
return content
DISCORD_URL = os.getenv("DISCORD-URL")
# webhook = DiscordWebhook(url=DISCORD_URL, content=getContent())
# webhook.execute()
@app.route('/backend', methods=['POST'])
def receive_data():
data = request.get_json()
first_name = data['firstName']
second_name = data['secondName']
selected_class = data['selectedClass']
authUser = data['authUser']
roomNumber = data['roomNumber']
if get_current_period() == "No ongoing period":
response = {'url': "None",'status':'444'}
return jsonify(response)
else:
URL = get_url(first_name, second_name, selected_class,authUser,roomNumber)
response = {'url': URL,'status':'200'}
return jsonify(response)
def get_url(forename,surename,register,authUser,roomNumber):
forename = forename.lower().capitalize()
surename = surename.lower().capitalize()
register = uppercase_register(register)
firstLink = f"https://docs.google.com/forms/u/{authUser}/d/e/1FAIpQLScRh9KkjqK-McprkNoCJCdprlK9cgfyIAEd9AxzzTleWNhhmg/formResponse?"
current_date = datetime.date.today()
# Extract the day, year, and month from the current date
day = current_date.strftime("%d")
month = current_date.strftime("%m")
year = current_date.strftime("%Y")
time = (datetime.datetime.now() + datetime.timedelta(hours=1)).time()
secondLink = f"entry.{find_entry(register)}={surename}+{forename}&entry.329194055_year={year}&entry.329194055_day={day}&entry.329194055_month={month}&entry.982001856={register}&entry.2550748={get_current_period()}&entry.1608292778={roomNumber}&emailAddress={forename.lower()}.{surename.lower()}%40{schoolorg}.org.uk&submit=Submit"
file = open("log.txt","a")
file.write(f"{forename} {surename},{register},{day}/{month}/{year},{time}\n")
file.close()
# webhook.content = getContent()
# webhook.edit()
return firstLink+secondLink
def uppercase_register(register):
newRegister = ""
for char in register:
if ord(char) >= ord("a") and ord(char) <= ord("z"):
newRegister += char.upper()
else:
newRegister += char
return newRegister
def find_entry(register):
# Read the JSON data from the file
with open("classes.json") as file:
data = json.load(file)
# Perform a linear search
entry = None
for class_entry in data["classes"]:
if class_entry["class"] == register:
entry = class_entry["entry"]
break
return entry
def get_current_period():
current_time = datetime.datetime.now().time()
current_datetime = datetime.datetime.combine(datetime.date.today(), current_time)
# Check if it's Saturday or Sunday
if current_datetime.weekday() in [5, 6]:
return "No ongoing period"
# Add one hour to the current datetime
updated_datetime = current_datetime + datetime.timedelta(hours=1)
# Extract the time from the updated datetime
updated_time = updated_datetime.time()
if datetime.time(8, 50) <= updated_time < datetime.time(9, 40):
return "Period+1"
elif datetime.time(9, 40) <= updated_time < datetime.time(10, 30):
return "Period+2"
elif datetime.time(10, 30) <= updated_time < datetime.time(11, 20):
return "Period+3"
elif datetime.time(11, 35) <= updated_time < datetime.time(12, 25):
return "Period+4"
elif datetime.time(12, 25) <= updated_time < datetime.time(13, 15):
return "Period+5"
elif datetime.time(14, 0) <= updated_time < datetime.time(14, 50):
return "Period+6"
elif datetime.time(14, 50) <= updated_time < datetime.time(15, 40):
return "Period+7"
else:
return "No ongoing period"
# Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual credentials
CLIENT_ID = CLIENT_ID
CLIENT_SECRET = CLIENT_SECRET
REDIRECT_URI = 'https://privatestudy.funkypanda.me/backend/google-auth/callback'
@app.route('/backend/google-auth')
def google_auth():
flow = Flow.from_client_secrets_file(
'client_secret.json',
scopes=['openid', 'email'],
redirect_uri=REDIRECT_URI
)
authorization_url, _ = flow.authorization_url(prompt='consent')
print(authorization_url)
return redirect(authorization_url, code=302)
@app.route('/backend/google-auth/callback')
def google_auth_callback():
authuser = request.args.get('authuser')
print(f"The number for the authuser is {authuser}")
# flow = Flow.from_client_secrets_file(
return redirect(f"https://privatestudy.funkypanda.me/?authuser={authuser}")
# return jsonify({'authuserIndex': authuser})
if __name__ == '__main__':
app.run(port=6060)