#!/usr/bin/python2.7

# based on
#     * https://github.com/saerdnaer/youtube-upload/blob/master/youtube_upload/republica_upload.py
#     * https://github.com/thomersch/Mikrowelle-OS/blob/master/webgen.py


import os
import sys
import rssgen as rssgen
import urllib
import lxml.etree
from datetime import datetime

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

settings = {
}



schedule = lxml.etree.parse("http://www.fossgis.de/konferenz/2014/programm/schedule.de.xml")


#for fmt in formats:
#		elements = _getElements(posts, settings, fmt)

fmt = "mp4"

channel = {
	"title": "FOSSGIS 2014 ({})".format(fmt),
	"link": "https://wiki.openstreetmap.org/wiki/FOSSGIS_2014#Videoaufzeichungen",
	"description": "Videoaufzeichnungen der FOSSGIS Konferenz 2014 in Berlin",
	"author": "FOSSGIS Video Team",
	"artwork": "http://recordings.fossgis.de/2014/logo.png",
        "flattrlink" : "http://flattr.com/thing/bd400c93a5760aa792bd2e8f49b87e7b/Fossgis-Streaming"
}




# mime type mapping
mimetypes = {
	"mp3": "audio/mpeg",
	"m4a": "audio/x-m4a",
	"opus": "audio/opus",
	"mp4": "video/mp4"
}

elements = []


for event_id in schedule.xpath('day/room[@name="Meising-Saal" or @name="H1" or @name="H2" or @name="H3"]/event/@id'):
    filename = 'http://ftp5.gwdg.de/pub/misc/openstreetmap/FOSSGIS2014/' + event_id + '-h264-hq.mp4'
    event = schedule.xpath('day/room/event[@id="' + event_id + '"]')[0]
    
    persons = event.find('persons').getchildren()
    info = urllib.urlopen(filename).info()    
    filesize = info.getheader("Content-Length")
    mime = mimetypes[fmt]
    guid = filename ##"{}{}.html.{}".format(baseurl, post["episode"], post["date"])

    title = event.find('title').text
    
    if filesize is None:
        sys.stderr.write("\033[91mERROR: " + title + " is not available as mp4 file \033[0m\n")
        continue
	
    elements.append(
	{
		"title": title,
		"link": 'http://www.fossgis.de/konferenz/2014/programm/events/{0}.de.html\n'.format(event_id),
		"description": event.find('description').text or "", #event_descript, #strip_tags(html_parser.unescape(event.find('description').text)),
		"guid": guid,
		"pubdate": info.getheader("Date"), ##datetime.strptime(info.getheaders("Date"), "%Y-%m-%dT%H:%M:%S.%fZ"),
		"enclosure": {
			"url": filename,
			"length": int(filesize),
			"type": mime
		},
                "chapters": []
	})


    print(title)

with open("{}.xml".format(fmt), "wb") as f:
	f.write(rssgen.generate(channel=channel, elements=elements, settings=settings))
