Source

zicbee / zicbee / core / httpdb.py

Full commit
  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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
""" Web database ``/db/`` handling classes """
# vim: et ts=4 sw=4
from __future__ import with_statement

__all__ = ['web_db_index', 'WEB_FIELDS', 'render']

import os
import web
import random
from threading import RLock
from time import time
from zicbee.core import zshell
from zicbee_lib.formats import compact_int, jdump, uncompact_int, dump_data_as_text
from zicbee_lib.parser import string2python
from zicbee_lib.config import config
from zicbee_lib.debug import DEBUG
from zicbee_lib import debug
from zicbee import __version__ as VERSION

#: web-available fields
WEB_FIELDS = 'artist album title length score tags __id__'.split()

web.internalerror = web.debugerror = web.debug = debug.log.debug

if debug.debug_enabled:
    web.config.debug = True
else:
    web.config.debug = None

# DB part

#: available formats in search form (html, txt, json, m3u, zip)
available_formats = [
        ('html', 'WWW Browser'),
        ('txt', 'Text'),
        ('json', 'JSON'),
        ('m3u', 'Playlist (m3u)'),
        ('zip', 'ZIP archive'),
        ]

DbSimpleSearchForm = web.form.Form(
        web.form.Hidden('id'),
        web.form.Textbox('pattern', description="Play pattern"),
        web.form.Dropdown('fmt', available_formats,
            value="html", description="Output"),
        )

def kill_server():
    zshell.songs.close()
    try:
        from zicbee.core.httpplayer import webplayer
        webplayer.player.close()
    except:
        pass

def allow_admin_mode():
    """ Tells if the admin operations are authorized
    See ``alow_remote_admin`` in :obj:`~zicbee_lib.config.config` and :ref:`set` command

    :rtype: bool
    """
    addr = web.ctx.env['REMOTE_ADDR']

    admins = config.allow_remote_admin
    allowed = ['127.0.0.1']
    if admins:
        if len(admins) == 1 and admins[0].lower() in ('yes', 'true', 'on'):
            return True
        allowed.extend(admins)
    return addr in allowed


# Set default headers & go to templates directory
web.ctx.headers = [('Content-Type', 'text/html; charset=utf-8'), ('Expires', 'Thu, 01 Dec 1994 16:00:00 GMT')]
from zicbee_lib.resources import resource_filename
try:
    render = web.template.render(resource_filename('zicbee.ui.web', 'templates'))
except Exception, e:
    DEBUG()
    class FakeRender(object):
        def __getattr__(self, name):
            return self
        def __call__(self, *args, **kw):
            return 'Unable to load templates'
    render = FakeRender()


import zipfile
#import cZipFile


class Zipper(list):
    """ Object used to handle zip files """
    def __init__(self, zipname):
        self.name = zipname

#    def extract(self, name=None, to_path=None, members=None, load=False):
#        name = name or self.name
#        zf = zipfile.ZipFile(name)
#        if load:
#            self[:] = [(x, '') for x in zf.namelist()]
#        zf.extractall(to_path, members)
#        zf.close()

    def saveSongs(self, as_name=None, prefix=''):
        name = as_name or self.name
        zf = zipfile.ZipFile(name, 'w', zipfile.ZIP_STORED)
        for uri, song in self:
            fname = song.filename
            fullname = u"/".join((song.artist, song.album, song.title))+u"."+(fname.rsplit(u'.', 1)[-1])
            zf.write(fname, str(fullname))
        zf.close()


def refresh_db():
    zshell.songs.commit()
    zshell.songs._create()
    zshell.songs.cleanup()

class web_db_index:
    """ Root of database web """

    _db_lock = RLock()

    def REQ_tag(self, song, tag):
        """ Tags a song
        tag/<song id>/<tag>

        :arg int song: The song id
        :arg str tag: The tag you want to add to that song
        """

        song_id = uncompact_int(song)
        try:
            tag = unicode(tag)
            with self._db_lock:
                sep = u','
                _t = zshell.songs[song_id].tags
                tag_set = set( _t.strip(sep).split(sep) ) if _t else set()
                for single_tag in tag.split(','):
                    tag_set.add(single_tag.strip())
                new_tag = ''.join((sep, sep.join(tag_set), sep))
                zshell.songs[song_id].update(tags=new_tag)
        except Exception, e:
            web.debug('E!%s'%e)
        finally:
            refresh_db()

    def REQ_rate(self, song, rating):
        """ Rate a song
        rate/<song id>/<rating>

        :arg int song: song id
        :arg int rating: the rate you want to give to that song
        """
        web.debug('rate: song=%s rating=%s'%(song,rating))
        try:
            with self._db_lock:
                song_id = uncompact_int(song)
                zshell.songs[song_id].update(score=int(rating))
        finally:
            refresh_db()

    def REQ_multirate(self, ratings_list):
        """ Rate a list of songs
        multirate/[song id=rating]<,song id2=rating2><,song id3=rating3>...

        :arg ratings_list: list of (songid, ratings)
        :type ratings_list: list of tuples
        """
        web.debug('rate: ratings_list=%s'%ratings_list)
        try:
            ratings = [rating.split('=') for rating in ratings_list.split(',')]
            with self._db_lock:
                for song, rating in ratings:
                        song_id = uncompact_int(song)
                        zshell.songs[song_id].update(score=int(rating))
        finally:
            refresh_db()

    def REQ_version(self):
        """ Returns version of zicbee used on that instance

        :returns: version name "major.minor[-special]"
        :rtype: str
        """
        yield VERSION

    def REQ_random(self):
        """ Returns a http-query-like pattern with a random artist query

         :arg str what: "artist" or "album" (defaults to "artist")
         :returns: the corresponding query as in ``pattern=(artist|album):random_value``
         :rtype: str
        """
        inp = web.input()
        what = inp.get('what', 'artist')
        if what.startswith('album'):
            what = ['album', list(zshell.songs.albums)]
        else:
            what = ['artist', list(zshell.songs.artists)]

        what[1] = random.choice(what[1])
        return 'pattern=%s:%s'%tuple(what)

    def REQ_artists(self):
        """ List all the artists

        :arg str fmt: (optionnal) output format, see :func:`~zicbee_lib.formats.dump_data_as_text`

        :Returns: A list of artists in desired format
        """
        inp = web.input()
        for d in dump_data_as_text(zshell.songs.artists, inp.get('fmt', 'txt')):
            yield d

    def REQ_albums(self):
        """ List all the albums

        :arg str fmt: (optionnal) output format, see :func:`~zicbee_lib.formats.dump_data_as_text`

        :Returns: A list of albums in desired format
        """
        inp = web.input()
        for d in dump_data_as_text(zshell.songs.albums, inp.get('fmt', 'txt')):
            yield d

    def REQ_genres(self):
        """ List all the genres

        :arg str fmt: (optionnal) output format, see :func:`~zicbee_lib.formats.dump_data_as_text`

        :returns: A list of genres in desired format
        """
        inp = web.input()
        for d in dump_data_as_text(zshell.songs.genres, inp.get('fmt', 'txt')):
            yield d

    def REQ_set(self):
        """ if :func:`allow_admin_mode` allows it, sets a configuration value

        :arg str k: key (config entry name) to set
        :arg str v: value to set

        :returns: key = new_value
        :rtype: str
        """
        if not allow_admin_mode():
            return "Not allowed"
        i = web.input()
        k = i.get('k')
        v = i.get('v')
        if v is not None:
            config[k] = v
        v = config[k]
        return "%s = %s"%(k, ', '.join(v) if isinstance(v, (list, tuple)) else v)

    def REQ_kill(self):
        """ Kills the application

        :Returns: "Aaaah!"
        """
        if allow_admin_mode():
            kill_server()
            yield 'Aaaah!'
            raise SystemExit()

    def REQ_infos(self, song_id):
        """ Show infos about a song
        Either positional parameter or ``id`` keyword has to be given

        :arg str fmt: (optionnal) output format, see :func:`~zicbee_lib.formats.dump_data_as_text`
        :arg str id: id of the song
        :arg int song_id: id of the song

        :Returns: all the metadatas in desired format
        """


        af = DbSimpleSearchForm()
        if af.validates():
            af.fill()
            song_id = uncompact_int(af['id'].value)
            fmt = af['fmt'].value

        song = zshell.songs[song_id]
        d = dict( (f, getattr(song, f)) for f in song.fields ) if song else {}
        return dump_data_as_text(d, fmt)

    def REQ_get(self, *args):
        """ Gets content of some entry, is the result of :obj:`DbSimpleSearchForm`
        """
        af = DbSimpleSearchForm()
        if af.validates():
            af.fill()
            song_id = uncompact_int(af['id'].value)
        filename = zshell.songs[song_id].filename
        web.header('Content-Type', 'application/x-audio')
        web.header('Content-Disposition',
                'attachment; filename:%s'%filename.rsplit('/', 1)[-1], unique=True)

        CHUNK=1024
        in_fd = file(filename)
        web.header('Content-Length', str( os.fstat(in_fd.fileno()).st_size ) )
        yield ''

        while True:
            data = in_fd.read(CHUNK)
            if not data: break
            y = (yield data)
        in_fd.close()
        return

    def GET(self, name):
        """ Main http dispatcher
        if :obj:`DbSimpleSearchForm` is satisfied, will return search content

        Redirects to ``REQ_<name>`` for subcommands

        :arg str fmt: (optionnal) output format, see :func:`~zicbee_lib.formats.dump_data_as_text`
            Added feature: supports m3u, html and zip too.

        :arg str pattern: Any valid :ref:`pattern`
        """
        hd = web.webapi.ctx.homedomain

        # try to replace "localhost" addresses with an external one
        if 'localhost' in hd or '127.0.0.1' in hd:
            if config.localhost:
                hd = config.localhost
        elif not config.localhost:
            config.localhost = hd

        inp = web.input()
        t0 = time()

        # XXX: move this to special commands, using dedicated Form()s
        # m3u flag has to move to "fmt"
        args = None
        song_id = None
        handler = None # special action handler executed before listing
        af = DbSimpleSearchForm()
        if af.validates():
            af.fill()
            song_id = af['id'].value

        if song_id:
            args = [song_id]

        if name:
            # Special actions (1rs level path)
            try:
                name, path = name.split('/', 1)
            except ValueError:
                name = name
                path = None
            try:
                handler = getattr(self, 'REQ_' + name)
            except AttributeError:
                handler = None

            if not args:
                if path:
                    args = path.split('/')
                else:
                    args = []

        if handler:
            # XXX: replace that with autodelegate as in httpplayer
            try:
                # execute the handler
                web.debug('%s: %r'%(handler, args))
                ret = handler(*args)
                if hasattr(ret, 'next'):
                    for chunk in ret:
                        yield chunk
                else:
                    yield ret
            except GeneratorExit:
                raise
            except Exception, e:
                DEBUG()

        else: # XXX: move that to a dedicated command ? (ex: .../db/q?pattern=... looks nice)
            # or use "index" ... (sounds good too !)
            format = af['fmt'].value or 'html'
            if format == 'm3u':
                web.header('Content-Type', 'audio/x-mpegurl')
            elif format == 'html':
                web.header('Content-Type', 'text/html; charset=utf-8')

            pattern = af['pattern'].value

            if pattern is None:
                res = xrange(0)
            else:
                pat, kw = string2python(pattern)
                web.debug('PAT %r KW %r'%(pat, kw))
                urlencode = web.http.urlencode
                ci = compact_int

                res = ([hd+'/db/get/%s?id=%s'%('song.'+ r.filename.rsplit('.', 1)[-1].lower(), ci(int(r.__id__))), r]
                        for r in zshell.songs.search(list(WEB_FIELDS+['filename']), pat, **kw)
                        )
            t_sel = time()

            if format == 'm3u':
                yield unicode(render.m3u(web.http.url, res))
            elif format == 'zip':
                web.header('Content-Type', 'application/zip')
                web.header('Content-Disposition',  'attachment; filename=music_download.zip')
                import tempfile
                tmp_file = tempfile.NamedTemporaryFile()
                z = Zipper(tmp_file.name)
                z[:]= res
                z.saveSongs()
                tmp_file.seek(0)
                CZ = 2**18

                while True:
                    dat = tmp_file.read(CZ)
                    if not dat:
                        break
                    yield dat

                tmp_file.close()
                return
            elif not format or format == 'html':
                yield unicode(render.index(af, res, config.web_skin or 'default'))
            elif format in ('json', 'txt'):
                some_db = zshell.songs.databases.itervalues().next()['handle']
                # try to pre-compute useful things
                field_decoder = zip( WEB_FIELDS,
                        (some_db.f_decode[some_db.fields[fname]] for fname in WEB_FIELDS)
                        )
                yield ''

                infos_iterator = ( [r[0]] + [d(r[1][r[1].fields.index(f)]) for f, d in field_decoder]
                        for r in res )
                if format == 'json':
                    d = jdump
                else:
                    def d(line):
                        return ' | '.join(line[:4])

                try:
                    # TODO: optimise this (jdump by 100 size blocks)
                    for r in infos_iterator:
                        yield d(r)
                        yield '\n'
                    web.debug('handled in %.2fs (%.2f for select)'%(time() - t0, t_sel - t0))
                except Exception, e:
                    DEBUG()
                    web.debug("ERR: %s(%s)"% (type(e), e))
            else:
                # TODO: add support for zip output (returns a zip stream with all the songs)
                web.debug('unknown search mode')
                for r in res:
                    yield dump_data_as_text(r, format)