tpdf/main.py

97 lines
2.5 KiB
Python
Executable File

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# GET me using a web browser,
# executing my code with a Python interpreter called by a CGI-compliant webserver!
# Example URI:
# http://www.example.org/path/main.py?format=format&title=title&author=author
# where:
# format:
# choose output format. Can be either `json` or `html` (default)
# title:
# title of the book to filter (optional)
# author:
# author of the book to filter (optional)
#
# Every parameter is optional.
# Please note that not providing filters results in all books in the library.
# Useful libraries (no pun intended)
import xml.etree.ElementTree as ET
import json
import sys
import cgitb, cgi
import zipfile
import shutil as sh
import os
import time
import configparser
# Our custom library (again no pun intended)
import tcparser
# Start CGI handling for webserver
cgitb.enable()
inputvars = cgi.FieldStorage()
# Detect desired format
try:
format = inputvars['format'].value
except KeyError:
format = 'html'
if format == 'html':
print('Content-Type: text/html; charset=utf-8')
else:
print('Content-Type: text/json; charset=utf-8')
print()
### End of HTTP headers: it is now safe to output things
##########################################################
# Read configuration files (latest files in list override previous settings)
conf = configparser.ConfigParser()
conf.read(['conf/conf.ini', 'conf/conf.custom.ini'])
luh = open('./output/lastupdate.txt', 'r')
lu = int(float(luh.read()))
luh.close()
mtime = os.path.getmtime(conf['default']['path'])
outdir = './output'
if int(lu) < int(mtime):
# Unzip Tellico .tc database
zipHandler = zipfile.ZipFile(conf['default']['path'], 'r')
zipHandler.extractall(outdir)
zipHandler.close()
luh = open('./output/lastupdate.txt', 'w')
luh.write(str(time.time()))
luh.close()
# Get a Python-friendly library struct from XML file
library = tcparser.getLibrary(outdir + "/tellico.xml", lu)
### Get filters to search for books ###
try:
title = inputvars['title'].value
except KeyError:
title = ''
try:
author = inputvars['author'].value
except KeyError:
author = ''
result = tcparser.filter(library, title=title, author=author)
if format == 'html':
htmlTree = tcparser.getHTML(result)
htmlString = ET.tostring(htmlTree.getroot(), encoding='unicode', method='html')
print(htmlString)
if format == 'json':
# Wanna get a pretty JSON encoded library to do your nasty things offline at home? ;-)
print(json.dumps(result, indent=4))