#TunaPie (c)2005-2008 James Stone. Released under the GNU GPL.
#
#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 St, Fifth Floor, Boston, MA 02110-1301 USA
#
#Version 0.4.5 15/09/08

import urllib
import getpass
import fcntl
import os
import sys
import string
import re
import commands
import unicodedata
import time

def pkill(program):
    flag=""
    rip = program
    me = commands.getoutput("whoami")
    if sys.platform.find("linux")==-1:
        flag="-"
    p = commands.getoutput("ps "+flag+"U "+me+" "+flag+"o pid "+flag+"o command")
    ids = p.split("\n")
    found=0
    firstrun=1
    for id in ids:
        if id.find(rip) < 0:
            continue
        if firstrun:
            if id.find('defunct')>-1:
                found=0
            else:
                found=1
            firstrun=0
        id=id.split(" ")
        try: 
            id=str(int(id[0]))
        except:
            id=str(int(id[1]))
        commands.getoutput("kill -15 %s" % id)
        if commands.getoutput("ps "+flag+"U "+me+" "+flag+"o pid "+flag+"o command").find(id) > -1:
            commands.getoutput("kill -9 %s" % id)
    return found

def unblock(fd):
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    try:
	fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY)
    except AttributeError:
	fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.FNDELAY)

def decode(file,radio,adult,fav=0):
    stationurl=[]
    stationname=[]
    stationgenre=[]
    stationplaying=[]
    stationbitrate=[]
    stationlisteners=[]
    stationmod=[]
    f=open(file,'r')
    pos=0
    oldpos=0
    data=f.read()
    while 1:
        name=data.find('name="',pos)
        if(name==-1 or pos<oldpos):
            try: stationbitrate[0]
            except IndexError:
                if fav==0:
                    stationname=['No Streams Available!']
                    stationurl=[' ']
                    stationgenre=['Nothing!']
                    stationplaying=['Nothing!']
                    stationbitrate=['0']
                    stationlisteners=['0']
            if(fav==0):
                return(stationurl,stationname,stationgenre,\
                          stationplaying,stationbitrate,stationlisteners)
            return(stationname,stationurl,stationgenre,stationplaying,\
                          stationbitrate,stationlisteners,stationmod)
        oldpos=pos
        nameend=data.find('"',name+6)
        url=data.find('id="',nameend)
        urlend=data.find('"',url+4)
        bitrate=data.find('br="',urlend)
        bitrateend=data.find('"',bitrate+4)
        genre=data.find('genre="',bitrateend)
        genreend=data.find('"',genre+7)
        playing=data.find('ct="',bitrateend)
        playingend=data.find('"',playing+4)
        listeners=data.find('lc="',playingend)
        listenersend=data.find('"',listeners+4)
        pos=listenersend+1
        if(radio==0):
            rating=data.find('rt="',oldpos)
            ratingend=data.find('"',rating+4)
        if(not(adult)):
            if(radio==0):
                if(data[rating+4:ratingend]=="NC17"):
                    continue
        if fav==1:
            mod=data.find('mod="',oldpos)
            modend=data.find('"',mod+5)
            try: stationmod.append(int(data[mod+5:modend]))
            except ValueError:
                if (data[mod+5:modend]=='True'):
                    stationmod.append(1)
                else:
                    stationmod.append(0)
            pos=modend+1
        if pos<oldpos:
            continue
        if data[url+4:urlend].find('http://')==-1:
            stationurl.append('http://www.shoutcast.com/sbin/shoutcast-playlist.pls?rn='+data[url+4:urlend])
        else:
            stationurl.append(data[url+4:urlend])
        thisname=data[name+6:nameend]
        if thisname=="ess.tv":
            thisname=data[genre+7:genreend]
        stationname.append(thisname)
        thisgenre=data[genre+7:genreend]
        if(radio==0):
            if(data[rating+4:ratingend]=="NC17"):
                if thisgenre.lower().find('porn')==-1:
                    thisgenre+=' Porn'
        stationgenre.append(thisgenre)
        stationplaying.append(data[playing+4:playingend])
        stationlisteners.append(data[listeners+4:listenersend])
        stationbitrate.append(data[bitrate+4:bitrateend])

def decodeice(file,radio):
    stationurl=[]
    stationname=[]
    stationgenre=[]
    stationplaying=[]
    stationbitrate=[]
    stationlisteners=[]
    f=open(file,'r')
    pos=0
    oldpos=0
    data=f.read()    
    while 1:
        name=data.find('<server_name>',pos)
        if(name==-1 or pos<oldpos):
            try: stationbitrate[0]
            except IndexError:
                stationname=['No Streams Available!']
                stationurl=[' ']
                stationgenre=['Nothing!']
                stationplaying=['Nothing!']
                stationbitrate=['0']
                stationlisteners=['0']
            return(stationurl,stationname,stationgenre,\
                          stationplaying,stationbitrate,stationlisteners)
        oldpos=pos
        nameend=data.find('</serv',name)
        url=data.find('<listen_url>',nameend)
        urlend=data.find('</list',url)
        servertype=data.find('<server_type>', urlend)
        servertypeend=data.find('</serv', servertype)
        bitrate=data.find('<bitrate>', servertypeend)
        bitrateend=data.find('</bitr', bitrate)
        genre=data.find('<genre>',bitrateend)
        genreend=data.find('</genr',genre)
        playing=data.find('<current_song>',genreend)
        playingend=data.find('</curr',playing)
        if not(radio):
            if (data[servertype:servertypeend].lower().find('video')==-1):
                pos=playingend+6
                continue
        else:
            if data[servertype:servertypeend].lower().find('video')>-1:
                pos=playingend+6
                continue
        pos=playingend+6
        if pos<oldpos:
            continue
        fixedname=fixunicode(data[name+13:nameend])
        stationname.append(fixedname)
        if data[url+12:urlend].find('http://')==-1:
            stationurl.append('http://dir.xiph.org/'+data[url+12:urlend])
        else:
            stationurl.append(data[url+12:urlend])
        fixedplaying=fixunicode(data[playing+14:playingend])
        stationplaying.append(fixedplaying)
        fixedgenre=fixunicode(data[genre+7:genreend])
        stationgenre.append(fixedgenre)
        stationlisteners.append("0")
        bitrate=data[bitrate+9:bitrateend]
        try: int(bitrate)
        except: bitrate="0"
        stationbitrate.append(bitrate)

def playselection(mediaplayer,pls,info=0):
        commands.getoutput("rm -rf /tmp/"+getpass.getuser()+"*_tunapie_temp.pls")
        tstamp=str(time.time())
        tempfile=open('/tmp/'+getpass.getuser()+tstamp+'_tunapie_temp.pls','w')
        playlist=urllib.urlopen(pls)
        if (info):
            return playlist.readlines()
        if mediaplayer.find('realplay')>-1:
            os.system(mediaplayer+" "+pls+" &")
            return
        plist=playlist.readlines()
        if len(plist)==1:
            os.spawnv(os.P_NOWAIT,commands.getoutput("which "+mediaplayer).split(" ")[0],[mediaplayer,plist[0]])
            return
        for line in plist:
            tempfile.write(line)
        os.spawnv(os.P_NOWAIT,commands.getoutput("which "+mediaplayer).split(" ")[0],[mediaplayer,'/tmp/'+getpass.getuser()+tstamp+'_tunapie_temp.pls'])
    
def playvid(mediaplayer,pls):
    playercommands=mediaplayer.split(" ")
    vidplayer=commands.getoutput("which "+str(playercommands[0]))
    playercommands.append(pls)
    os.spawnv(os.P_NOWAIT, vidplayer, playercommands)

def savefavorites(home,favname,favurl,favlist,favplay,favbit,favgen,favmod):
    favfile=open(home+'/.tunapie/favorites','w')
    for i in range(len(favname)):
        favfile.write('name="'+favname[i]+'"\n')
        favfile.write('id="'+favurl[i]+'"\n')
        favfile.write('br="'+favbit[i]+'"\n')
        favfile.write('genre="'+favgen[i]+'"\n')
        favfile.write('ct="'+favplay[i]+'"\n')
        favfile.write('lc="'+favlist[i]+'"\n')
        favfile.write('mod="'+str(favmod[i])+'"\n')

def writeprefs(home,audio,video,term,rip,rdir,shoutice,maxd,fontsize,browser):
    preffile=open(home+'/.tunapie/prefs','w')
    preffile.write("audioplayer="+audio+'\n')
    preffile.write("videoplayer="+video+'\n')
    preffile.write("xterm="+term+'\n')
    preffile.write("streamripper="+rip+'\n')
    preffile.write("ripdirectory="+rdir+'\n')
    preffile.write("icecast(0)/shoutcast(1)="+str(int(shoutice))+'\n')
    preffile.write("max streams to display="+str(int(maxd))+'\n')
    preffile.write("font size="+str(int(fontsize))+'\n')
    preffile.write("web browser="+browser+'\n')

def readprefs(home,rdir,shoutice,maxd,fontsize):
    try: preffile=open(home+'/.tunapie/prefs','r')
    except IOError:
        return "","","","",rdir,shoutice,maxd,fontsize,""
    preferences=preffile.read().split('\n')
    returnvals=[]
    for i in preferences:
        try:returnvals.append(i.split("=")[1])
        except IndexError: pass
    if len(returnvals)<9:
        return "","","","",rdir,shoutice,maxd,fontsize,""
    return(returnvals[0],returnvals[1],returnvals[2],returnvals[3],\
            returnvals[4],returnvals[5],returnvals[6], returnvals[7],\
            returnvals[8])
                
def recordselection(terminal,args):
    recordcommand=terminal+args+"&"
    os.system(recordcommand)

def showpage(browser,url):
    urlcommand=[browser,url]
    os.spawnv(os.P_NOWAIT,commands.getoutput("which "+browser).split(" ")[0],urlcommand)

def adultset():
    try: adultconfig=open('/etc/tunapie.config')
    except IOError: return 0
    setadult=adultconfig.readline()
    return int(setadult)

def fixunicode(text):
    fixed=""
    for letter in text:
        try: fixed=fixed+letter.encode()
        except: pass
    #fixed = unicodedata.normalize('NFKD', temp).encode('ASCII', 'replace')
    return fixed
    