update librarian
[redakcja.git] / scripts / bkmanip.py
1 #!/usr/bin/env python
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.
5 #
6 import sys
7 sys.path.append('.')
8 sys.path.append('./apps')
9 sys.path.append('./lib')
10
11 from django.core.management import setup_environ
12 from redakcja import settings
13 from getopt import getopt
14
15 setup_environ(settings)
16
17 from catalogue.models import Book, Chunk
18 import re
19
20 from django.db import transaction
21
22 me = None
23
24 def books_by_slug(term, just_one=False, exclude=None):
25     books = Book.objects.filter(slug__contains=term)
26     if exclude:
27         books = filter(lambda not b.slug in exclude, books)
28     def show_them():
29         for b in range(len(books)):
30             print "%d) %s" % (b+1, books[b].slug)
31
32     if just_one:
33         if len(books) > 1:
34             show_them()
35             print "Which one? "
36             ch = int(raw_input())
37             book = books[ch-1]
38         else:
39             book = books[0]
40         return book
41     else:
42         show_them()
43         print "Is this ok? "
44         ch = raw_input()
45         if ch[0] in ('y', 'Y'):
46             return books
47         else:
48             raise Exception("please change your query then")
49
50 def looks_good(book):
51     for c in book:
52         print "%02d. %s [%s]" % (c.number, c.title, c.slug)
53     while True:
54         print "is this ok (y/n)? "
55         resp = raw_input()
56         if resp[0] == 'y':
57             break
58         elif resp[0] == 'n':
59             raise Exception("Aborting")
60
61
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)
66
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)
70
71         moving_chunk.number = max_number+2
72         moving_chunk.save()
73
74         adjust = 1
75         for i in range(chunks_total-1, -1, -1):
76             chunk = book[i]
77             chunk.number = i + 1 + adjust
78             chunk.save()
79             if i + 1 == new_position:
80                 adjust = 0
81
82
83         moving_chunk.number = new_position
84         moving_chunk.save()
85
86         book = Book.objects.get(pk=book.pk)
87         looks_good(book)
88
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]
97         for b in bookl:
98             if b.id == dest.id: continue
99             print "Appending %s (%s)" % (b.title, b.slug)
100             for c in b:
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'])
107         looks_good(dest)
108                 
109
110 DEFAULT_USER='marcinkoziej'
111
112 if __name__ == '__main__':
113     opts, args = getopt(sys.argv[1:], "ma:Au:S")
114     opdic = dict(opts)
115
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'):
120         move_chunk(*args)
121         sys.exit(0)
122     elif opdic.has_key('-a'):
123         dest_slug = opdic['-a']
124         books_slug = args[0]
125         append_chunks(books_slug, dest_slug, opdic)
126     else:
127         print "-m for move, -a for append"
128         sys.exit(-1)