Advertisement
Jx7

Téléchargement des émissions du site de Canal +

Jx7
Nov 14th, 2012
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.33 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding:Utf-8 -*-
  3.  
  4. ###########################################################################
  5. # Copyright (C) 2010  La_Poigne                                           #
  6. # This program is free software: you can redistribute it and/or modify    #
  7. #  it under the terms of the GNU General Public License as published by   #
  8. #  the Free Software Foundation, either version 2 of the License, or      #
  9. #  any later version.                                                     #
  10. # This program is distributed in the hope that it will be useful,         #
  11. #  but WITHOUT ANY WARRANTY without even the implied warranty of          #
  12. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          #
  13. #  GNU General Public License for more details.                           #
  14. # You should have received a copy of the GNU General Public License       #
  15. #  along with this program.  If not, see <http://www.gnu.org/licenses/>.  #
  16. ###########################################################################
  17. #
  18. # ---------------------------------------------------------
  19. # Script de téléchargement des émissions du site de Canal +
  20. # ---------------------------------------------------------
  21. #
  22. #Changelog:
  23. #V 0.1
  24. #21-12-2010 : Création par vincentp010
  25. #V 0.4
  26. #10-11-2012 : Refonte par Jx7
  27.  
  28. import os, urllib, subprocess, time, sys
  29. from xml.dom import minidom
  30.  
  31. # Identifiants des émissions ([ID de l'émission, emplacement de la date, nom de l'émission])
  32. ShowList = []
  33. #ShowList.append([37,3,"Action discrete"])                              # 304 ?
  34. #ShowList.append([62,4,"Le boucan du jour"])                            # 204 205 206 316 ?
  35. #ShowList.append([627,4,"Bref"])
  36. #ShowList.append([104,4,"Le grand journal"])                            # 129
  37. ShowList.append([254,2,"Groland"])
  38. ShowList.append([48,3,"Guignols de l'info (les)"])                      # 222 555 ?
  39. #ShowList.append([242,4,"Du hard ou du cochon"])
  40. #ShowList.append([451,4,"Jamel comedy club"])                           # 943 953 ?
  41. #ShowList.append([896,4,"Le journal du hard"])
  42. #ShowList.append([39,4,"La matinale"])                                  # 105 ?
  43. #ShowList.append([215,4,"Le meilleur du hier"])                     # 63 107 110 112 ?
  44. #ShowList.append([47,4,"Les pépites du net"])                          # 319 321 ?
  45. ShowList.append([249,4,"Petit journal (le)"])                           # 249 250 556 557 558 559 ?
  46. #ShowList.append([843,4,"La question de plus"])
  47. #ShowList.append([294,4,"La revue de presse de Catherine et Eliane"])   # 852 ?
  48. #ShowList.append([182,4,"Salut les terriens"])                          # ???
  49. #ShowList.append([680,4,"Salut les terriens - edito de Blako"])
  50. #ShowList.append([1064,4,"Salut les terriens - Gaspard Proust"])
  51. #ShowList.append([1072,4,"Salut les terriens - les martiens de la semaine"])
  52. #ShowList.append([252,4,"SAV des émissions"])                          # 406 ?
  53. #ShowList.append([936,4,"Tweet en clair"])
  54. ShowList.append([201,2,"Zapping (le)"])                             # 130 207 ?
  55.  
  56. # Qualité voulue des vidéos (BAS_DEBIT, HAUT_DEBIT, HD)
  57. Quality = "HD"
  58.  
  59. # Répertoires (à créer avant)
  60. HomeDir = os.path.expanduser('~/.cplus')
  61. DownloadsDir = HomeDir + "/downloads"
  62.  
  63. #Fichiers
  64. LogFile = HomeDir + "/cplus_log"
  65. HistoryFile = HomeDir + "/cplus_history"
  66. UnwantedFile = HomeDir + "/cplus_unwanted"
  67.  
  68. # Paramètres Web de Canal +
  69. ShowURL_XML = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getMEAs/"
  70. VideoURL_XML = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getVideos/"
  71.  
  72. # Autres variables
  73. Debug = True
  74. #Debug = False
  75.  
  76. # fonction: Télécharge un XML à partir d'une URL
  77. def DownloadXML(_URL):
  78.     try:
  79.         _XMLFileSock = urllib.urlopen(_URL)
  80.         _XMLFile = _XMLFileSock.read()
  81.     except Exception, e:
  82.         return 1
  83.     try:
  84.         _XML = minidom.parseString(_XMLFile)
  85.     except Exception, e:
  86.         _XML = 1
  87.     return _XML
  88.  
  89. # fonction: Récupère les ID des vidéos en parsant les balises MEA d'un XML
  90. def ParseMEAs(_XML):
  91.     _IDs = []
  92.     _MEAs = _XML.getElementsByTagName('MEA')
  93.     for i in _MEAs:
  94.         if i.getElementsByTagName('ID')[0].childNodes != []:
  95.             #_ID = i.getElementsByTagName('ID')[0].childNodes[0].nodeValue
  96.             #_IDs.append(_ID)
  97.             _IDs.append(i.getElementsByTagName('ID')[0].childNodes[0].nodeValue)
  98.     return _IDs
  99.  
  100. # fonction: Récupère l'URL d'un fichier en parsant un XML
  101. def GetVideoURL(_XML):
  102.     _FileURL = []
  103.     _Videos = _XML.getElementsByTagName('VIDEO')
  104.     for i in _Videos:
  105.         try:
  106.             _Video = i.getElementsByTagName('MEDIA')[0].getElementsByTagName('VIDEOS')[0]
  107.         except Exception:
  108.             _Video = ""
  109.         try:
  110.             _RTMP = _Video.getElementsByTagName(Quality)[0].childNodes[0].nodeValue
  111.         except Exception:
  112.             _RTMP = ""
  113.         _FileURL.append(_RTMP)
  114.     return _FileURL[0]
  115.  
  116. # fonction: Exécute une commande et log le résultat dans un fichier de sortie
  117. def Execute(_Params, _File):
  118.     p = subprocess.Popen(_Params,stdout=_File)
  119.     p.wait()
  120.     return p.returncode
  121.  
  122. # fonction: Ajoute une vidéo à l'historique
  123. def AddHistory(_File):
  124.     HistoryFile_ = open(HistoryFile, 'a')
  125.     HistoryFile_.write(_File.encode('utf-8') + '\n')
  126.     HistoryFile_.close()
  127.  
  128. # fonction: Vérifie si une vidéo est non voulue
  129. def CheckUnwanted(_File):
  130.     _Unwanted = 0
  131.     UnwantedFile_ = open(UnwantedFile, 'r')
  132.     for _Line in UnwantedFile_:
  133.         _Line = _Line[0:len(_Line) - 2]
  134.         if _Line.decode('utf-8') in _File:
  135.             _Unwanted = 1
  136.     UnwantedFile_.close()
  137.     return _Unwanted
  138.  
  139. # fonction: Vérifie l'historique
  140. def CheckHistory(_File):
  141.     _History = 0
  142.     HistoryFile_ = open(HistoryFile, 'r')
  143.     for _Line in HistoryFile_:
  144.         if _Line.decode('utf-8') == _File + '\n':
  145.             _History = 1
  146.     HistoryFile_.close()
  147.     return _History
  148.  
  149. # fonction: Affiche à l'écran et écrit dans la log un message
  150. def ToDebug(_LogFile, _Log):
  151.     print _Log
  152.     LogFile_ = open(_LogFile, "a")
  153.     LogFile_.write(_Log + '\n')
  154.     LogFile_.close()
  155.     return 0
  156.  
  157. # fonction: Initiliase les infos globales
  158. def InitInfos():
  159.     global ShowName;    ShowName = "N/A"
  160.     global ShowID;      ShowID = "N/A"
  161.     global ShowURL;     ShowURL = "N/A"
  162.     global VideoID;     VideoID = "N/A"
  163.     global VideoURL;    VideoURL = "N/A"
  164.     global FileName;    FileName = "N/A"
  165.     global TargetFile;  TargetFile = "N/A"
  166.     global FileURL;     FileURL = "N/A"
  167.     global Message;     Message = ""
  168.  
  169. # fonction: Affiche les infos globales
  170. def PrintInfos():
  171.     os.system('clear')
  172.     print "Emission:"
  173.     print " -Nom: " + ShowName
  174.     print " -ID: " + str(ShowID)
  175.     print " -URL: " + ShowURL + '\n'
  176.     print "Video:"
  177.     print " -ID: " + VideoID
  178.     print " -URL: " + VideoURL + '\n'
  179.     print "Fichier:"
  180.     print " -Nom: " + FileName
  181.     print " -Cible: " + TargetFile
  182.     print " -URL: " + FileURL + '\n'
  183.     print "Infos:"
  184.     print Message
  185.  
  186. # fonction: Log les infos globales
  187. def LogInfos(_LogFile):
  188.     LogFile_ = open(_LogFile, "a")
  189.     LogFile_.write("Emission:" + '\n')
  190.     LogFile_.write(" -Nom: " + ShowName + '\n')
  191.     LogFile_.write(" -ID: " + str(ShowID) + '\n')
  192.     LogFile_.write(" -URL: " + ShowURL + '\n\n')
  193.     LogFile_.write("Video:" + '\n')
  194.     LogFile_.write(" -ID: " + VideoID + '\n')
  195.     LogFile_.write(" -URL: " + VideoURL + '\n\n')
  196.     LogFile_.write("Fichier:" + '\n')
  197.     LogFile_.write(" -Nom: " + FileName + '\n')
  198.     LogFile_.write(" -Cible: " + TargetFile + '\n')
  199.     LogFile_.write(" -URL: " + FileURL + '\n\n')
  200.     LogFile_.write("Infos:" + '\n')
  201.     LogFile_.write(Message + '\n')
  202.     LogFile_.write("--------------------------------------------------" + '\n\n')
  203.     LogFile_.close()
  204.  
  205. #fonction: Classement alphabétique des lignes d'un fichier
  206. def SortFile(_TextFile):
  207.     f = open(_TextFile, 'r')
  208.     lines = f.readlines()
  209.     lines.sort()
  210.     f.close()
  211.     f = open(_TextFile, 'w')
  212.     f.writelines(lines)
  213.     f.close()
  214.  
  215. # MAIN
  216. if __name__ == "__main__":
  217.  
  218.     # Teste l'existance des fichiers textes et les crée si besoin
  219.     if os.path.exists(UnwantedFile) == False:
  220.         UnwantedFile_ = open(UnwantedFile, 'w')
  221.         UnwantedFile_.close()
  222.     else:
  223.         # Classement alphabétique du fichier des non voulus
  224.         SortFile(UnwantedFile)
  225.     if os.path.exists(HistoryFile) == False:
  226.         HistoryFile_ = open(HistoryFile, 'w')
  227.         HistoryFile_.close()
  228.     if os.path.exists(LogFile) == False:
  229.         LogFile_ = open(LogFile, "w")
  230.         LogFile_.close()
  231.  
  232.     # Activation/Désactivation du mode debug
  233.     if ( len(sys.argv) == 2 and sys.argv[1] == "--debug" ):
  234.         Debug = True
  235.         ToDebug(LogFile, "-------------------" + '\n' + time.strftime("%Y.%m.%d %H:%M:%S") + '\n' + "-------------------")
  236.  
  237.     # Traitement émission par émission
  238.     for x in range(len(ShowList)):
  239.         InitInfos()
  240.         ShowName = ShowList[x][2]
  241.         ShowID = ShowList[x][0]
  242.         ShowURL = ShowURL_XML + str(ShowID)
  243.         ShowXML = DownloadXML(ShowURL)
  244.         if Debug: PrintInfos()
  245.         if ShowXML == 1:
  246.             Message = "ERREUR : IMPOSSIBLE DE TÉLÉCHARGER LE XML DE L'ÉMISSION."
  247.             if Debug: PrintInfos(); LogInfos(LogFile)
  248.         else:
  249.  
  250.             # Traitement vidéo par vidéo pour l'émission en cours
  251.             VideosIDsList = ParseMEAs(ShowXML)
  252.             for VideoID in VideosIDsList:
  253.                 VideoURL = VideoURL_XML + VideoID
  254.                 VideoXML = DownloadXML(VideoURL)
  255.                 if Debug: PrintInfos()
  256.                 if VideoXML == 1:
  257.                     Message = "ERREUR : IMPOSSIBLE DE TÉLÉCHARGER LE XML DE LA VIDÉO."
  258.                     if Debug: PrintInfos(); LogInfos(LogFile)
  259.                 else:
  260.                     FileURL = GetVideoURL(VideoXML)
  261.                     head, FileName = os.path.split(FileURL)
  262.                     if Debug: PrintInfos()
  263.  
  264.                     # Comparaison du nom de fichier avec les fichiers non voulus et déjà téléchargées
  265.                     Unwanted = CheckUnwanted(FileName)
  266.                     History = CheckHistory(FileName)
  267.                     if Unwanted + History != 0:
  268.                         if Unwanted != 0:
  269.                             Message = "Vidéo non voulue."
  270.                             if Debug: PrintInfos(); LogInfos(LogFile)
  271.                         elif History != 0:
  272.                             Message = "Vidéo déjà téléchargée."
  273.                             if Debug: PrintInfos(); LogInfos(LogFile)
  274.  
  275.                     # Nommage simple du fichier en cours
  276.                     else:
  277.                         basename, extension = os.path.splitext(FileName)
  278.                         words = basename.split('_')
  279.                         if Debug: PrintInfos()
  280.                         if len(words) <= 1:
  281.                             FileName = "N/A"
  282.                             FileURL = "N/A"
  283.                             Message = "Nom de fichier indeterminable."
  284.                             if Debug: PrintInfos(); LogInfos(LogFile)
  285.                         else:
  286.                             date = words[ShowList[x][1]]
  287.                             date = "20" + date[:2] + "." + date[2:4] + "." + date[-2:]
  288.                             FileSimpleName = date + "_" + Quality + extension
  289.                             if not os.path.isdir(DownloadsDir + "/" + ShowName):
  290.                                 os.makedirs(DownloadsDir + "/" + ShowName)
  291.                             TargetFile = DownloadsDir + "/" + ShowName + "/" + FileSimpleName
  292.                             if Debug: PrintInfos()
  293.  
  294.                             # Téléchargement via flvstreamer si le protocole utilisé dans l'URL est RTMP
  295.                             if FileURL.find("rtmp") != -1:
  296.                                 Message = "Téléchargement via flvstreamer."
  297.                                 params=['flvstreamer', '-r', FileURL]
  298.                                 target_ = open(TargetFile, 'w')
  299.                                 if Debug: PrintInfos()
  300.                                 r = Execute(params, target_)
  301.                                 #r = 0
  302.                                 target_.close()
  303.  
  304.                             # Téléchargement direct dans les autres cas
  305.                             else:
  306.                                 Message = "Téléchargement direct."
  307.                                 if Debug: PrintInfos()
  308.                                 try:
  309.                                     urllib.urlretrieve(FileURL, TargetFile)
  310.                                     r=0
  311.                                 except Exception:
  312.                                     r=1
  313.  
  314.                             # Ajout dans l'historique s'il n'y a pas eu d'erreur
  315.                             if r == 0:
  316.                                 Message += '\n' + "Téléchargement terminé, ajout dans l'historique."
  317.                                 if Debug: PrintInfos(); LogInfos(LogFile)
  318.                                 AddHistory(FileName)
  319.  
  320.                             # Suppression du fichier s'il y a eu une erreur
  321.                             else:
  322.                                 if os.path.exists(TargetFile):
  323.                                     os.remove(TargetFile)
  324.                                 Message += '\n' + "ERREUR : PROBLÈME DE TÉLÉCHARGEMENT."
  325.                                 if Debug: PrintInfos(); LogInfos(LogFile)
  326.  
  327.     #time.sleep(1)
  328.     # Classement alphabétique du fichier d'historique
  329.     SortFile(HistoryFile)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement