#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
##    Copyright (C) 2005 manatlan manatlan[at]gmail(dot)com
##
## 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; version 2 only.
##
## 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.
##


from BeautifulSoup import BeautifulSoup
import urllib,re,sys

def getHtmlFromUrl(url):
    """ retourne le code html derriere l'url """
    f = urllib.urlopen(url)
    return f.read()

def getRtspFromCode(code,debit="T"):
    """ retourne l'adresse rtsp en fonction du code de la video """
    soup = BeautifulSoup( getHtmlFromUrl("http://www.allocine.fr/webtv/acvision.asp?nopub=1&cvid=%s&player=RG2&debit=%s&emission=" % (code,debit)) )
    l=soup("param",{"name":"src"})
    if len(l)>0:
        return getHtmlFromUrl(getHtmlFromUrl(l[0]["value"]))

def getCodesFromIdFilm(id):
    """ retourne l'ensemble des "codes-videos" de ce film """
    list=[]
    soup = BeautifulSoup( getHtmlFromUrl("http://www.allocine.fr/film/video_gen_cfilm=%s.html" % id) )
    for i in soup("a",{"href":re.compile("^javascript. ?FenACVision.*")}):
        list.append( (re.compile(r"^.*\(([^,]+),.*\)$").match(i["href"]).group(1),i.b.string) )
    return list

def getIdFilmFromString(s):
    g=re.compile(r"^/film/fichefilm_gen_cfilm=([^\.]+)\.html$").match(s)
    if g:
        return g.group(1)


def getRtspFromIdFilm(id):
    list= getCodesFromIdFilm(id)
    if len(list)>0:
        code1=list[0][0]    # prends le premier (generallement la Bande annonce)

        rtsp=getRtspFromCode(code1,"HD")    # tente le HD en prems
        if rtsp:
            return rtsp
        else:
            rtsp=getRtspFromCode(code1)     # sinon se rabat sur le T
            if rtsp:
                return rtsp

if __name__ == "__main__":
    if len(sys.argv)==1:
        # mode genere la playlist
        list=[]
        soup=BeautifulSoup(getHtmlFromUrl("http://www.allocine.fr/"))
        # sorties de la semaine
        for i in soup("td",{"style":"padding: 3 0 2 0"}):
            id=getIdFilmFromString(i.a["href"])
            if id:
                list.append( (id,"NEW: "+i.a.b.string) )


        # toujours a l'affiche
        for i in soup("td",{"style":"padding: 2 0 3 0"}):
            id=getIdFilmFromString(i.a["href"])
            if id:
                list.append( (id,i.a.b.string) )

        fid=open("allocine.m3u","w")
        fid.write("#EXTM3U\n")
        for id,titre in list:
            rtsp=getRtspFromIdFilm(id)
            titre=titre.decode("iso8859_15").encode("utf_8")
            if rtsp:
                print titre
                fid.write("#EXTINF:0,"+titre+"\n")
                fid.write( rtsp+"\n" )
            else:
                print titre,": PAS DE BANDE ANNONCE"
        fid.close()

    elif len(sys.argv)==2:
        # mode film unique
        num = sys.argv[1]
        if int(num)>10000000:
            # c un code de video
            print getRtspFromCode(num)
        else:
            # c un code de film
            print getRtspFromIdFilm(num)


