videoob_web.py 4.35 KB
Newer Older
1 2
# -*- coding: utf-8 -*-

3
# Copyright(C) 2010-2011 Christophe Benz
4
#
5
# This file is part of weboob.
6
#
7
# weboob is free software: you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9 10 11 12
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
19

20
from __future__ import print_function
21 22 23 24 25 26 27 28 29 30 31

import os

from mako.lookup import TemplateLookup
from mako.runtime import Context
from routes import Mapper
from StringIO import StringIO
from webob.dec import wsgify
from webob import exc
from wsgiref.simple_server import make_server

32
from weboob.capabilities.video import CapVideo
33
from weboob.tools.application.base import Application
34 35 36 37 38 39 40 41 42


__all__ = ['VideoobWeb']


template_lookup = TemplateLookup(directories=[os.path.join(os.path.dirname(__file__), 'templates')],
                                 output_encoding='utf-8', encoding_errors='replace')


43
class VideoobWeb(Application):
44
    APPNAME = 'videoob-webserver'
Romain Bignon's avatar
Romain Bignon committed
45
    VERSION = '1.6'
Romain Bignon's avatar
Romain Bignon committed
46
    COPYRIGHT = 'Copyright(C) 2010-2011 Christophe Benz'
47
    DESCRIPTION = 'WSGI web server application allowing to search for videos on various websites.'
48
    CAPS = CapVideo
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
    CONFIG = dict(host='localhost', port=8080)

    @wsgify
    def make_app(self, req):
        map = Mapper()
        map.connect('index', '/', method='index')

        results = map.routematch(environ=req.environ)
        if results:
            match, route = results
            req.urlvars = ((), match)
            kwargs = match.copy()
            method = kwargs.pop('method')
            return getattr(self, method)(req, **kwargs)
        else:
            public_path = os.path.join(os.path.dirname(__file__), 'public')
            if not os.path.exists(public_path):
                return exc.HTTPNotFound()
            path = req.path
            if path.startswith('/'):
                path = path[1:]
            public_file_path = os.path.join(public_path, path)
            if os.path.exists(public_file_path):
                if path.endswith('.css'):
                    req.response.content_type = 'text/css'
                elif path.endswith('.js'):
                    req.response.content_type = 'text/javascript'
                return open(public_file_path, 'r').read().strip()
            else:
                return exc.HTTPNotFound()

    def main(self, argv):
        self.load_config()
82
        self.weboob.load_backends(CapVideo)
83 84
        print('Web server created. Listening on http://%s:%s' % (
            self.config.get('host'), int(self.config.get('port'))))
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        srv = make_server(self.config.get('host'), int(self.config.get('port')), self.make_app)
        srv.serve_forever()

    def index(self, req):
        c = {}
        nsfw = req.params.get('nsfw')
        nsfw = False if not nsfw or nsfw == '0' else True
        q = req.params.get('q', u'')
        merge = req.params.get('merge')
        merge = False if not merge or merge == '0' else True
        c['merge'] = merge
        c['form_data'] = dict(q=q)
        c['results'] = [] if merge else {}
        if q:
            for backend in self.weboob.iter_backends():
                videos = [dict(title=video.title,
                               page_url=video.page_url,
                               url=video.url if video.url else '/download?id=%s' % video.id,
103
                               thumbnail_url=video.thumbnail.url,
104
                             )
105
                         for video in backend.search_videos(pattern=q, nsfw=nsfw)]
106 107 108 109 110 111 112 113 114 115 116 117
                if videos:
                    if merge:
                        c['results'].extend(videos)
                    else:
                        c['results'][backend.name] = videos
            if merge:
                c['results'] = sorted(c['results'], key=lambda video: video['title'].lower())
        template = template_lookup.get_template('index.mako')
        buf = StringIO()
        ctx = Context(buf, **c)
        template.render_context(ctx)
        return buf.getvalue().strip()