#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
 Copyright (C) 2004 jan gerber <j@reboot.fm>

 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
'''

# streamrecorder - records an ogg stream from and icecast server
#										saves each logical oggstream into a file.
#
# TODO:
# - trigger metadata collection after file is switched.
# - UID should be in the stream, if its live.
#
#	version 0.2
import os
from os.path import join
import string
from time import *
from math import *
from sys import exit,stdout
from ogg import OggSyncState, vorbis
from types import NoneType
from urllib2 import urlopen

class backupogg :
	def __init__(self) :
		self.ogg = OggSyncState()
		self.page = 0
		self.serial = 1
		self.switch=0
		self.url=None		
		self.record_base=""
		self.stream=""
		self.record=None

	def __call__(self, data) :
		self.ogg.bytesin(data)
		while 1:
			newpage = self.ogg.pageseek()
			if newpage == None : 
				if self.switch  == 1:
						self.switch  = 0
						#switching the file
						self.record_file="%s.ogg" % strftime("%Y-%m-%d_%H.%M.%S")						
						self.record.close()
						self.record=file(join(self.record_base,self.record_file),'w')	
						##since we switch only on eos this is not needed any longer
						##
						##reconnecting to server
						#self.url.close()
						#self.url=urlopen(self.stream)
						##resetting the ogg,page,serial variables. (is needed)
						#self.ogg = OggSyncState()
						#self.page = 0
						#self.serial = 1
						print_log("switching to next file: %s" % self.record_file)
				break
			if self.page == 0 :
				self.page = newpage
				continue
			if self.page.serialno != newpage.serialno : self.page.eos = 1
			if newpage.pageno==0 : self.page.eos = 1
			self.page.serialno=self.serial
			if self.page.eos == 1 :	
				#without reconnect that is not needed 
				#if time() - self.switch_time>15:	
				self.switch=1
				if self.serial<65536 : self.serial = self.serial + 1 
				else : self.serial = 0
			out=self.page.header+self.page.body
			self.record.write(out)
			self.page=newpage
		return

def print_log(string):
		print time(),"\t:",string
		stdout.flush()

bo=backupogg()

#bo.stream="http://212.42.235.122:8000/bootcast.ogg"

bo.stream="http://10.0.0.8:8000/bootcast.ogg"
bo.ics_url = "http://100tage.reboot.fm/vcal/current.ics"
#bo.metadata_url = "http://100tage.reboot.fm/dc/emmission-id/"

#bo.record_base="/data/recording/studioA/"
bo.record_base="/home/music/py.rec/"



while 1 :
	try:
		bo.url=urlopen(bo.stream)
	except:
		print_log("could not open %s" % bo.stream)
		sleep(5)
		continue
	bo.record_file="%s.ogg" % strftime("%Y-%m-%d_%H.%M.%S")
	bo.record=file(join(bo.record_base,bo.record_file),'w')
	print_log("restarted and connected to %s" % bo.stream)
	while 1:
		read = bo.url.read(4096)
		length=len(read)
		if length == 0 :
			bo.url.close()
			print_log("reconnect to server")
			break
		bo(read)
	bo.url.close()
	bo.record.close()
