gancio-flyers/app.py

73 lines
2.5 KiB
Python
Executable file

#!/usr/bin/env python3
import requests
import json
import datetime
import pathlib
from jinja2 import Environment, FileSystemLoader
from flask import Flask
from flask import render_template, request
app = Flask(__name__)
gancio_instance = 'balotta.org'
templates = json.load(open('./templates.json'))
default_template = 'simple'
events_ep = f'https://{gancio_instance}/api/events'
def day2giorno(day):
days = {
'Monday': 'Lunedì',
'Tuesday': 'Martedì',
'Wednesday': 'Mercoledì',
'Thursday': 'Giovedì',
'Friday': 'Venerdì',
'Saturday': 'Sabato',
'Sunday': 'Domenica'
}
if day in days:
return days[day]
def fetch_events(api_endpoint):
events = requests.get(events_ep).json()
for event in events:
start_dt = datetime.datetime.fromtimestamp(event['start_datetime'])
start_day = f"{day2giorno(start_dt.strftime('%A'))} {start_dt.strftime('%d')}"
start_hour = start_dt.strftime("%H:%M")
when = f"{start_day} dalle {start_hour}"
if event['end_datetime']:
end_dt = datetime.datetime.fromtimestamp(event['end_datetime'])
end_day = f"{day2giorno(start_dt.strftime('%A'))} {end_dt.strftime('%d')}"
end_hour = end_dt.strftime("%H:%M")
if event['multidate']:
when = f"da {when} a {end_day}"
when += " alle "
when += end_hour
event['when'] = when
event['media'][0]['thumbnailPosition'] = f"{(event['media'][0]['focalpoint'][0] + 1) * 50}% {(event['media'][0]['focalpoint'][1] + 1) * 50}%"
return events
@app.route("/")
def main():
events = fetch_events(events_ep)
return render_template('index.html',
events=events,
templates=templates,
default_template=default_template)
@app.route("/flyer")
def flyer():
relevant_events = request.args.getlist('events', type=int)
template = request.args.get("template", default=default_template, type=str)
if template not in [ t['name'] for t in templates ]:
return "template not found", 404
template = [t for t in templates if t['name'] == template][0]
events = fetch_events(events_ep)
events = [ e for e in events if e['id'] in relevant_events ]
params = {}
if 'params' in template:
params = template['params']
return render_template(f'flyers/{template["baseTemplate"]}.html', events=events, params=params)