Improved exporting functions and added boiler plate for other stuff

This commit is contained in:
Ed 2023-07-04 23:07:39 +02:00
parent 5ca739cec2
commit b7bb609d81
3 changed files with 54 additions and 22 deletions

25
app.py
View File

@ -5,11 +5,16 @@ from time import time
import httpx import httpx
import re import re
import json import json
import logging
from os.path import join from os.path import join
from ext import * from ext import *
from config import * from config import *
from aztec_code_generator import AztecCode from aztec_code_generator import AztecCode
from io import BytesIO from io import BytesIO
from asyncio import Queue
import sqlite3
log = logging.getLogger()
app = Sanic(__name__) app = Sanic(__name__)
app.static("/res", "res/") app.static("/res", "res/")
@ -24,8 +29,12 @@ from export import bp as export_bp
from stats import bp as stats_bp from stats import bp as stats_bp
from api import bp as api_bp from api import bp as api_bp
from carpooling import bp as carpooling_bp from carpooling import bp as carpooling_bp
from nfc import bp as nfc_bp
from checkin import bp as checkin_bp
from money import bp as money_bp
from boop import bp as boop_bp
app.blueprint([room_bp, karaoke_bp, propic_bp, export_bp, stats_bp, api_bp, carpooling_bp]) app.blueprint([room_bp, karaoke_bp, propic_bp, export_bp, stats_bp, api_bp, carpooling_bp, nfc_bp, checkin_bp, money_bp, boop_bp])
@app.exception(exceptions.SanicException) @app.exception(exceptions.SanicException)
async def clear_session(request, exception): async def clear_session(request, exception):
@ -42,7 +51,21 @@ async def main_start(*_):
print(">>>>>> main_start <<<<<<") print(">>>>>> main_start <<<<<<")
app.ctx.om = OrderManager() app.ctx.om = OrderManager()
if FILL_CACHE:
log.info("Filling cache!")
await app.ctx.om.fill_cache()
log.info("Cache fill done!")
app.ctx.nfc_counts = sqlite3.connect('data/nfc_counts.db')
app.ctx.boop = sqlite3.connect('data/boop.db')
app.ctx.money = sqlite3.connect('data/money.db')
app.ctx.money.row_factory = sqlite3.Row
app.ctx.login_codes = {} app.ctx.login_codes = {}
app.ctx.nfc_reads = {}
app.ctx.boops = Queue()
app.ctx.tpl = Environment(loader=FileSystemLoader("tpl"), autoescape=True) app.ctx.tpl = Environment(loader=FileSystemLoader("tpl"), autoescape=True)
app.ctx.tpl.globals.update(time=time) app.ctx.tpl.globals.update(time=time)
app.ctx.tpl.globals.update(PROPIC_DEADLINE=PROPIC_DEADLINE) app.ctx.tpl.globals.update(PROPIC_DEADLINE=PROPIC_DEADLINE)

View File

@ -52,7 +52,7 @@ async def export_csv(request, order: Order):
return text(ret) return text(ret)
@bp.route("/hotel_export.csv") @bp.route("/hotel_export.csv")
async def export_csv(request, order: Order): async def export_hotel_csv(request, order: Order):
if not order: raise exceptions.Forbidden("You have been logged out. Please access the link in your E-Mail to login again!") if not order: raise exceptions.Forbidden("You have been logged out. Please access the link in your E-Mail to login again!")
if order.code not in ['HWUC9','9YKGJ']: raise exceptions.Forbidden("Birichino :)") if order.code not in ['HWUC9','9YKGJ']: raise exceptions.Forbidden("Birichino :)")

49
ext.py
View File

@ -31,6 +31,7 @@ class Order:
self.last_name = None self.last_name = None
self.country = None self.country = None
self.address = None self.address = None
self.checked_in = False
for p in self.data['positions']: for p in self.data['positions']:
if p['item'] in [16, 38]: if p['item'] in [16, 38]:
@ -39,6 +40,7 @@ class Order:
self.answers = p['answers'] self.answers = p['answers']
self.barcode = p['secret'] self.barcode = p['secret']
self.address = f"{p['street']} - {p['zipcode']} {p['city']} - {p['country']}" self.address = f"{p['street']} - {p['zipcode']} {p['city']} - {p['country']}"
self.checked_in = bool(p['checkins'])
if p['item'] == 17: if p['item'] == 17:
self.has_card = True self.has_card = True
@ -77,6 +79,8 @@ class Order:
self.is_artist = True if self.ans('is_artist') != 'No' else False self.is_artist = True if self.ans('is_artist') != 'No' else False
self.is_fursuiter = True if self.ans('is_fursuiter') != 'No' else False self.is_fursuiter = True if self.ans('is_fursuiter') != 'No' else False
self.is_allergic = True if self.ans('is_allergic') != 'No' else False self.is_allergic = True if self.ans('is_allergic') != 'No' else False
self.notes = self.ans('notes')
self.badge_id = int(self.ans('badge_id')) if self.ans('badge_id') else None
self.propic_locked = self.ans('propic_locked') self.propic_locked = self.ans('propic_locked')
self.propic_fursuiter = self.ans('propic_fursuiter') self.propic_fursuiter = self.ans('propic_fursuiter')
self.propic = self.ans('propic') self.propic = self.ans('propic')
@ -96,7 +100,7 @@ class Order:
self.app_token = self.ans('app_token') self.app_token = self.ans('app_token')
self.nfc_id = self.ans('nfc_id') self.nfc_id = self.ans('nfc_id')
self.can_scan_nfc = True if self.ans('can_scan_nfc') != 'No' else False self.can_scan_nfc = True if self.ans('can_scan_nfc') != 'No' else False
self.actual_room_id = self.ans('actual_room_id') self.actual_room = self.ans('actual_room')
self.telegram_username = self.ans('telegram_username').strip('@') if self.ans('telegram_username') else None self.telegram_username = self.ans('telegram_username').strip('@') if self.ans('telegram_username') else None
def __getitem__(self, var): def __getitem__(self, var):
@ -105,7 +109,7 @@ class Order:
def ans(self, name): def ans(self, name):
for p in self.data['positions']: for p in self.data['positions']:
for a in p['answers']: for a in p['answers']:
if a['question_identifier'] == name: if a.get('question_identifier', None) == name:
if a['answer'] in ['True', 'False']: if a['answer'] in ['True', 'False']:
return bool(a['answer'] == 'True') return bool(a['answer'] == 'True')
return a['answer'] return a['answer']
@ -115,7 +119,7 @@ class Order:
found = False found = False
self.pending_update = True self.pending_update = True
for key in range(len(self.answers)): for key in range(len(self.answers)):
if self.answers[key]['question_identifier'] == name: if self.answers[key].get('question_identifier', None) == name:
if new_answer != None: if new_answer != None:
print('EXISTING ANSWER UPDATE', name, '=>', new_answer) print('EXISTING ANSWER UPDATE', name, '=>', new_answer)
self.answers[key]['answer'] = new_answer self.answers[key]['answer'] = new_answer
@ -207,27 +211,32 @@ class OrderManager:
del self.cache[code] del self.cache[code]
self.order_list.remove(code) self.order_list.remove(code)
async def get_order(self, request=None, code=None, secret=None, cached=False): async def fill_cache(self):
p = 0
# Fill the cache on first load
if not self.cache and FILL_CACHE:
p = 0
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
while 1: while 1:
p += 1 p += 1
res = await client.get(join(base_url, f"orders/?page={p}"), headers=headers) res = await client.get(join(base_url, f"orders/?page={p}"), headers=headers)
if res.status_code == 404: break if res.status_code == 404: break
data = res.json() data = res.json()
for o in data['results']: for o in data['results']:
o = Order(o) o = Order(o)
if o.status in ['canceled', 'expired']: if o.status in ['canceled', 'expired']:
self.remove_cache(o.code) self.remove_cache(o.code)
else: else:
self.add_cache(Order(o)) self.add_cache(Order(o))
async def get_order(self, request=None, code=None, secret=None, nfc_id=None, cached=False):
# if it's a nfc id, just retorn it
if nfc_id:
for order in self.cache.values():
if order.nfc_id == nfc_id:
return order
# If a cached order is needed, just get it if available # If a cached order is needed, just get it if available
if code and cached and code in self.cache and time()-self.cache[code].time < 3600: if code and cached and code in self.cache and time()-self.cache[code].time < 3600:
return self.cache[code] return self.cache[code]