diff options
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | lib/books.py | 9 | ||||
-rw-r--r-- | lib/util.py | 7 | ||||
-rwxr-xr-x | roka.py | 75 | ||||
-rw-r--r-- | templates/index.html | 2 |
5 files changed, 81 insertions, 13 deletions
@@ -3,5 +3,6 @@ __pycache__ cache sandbox +static app.cfg uwsgi.ini diff --git a/lib/books.py b/lib/books.py index 1c4b4a5..6f3510b 100644 --- a/lib/books.py +++ b/lib/books.py @@ -15,7 +15,8 @@ JSON_PATH = os.path.join(CACHE_PATH, 'audiobooks.json') # use Flask's config parser, configparser would be hacky APP = Flask(__name__) -APP.config.from_pyfile(os.path.join(ABS_PATH, '../', 'app.cfg')) +if os.path.exists(os.path.join(ABS_PATH, '../', 'app.cfg')): + APP.config.from_pyfile(os.path.join(ABS_PATH, '../', 'app.cfg')) class Books: def __init__(self): @@ -86,7 +87,7 @@ class Books: now = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") print('%s %s' % (now, msg)) - def scan_books(self): + def scan_books(self, audiobook_path=None): ''' Discover audiobooks under :root_path: and populate books object @@ -94,7 +95,7 @@ class Books: (existing content is not re-hashed) ''' ex = self._get_path_hash_dict() - dirs = self._get_dirs(APP.config['ROOT_PATH']) + dirs = self._get_dirs(audiobook_path or APP.config['ROOT_PATH']) books = dict() for path in dirs: @@ -145,7 +146,7 @@ class Books: # previous conditions met, we've found at least one track is_book = True - self._log(f) + self._log(os.path.join(path, f)) # hash track (used as a key) and update folder hash file_hash = hashlib.md5() diff --git a/lib/util.py b/lib/util.py index 1eb6af6..4693ef1 100644 --- a/lib/util.py +++ b/lib/util.py @@ -78,9 +78,7 @@ def escape(s): return s -def generate_rss(request, books): - book = request.args.get('a') # audiobook hash - +def generate_rss(base_url, book, books, static=False): # we only make use of the itunes ns, others provided for posterity namespaces = { 'itunes':'http://www.itunes.com/dtds/podcast-1.0.dtd', @@ -156,8 +154,9 @@ def generate_rss(request, books): pub_format = '%a, %d %b %Y %H:%M:%S %z' pub_date.text = (date(2000, 12, 31) - timedelta(days=idx)).strftime( pub_format) + url_format = '{}{}/{}.mp3' if static else '{}?a={}&f={}' enc_attr = { - 'url': '{}?a={}&f={}'.format(request.base_url, book, f), + 'url': url_format.format(base_url, book, f), 'length': str(books[book]['files'][f]['size_bytes']), 'type': 'audio/mpeg' } @@ -2,13 +2,15 @@ import argparse import os -from flask import Flask, request, Response, render_template, send_file +import shutil +from flask import Flask, request, Response, render_template, send_file, templating from lib.books import Books from lib.util import check_auth, escape, generate_rss, read_cache abs_path = os.path.dirname(os.path.abspath(__file__)) app = Flask(__name__) -app.config.from_pyfile(os.path.join(abs_path, 'app.cfg')) +if os.path.exists(os.path.join(abs_path, 'app.cfg')): + app.config.from_pyfile(os.path.join(abs_path, 'app.cfg')) cache_path = os.path.join(abs_path, 'cache') json_path = os.path.join(cache_path, 'audiobooks.json') @@ -40,7 +42,7 @@ def list_books(): if not books.get(a): return 'book not found', 404 - rss = generate_rss(request, books) + rss = generate_rss(request.base_url, a, books) return Response(rss, mimetype='text/xml') else: @@ -51,17 +53,82 @@ def list_books(): return render_template('index.html', books=books) +# TODO does this really need to be here? +def my_render_template( + app, template_name_or_list, **context +) -> str: + """Renders a template from the template folder with the given + context. + + :param template_name_or_list: the name of the template to be + rendered, or an iterable with template names + the first one existing will be rendered + :param context: the variables that should be available in the + context of the template. + """ + app.update_template_context(context) + return templating._render( + app.jinja_env.get_or_select_template(template_name_or_list), + context, + app, + ) + +def generate(static_path, base_url, audiobook_dirs): + static_index_path = os.path.join(static_path, 'index.html') + + books = Books() + books.scan_books(audiobook_dirs) + # TODO avoid writing and reading cache + books.write_cache() + books = read_cache(json_path) + index = my_render_template(app, 'index.html', books=books, static=True) + + os.makedirs(static_path, exist_ok=True) + + indexfile = open(static_index_path, 'w') + indexfile.write(index) + indexfile.close() + + for b_key, book in books.items(): + rss = generate_rss(base_url, b_key, books, static=True) + rss_path = os.path.join(static_path, b_key + '.xml') + rssfile = open(rss_path, 'w') + rssfile.write(rss.decode('utf-8')) + rssfile.close() + + book_dir = os.path.join(static_path, b_key) + os.makedirs(book_dir, exist_ok=True) + + for f_key, file in book['files'].items(): + f_path = file['path'] + copy_path = os.path.join(book_dir, f_key + '.mp3') + shutil.copyfile(f_path, copy_path) + if __name__ == '__main__': desc = 'roka: listen to audiobooks with podcast apps via RSS' parser = argparse.ArgumentParser(description=desc) parser.add_argument('--scan', dest='scan', action='store_true', help='scan audiobooks directory for new books', required=False) + parser.add_argument('--generate', dest='static_path', type=str, action='store', + help='Output directory to generate static files', + required=False) + parser.add_argument('--base_url', dest='base_url', type=str, action='store', + help='Base URL to use in static files', + required=False) + parser.add_argument('--scan_dir', dest='scan_dir', type=str, action='store', + help='Directory to scan for audiobooks', + required=False) args = parser.parse_args() + if args.static_path and not args.base_url or args.base_url and not args.static_path: + parser.error('--generate and --base_url must be included together') + if args.scan: books = Books() - books.scan_books() + books.scan_books(args.scan_dir) books.write_cache() + elif args.static_path: + generate(args.static_path, args.base_url, args.scan_dir) else: app.run(host='127.0.0.1', port='8085', threaded=True) diff --git a/templates/index.html b/templates/index.html index c05ff8e..4e6998d 100644 --- a/templates/index.html +++ b/templates/index.html @@ -35,7 +35,7 @@ </tr> {% for b, v in books.items() %} <tr> - <td><a href="?a={{ b }}">{{ v['title']|escape }}</a></td> + <td><a href="{{'?a=' if not static else '/'}}{{ b }}{{'.xml' if static}}">{{ v['title']|escape }}</a></td> <td>{{ v['path']|escape }}</td> <td>{{ v['files']|length }}</td> <td>{{ v['duration_str'] }}</td> |