Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/sugar_network/model/routes.py
blob: 6abb758949057f8e84dea4d5915981e99ffe0920 (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
# Copyright (C) 2013 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import mimetypes
from os.path import join, split

from sugar_network import static, db
from sugar_network.toolkit.router import route, fallbackroute, Blob, ACL
from sugar_network.toolkit import coroutine


_logger = logging.getLogger('model.routes')


class VolumeRoutes(db.Routes):

    @route('GET', ['context', None], cmd='feed',
            mime_type='application/json')
    def feed(self, request, distro):
        context = self.volume['context'].get(request.guid)
        implementations = self.volume['implementation']
        versions = []

        impls, __ = implementations.find(context=context.guid,
                not_layer='deleted', **request)
        for impl in impls:
            version = impl.properties([
                'guid', 'ctime', 'layer', 'author', 'tags',
                'version', 'stability', 'license', 'notes',
                ])
            if context['dependencies']:
                requires = version.setdefault('requires', {})
                for i in context['dependencies']:
                    requires.setdefault(i, {})
            version['data'] = data = impl.meta('data')
            for key in ('mtime', 'seqno', 'blob'):
                if key in data:
                    del data[key]
            versions.append(version)

        result = {'implementations': versions}
        if distro:
            aliases = context['aliases'].get(distro)
            if aliases and 'binary' in aliases:
                result['packages'] = aliases['binary']
        return result


class FrontRoutes(object):

    def __init__(self):
        self._pooler = _Pooler()

    @route('GET', mime_type='text/html')
    def hello(self):
        return _HELLO_HTML

    @route('OPTIONS')
    def options(self, request, response):
        if request.environ['HTTP_ORIGIN']:
            response['Access-Control-Allow-Methods'] = \
                    request.environ['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
            response['Access-Control-Allow-Headers'] = \
                    request.environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
        else:
            response['Allow'] = 'GET, HEAD, POST, PUT, DELETE'
        response.content_length = 0

    @route('GET', cmd='subscribe', mime_type='text/event-stream')
    def subscribe(self, request=None, response=None, ping=False, **condition):
        """Subscribe to Server-Sent Events."""
        if request is not None and not condition:
            condition = request
        if response is not None:
            response.content_type = 'text/event-stream'
            response['Cache-Control'] = 'no-cache'
        return self._pull_events(ping, condition)

    @route('POST', cmd='broadcast',
            mime_type='application/json', acl=ACL.LOCAL)
    def broadcast(self, event=None, request=None):
        if request is not None:
            event = request.content
        _logger.debug('Broadcast event: %r', event)
        self._pooler.notify_all(event)

    @fallbackroute('GET', ['static'])
    def get_static(self, request):
        path = join(static.PATH, *request.path[1:])
        if not mimetypes.inited:
            mimetypes.init()
        mime_type = mimetypes.types_map.get('.' + path.rsplit('.', 1)[-1])
        return Blob({
            'blob': path,
            'filename': split(path)[-1],
            'mime_type': mime_type,
            })

    @route('GET', ['robots.txt'], mime_type='text/plain')
    def robots(self, request, response):
        return 'User-agent: *\nDisallow: /\n'

    @route('GET', ['favicon.ico'])
    def favicon(self, request, response):
        return Blob({
            'blob': join(static.PATH, 'favicon.ico'),
            'mime_type': 'image/x-icon',
            })

    def _pull_events(self, ping, condition):
        if ping:
            # XXX The whole commands' kwargs handling should be redesigned
            if 'ping' in condition:
                condition.pop('ping')
            # If non-greenlet application needs only to initiate
            # a subscription and do not stuck in waiting for the first event,
            # it should pass `ping` argument to return fake event to unblock
            # `GET /?cmd=subscribe` call.
            yield {'event': 'pong'}

        while True:
            event = self._pooler.wait()
            for key, value in condition.items():
                if value.startswith('!'):
                    if event.get(key) == value[1:]:
                        break
                elif event.get(key) != value:
                    break
            else:
                yield event


class _Pooler(object):
    """One-producer-to-many-consumers events delivery."""

    def __init__(self):
        self._value = None
        self._waiters = 0
        self._ready = coroutine.Event()
        self._open = coroutine.Event()
        self._open.set()

    def wait(self):
        self._open.wait()
        self._waiters += 1
        try:
            self._ready.wait()
        finally:
            self._waiters -= 1
            if self._waiters == 0:
                self._ready.clear()
                self._open.set()
        return self._value

    def notify_all(self, value=None):
        self._open.wait()
        if not self._waiters:
            return
        self._open.clear()
        self._value = value
        self._ready.set()


_HELLO_HTML = """\
<h2>Welcome to Sugar Network API!</h2>
Visit the <a href="http://wiki.sugarlabs.org/go/Sugar_Network/API">
Sugar Labs Wiki</a> to learn how it can be used.
"""