2 # -*- coding: utf-8 -*-
3 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
8 sys.path.append('./apps')
9 sys.path.append('./lib')
11 from django.core.management import setup_environ
12 from redakcja import settings
13 from getopt import getopt
15 setup_environ(settings)
17 from catalogue.models import Book, Chunk
20 from django.db import transaction
24 def books_by_slug(term, just_one=False, exclude=None):
25 books = Book.objects.filter(slug__contains=term)
27 books = filter(lambda not b.slug in exclude, books)
29 for b in range(len(books)):
30 print "%d) %s" % (b+1, books[b].slug)
45 if ch[0] in ('y', 'Y'):
48 raise Exception("please change your query then")
52 print "%02d. %s [%s]" % (c.number, c.title, c.slug)
54 print "is this ok (y/n)? "
59 raise Exception("Aborting")
62 def move_chunk(term, chunk_idx, new_position):
63 with transaction.commit_on_success():
64 books = Book.objects.filter(slug__contains=term)
65 book = books_by_slug(term, just_one=True)
67 chunks_total = len(book)
68 max_number = max(c.number for c in book)
69 moving_chunk = next(c for c in book if c.number == chunk_idx)
71 moving_chunk.number = max_number+2
75 for i in range(chunks_total-1, -1, -1):
77 chunk.number = i + 1 + adjust
79 if i + 1 == new_position:
83 moving_chunk.number = new_position
86 book = Book.objects.get(pk=book.pk)
89 def append_chunks(books_slug, dest_slug, opts={}):
90 inherit_slug = opts.has_key('-S')
91 with transaction.commit_on_success():
92 print "Choose destination:"
93 dest = books_by_slug(dest_slug, just_one=opts.has_key('-A'))
94 print "Choose source(s)"
95 bookl = books_by_slug(books_slug, just_one=False, exclude=set(dest.slug))
96 last = dest[len(dest)-1]
98 if b.id == dest.id: continue
99 print "Appending %s (%s)" % (b.title, b.slug)
101 print "Appending %s (%s)" % (c.title, c.slug)
102 last = last.split(inherit_slug and b.slug or c.slug,
103 inherit_slug and b.title or c.title)
104 last.commit(c.materialize(), None,
105 author_name=opts['user_name'],
106 author_email=opts['user_email'])
110 DEFAULT_USER='marcinkoziej'
112 if __name__ == '__main__':
113 opts, args = getopt(sys.argv[1:], "ma:Au:S")
116 # opts['me'] = User.objects.get(username=opts.get('u', DEFAULT_USER))
117 opdic['user_name'] = opdic.get('-U', 'Redakcja FNP')
118 opdic['user_email'] = opdic.get('-E', 'redakcja@nowoczesnapolska.org.pl')
119 if opdic.has_key('-m'):
122 elif opdic.has_key('-a'):
123 dest_slug = opdic['-a']
125 append_chunks(books_slug, dest_slug, opdic)
127 print "-m for move, -a for append"