Dynastie/generators/category.py

96 lines
3.5 KiB
Python

import os
from xml.dom.minidom import parse, parseString
from dynastie.generators.generator import DynastieGenerator
from dynastie.generators.index import Index
from django.db import models
class Category(Index):
cur_page = 0
nb_pages = 0
cur_article = 0
articles_per_page = 0
filename = 'index'
dirname = ''
cur_category = None
def createCategory(self, articles, dom, root, node):
if node.hasAttribute('name'):
self.replaceByText(dom, root, node, self.cur_category.name)
if node.hasAttribute('description'):
self.replaceByText(dom, root, node, self.cur_category.description)
def generate(self, blog, src, output):
from dynastie.models import Article, Blog, Category
hooks = {'articles' : self.createArticles,
'navigation' : self.createNavigation,
'category' : self.createCategory}
if not os.path.exists(src + '/_category.html'):
self.addError('No _category.html found, exiting')
return self.report
try:
dom = parse(src + '/_category.html')
except xml.dom.DOMException as e:
self.addError('Error parsing _category.html : ' + e)
return self.report
if not os.path.exists(output + '/category'):
os.mkdir(output + '/category')
article_nodes = dom.getElementsByTagNameNS(self.URI, "articles")
if not article_nodes is None:
if article_nodes[0].hasAttribute("limit"):
self.articles_per_page = int(article_nodes[0].getAttribute("limit"))
else:
self.articles_per_page = 5
else:
self.addError('No tag dyn:articles found')
categories = Category.objects.all()
for category in categories:
self.cur_category = category
filename = self.filename + '.html'
articles = Article.objects.filter(category__exact=category, published=True).order_by('-creation_date')
self.nb_pages = 0
self.cur_page = 0
self.cur_article = 0
self.dirname = '/category/' + category.name_slug
if articles.count() > self.articles_per_page:
self.nb_pages = self.computeNbPages(articles.count(), self.articles_per_page)
if not os.path.exists(output + self.dirname):
os.mkdir(output + self.dirname)
while self.cur_page <= self.nb_pages:
#print 'Generate ' + filename
nodes = dom.getElementsByTagName("*")
nodes[0] = self.parse(src, hooks, articles, dom, nodes[0])
self.writeIfNotTheSame(output + self.dirname + '/' + filename, nodes[0])
self.cur_page = self.cur_page + 1
filename = self.filename + str(self.cur_page) + '.html'
dom = parse(src + '/_category.html')
while os.path.exists(filename):
self.addReport('Removing unused ' + filename)
os.unlink(filename)
filename = filename + '.gz'
if os.path.exists(filename):
self.addReport('Removing unused ' + filename)
os.unlink(filename)
self.cur_page = self.cur_page + 1
filename = output + self.dirname + '/' + self.filename + str(self.cur_page) + '.html'
if not self.somethingWrote:
self.addReport('Nothing changed')
return self.report