-
Notifications
You must be signed in to change notification settings - Fork 8
/
rhythmweb.py
759 lines (639 loc) · 29.8 KB
/
rhythmweb.py
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
#
# Rhythmweb - a web site for your Rhythmbox.
# GTK3 port to work with v2.96 Rhythmbox
# This is derivate software originally created by Michael Gratton, (c) 2007.
# Copyright (c) 2012 fossfreedom and Taylor Raack
# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import cgi
try: import simplejson as json
except ImportError: import json
import os
import re
import sys
import time
import socket
from wsgiref.simple_server import WSGIRequestHandler
from wsgiref.simple_server import make_server
from gi.repository import Gio
from gi.repository import Gtk
from gi.repository import GObject
from gi.repository import RB
from gi.repository import Peas
from rhythmweb_prefs import Preferences
import rb
PYVER = sys.version_info[0]
if PYVER >=3:
import io
def bytestring(string):
log("bytestring", string)
if PYVER >= 3:
return string.encode()
else:
return string
def iostring(bytestr):
log("iostring", bytestr)
if PYVER >= 3:
return io.BytesIO(bytestring(bytestr))
else:
return bytestr
# try to load avahi, don't complain if it fails
try:
import dbus
import avahi
use_mdns = True
except:
use_mdns = False
class RhythmwebPlugin(GObject.GObject, Peas.Activatable):
__gtype_name__ = 'RhythmwebPlugin'
object = GObject.property(type=GObject.GObject)
port = GObject.property(type=int, default=8000)
def __init__(self):
super(RhythmwebPlugin, self).__init__()
def do_activate(self):
self.shell = self.object
self.player = self.shell.props.shell_player
self.db = self.shell.props.db
self.shell_cb_ids = (
self.player.connect ('playing-song-changed',
self._playing_entry_changed_cb),
self.player.connect ('playing-changed',
self._playing_changed_cb)
)
self.db_cb_ids = (
self.db.connect ('entry-extra-metadata-notify',
self._extra_metadata_changed_cb)
,)
settings = Gio.Settings("org.gnome.rhythmbox.plugins.rhythmweb")
settings.bind('port', self,
'port', Gio.SettingsBindFlags.GET)
self.server = RhythmwebServer('', self.port, self)
self._mdns_publish()
def do_deactivate(self):
self._mdns_withdraw()
self.server.shutdown()
self.server = None
for id in self.shell_cb_ids:
self.player.disconnect(id)
for id in self.db_cb_ids:
self.db.disconnect(id)
self.player = None
self.shell = None
self.db = None
def _mdns_publish(self):
if use_mdns:
bus = dbus.SystemBus()
avahi_bus = bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER)
avahi_svr = dbus.Interface(avahi_bus, avahi.DBUS_INTERFACE_SERVER)
servicetype = '_http._tcp'
servicename = 'Rhythmweb on %s' % (socket.gethostname())
eg_path = avahi_svr.EntryGroupNew()
eg_obj = bus.get_object(avahi.DBUS_NAME, eg_path)
self.entrygroup = dbus.Interface(eg_obj,
avahi.DBUS_INTERFACE_ENTRY_GROUP)
self.entrygroup.AddService(avahi.IF_UNSPEC,
avahi.PROTO_UNSPEC,
0,
servicename,
servicetype,
"",
"",
dbus.UInt16(self.port),
())
self.entrygroup.Commit()
def _mdns_withdraw(self):
if use_mdns and self.entrygroup != None:
self.entrygroup.Reset()
self.entrygroup.Free()
self.entrygroup = None
def _playing_changed_cb(self, player, playing):
self._update_entry(player.get_playing_entry())
def _playing_entry_changed_cb(self, player, entry):
self._update_entry(entry)
def _extra_metadata_changed_cb(self, db, entry, field, metadata):
if entry == self.player.get_playing_entry():
self._update_entry(entry)
def _update_entry(self, entry):
if entry:
uri = entry.get_ulong(RB.RhythmDBPropType.ENTRY_ID)
artist = entry.get_string(RB.RhythmDBPropType.ARTIST)
album = entry.get_string(RB.RhythmDBPropType.ALBUM)
title = entry.get_string(RB.RhythmDBPropType.TITLE)
stream = None
stream_title = \
self.db.entry_request_extra_metadata(entry,
'rb:stream-song-title')
if stream_title:
stream = title
title = stream_title
if not artist:
artist = self.db.\
entry_request_extra_metadata(entry,
'rb:stream-song-artist')
if not album:
album = self.db.\
entry_request_extra_metadata(entry,
'rb:stream-song-album')
self.server.set_playing(artist, album, title, stream, uri)
else:
self.server.set_playing(None, None, None, None, None)
class RhythmwebServer(object):
def __init__(self, hostname, port, plugin):
self.plugin = plugin
self.running = True
self.artist = None
self.album = None
self.title = None
self.stream = None
self.initial_playlist_rows = None
self._httpd = make_server(hostname, port, self._wsgi)
self._watch_cb_id = GObject.io_add_watch(self._httpd.socket,
GObject.IO_IN,
self._idle_cb)
self._cover_db = RB.ExtDB(name='album-art')
def shutdown(self):
GObject.source_remove(self._watch_cb_id)
self.running = False
self.plugin = None
def set_playing(self, artist, album, title, stream, uri):
self.artist = artist
self.album = album
self.title = title
self.stream = stream
self.uri = uri
def _idle_cb(self, source, cb_condition):
if not self.running:
return False
self._httpd.handle_request()
return True
def _wsgi(self, environ, response):
path = environ['PATH_INFO']
log("wsgi", path)
if path in ('/', ''):
log("interface", response)
return self._handle_interface(environ, response)
elif path == '/playlists':
log("interface", response)
return self._handle_playlists(environ, response)
elif path == '/playlist/initial':
log("initial", response)
return self._handle_playlist_init(response)
elif path == '/playlist/slice':
log("slice", response)
return self._handle_playlist_init(response, environ)
elif path == '/playlist/current':
log("current", response)
return self._handle_current(response)
elif re.match("/playlist/.*", path) is not None:
log("playlistinfo", response)
return self._handle_playlist_info(environ, response, re.match("/playlist/(.*)", path).group(1))
elif path == '/playqueue':
log("playqueue", response)
return self._handle_playqueue_info(environ, response)
elif path.startswith('/stock/'):
log("stock", response)
return self._handle_stock(environ, response)
elif path.startswith('/cover/'):
log("cover", response)
return self._handle_cover(environ, response)
else:
return self._handle_static(environ, response)
def _handle_interface(self, environ, response):
player = self.plugin.player
shell = self.plugin.shell
db = self.plugin.db
queue = shell.props.queue_source
playlist_rows = []
if player.get_playing_source() is not None:
# something is playing; get the track list from the play queue or the current playlists
playlist_rows = player.get_playing_source().get_entry_view().props.model
else:
# nothing is playing,
# but there are some songs in the play queue; the track listing should show the play queue
playlist_rows = queue.props.query_model
# handle any action
if environ['REQUEST_METHOD'] == 'POST':
try:
params = parse_post(environ)
action = params[bytestring('action')][0]
except:
params = []
action = "unknown"
log('action', action)
responsetext = ''
entry = player.get_playing_entry()
if action == bytestring('play') and not entry and \
not player.get_playing_source():
# no current playlist is playing.
if bytestring('playlist') in params and len(params[bytestring('playlist')]) > 0:
# play the playlist that was requested
playlist = params[bytestring('playlist')][0]
log("play", playlist)
if(playlist == bytestring('Play Queue')):
log("play", "play queue")
if playlist_rows.get_size() > 0:
log("play", "get size")
player.play_entry(iter(playlist_rows).next()[0],
queue)
#player.play_entry(playlist_rows[0], queue)
responsetext = {'playing':'true'}
else:
log("play", "no rows in playqueue")
else:
# get the first track in the requested playlist
log("play", "first track")
selected_track = None
if bytestring('track') in params and len(params[bytestring('track')]) > 0:
selected_track = params[bytestring('track')][0]
self._play_track(player, shell, selected_track, playlist)
responsetext = {'playing':'true'}
else:
if playlist_rows.get_size() > 0:
log("play", "get size(2)")
player.play_entry(iter(playlist_rows).next()[0],
queue)
responsetext = {'playing':'true'}
#log("play", iter(playlist_rows)[0])
#player.play_entry(iter(playlist_rows)[0], queue)
else:
log("play", "no rows in playqueue(2)")
elif action == bytestring('play'):
player.playpause(True)
r, val = player.get_playing()
responsetext = {'playing':val}
log("play", "pause")
elif action == bytestring('play-track') and \
bytestring('track') in params and len(params[bytestring('track')]) > 0:
# user wants to play a specific song in the play list
track = params[bytestring('track')][0]
playlist = ''
if bytestring('playlist') in params and len(params[bytestring('playlist')]) > 0:
playlist = params[bytestring('playlist')][0]
self._play_track(player, shell, track, playlist)
elif action == bytestring('play-playlist') and \
bytestring('playlist') in params and len(params[bytestring('playlist')]) > 0:
# user wants to play a specific playlist
log('play playlist','')
playlist = params[bytestring('playlist')][0]
self._play_playlist(player, shell, playlist)
elif action == bytestring('pause'):
player.pause()
responsetext = {'playing':'false'}
elif action == bytestring('next'):
player.do_next()
self.plugin._update_entry(entry)
elif action == bytestring('prev'):
player.do_previous()
self.plugin._update_entry(entry)
elif action == bytestring('stop'):
player.stop()
responsetext = {'playing':'false'}
elif action == bytestring('toggle-repeat'):
self._toggle_play_order(player, False)
elif action == bytestring('toggle-shuffle'):
self._toggle_play_order(player, True)
elif action == bytestring('vol-up'):
(dummy, vol) = player.get_volume()
player.set_volume(vol + 0.05)
elif action == bytestring('vol-down'):
(dummy, vol) = player.get_volume()
player.set_volume(vol - 0.05)
else:
log("dunno1", action)
log("environ", environ)
log("response", response)
if responsetext != '':
response_headers = [('Content-type','application/json; charset=UTF-8')]
response('200 OK', response_headers)
return iostring(json.dumps(responsetext))
else:
#response('204 No Content', [('Content-type','text/plain')])
response('204 No Content', [])
return bytestring('OK')
# generate the playing headline
title = 'Rhythmweb'
playing = '<span id="not-playing">Not playing</span>'
play = ''
if self.stream or self.title:
play = 'class="active"'
playing = ''
title = ''
if self.title:
playing = '<cite id="title">%s</cite>' % self.title
title = self.title
if self.artist:
playing = ('%s by <cite id="artist">%s</cite>' %
(playing, self.artist))
title = '%s by %s' % (title, self.artist)
if self.album:
playing = ('%s from <cite id="album">%s</cite>' %
(playing, self.album))
title = '%s from %s' % (title, self.album)
if self.stream:
if playing:
playing = ('%s <cite id="stream">(%s)</cite>' %
(playing, self.stream))
title = '%s (%s)' % (title, self.album)
else:
playing = self.stream
title = self.stream
toggle_repeat_active = ''
toggle_shuffle_active = ''
if (player.props.play_order == 'linear-loop') or (player.props.play_order == 'random-by-age-and-rating'):
toggle_repeat_active = 'class="active"'
if (player.props.play_order == 'shuffle') or (player.props.play_order == 'random-by-age-and-rating'):
toggle_shuffle_active = 'class="active"'
r, val = player.get_playing()
# display the page
player_html = open(resolve_path('player.html'))
result = player_html.read() % { 'title': title,
'play': play,
'playing': playing,
'toggle_repeat_active': toggle_repeat_active,
'toggle_shuffle_active': toggle_shuffle_active,
'currentlyplaying': val
}
response_headers = [('Content-type','text/html; charset=UTF-8'),
('Content-Length', str(len(result)))]
response('200 OK', response_headers)
player_html.close()
return iostring(result)
def _handle_playlists(self, environ, response):
# get a list of all of the playlists
playlists = []
current_playlist_name = ''
if self.plugin.player.get_playing_source() is not None:
current_playlist_name = self.plugin.player.get_playing_source().props.name
if current_playlist_name.startswith('Play Queue'):
# strip the number of play queue tracks from the playlist name
current_playlist_name = "Play Queue"
else:
# if no playlist is playing, the current playlist should be the play queue
current_playlist_name = "Play Queue"
playlist_model_entries = self.plugin.shell.props.playlist_manager.get_playlists()
if playlist_model_entries:
for playlist in playlist_model_entries:
if playlist.props.is_local and \
isinstance(playlist, RB.StaticPlaylistSource):
playlists.append(playlist.props.name)
# return playlists as json
playlist_data = {'selected': current_playlist_name, 'playlists': playlists};
response_headers = [('Content-type','application/json; charset=UTF-8')]
response('200 OK', response_headers)
return iostring(json.dumps(playlist_data))
def _handle_playlist_info(self, environ, response, playlist_name):
log('getting playlist info for playlist ', playlist_name)
playlist_candidate = self._find_playlist_by_name(playlist_name)
if playlist_candidate is not None:
playlist_rows = playlist_candidate.get_query_model()
return self._process_tracks_to_json_response(playlist_name, playlist_rows, response)
# if we get here, the playlist wasn't found
response('404 Not Found', [])
return json.dumps({"error": "playlist not found"})
def _handle_playlist_init(self, response, environ = None):
if self.initial_playlist_rows is None:
player = self.plugin.player
if player.get_playing_source() is not None:
self.initial_playlist_rows = player.get_playing_source().get_entry_view().props.model
else:
self.initial_playlist_rows = player.props.source.get_entry_view().props.model
if environ is not None:
params = parse_post(environ)
start = int(params[bytestring('start')][0])
end = int(params[bytestring('end')][0])
playlist_rows = list(self.initial_playlist_rows)[start:end]
return self._process_tracks_to_json_response('initial', playlist_rows, response)
def _handle_current(self, response):
title = ''
artist = ''
album = ''
if self.title:
title = self.title
if self.artist:
artist = self.artist
if self.album:
album = self.album
cover = self._get_cover_name_for_playing_track()
return_data = {'title': title, 'artist': artist, 'album': album, 'stream': self.stream, 'cover': cover};
response_headers = [('Content-type','application/json; charset=UTF-8')]
response('200 OK', response_headers)
return iostring(json.dumps(return_data))
def _handle_playqueue_info(self, environ, response):
log('getting playqueue info', '')
shell = self.plugin.shell
queue = shell.props.queue_source
playlist_rows = queue.props.query_model
return self._process_tracks_to_json_response("Play Queue", playlist_rows, response)
def _process_tracks_to_json_response(self, playlist_name, playlist_rows, response):
tracks = []
for row in playlist_rows:
track_info = row[0]
track = {'id': track_info.get_ulong(RB.RhythmDBPropType.ENTRY_ID),
'title': track_info.get_string(RB.RhythmDBPropType.TITLE),
'artist': track_info.get_string(RB.RhythmDBPropType.ARTIST),
'album': track_info.get_string(RB.RhythmDBPropType.ALBUM)}
tracks.append(track)
playlist_data = {'name': playlist_name, 'tracks': tracks};
response_headers = [('Content-type','application/json; charset=UTF-8')]
response('200 OK', response_headers)
return iostring(json.dumps(playlist_data))
def _play_track(self, player, shell, track, playlist):
source = ''
log("playing from playlist ", playlist)
if playlist == '':
# find the current playing source, or select the active queue source
if player.get_playing_source() is not None:
source = player.get_playing_source()
else:
source = shell.props.queue_source
else:
# play in a specific playlist
source = self._find_playlist_by_name(playlist)
if track is not None:
# find the rhythmbox database entry for the track uri
entry = shell.props.db.entry_lookup_by_id(int(track))
else:
log('no specific track requested; playing from top','')
playlist_rows = source.get_query_model()
if playlist_rows.get_size() > 0:
log('got entries for playlist','')
entry = iter(playlist_rows).next()[0]
if entry is not None:
log('about to play entry ', entry)
# play the track on the source
player.play_entry(entry, source)
def _find_playlist_by_name(self, playlist_name):
playlist_model_entries = self.plugin.shell.props.playlist_manager.get_playlists()
if playlist_model_entries:
for playlist_candidate in playlist_model_entries:
if playlist_candidate.props.name == playlist_name:
# found the right playlist
return playlist_candidate
#assume the queue if playlist is not found
return self.plugin.shell.props.queue_source
def _play_playlist(self, player, shell, playlist_name):
if PYVER >= 3:
playlist_name.decode('utf-8')
playlist_candidate = self._find_playlist_by_name(playlist_name)
if playlist_candidate is not None:
playlist_rows = playlist_candidate.get_query_model()
for row in playlist_rows:
# find the first track in this playlist
entry = shell.props.db.entry_lookup_by_id(row[0].get_ulong(RB.RhythmDBPropType.ENTRY_ID))
# play the first track
player.play_entry(entry, playlist_candidate)
break
def _toggle_play_order(self, player, toggle_shuffle):
# get current play order
current_play_order = player.props.play_order
# determine which next shuffle shall be
if current_play_order == 'linear':
current_play_order = 'shuffle' if toggle_shuffle == True else 'linear-loop'
elif current_play_order == 'shuffle':
current_play_order = 'linear' if toggle_shuffle == True else 'random-by-age-and-rating'
elif current_play_order == 'linear-loop':
current_play_order = 'random-by-age-and-rating' if toggle_shuffle == True else 'linear'
else:
current_play_order = 'linear-loop' if toggle_shuffle == True else 'shuffle'
# set play order state
Gio.Settings.new('org.gnome.rhythmbox.player').set_string("play-order",current_play_order)
def _handle_stock(self, environ, response):
path = environ['PATH_INFO']
stock_id = path[len('/stock/'):]
icons = Gtk.IconTheme.get_default()
iconinfo = icons.lookup_icon(stock_id, 24, 0)
if not iconinfo:
iconinfo = icons.lookup_icon(stock_id, 32, 0)
if not iconinfo:
iconinfo = icons.lookup_icon(stock_id, 48, 0)
if not iconinfo:
iconinfo = icons.lookup_icon(stock_id, 16, 0)
if iconinfo:
fname = iconinfo.get_filename()
boolval = False
# use gio to guess at the content type based on filename
content_type, val = Gio.content_type_guess(filename=fname, data=None)
if PYVER >= 3:
icon = open(fname, "rb")
else:
icon = open(fname)
lastmod = time.gmtime(os.path.getmtime(fname))
lastmod = time.strftime("%a, %d %b %Y %H:%M:%S +0000", lastmod)
response_headers = [('Content-type',content_type),
('Last-Modified', lastmod)]
response('200 OK', response_headers)
if PYVER >= 3:
result = io.BytesIO(icon.read())
else:
result = icon.read()
icon.close()
return result
else:
log("icon", "none")
response_headers = [('Content-type','text/plain')]
response('404 Not Found', response_headers)
return iostring('Stock not found: %s' % stock_id)
def _handle_cover(self, environ, response):
fname = self._get_cover_name_for_playing_track()
# use gio to guess at the content type based on filename
content_type, val = Gio.content_type_guess(filename=fname, data=None)
if PYVER >= 3:
icon = open(fname, "rb")
else:
icon = open(fname)
lastmod = time.gmtime(os.path.getmtime(fname))
lastmod = time.strftime("%a, %d %b %Y %H:%M:%S +0000", lastmod)
response_headers = [('Content-type',content_type),
('Last-Modified', lastmod)]
response('200 OK', response_headers)
if PYVER >= 3:
result = io.BytesIO(icon.read())
else:
result = icon.read()
icon.close()
return result
def _get_cover_name_for_playing_track(self):
player = self.plugin.player
fname = ''
if player.get_playing_source() is not None:
# something is playing;
entry = player.get_playing_entry()
key = entry.create_ext_db_key(RB.RhythmDBPropType.ALBUM)
#player.props.db.unref(entry) - unsupported yet
fname = self._cover_db.lookup(key)
log("handle", fname)
return fname
def _handle_static(self, environ, response):
rpath = environ['PATH_INFO']
path = rpath.replace('/', os.sep)
path = os.path.normpath(path)
if path[0] == os.sep and not path.startswith(os.sep + 'home'):
path = path[1:]
path = resolve_path(path)
if os.path.isfile(path):
lastmod = time.gmtime(os.path.getmtime(path))
lastmod = time.strftime("%a, %d %b %Y %H:%M:%S +0000", lastmod)
response_headers = [('Content-type','text/css'),
('Last-Modified', lastmod)]
response('200 OK', response_headers)
if PYVER >= 3:
return open(path, "rb")
else:
return open(path)
else:
response_headers = [('Content-type','text/plain')]
response('404 Not Found', response_headers)
return iostring('File not found: %s' % rpath)
def parse_post(environ):
if 'CONTENT_TYPE' in environ:
length = -1
if 'CONTENT_LENGTH' in environ:
contLength = environ['CONTENT_LENGTH']
if contLength:
length = int(contLength)
if environ['CONTENT_TYPE'].startswith('application/x-www-form-urlencoded'):
return cgi.parse_qs(environ['wsgi.input'].read(length))
if environ['CONTENT_TYPE'].startswith('multipart/form-data'):
return cgi.parse_multipart(environ['wsgi.input'].read(length))
return None
def return_redirect(path, environ, response):
if not path.startswith('/'):
path_prefix = environ['REQUEST_URI']
if path_prefix.endswith('/'):
path = path_prefix + path
else:
path = path_prefix.rsplit('/', 1)[0] + path
scheme = environ['wsgi.url_scheme']
if 'HTTP_HOST' in environ:
authority = environ['HTTP_HOST']
else:
authority = environ['SERVER_NAME']
port = environ['SERVER_PORT']
if ((scheme == 'http' and port != '80') or
(scheme == 'https' and port != '443')):
authority = '%s:%s' % (authority, port)
location = '%s://%s%s' % (scheme, authority, path)
status = '303 See Other'
response_headers = [('Content-Type', 'text/plain'),
('Location', location)]
response(status, response_headers)
#log("response", response)
return [ bytestring('Redirecting...') ]
def resolve_path(path):
return os.path.join(os.path.dirname(__file__), path)
def log(message, args):
# when debugging incomment the following line
#sys.stdout.write("log %s:[%s]\n" % (message, args))
return