diff --git a/djaif/book/book_map.py b/djaif/book/book_map.py new file mode 100644 index 0000000..f52be31 --- /dev/null +++ b/djaif/book/book_map.py @@ -0,0 +1,47 @@ +from graphviz import Digraph + +from djaif.book import models + + +def book_map(book): + dig = Digraph('Map') + + for page in book.bookpage_set.all(): + dig.node( + _pid(page), + label='{page.id}:"{page.title}"\n{items}'.format( + page=page, + items='\n'.join( + '+ {id}:"{name}"'.format( + id=i.id, name=i.name[:10], + ) for i in page.items.all(), + ), + ), + tooltip=page.body, + href='/admin/book/bookpage/{0.id}/change'.format(page), + ) + + links = models.PageLink.objects.filter(from_page__book_id=book.id) + for link in links.all(): + dig.edge( + _pid(link.from_page), + _pid(link.to_page), + label='{link.id}:"{shortname}"\n{items}'.format( + link=link, + shortname=link.name[:10], + items='\n'.join( + '? {id}:"{name}"'.format( + id=i.id, name=i.name[:10], + ) for i in link.items.all(), + ), + ), + labeltooltip=link.name, + labelhref='/admin/book/pagelink/{0.id}/change'.format(link), + ) + + dig.format = 'svg' # noqa: WPS125 + return dig.pipe().decode('utf-8') + + +def _pid(page): + return 'page_{id}'.format(id=page.id) diff --git a/djaif/book/views.py b/djaif/book/views.py index 0d69cbe..71d9799 100644 --- a/djaif/book/views.py +++ b/djaif/book/views.py @@ -3,9 +3,8 @@ from django.http import FileResponse from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse -from graphviz import Digraph -from djaif.book import models +from djaif.book import book_map, models def _return_to(book_id): @@ -124,34 +123,4 @@ def delete_save(request, book_id, save_id): def view_book_map(request, book_id): book = get_object_or_404(models.Book, id=book_id) - - g = Digraph('Map', filename='map.gv', directory='/tmp') - - def pid(page): - return 'page_{id}'.format(id=page.id) - - for page in book.bookpage_set.all(): - g.node( - pid(page), - label='\n'.join( - [str(page.id), page.title] + [ - i.name for i in page.items.all() - ] - ), - tooltip=page.body, - href='/admin/book/bookpage/{}/change'.format(page.id), - ) - - for link in models.PageLink.objects.filter( - from_page__book_id=book_id, - ).all(): - g.edge(pid(link.from_page), pid(link.to_page), label='\n'.join( - [str(link.id), link.name[:10]] + [ - i.name for i in link.items.all() - ]), - labeltooltip=link.name, - labelhref='/admin/book/pagelink/{}/change'.format(link.id), - ) - - g.render(quiet=True, view=False, format='svg') - return FileResponse(open('/tmp/map.gv.svg', 'rb')) + return FileResponse(book_map.book_map(book), filename='map.svg')