Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding:Utf-8 -*-
- ###########################################################################
- # Copyright (C) 2010 La_Poigne #
- # 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 #
- # 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, see <http://www.gnu.org/licenses/>. #
- ###########################################################################
- #
- # ---------------------------------------------------------
- # Script de téléchargement des émissions du site de Canal +
- # ---------------------------------------------------------
- #
- #Changelog:
- #V 0.1
- #21-12-2010 : Création par vincentp010
- #V 0.4
- #10-11-2012 : Refonte par Jx7
- import os, urllib, subprocess, time, sys
- from xml.dom import minidom
- # Identifiants des émissions ([ID de l'émission, emplacement de la date, nom de l'émission])
- ShowList = []
- #ShowList.append([37,3,"Action discrete"]) # 304 ?
- #ShowList.append([62,4,"Le boucan du jour"]) # 204 205 206 316 ?
- #ShowList.append([627,4,"Bref"])
- #ShowList.append([104,4,"Le grand journal"]) # 129
- ShowList.append([254,2,"Groland"])
- ShowList.append([48,3,"Guignols de l'info (les)"]) # 222 555 ?
- #ShowList.append([242,4,"Du hard ou du cochon"])
- #ShowList.append([451,4,"Jamel comedy club"]) # 943 953 ?
- #ShowList.append([896,4,"Le journal du hard"])
- #ShowList.append([39,4,"La matinale"]) # 105 ?
- #ShowList.append([215,4,"Le meilleur du hier"]) # 63 107 110 112 ?
- #ShowList.append([47,4,"Les pépites du net"]) # 319 321 ?
- ShowList.append([249,4,"Petit journal (le)"]) # 249 250 556 557 558 559 ?
- #ShowList.append([843,4,"La question de plus"])
- #ShowList.append([294,4,"La revue de presse de Catherine et Eliane"]) # 852 ?
- #ShowList.append([182,4,"Salut les terriens"]) # ???
- #ShowList.append([680,4,"Salut les terriens - edito de Blako"])
- #ShowList.append([1064,4,"Salut les terriens - Gaspard Proust"])
- #ShowList.append([1072,4,"Salut les terriens - les martiens de la semaine"])
- #ShowList.append([252,4,"SAV des émissions"]) # 406 ?
- #ShowList.append([936,4,"Tweet en clair"])
- ShowList.append([201,2,"Zapping (le)"]) # 130 207 ?
- # Qualité voulue des vidéos (BAS_DEBIT, HAUT_DEBIT, HD)
- Quality = "HD"
- # Répertoires (à créer avant)
- HomeDir = os.path.expanduser('~/.cplus')
- DownloadsDir = HomeDir + "/downloads"
- #Fichiers
- LogFile = HomeDir + "/cplus_log"
- HistoryFile = HomeDir + "/cplus_history"
- UnwantedFile = HomeDir + "/cplus_unwanted"
- # Paramètres Web de Canal +
- ShowURL_XML = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getMEAs/"
- VideoURL_XML = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getVideos/"
- # Autres variables
- Debug = True
- #Debug = False
- # fonction: Télécharge un XML à partir d'une URL
- def DownloadXML(_URL):
- try:
- _XMLFileSock = urllib.urlopen(_URL)
- _XMLFile = _XMLFileSock.read()
- except Exception, e:
- return 1
- try:
- _XML = minidom.parseString(_XMLFile)
- except Exception, e:
- _XML = 1
- return _XML
- # fonction: Récupère les ID des vidéos en parsant les balises MEA d'un XML
- def ParseMEAs(_XML):
- _IDs = []
- _MEAs = _XML.getElementsByTagName('MEA')
- for i in _MEAs:
- if i.getElementsByTagName('ID')[0].childNodes != []:
- #_ID = i.getElementsByTagName('ID')[0].childNodes[0].nodeValue
- #_IDs.append(_ID)
- _IDs.append(i.getElementsByTagName('ID')[0].childNodes[0].nodeValue)
- return _IDs
- # fonction: Récupère l'URL d'un fichier en parsant un XML
- def GetVideoURL(_XML):
- _FileURL = []
- _Videos = _XML.getElementsByTagName('VIDEO')
- for i in _Videos:
- try:
- _Video = i.getElementsByTagName('MEDIA')[0].getElementsByTagName('VIDEOS')[0]
- except Exception:
- _Video = ""
- try:
- _RTMP = _Video.getElementsByTagName(Quality)[0].childNodes[0].nodeValue
- except Exception:
- _RTMP = ""
- _FileURL.append(_RTMP)
- return _FileURL[0]
- # fonction: Exécute une commande et log le résultat dans un fichier de sortie
- def Execute(_Params, _File):
- p = subprocess.Popen(_Params,stdout=_File)
- p.wait()
- return p.returncode
- # fonction: Ajoute une vidéo à l'historique
- def AddHistory(_File):
- HistoryFile_ = open(HistoryFile, 'a')
- HistoryFile_.write(_File.encode('utf-8') + '\n')
- HistoryFile_.close()
- # fonction: Vérifie si une vidéo est non voulue
- def CheckUnwanted(_File):
- _Unwanted = 0
- UnwantedFile_ = open(UnwantedFile, 'r')
- for _Line in UnwantedFile_:
- _Line = _Line[0:len(_Line) - 2]
- if _Line.decode('utf-8') in _File:
- _Unwanted = 1
- UnwantedFile_.close()
- return _Unwanted
- # fonction: Vérifie l'historique
- def CheckHistory(_File):
- _History = 0
- HistoryFile_ = open(HistoryFile, 'r')
- for _Line in HistoryFile_:
- if _Line.decode('utf-8') == _File + '\n':
- _History = 1
- HistoryFile_.close()
- return _History
- # fonction: Affiche à l'écran et écrit dans la log un message
- def ToDebug(_LogFile, _Log):
- print _Log
- LogFile_ = open(_LogFile, "a")
- LogFile_.write(_Log + '\n')
- LogFile_.close()
- return 0
- # fonction: Initiliase les infos globales
- def InitInfos():
- global ShowName; ShowName = "N/A"
- global ShowID; ShowID = "N/A"
- global ShowURL; ShowURL = "N/A"
- global VideoID; VideoID = "N/A"
- global VideoURL; VideoURL = "N/A"
- global FileName; FileName = "N/A"
- global TargetFile; TargetFile = "N/A"
- global FileURL; FileURL = "N/A"
- global Message; Message = ""
- # fonction: Affiche les infos globales
- def PrintInfos():
- os.system('clear')
- print "Emission:"
- print " -Nom: " + ShowName
- print " -ID: " + str(ShowID)
- print " -URL: " + ShowURL + '\n'
- print "Video:"
- print " -ID: " + VideoID
- print " -URL: " + VideoURL + '\n'
- print "Fichier:"
- print " -Nom: " + FileName
- print " -Cible: " + TargetFile
- print " -URL: " + FileURL + '\n'
- print "Infos:"
- print Message
- # fonction: Log les infos globales
- def LogInfos(_LogFile):
- LogFile_ = open(_LogFile, "a")
- LogFile_.write("Emission:" + '\n')
- LogFile_.write(" -Nom: " + ShowName + '\n')
- LogFile_.write(" -ID: " + str(ShowID) + '\n')
- LogFile_.write(" -URL: " + ShowURL + '\n\n')
- LogFile_.write("Video:" + '\n')
- LogFile_.write(" -ID: " + VideoID + '\n')
- LogFile_.write(" -URL: " + VideoURL + '\n\n')
- LogFile_.write("Fichier:" + '\n')
- LogFile_.write(" -Nom: " + FileName + '\n')
- LogFile_.write(" -Cible: " + TargetFile + '\n')
- LogFile_.write(" -URL: " + FileURL + '\n\n')
- LogFile_.write("Infos:" + '\n')
- LogFile_.write(Message + '\n')
- LogFile_.write("--------------------------------------------------" + '\n\n')
- LogFile_.close()
- #fonction: Classement alphabétique des lignes d'un fichier
- def SortFile(_TextFile):
- f = open(_TextFile, 'r')
- lines = f.readlines()
- lines.sort()
- f.close()
- f = open(_TextFile, 'w')
- f.writelines(lines)
- f.close()
- # MAIN
- if __name__ == "__main__":
- # Teste l'existance des fichiers textes et les crée si besoin
- if os.path.exists(UnwantedFile) == False:
- UnwantedFile_ = open(UnwantedFile, 'w')
- UnwantedFile_.close()
- else:
- # Classement alphabétique du fichier des non voulus
- SortFile(UnwantedFile)
- if os.path.exists(HistoryFile) == False:
- HistoryFile_ = open(HistoryFile, 'w')
- HistoryFile_.close()
- if os.path.exists(LogFile) == False:
- LogFile_ = open(LogFile, "w")
- LogFile_.close()
- # Activation/Désactivation du mode debug
- if ( len(sys.argv) == 2 and sys.argv[1] == "--debug" ):
- Debug = True
- ToDebug(LogFile, "-------------------" + '\n' + time.strftime("%Y.%m.%d %H:%M:%S") + '\n' + "-------------------")
- # Traitement émission par émission
- for x in range(len(ShowList)):
- InitInfos()
- ShowName = ShowList[x][2]
- ShowID = ShowList[x][0]
- ShowURL = ShowURL_XML + str(ShowID)
- ShowXML = DownloadXML(ShowURL)
- if Debug: PrintInfos()
- if ShowXML == 1:
- Message = "ERREUR : IMPOSSIBLE DE TÉLÉCHARGER LE XML DE L'ÉMISSION."
- if Debug: PrintInfos(); LogInfos(LogFile)
- else:
- # Traitement vidéo par vidéo pour l'émission en cours
- VideosIDsList = ParseMEAs(ShowXML)
- for VideoID in VideosIDsList:
- VideoURL = VideoURL_XML + VideoID
- VideoXML = DownloadXML(VideoURL)
- if Debug: PrintInfos()
- if VideoXML == 1:
- Message = "ERREUR : IMPOSSIBLE DE TÉLÉCHARGER LE XML DE LA VIDÉO."
- if Debug: PrintInfos(); LogInfos(LogFile)
- else:
- FileURL = GetVideoURL(VideoXML)
- head, FileName = os.path.split(FileURL)
- if Debug: PrintInfos()
- # Comparaison du nom de fichier avec les fichiers non voulus et déjà téléchargées
- Unwanted = CheckUnwanted(FileName)
- History = CheckHistory(FileName)
- if Unwanted + History != 0:
- if Unwanted != 0:
- Message = "Vidéo non voulue."
- if Debug: PrintInfos(); LogInfos(LogFile)
- elif History != 0:
- Message = "Vidéo déjà téléchargée."
- if Debug: PrintInfos(); LogInfos(LogFile)
- # Nommage simple du fichier en cours
- else:
- basename, extension = os.path.splitext(FileName)
- words = basename.split('_')
- if Debug: PrintInfos()
- if len(words) <= 1:
- FileName = "N/A"
- FileURL = "N/A"
- Message = "Nom de fichier indeterminable."
- if Debug: PrintInfos(); LogInfos(LogFile)
- else:
- date = words[ShowList[x][1]]
- date = "20" + date[:2] + "." + date[2:4] + "." + date[-2:]
- FileSimpleName = date + "_" + Quality + extension
- if not os.path.isdir(DownloadsDir + "/" + ShowName):
- os.makedirs(DownloadsDir + "/" + ShowName)
- TargetFile = DownloadsDir + "/" + ShowName + "/" + FileSimpleName
- if Debug: PrintInfos()
- # Téléchargement via flvstreamer si le protocole utilisé dans l'URL est RTMP
- if FileURL.find("rtmp") != -1:
- Message = "Téléchargement via flvstreamer."
- params=['flvstreamer', '-r', FileURL]
- target_ = open(TargetFile, 'w')
- if Debug: PrintInfos()
- r = Execute(params, target_)
- #r = 0
- target_.close()
- # Téléchargement direct dans les autres cas
- else:
- Message = "Téléchargement direct."
- if Debug: PrintInfos()
- try:
- urllib.urlretrieve(FileURL, TargetFile)
- r=0
- except Exception:
- r=1
- # Ajout dans l'historique s'il n'y a pas eu d'erreur
- if r == 0:
- Message += '\n' + "Téléchargement terminé, ajout dans l'historique."
- if Debug: PrintInfos(); LogInfos(LogFile)
- AddHistory(FileName)
- # Suppression du fichier s'il y a eu une erreur
- else:
- if os.path.exists(TargetFile):
- os.remove(TargetFile)
- Message += '\n' + "ERREUR : PROBLÈME DE TÉLÉCHARGEMENT."
- if Debug: PrintInfos(); LogInfos(LogFile)
- #time.sleep(1)
- # Classement alphabétique du fichier d'historique
- SortFile(HistoryFile)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement