2abbfb3d3442a5a3695f34f576f03c48bffed9c8
[wolnelektury.git] / apps / api / management / commands / mobileinit.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from datetime import datetime
6 import os
7 import os.path
8 import re
9 import sqlite3
10 from django.core.management.base import BaseCommand
11
12 from api.helpers import timestamp
13 from api.settings import MOBILE_INIT_DB
14 from catalogue.models import Book, Tag
15
16
17 class Command(BaseCommand):
18     help = 'Creates an initial SQLite file for the mobile app.'
19
20     def handle(self, **options):
21         # those should be versioned
22         last_checked = timestamp(datetime.now())
23         db = init_db(last_checked)
24         for b in Book.objects.all():
25             add_book(db, b)
26         for t in Tag.objects.exclude(
27                 category__in=('book', 'set', 'theme')).exclude(book_count=0):
28             # only add non-empty tags
29             add_tag(db, t)
30         db.commit()
31         db.close()
32         current(last_checked)
33
34
35 def pretty_size(size):
36     """ Turns size in bytes into a prettier string.
37
38         >>> pretty_size(100000)
39         '97 KiB'
40     """
41     if not size:
42         return None
43     units = ['B', 'KiB', 'MiB', 'GiB']
44     size = float(size)
45     unit = units.pop(0)
46     while size > 1000 and units:
47         size /= 1024
48         unit = units.pop(0)
49     if size < 10:
50         return "%.1f %s" % (size, unit)
51     return "%d %s" % (size, unit)
52
53
54     if not isinstance(value, unicode):
55         value = unicode(value, 'utf-8')
56
57     # try to replace chars
58     value = re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, value)
59     value = value.lower()
60     value = re.sub(r'[^a-z0-9{|}]+', '~', value)
61     
62     return value.encode('ascii', 'ignore')
63
64
65
66 def init_db(last_checked):
67     if not os.path.isdir(MOBILE_INIT_DB):
68         os.makedirs(MOBILE_INIT_DB)
69     db = sqlite3.connect(os.path.join(MOBILE_INIT_DB, 'initial.db-%d' % last_checked))
70
71     schema = """
72 CREATE TABLE book (
73     id INTEGER PRIMARY KEY, 
74     title VARCHAR, 
75     html_file VARCHAR, 
76     html_file_size INTEGER, 
77     parent INTEGER,
78     parent_number INTEGER,
79
80     sort_key VARCHAR,
81     pretty_size VARCHAR,
82     authors VARCHAR,
83     _local BOOLEAN
84 );
85 CREATE INDEX IF NOT EXISTS book_title_index ON book (sort_key);
86 CREATE INDEX IF NOT EXISTS book_title_index ON book (title);
87 CREATE INDEX IF NOT EXISTS book_parent_index ON book (parent);
88
89 CREATE TABLE tag (
90     id INTEGER PRIMARY KEY, 
91     name VARCHAR, 
92     category VARCHAR, 
93     sort_key VARCHAR, 
94     books VARCHAR);
95 CREATE INDEX IF NOT EXISTS tag_name_index ON tag (name);
96 CREATE INDEX IF NOT EXISTS tag_category_index ON tag (category);
97 CREATE INDEX IF NOT EXISTS tag_sort_key_index ON tag (sort_key);
98
99 CREATE TABLE state (last_checked INTEGER);
100 """
101
102     db.executescript(schema)
103     db.execute("INSERT INTO state VALUES (:last_checked)", locals())
104     return db
105
106
107 def current(last_checked):
108     target = os.path.join(MOBILE_INIT_DB, 'initial.db')
109     if os.path.lexists(target):
110         os.unlink(target)
111     os.symlink(
112         'initial.db-%d' % last_checked,
113         target,
114     )
115     
116
117
118 book_sql = """
119     INSERT INTO book 
120         (id, title, html_file,  html_file_size, parent, parent_number, sort_key, pretty_size, authors) 
121     VALUES 
122         (:id, :title, :html_file, :html_file_size, :parent, :parent_number, :sort_key, :size_str, :authors);
123 """
124 book_tag_sql = "INSERT INTO book_tag (book, tag) VALUES (:book, :tag);"
125 tag_sql = """
126     INSERT INTO tag
127         (id, category, name, sort_key, books)
128     VALUES
129         (:id, :category, :name, :sort_key, :book_ids);
130 """
131 categories = {'author': 'autor',
132               'epoch': 'epoka', 
133               'genre': 'gatunek', 
134               'kind': 'rodzaj', 
135               'theme': 'motyw'
136               }
137
138
139 def add_book(db, book):
140     id = book.id
141     title = book.title
142     if book.html_file:
143         html_file = book.html_file.url
144         html_file_size = book.html_file.size
145     else:
146         html_file = html_file_size = None
147     parent = book.parent_id
148     parent_number = book.parent_number
149     sort_key = book.sort_key
150     size_str = pretty_size(html_file_size)
151     authors = ", ".join(t.name for t in book.tags.filter(category='author'))
152     db.execute(book_sql, locals())
153
154
155 def add_tag(db, tag):
156     id = tag.id
157     category = categories[tag.category]
158     name = tag.name
159     sort_key = tag.sort_key
160
161     books = Book.tagged_top_level([tag])
162     book_ids = ','.join(str(b.id) for b in books)
163     db.execute(tag_sql, locals())