#!/usr/bin/env python # cast.py - audio queuer # Copyright (C) 2006 Lenny Domnitser # # 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. ''' Run this as a CGI script. The file cast.queue must be readable and writable by the server. Useful with this bookmarklet: javascript:(function(){function openForm(url,title){open('http://domnit.org/cast.cgi/add?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title),'','width=400,height=100');}switch(document.contentType.split('/')[0]){case'audio':case'video':openForm(location.href,document.title);return;}addEventListener('click',function(event){if(event.target.nodeName.toLowerCase()=='a'){event.preventDefault();openForm(event.target.href,event.target.textContent);removeEventListener('click',arguments.callee,false);}},false);})(); ''' import cgi import string import os import cgitb; cgitb.enable() def init_vars(): global url, title fs = cgi.FieldStorage() url = (fs.getfirst('url') or '').replace('&', '&').replace('<', '<') title = (fs.getfirst('title') or '').replace('&', '&').replace('<', '<') def add_item(): init_vars() print >> open('cast.queue', 'a'), url, title return 'Status: 200 OK\nContent-Type:text/html', ''' tnx bye ''' def get_form(): init_vars() the_form = string.Template(''' Post audio
''').substitute(globals()) return 'Content-Type: text/html', the_form def get_feed(): feed_tmpl = string.Template(''' My Audio Queue $items ''') item_tmpl = string.Template(''' $title ''') if os.stat('cast.queue').st_size == 0: return 'Status: 304 Not Modified', '' items = [] for item in open('cast.queue'): url, title = item.split(' ', 1) items.append(item_tmpl.substitute(locals())) items = '\n'.join(items) feed = feed_tmpl.substitute(locals()) open('cast.queue', 'w').close() return 'Content-Type: application/xml', feed def handle_cgi(): method = os.environ.get('REQUEST_METHOD') path = os.environ.get('PATH_INFO') try: response = { ('POST', '/add'): add_item, ('GET', '/add'): get_form, ('GET', '/feed'): get_feed, }[(method, path)]() print '\n\n'.join(response) except KeyError: print 'Status: 404 Not Found\nContent-Type: text/plain\n\nbad url' if __name__ == '__main__': handle_cgi()