summaryrefslogtreecommitdiffstats
path: root/amarok/src/scripts/webcontrol/RequestHandler.py
blob: 2d0b2cb33686eb570bc1d3953977c2ca752a38ba (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
#!/usr/bin/env python
# -*- coding: Latin-1 -*-

"""
 This scripts starts a small http-server that serves the current-playlist as
 HTML. Start it and point your browser to http://localhost:4773/

 Author: André Kelpe fs111 at web dot de
       : Jonas Drewsen kde at xspect dot dk

 License: GPL

"""
import http.server
import http.server
from Playlist import Playlist
import Globals

import time

# necessary for <= python2.2 that cannot handle "infds" in var
import string

PLIST = None

# keep track of request ids in order to not repeat
# requests if user refreshes his browser
REQ_IDS = {}

#
# Holding current AmarokStatus. A bunch of init_XXX functions in
# order to begin dcop requests as early as possible to avoid too
# much latency
#
class AmarokStatus:

    EngineEmpty = 1
    EngineIdle = 2
    EnginePause = 3
    EnginePlay = 4

    allowControl = 0
    publish = 0
    playState = -1

    dcop_isplaying = None
    dcop_volume = None
    dcop_trackcurrentindex = None
    dcop_trackcurrenttime = None
    dcop_tracktotaltime = None
    
    def __init__(self):
        self.controls_enabled = 0
        self.time_left = None

        self.dcop_isplaying = Globals.PlayerDcop("isPlaying")
        self.dcop_volume = Globals.PlayerDcop("getVolume")
        self.dcop_trackcurrentindex = Globals.PlaylistDcop("getActiveIndex")
        self.dcop_trackcurrenttime = Globals.PlayerDcop("trackCurrentTime")
        self.dcop_tracktotaltime = Globals.PlayerDcop("trackTotalTime")
        
    def isPlaying(self):
        if self.playState != -1:
            res = self.playState == self.EnginePlay
        else:
            if "true" in self.dcop_isplaying.result():
                self.playState = self.EnginePlay
            else:
                self.playState = self.EnginePause
        
        return res

    def getActiveIndex(self):
        return int(self.dcop_trackcurrentindex.result())

    def getVolume(self):
        return int(self.dcop_volume.result())

    def timeLeft(self):
        cur =   int(self.dcop_trackcurrenttime.result())
        total = int(self.dcop_tracktotaltime.result())
        return total - cur

    def controlsEnabled(self):
        return self.allowControl

class RequestHandler(http.server.SimpleHTTPRequestHandler):
    """We need our own 'RequestHandler, to handle the requests, that arrive at
    our server."""
    
    def _amarokPlay(self):
        AmarokStatus.playState = AmarokStatus.EnginePlay
        Globals._dcopCallPlayer("play")

    def _amarokPause(self):
        AmarokStatus.playState = AmarokStatus.EnginePause
        Globals._dcopCallPlayer("pause")

    def _amarokNext(self):
        Globals._dcopCallPlayer("next")

    def _amarokGoto(self,index):
        AmarokStatus.playState = AmarokStatus.EnginePlay
        AmarokStatus.currentTrackIndex = int(index)
        Globals._dcopCallPlaylistArg("playByIndex",index)

    def _amarokPrev(self):
        Globals._dcopCallPlayer("prev")

    def _amarokStop(self):
        Globals._dcopCallPlayer("stop")
        AmarokStatus.playState = AmarokStatus.EngineStop
        
    def _amarokSetVolume(self, val):
        Globals._dcopCallPlayerArg("setVolume",val)

    def _parseQueryVars(self):
        querystr = self.path.split("?")

        qmap = {}

        if len(querystr) <= 1:
            return qmap

        queries = querystr[-1].split("&");

        for query in queries:
            var = query.split("=")
            if len(var) != 2:
                continue
            qmap[var[0]] = var[1]

        return qmap

    def _handleAction(self, qmap):
        global REQ_IDS

        # get the sessions last reqid
        try:
            req_id = REQ_IDS[qmap["sesid"]]
        except:
            return 0
        
        # abort a request that has already been completed
        # probably a refresh from the users browser
        if "reqid" in qmap and req_id == int(qmap["reqid"]):
            return 0

        if "action" in qmap:
            a = qmap["action"]
            if a == "stop":
                self._amarokStop()
            elif a == "play":
                self._amarokPlay()
            elif a == "pause":
                self._amarokPause()
            elif a == "prev":
                self._amarokPrev()
            elif a == "next":
                self._amarokNext()
            elif a == "goto":
                self._amarokGoto(qmap["value"])
            elif a == "setvolume":
                self._amarokSetVolume(qmap["value"])
        return 1
    
    def _amarokStatus(self):
        status = AmarokStatus()
        return status
        
    def _sendFile(self, path):
        # only allow doc root dir access
        elem = self.path.split("/")
        if len(elem):
            path = elem[-1]
            f = open(Globals.EXEC_PATH + "/" + path, 'r')
            self.copyfile(f, self.wfile)

    def do_HEAD(self):
        """Serve a HEAD request."""
        RequestHandler.extensions_map.update({
            '': 'application/octet-stream', # Default
            '.png': 'image/png',
            '.js': 'text/plain',
            '.css': 'text/plain'
            })
        f = self.send_head()
        if f:
            f.close()

    def _getSessionInfo(self, qmap):
        # get the sessions last reqid
        last_req_id = 0
        session_id = None
        if "sesid" in qmap:
            session_id = qmap["sesid"]
            if session_id in REQ_IDS:
                last_req_id = REQ_IDS[session_id]
            else:
                REQ_IDS[session_id] = last_req_id
        else:
            # Create a session 
            session_id = str(time.time())
            REQ_IDS[session_id] = last_req_id
        return session_id, last_req_id
   
    def do_GET(self):
        """Overwrite the do_GET-method of the super class."""
        RequestHandler.extensions_map.update({
            '': 'application/octet-stream', # Default
            '.png': 'image/png',
            '.js': 'text/plain',
            '.css': 'text/plain'
            })

        global REQ_IDS

        qmap = self._parseQueryVars()
        session_id, last_req_id = self._getSessionInfo(qmap)
            
        if AmarokStatus.allowControl and self._handleAction(qmap):
            last_req_id = last_req_id + 1
            REQ_IDS[session_id] = last_req_id
        
        newreqid = last_req_id + 1
        
        #
        # Surely there must be a better way that this:)
        #
        self.send_response(200)
        if ".png" in self.path:
            self.send_header("content-type","image/png")
            self.end_headers()
            self._sendFile(self.path)
        elif ".js" in self.path:
            self.send_header("content-type","text/plain")
            self.end_headers()
            self._sendFile(self.path)
        elif ".css" in self.path:
            self.send_header("content-type","text/css")
            self.end_headers()
            self._sendFile(self.path)
        else:
            status = self._amarokStatus()
            status.dcop_volume.init()
            status.dcop_trackcurrenttime.init()
            status.dcop_tracktotaltime.init()
            self.send_header("content-type","text/html")
            self.send_header("Cache-Control","no-cache")
            self.end_headers()
            status.reqid = newreqid
            status.sesid = session_id
            self.wfile.write(PLIST.toHtml(status))

def main():
    """main is the starting-point for our script."""
    global PLIST
    PLIST = Playlist()
    srv = http.server.HTTPServer(('',Globals.PORT),RequestHandler)
    srv.serve_forever()


if __name__ == "__main__":
    main()