Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/atoidejouer/db/story.py
blob: 515be85de98e4c541ab6c526b73ec42d69552173 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# python import
import copy, logging

# get application logger
logger = logging.getLogger('atoidejouer')

# sqlite import
import sqlite3;

# atoidejouer import
from atoidejouer.tools import image, storage


WHERE_COLS = [
    'id',
    'title',
    'mime_type',
    'time',
    'timestamp'
    ]

SET_COLS = [
    'layer',
    'x',
    'y',
    'duration',
    'loop'
    ]

INSERT_COLS = [
    'title',
    'mime_type',
    'time',
    'layer',
    'timestamp',
    'x',
    'y',
    'duration',
    'loop'
    ]

NUMERIC_COLS = [
    'time',
    'layer',
    'x',
    'y',
    'duration',
    'loop'
    ]


class Key(object):

    def __init__(self, id=None, title=None, mime_type=None, timestamp=None, **kargs):
        self.id, self.title, self.mime_type, self.timestamp = id, title, mime_type, timestamp
        # ensure value if select row returns None value
        for arg in ['time', 'layer', 'x', 'y', 'duration', 'loop', 'path']:
            setattr(self, arg, kargs[arg] if arg in kargs and kargs[arg] else 0)

    def _get_obj(self):
        for _ds_obj in storage.journal_query({
            'mime_type': self.mime_type,
            'title': self.title
            }):
            return _ds_obj

    def get_preview(self):
        if self.mime_type == 'image/png':
            _ds_obj = self._get_obj()
            return storage.get_pixbuf_from_data(
                        _ds_obj.metadata['preview'],
                        size=(64, 48)
                        )
        else:
            _path = storage.get_image_path('sound', dir_='data')
            return image.get_pixbuf(_path, 64, 48)

    def get_path(self):
        if self.path == 0:
            _ds_obj   = self._get_obj()
            self.path = _ds_obj.file_path if _ds_obj else 0
        return self.path

    def set_path(self, path):
        self.path = path

    def __repr__(self):
        return "%s|title=%s|mime_type=%s|timestamp=%s|time=%s|layer=%s|"\
                "x=%s|y=%s|duration=%s|loop=%s"\
                % (self.id, self.title, self.mime_type, self.timestamp,
                        self.time, self.layer,
                        self.x, self.y,
                        self.duration, self.loop)

    def __cmp__(self, other):
        return cmp(
                (self.title, self.mime_type, self.timestamp, self.time, self.layer),
                (other.title, other.mime_type, self.timestamp, other.time, other.layer)
                )

    def create(self):
        return "create table story("\
                "id integer primary key autoincrement not null,"\
                "title text,"\
                "mime_type text,"\
                "timestamp text,"\
                "time integer,"\
                "layer integer,"\
                "x integer,"\
                "y integer,"\
                "duration integer,"\
                "loop integer"\
                ")"

    def insert(self):
        columns = list()
        values  = list()
        for c in INSERT_COLS:
            v = getattr(self, c)
            if v is not None and v != -1:
                columns.append(c)
                values.append(str(v) if c in NUMERIC_COLS else "'%s'" % v)
        return "insert into story (%s) values (%s)" % (
                ",".join(columns),
                ",".join(values)
                )

    def _params(self, crit):
        values = list()
        joiner = ' and '    if crit == 'where' else ', '
        cols   = WHERE_COLS if crit == 'where' else SET_COLS
        for c in cols:
            v = getattr(self, c)
            if v is not None and v != -1:
                v = str(v) if c in NUMERIC_COLS else "'%s'" % v
                values.append("%s=%s" % (c, v))
        return "%s %s" % (crit, joiner.join(values))

    def where(self):
        """Prepares simple where query according OO parameters.
        """
        return self._params('where')

    def set(self):
        """Prepares simple where query according OO parameters.
        """
        return self._params('set')

    def select(self):
        """Prepares simple select query according OO parameters.
        """
        return "select * from story %s" % self.where()

    def update(self):
        return "update story %s where id=%s" % (self.set(), self.id)

    def delete(self, all=False):
        """Prepares simple delete query according OO parameters.
        """
        q = "delete from story"
        if all is True:
            return q
        else:
            return "%s %s" % (q, self.where())

    def _query_duration(self, time, sign='=', order=''):
        return "select * from story where %s order by %stime" % (
                " and ".join([
                    "%s='%s'"  % ("title",       self.title),
                    "%s='%s'"  % ("mime_type",   self.mime_type),
                    "%s='%s'"  % ("timestamp",   self.timestamp),
                    "%s=%s"    % ("layer",       self.layer),
                    "%s%s%s"   % ("time", sign,  time),
                    ]),
                order)

    def update_duration(self, duration):
        # list next keys
        key_dura = duration
        start = self.time + 1
        _range = self.duration if self.duration > duration else duration
        for time in range(start, start + _range):
            key = None
            for key in DB()._all(query=self._query_duration(time)):
                break
            key_dura -= 1
            # DEBUG
            # print '\nup time: %s' % time
            # print 'up query : %s' % self._query_duration(time)
            # print 'up key : %s' % key
            # print 'up key_dura: %s' % key_dura
            # no key?
            if key is None:
                new_key = copy.copy(self)
                new_key.id = None
                new_key.time = time
                new_key.duration = key_dura
                # DEBUG
                # print 'up new_key: %s' % new_key
                DB().add(new_key)
            # remove next keys
            elif key.time > self.time + duration:
                key._del(refresh=False)
                break
            # update duration of existing key
            else:
                key.duration = key_dura
                DB().update(key)
        # update key duration after check
        self.duration = duration
        DB().update(self)
        # need some refresh
        self._duration_refresh()

    def _duration_refresh(self):
        """Ensure valid duration logic.
        """
        def _do_fresh(iter_):
            """Common method for our generator.
            """
            cur = None
            for key in iter_:
                if cur is None or key.time < cur - 1:
                    cur = 0
                    key.duration = cur
                else:
                    cur += 1
                    key.duration = cur
                # DEBUG
                # print 'fresh: %s' % key
                # and update
                DB().update(key)
        # update previous
        end = self.time
        _do_fresh(DB()._all(query=self._query_duration(end, sign='<', order='-')))
        # update next
        start = self.time + self.duration
        _do_fresh(DB()._all(query=self._query_duration(start, sign='>', order='-')))

    def _del(self, refresh=True):
        # list next keys
        key_dura = 0
        ran_time = self.time + 1
        ran_dura = self.duration
        for time in range(ran_time, ran_time + ran_dura):
            key = None
            for key in DB()._all(query=self._query_duration(time)):
                break
            # DEBUG
            # print '\ndel time: %s' % time
            # print 'del query : %s' % self._query_duration(time)
            # print 'del key : %s' % key
            # print 'del key_dura: %s' % key_dura
            if key is None:
                pass
            # finish
            elif key.time > time:
                break
            # update duration of existing key
            else:
                key.duration = key_dura
                DB()._del(key)
            # update next duration
            key_dura += 1
        # DEBUG
        # print 'del old key: %s' % self
        # and del
        DB()._del(self)
        # need some refresh
        if refresh is True:
            self._duration_refresh()

class DB(object):

    class __Singleton:

        def __init__(self, config=None, name="story", obj=Key):
            self.name, self.obj = name, obj
            db_path = storage.get_db_path('default')
            self.con = sqlite3.connect(db_path,
                    detect_types=sqlite3.PARSE_DECLTYPES)
            self.con.row_factory = sqlite3.Row
            self.__check()

        def __check(self):
            cur = self.con.cursor()
            # remove all first
            try:
                cur.execute("drop table %s" % self.name)
            except Exception, e:
                pass
            # create fresh db
            cur.execute(self.obj().create())
            # and close
            cur.close()

        def add(self, obj):
            cur = self.con.cursor()
            cur.execute(obj.insert())
            count = cur.rowcount
            cur.close()
            return count

        def _fetch(self, cur):
            row = cur.fetchone()
            while(row):
                yield self.obj(**row)
                row = cur.fetchone()

        def _all(self, query=None):
            cur = self.con.cursor()
            query = "select * from %s" % self.name\
                    if query is None\
                    else query
            cur.execute(query)
            for obj in self._fetch(cur):
                yield obj
            cur.close()

        def get(self, obj):
            cur = self.con.cursor()
            # DEBUG
            # logger.debug('[db.story] get - query: %s' % obj.select())
            # DEBUG
            cur.execute(obj.select())
            for obj in self._fetch(cur):
                yield obj
            cur.close()

        def one(self, obj):
            for one in self.get(obj):
                return one

        def get_max(self, max_):
            query = "select %(max_)s from %(name)s order by -%(max_)s"\
                    % {'name': self.name, 'max_': max_}
            for obj in self._all(query=query):
                return getattr(obj, max_)
            return 0

        def update(self, obj):
            cur = self.con.cursor()
            cur.execute(obj.update())
            rowcount = cur.rowcount
            cur.close()
            return rowcount

        def _del(self, obj=None, all=False):
            cur = self.con.cursor()
            obj = self.obj() if obj is None else obj
            cur.execute(obj.delete(all=all))
            rowcount = cur.rowcount
            cur.close()
            return rowcount

    # singleton instance
    instance = None

    def __new__(c, force=False):
        """Singleton new init.
        """
        # if doesn't already initialized
        if not DB.instance\
        or force is True:
            # create a new instance
            DB.instance = DB.__Singleton()
        # return the manager object
        return DB.instance