code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
import os.path
import time
import threading
from PyQt4 import QtGui, QtCore
from GUI.Qt.MyQTableWidget import MyQTableWidget
from GUI.Qt.MyQPushButton import MyQPushButton
from GUI.ConvertQString import *
from API import API
from GUI.Signaux import Signaux
from PluginManager import PluginManager
from Preferences import Preferences
from GUI.PreferencesDialog import PreferencesDialog
from GUI.PreferencePluginDialog import PreferencePluginDialog
from Downloader import Downloader
from GUI.AProposDialog import AProposDialog
from Fichier import Fichier
from Historique import Historique
from GUI.FenetreAttenteProgressDialog import FenetreAttenteProgressDialog
from GUI.UpdateManagerDialog import UpdateManagerDialog
##########
# Classe #
##########
## Fenetre principale de l'application
class MainWindow( QtGui.QMainWindow ):
## Constructeur
# Le constructeur va creer la fenetre principale en y ajoutant tous les widgets necessaires au programme
def __init__( self ):
# Appel au constructeur de la classe mere
QtGui.QMainWindow.__init__( self )
###########
# Fenetre #
###########
###
# Reglages de la fenetre principale
###
# Nom de la fenetre
self.setWindowTitle( "TVDownloader" )
# Mise en place de son icone
self.setWindowIcon( QtGui.QIcon( "ico/TVDownloader.png" ) )
###
# Mise en place des widgets dans la fenetre
###
# Widget central qui contiendra tout
self.centralWidget = QtGui.QWidget( self )
#
# Barre du haut
#
# Layout horizontal qui contiendra les listes deroulantes
self.horizontalLayoutBarreHaut = QtGui.QHBoxLayout()
# Liste deroulante pour choisir le site (plugin)
self.comboBoxSite = QtGui.QComboBox( self.centralWidget )
self.horizontalLayoutBarreHaut.addWidget( self.comboBoxSite )
# Liste deroulante pour choisir une chaine du site courant
self.comboBoxChaine = QtGui.QComboBox( self.centralWidget)
self.horizontalLayoutBarreHaut.addWidget( self.comboBoxChaine )
# Liste deroulante pour choisir une emission de la chaine courante
self.comboBoxEmission = QtGui.QComboBox( self.centralWidget )
self.horizontalLayoutBarreHaut.addWidget( self.comboBoxEmission )
#
# Onglets
#
# Gestionnaire onglets
self.tabWidget = QtGui.QTabWidget( self.centralWidget )
# Onglet Fichiers
self.tabFichiers = QtGui.QSplitter( self.centralWidget ) # L'onglet Fichier contient un splitter
self.tabWidget.addTab( self.tabFichiers, u"Choix des fichiers" )
# Onglet Telechargements
self.tabTelechargements = QtGui.QWidget( self.centralWidget )
self.tabWidget.addTab( self.tabTelechargements, u"Téléchargements" )
#
# Liste des fichiers
#
# Layout de grille qui contient le tableau qui liste les fichiers + boutons
self.gridLayoutFichiers = QtGui.QGridLayout( self.tabFichiers )
# Tableau qui contient la liste des fichiers disponibles pour l'emission courante
self.tableWidgetFichier = MyQTableWidget( self.tabFichiers )
# Il a 4 colonnes et 0 ligne (pour l'instant)
self.tableWidgetFichier.setColumnCount( 3 )
self.tableWidgetFichier.setRowCount( 0 )
# On ajoute les titres
self.tableWidgetFichier.setHorizontalHeaderItem( 0,
self.tableWidgetFichier.creerItem( "" ) )
self.tableWidgetFichier.setHorizontalHeaderItem( 1,
self.tableWidgetFichier.creerItem( "Date" ) )
self.tableWidgetFichier.setHorizontalHeaderItem( 2,
self.tableWidgetFichier.creerItem( "Emission" ) )
# On l'ajoute au layout
self.gridLayoutFichiers.addWidget( self.tableWidgetFichier, 0, 1, 6, 1 )
# Icones du tableWidget
self.iconeFichier = QtGui.QIcon( "ico/gtk-file.svg" )
self.iconeAjoute = QtGui.QIcon( "ico/gtk-add.svg" )
self.iconeTelecharge = QtGui.QIcon( "ico/gtk-apply.svg" )
# Bouton pour ajouter tous les fichiers a la liste des telechargements
self.pushButtonToutAjouter = MyQPushButton( self.tabFichiers )
self.pushButtonToutAjouter.setIcon( QtGui.QIcon( "ico/gtk-add.svg" ) )
self.pushButtonToutAjouter.setToolTip( u"Ajouter tous les fichiers à la liste des téléchargements" )
self.gridLayoutFichiers.addWidget( self.pushButtonToutAjouter, 0, 0, 2, 1 )
# Bouton pour rafraichir le plugin courant
self.pushButtonRafraichirPlugin = MyQPushButton( self.tabFichiers )
self.pushButtonRafraichirPlugin.setIcon( QtGui.QIcon( "ico/gtk-refresh.svg" ) )
self.pushButtonRafraichirPlugin.setToolTip( "Rafraichir le plugin" )
self.gridLayoutFichiers.addWidget( self.pushButtonRafraichirPlugin, 2, 0, 2, 1 )
# Bouton pour ouvrir la fenetre des preferences du plugin courant
self.pushButtonPreferencesPlugin = MyQPushButton( self.tabFichiers )
self.pushButtonPreferencesPlugin.setIcon( QtGui.QIcon( "ico/gtk-preferences.svg" ) )
self.pushButtonPreferencesPlugin.setToolTip( u"Ouvrir les préférences du plugin" )
self.gridLayoutFichiers.addWidget( self.pushButtonPreferencesPlugin, 4, 0, 2, 1 )
# On met en place ce layout sur un widget (pour le splitter)
self.widgetFichiers = QtGui.QWidget()
self.widgetFichiers.setLayout( self.gridLayoutFichiers )
#
# Descriptif des fichiers
#
# Layout de grille
self.gridLayoutDescriptif = QtGui.QGridLayout()
# Label pour afficher un logo
self.logoFichierDefaut = QtGui.QPixmap()
self.logoFichierDefaut.load( "img/gtk-dialog-question.svg" )
self.labelLogo = QtGui.QLabel( self.centralWidget )
self.labelLogo.setPixmap( self.logoFichierDefaut.scaled( QtCore.QSize( 150, 150 ), QtCore.Qt.KeepAspectRatio ) )
self.gridLayoutDescriptif.addWidget( self.labelLogo, 0, 0, 1, 1 )
# Zone de texte pour afficher un descriptif
self.plainTextEdit = QtGui.QPlainTextEdit( self.centralWidget )
self.gridLayoutDescriptif.addWidget( self.plainTextEdit, 0, 1, 1, 2 )
# On met en place ce layout sur un widget (pour le splitter)
self.widgetDescriptif = QtGui.QWidget()
self.widgetDescriptif.setLayout( self.gridLayoutDescriptif )
# Onrientation verticale du splitter
self.tabFichiers.setOrientation( QtCore.Qt.Vertical )
# On ajoute les 2 elements au splitter (qui est notre onglet)
self.tabFichiers.addWidget( self.widgetFichiers )
self.tabFichiers.addWidget( self.widgetDescriptif )
#
# Liste des telechargements
#
# Layout de grille qui contient le tableau qui liste les fichiers a telecharger + les boutons pour le controller
self.gridLayoutTelechargement = QtGui.QGridLayout( self.tabTelechargements )
# Tableau qui contient la liste des fichiers a telecharger
self.tableWidgetTelechargement = MyQTableWidget( self.tabTelechargements )
# Il a 5 colonnes et 0 ligne (pour l'instant)
self.tableWidgetTelechargement.setColumnCount( 3 )
self.tableWidgetTelechargement.setRowCount( 0 )
# On ajoute le titre des 5 colonnes
self.tableWidgetTelechargement.setHorizontalHeaderItem( 0,
self.tableWidgetTelechargement.creerItem( "Date" ) )
self.tableWidgetTelechargement.setHorizontalHeaderItem( 1,
self.tableWidgetTelechargement.creerItem( "Emission" ) )
self.tableWidgetTelechargement.setHorizontalHeaderItem( 2,
self.tableWidgetTelechargement.creerItem( "Etat" ) )
# On l'ajoute au layout
self.gridLayoutTelechargement.addWidget( self.tableWidgetTelechargement, 0, 1, 4, 1 )
# Bouton pour monter l'element selectionne tout en haut de la liste
self.pushButtonExtremiteMonter = MyQPushButton( self.tabTelechargements )
self.pushButtonExtremiteMonter.setIcon( QtGui.QIcon( "ico/gtk-jump-to-rtl.svg" ) )
self.pushButtonExtremiteMonter.setToolTip( u"Placer l'élément sélectionné tout en haut" )
self.gridLayoutTelechargement.addWidget( self.pushButtonExtremiteMonter, 0, 0, 1, 1 )
# Bouton pour monter l'element selectionne d'un cran dans la liste
self.pushButtonMonter = MyQPushButton( self.tabTelechargements )
self.pushButtonMonter.setIcon( QtGui.QIcon( "ico/gtk-go-up.svg" ) )
self.pushButtonMonter.setToolTip( u"Monter l'élément sélectionné" )
self.gridLayoutTelechargement.addWidget( self.pushButtonMonter, 1, 0, 1, 1 )
# Bouton pour descendre l'element selectionne d'un cran dans la liste
self.pushButtonDescendre = MyQPushButton( self.tabTelechargements )
self.pushButtonDescendre.setIcon( QtGui.QIcon( "ico/gtk-go-down.svg" ) )
self.pushButtonDescendre.setToolTip( u"Descendre l'élément selectionné" )
self.gridLayoutTelechargement.addWidget( self.pushButtonDescendre, 2, 0, 1, 1 )
# Bouton pour descendre l'element selectionne tout en bas de la liste
self.pushButtonExtremiteDescendre = MyQPushButton( self.tabTelechargements )
self.pushButtonExtremiteDescendre.setIcon( QtGui.QIcon( "ico/gtk-jump-to-ltr.svg" ) )
self.pushButtonExtremiteDescendre.setToolTip( u"Placer l'élément sélectionné tout en bas" )
self.gridLayoutTelechargement.addWidget( self.pushButtonExtremiteDescendre, 3, 0, 1, 1 )
# Bouton pour supprimer tous les elements de la liste
self.pushButtonToutSupprimer = MyQPushButton( self.tabTelechargements )
self.pushButtonToutSupprimer.setIcon( QtGui.QIcon( "ico/gtk-cancel.svg" ) )
self.pushButtonToutSupprimer.setToolTip( u"Supprimer tous les téléchargements" )
self.gridLayoutTelechargement.addWidget( self.pushButtonToutSupprimer, 0, 2, 1, 1 )
# Bouton pour supprimer de la liste les telechargements termines
self.pushButtonNettoyer = MyQPushButton( self.tabTelechargements )
self.pushButtonNettoyer.setIcon( QtGui.QIcon( "ico/gtk-delete-full.svg" ) )
self.pushButtonNettoyer.setToolTip( u"Supprimer les téléchargement terminés" )
self.gridLayoutTelechargement.addWidget( self.pushButtonNettoyer, 1, 2, 1, 1 )
# Bouton pour ouvrir le dossier des telechargements
self.pushButtonOuvrirDossierTelechargement = MyQPushButton( self.tabTelechargements )
self.pushButtonOuvrirDossierTelechargement.setIcon( QtGui.QIcon( "ico/gtk-folder.svg" ) )
self.pushButtonOuvrirDossierTelechargement.setToolTip( u"Ouvrir le dossier des téléchargements" )
self.gridLayoutTelechargement.addWidget( self.pushButtonOuvrirDossierTelechargement, 2, 2, 1, 1 )
#
# Barre progression de telechargement d'un fichier
#
self.progressBarTelechargementFichier = QtGui.QProgressBar( self.centralWidget )
self.progressBarTelechargementFichier.setProperty( "value", 0 )
#
# Barre de progression de telechargement des fichiers
#
self.progressBarTelechargement = QtGui.QProgressBar( self.centralWidget )
self.progressBarTelechargement.setProperty( "value", 0 )
#
# Boutons du bas pour gerer ajouter/supprimer/lancer telechargements
#
# Layout horizontal qui contiendra les boutons
self.horizontalLayoutBarreBas = QtGui.QHBoxLayout()
# Bouton pour lancer les telechargements
self.pushButtonLancer = QtGui.QPushButton( QtGui.QIcon( "ico/gtk-media-play-ltr.svg" ), u"Lancer téléchargement", self.centralWidget )
self.horizontalLayoutBarreBas.addWidget( self.pushButtonLancer )
# Bouton pour stopper les telechargements
self.pushButtonStop = QtGui.QPushButton( QtGui.QIcon( "ico/gtk-media-stop.svg" ), u"Stopper le téléchargement", self.centralWidget )
self.pushButtonStop.setEnabled( False )
self.horizontalLayoutBarreBas.addWidget( self.pushButtonStop )
###
# Positionnement des differents widgets/layouts sur le layout de grille
###
# Layout de grille dans lequel on va placer nos widgets/layouts
self.gridLayout = QtGui.QGridLayout( self.centralWidget )
# On ajoute la barre du haut
self.gridLayout.addLayout( self.horizontalLayoutBarreHaut, 0, 0, 1, 3 )
# On ajoute le gestionnaire d'onglets
self.gridLayout.addWidget( self.tabWidget, 1, 0, 1, 3 )
# On ajoute la barre de progression de telechargement d'un fichier
self.gridLayout.addWidget( self.progressBarTelechargementFichier, 2, 0, 1, 3 )
# On ajoute la barre de progression de telechargement des fichiers
self.gridLayout.addWidget( self.progressBarTelechargement, 3, 0, 1, 3 )
# On ajoute les boutons ajouter/supprimer/lancer
self.gridLayout.addLayout( self.horizontalLayoutBarreBas, 4, 0, 1, 3 )
###
# Mise en place le central widget dans la fenetre
###
self.setCentralWidget( self.centralWidget )
###
# Mise en place du menu
###
# Menu barre
self.menubar = QtGui.QMenuBar( self )
self.menubar.setGeometry( QtCore.QRect( 0, 0, 480, 25 ) )
# Menu Fichier
self.menuFichier = QtGui.QMenu( "&Fichier", self.menubar )
self.menubar.addAction( self.menuFichier.menuAction() )
# Action Fichier -> Quitter
self.actionQuitter = QtGui.QAction( QtGui.QIcon( "ico/gtk-quit.svg" ), "&Quitter", self )
self.actionQuitter.setIconVisibleInMenu( True )
self.menuFichier.addAction( self.actionQuitter )
# Menu Edition
self.menuEdition = QtGui.QMenu( "&Edition", self.menubar )
self.menubar.addAction( self.menuEdition.menuAction() )
# Action Edition -> Mise a jour
self.actionMAJ = QtGui.QAction( QtGui.QIcon( "ico/gtk-refresh.svg" ), u"&Mise à jour des plugins", self )
self.actionMAJ.setIconVisibleInMenu( True )
self.menuEdition.addAction( self.actionMAJ )
# Action Edition -> Preferences
self.actionPreferences = QtGui.QAction( QtGui.QIcon( "ico/gtk-preferences.svg" ), u"&Préférences", self )
self.actionPreferences.setIconVisibleInMenu( True )
self.menuEdition.addAction( self.actionPreferences )
# Menu Aide
self.menuAide = QtGui.QMenu( "&Aide", self.menubar )
self.menubar.addAction( self.menuAide.menuAction() )
# Action Aide -> A propos
self.actionAPropos = QtGui.QAction( QtGui.QIcon( "ico/gtk-about.svg" ), u"À p&ropos", self )
self.actionAPropos.setIconVisibleInMenu( True )
self.menuAide.addAction( self.actionAPropos )
# Ajout du menu a l'interface
self.setMenuBar( self.menubar )
###
# Signaux provenants de l'interface
###
QtCore.QObject.connect( self.tableWidgetFichier,
QtCore.SIGNAL( "cellClicked(int,int)" ),
self.afficherInformationsFichier )
QtCore.QObject.connect( self.tableWidgetFichier,
QtCore.SIGNAL( "cellDoubleClicked(int,int)" ),
self.gererTelechargement )
QtCore.QObject.connect( self.pushButtonToutAjouter,
QtCore.SIGNAL( "clicked()" ),
self.ajouterTousLesFichiers )
QtCore.QObject.connect( self.pushButtonRafraichirPlugin,
QtCore.SIGNAL( "clicked()" ),
self.rafraichirPlugin )
QtCore.QObject.connect( self.tableWidgetTelechargement,
QtCore.SIGNAL( "cellDoubleClicked(int,int)" ),
self.supprimerTelechargement )
QtCore.QObject.connect( self.pushButtonExtremiteMonter,
QtCore.SIGNAL( "clicked()" ),
lambda versLeHaut = True, extremite = True : self.tableWidgetTelechargement.deplacerLigne( versLeHaut, extremite ) )
QtCore.QObject.connect( self.pushButtonMonter,
QtCore.SIGNAL( "clicked()" ),
lambda versLeHaut = True, extremite = False : self.tableWidgetTelechargement.deplacerLigne( versLeHaut, extremite ) )
QtCore.QObject.connect( self.pushButtonDescendre,
QtCore.SIGNAL( "clicked()" ),
lambda versLeHaut = False, extremite = False : self.tableWidgetTelechargement.deplacerLigne( versLeHaut, extremite ) )
QtCore.QObject.connect( self.pushButtonExtremiteDescendre,
QtCore.SIGNAL( "clicked()" ),
lambda versLeHaut = False, extremite = True : self.tableWidgetTelechargement.deplacerLigne( versLeHaut, extremite ) )
QtCore.QObject.connect( self.pushButtonToutSupprimer,
QtCore.SIGNAL( "clicked()" ),
self.supprimerTousLesTelechargements )
QtCore.QObject.connect( self.pushButtonNettoyer,
QtCore.SIGNAL( "clicked()" ),
self.nettoyer )
QtCore.QObject.connect( self.pushButtonLancer,
QtCore.SIGNAL( "clicked()" ),
self.lancerTelechargement )
QtCore.QObject.connect( self.pushButtonStop,
QtCore.SIGNAL( "clicked()" ),
self.stopperTelechargement )
QtCore.QObject.connect( self.actionQuitter,
QtCore.SIGNAL( "triggered()" ),
self.close )
################################################
# Instanciations + initialisation de variables #
################################################
# Fenetre About
self.aProposDialog = None
# Fenetre des preferences du logiciel
self.preferencesDialog = None
# Fenetre de mise a jour des plugins
self.updateManagerDialog = None
# Nom plugin courant
self.nomPluginCourant = ""
# Liste des fichiers
self.listeFichiers = []
# Liste des fichiers a telecharger
self.listeFichiersATelecharger = []
# Cache des images descriptive
# Clef : urlImage Valeur : image (binaire)
self.cacheImage = {}
# On intancie le lanceur de signaux
self.signaux = Signaux()
# On instancie le gestionnaire de preferences
self.preferences = Preferences()
# On instancie le gestionnaire de preferences des plugins
self.preferencesPluginDialog = PreferencePluginDialog( self )
# On instancie le gestionnaire de download
self.downloader = Downloader( self.signaux )
# On recupere l'instance de API
self.api = API.getInstance()
# On instancie le gestionnaire d'historique
self.historique = Historique()
# On instancie la fenetre d'attente
self.fenetreAttenteProgressDialog = FenetreAttenteProgressDialog( self )
# On instancie le gest
#
# Fenetre de confirmation pour quitter le logiciel
#
self.quitterMessageBox = QtGui.QMessageBox( self )
self.quitterMessageBox.setWindowTitle( "Fermeture de TVDownloader" )
self.quitterMessageBox.setText( u"Voulez-vous réellement quitter TVDownloader ?" )
self.quitterMessageBox.setInformativeText( u"Votre liste de téléchargement sera perdue" )
self.quitterMessageBox.addButton( "Oui", QtGui.QMessageBox.AcceptRole )
self.quitterMessageBox.addButton( "Non", QtGui.QMessageBox.RejectRole )
############################################################
# On connecte les signaux des instances precedements crees #
############################################################
QtCore.QObject.connect( self.pushButtonOuvrirDossierTelechargement,
QtCore.SIGNAL( "clicked()" ),
self.ouvrirRepertoireTelechargement )
QtCore.QObject.connect( self.comboBoxSite,
QtCore.SIGNAL( "activated(QString)" ),
self.listerChaines )
QtCore.QObject.connect( self.comboBoxChaine,
QtCore.SIGNAL( "activated(QString)" ),
self.listerEmissions )
QtCore.QObject.connect( self.comboBoxEmission,
QtCore.SIGNAL( "activated(QString)" ),
self.listerFichiers )
QtCore.QObject.connect( self.pushButtonPreferencesPlugin,
QtCore.SIGNAL( "clicked()" ),
self.ouvrirPreferencesPlugin )
QtCore.QObject.connect( self.actionPreferences,
QtCore.SIGNAL( "triggered()" ),
self.ouvrirPreferencesLogiciel )
QtCore.QObject.connect( self.actionMAJ,
QtCore.SIGNAL( "triggered()" ),
self.ouvrirFenetreMiseAJour )
QtCore.QObject.connect( self.actionAPropos,
QtCore.SIGNAL( "triggered()" ),
self.ouvrirFenetreAPropos )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ) , self.fenetreAttenteProgressDialog.ouvrirFenetreAttente )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "finActualisation()" ) , self.fenetreAttenteProgressDialog.fermerFenetreAttente )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "actualiserListesDeroulantes()" ) , self.actualiserListesDeroulantes )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "listeChaines(PyQt_PyObject)" ) , self.ajouterChaines )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "listeEmissions(PyQt_PyObject)" ) , self.ajouterEmissions )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "listeFichiers(PyQt_PyObject)" ) , self.ajouterFichiers )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "nouvelleImage(PyQt_PyObject)" ) , self.mettreEnPlaceImage )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "debutTelechargement(int)" ) , self.debutTelechargement )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "finTelechargement(int)" ) , self.finTelechargement )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "finDesTelechargements()" ) , self.activerDesactiverInterface )
QtCore.QObject.connect( self.signaux, QtCore.SIGNAL( "pourcentageFichier(int)" ) , self.progressBarTelechargementFichier.setValue )
#########
# Début #
#########
# La fenetre prend la dimension qu'elle avait a sa fermeture
taille = self.preferences.getPreference( "tailleFenetre" )
self.resize( taille[ 0 ], taille[ 1 ] )
# Si aucun plugin n'est active, on ouvre la fenetre des preferences
if( len( self.preferences.getPreference( "pluginsActifs" ) ) == 0 ):
self.ouvrirPreferencesLogiciel()
# On actualise tous les plugins
self.rafraichirTousLesPlugins()
## Methode qui execute les actions necessaires avant de quitter le programme
def actionsAvantQuitter( self ):
# On sauvegarde les options des plugins
self.api.fermeture()
# On sauvegarde la taille de la fenetre
taille = self.size()
self.preferences.setPreference( "tailleFenetre", [ taille.width(), taille.height() ] )
# On sauvegarde les options du logiciel
self.preferences.sauvegarderConfiguration()
# On sauvegarde l'historique
self.historique.sauverHistorique()
# On stoppe les telechargements
self.stopperTelechargement()
#########################################
# Surcharge des methodes de QMainWindow #
#########################################
## Surcharge de la methode appelee lors de la fermeture de la fenetre
# Ne doit pas etre appele explicitement
# @param evenement Evenement qui a provoque la fermeture
def closeEvent( self, evenement ):
# On affiche une fenetre pour demander la fermeture si des fichiers sont dans la liste de telechargement
if( self.tableWidgetTelechargement.rowCount() > 0 ):
# On affiche une fenetre qui demande si on veut quitter
retour = self.quitterMessageBox.exec_()
# Si on veut quitter
if( retour == 0 ):
# On execute les actions necessaires
self.actionsAvantQuitter()
# On accept la fermeture
evenement.accept()
else:
# On refuse la fermeture
evenement.ignore()
else: # S'il n'y a pas de fichier
# On execute les actions necessaires
self.actionsAvantQuitter()
# On accept la fermeture
evenement.accept()
##############################################
# Methodes pour remplir les menus deroulants #
##############################################
## Methode qui actualise les listes deroulantes
def actualiserListesDeroulantes( self ):
# On lance juste l'ajout des sites en se basant sur les plugins actifs
self.ajouterSites( self.preferences.getPreference( "pluginsActifs" ) )
## Methode qui lance le listage des chaines
# @param site Nom du plugin/site pour lequel on va lister les chaines
def listerChaines( self, site ):
def threadListerChaines( self, nomPlugin ):
self.signaux.signal( "debutActualisation", nomPlugin )
listeChaines = self.api.getPluginListeChaines( nomPlugin )
self.signaux.signal( "listeChaines", listeChaines )
self.signaux.signal( "finActualisation" )
if( site != "" ):
self.nomPluginCourant = qstringToString( site )
threading.Thread( target = threadListerChaines, args = ( self, self.nomPluginCourant ) ).start()
# On active (ou pas) le bouton de preference du plugin
self.pushButtonPreferencesPlugin.setEnabled( self.api.getPluginListeOptions( self.nomPluginCourant ) != [] )
## Methode qui lance le listage des emissions
# @param chaine Nom de la chaine pour laquelle on va lister les emissions
def listerEmissions( self, chaine ):
def threadListerEmissions( self, nomPlugin, chaine ):
self.signaux.signal( "debutActualisation", nomPlugin )
listeEmissions = self.api.getPluginListeEmissions( nomPlugin, chaine )
self.signaux.signal( "listeEmissions", listeEmissions )
self.signaux.signal( "finActualisation" )
if( chaine != "" ):
threading.Thread( target = threadListerEmissions, args = ( self, self.nomPluginCourant, qstringToString( chaine ) ) ).start()
## Methode qui lance le listage des fichiers
# @param emission Nom de l'emission pour laquelle on va lister les fichiers
def listerFichiers( self, emission ):
def threadListerFichiers( self, nomPlugin, emission ):
self.signaux.signal( "debutActualisation", nomPlugin )
listeFichiers = self.api.getPluginListeFichiers( nomPlugin, emission )
self.signaux.signal( "listeFichiers", listeFichiers )
self.signaux.signal( "finActualisation" )
if( emission != "" ):
threading.Thread( target = threadListerFichiers, args = ( self, self.nomPluginCourant, qstringToString( emission ) ) ).start()
## Methode qui met en place une liste de sites sur l'interface
# @param listeSites Liste des sites a mettre en place
def ajouterSites( self, listeSites ):
# On efface la liste des sites
self.comboBoxSite.clear()
# On met en place les sites
for site in listeSites:
self.comboBoxSite.addItem( stringToQstring( site ) )
# On selectionne par defaut celui choisis dans les preference
index = self.comboBoxSite.findText( stringToQstring( self.preferences.getPreference( "pluginParDefaut" ) ) )
if( index != -1 ):
self.comboBoxSite.setCurrentIndex( index )
# On lance l'ajout des chaines
self.listerChaines( self.comboBoxSite.currentText() )
## Methode qui met en place une liste de chaines sur l'interface
# @param listeChaines Liste des chaines a mettre en place
def ajouterChaines( self, listeChaines ):
# On trie la liste des chaines
listeChaines.sort()
# On efface la liste des chaines
self.comboBoxChaine.clear()
# On efface la liste des emissions
self.comboBoxEmission.clear()
# On efface la liste des fichiers
self.tableWidgetFichier.toutSupprimer()
# On met en place les chaines
for chaine in listeChaines:
self.comboBoxChaine.addItem( stringToQstring( chaine ) )
# Si on a juste une seule chaine
if( self.comboBoxChaine.count() == 1 ):
# On lance l'ajout des emissions
self.listerEmissions( self.comboBoxChaine.currentText() )
else:
# On ne selectionne pas de chaine
self.comboBoxChaine.setCurrentIndex( -1 )
## Methode qui met en place une liste d'emissions sur l'interface
# @param listeEmissions Liste des emissions a mettre en place
def ajouterEmissions( self, listeEmissions ):
# On trie la liste des emissions
listeEmissions.sort()
# On efface la liste des emissions
self.comboBoxEmission.clear()
# On efface la liste des fichiers
self.tableWidgetFichier.toutSupprimer()
# On met en place la liste des emissions
for emission in listeEmissions:
self.comboBoxEmission.addItem( stringToQstring( emission ) )
# Si on a juste une seule emission
if( self.comboBoxEmission.count() == 1 ):
# On lance l'ajout des fichiers
self.listerFichiers( self.comboBoxEmission.currentText() )
else:
# On ne selectionne pas d'emission
self.comboBoxEmission.setCurrentIndex( -1 )
###############################################
# Methodes pour remplir la liste des fichiers #
###############################################
## Methode pour ajouter des fichiers a l'interface
# @param listeFichiers Liste des fichiers a ajouter
def ajouterFichiers( self, listeFichiers ):
self.listeFichiers = listeFichiers
# On efface la liste des fichiers
self.tableWidgetFichier.toutSupprimer()
# On commence au depart
ligneCourante = 0
# On met en place chacun des fichiers
for fichier in listeFichiers:
# On ajoute une ligne
self.tableWidgetFichier.insertRow( ligneCourante )
# On ajoute les informations au tableWidgetFichier
liste = []
liste.append( self.tableWidgetFichier.creerItem( "" ) )
liste.append( self.tableWidgetFichier.creerItem( getattr( fichier, "date" ) ) )
liste.append( self.tableWidgetFichier.creerItem( getattr( fichier, "nom" ) ) )
self.tableWidgetFichier.setLigne( ligneCourante, liste )
# On met en place l'icone qui va bien
self.gererIconeListeFichier( fichier )
ligneCourante += 1
# On adapte la taille des colonnes
self.tableWidgetFichier.adapterColonnes()
## Methode qui rafraichit le plugin courant
def rafraichirPlugin( self ):
def threadRafraichirPlugin( self, nomPlugin ):
self.signaux.signal( "debutActualisation", nomPlugin )
self.api.pluginRafraichir( nomPlugin )
self.signaux.signal( "finActualisation" )
threading.Thread( target = threadRafraichirPlugin, args = ( self, self.nomPluginCourant ) ).start()
## Methode qui met en place l'image de la description d'un fichier
# @param image Image a mettre en place (binaire)
def mettreEnPlaceImage( self, image ):
logoFichier = QtGui.QPixmap()
logoFichier.loadFromData( image )
self.labelLogo.setPixmap( logoFichier.scaled( QtCore.QSize( 150, 150 ), QtCore.Qt.KeepAspectRatio ) )
## Methode qui affiche des informations sur le fichier selectionne
def afficherInformationsFichier( self, ligne, colonne ):
def threadRecupererImage( self, urlImage ):
image = self.api.getPage( urlImage )
self.cacheImage[ urlImage ] = image
self.signaux.signal( "nouvelleImage", image )
fichier = self.listeFichiers[ ligne ]
# On recupere le lien de l'image et le texte descriptif
urlImage = getattr( fichier, "urlImage" )
texteDescriptif = getattr( fichier, "descriptif" )
self.plainTextEdit.clear()
# Si on a un texte descriptif, on l'affiche
if( texteDescriptif != "" ):
self.plainTextEdit.appendPlainText( stringToQstring( texteDescriptif ) )
else:
self.plainTextEdit.appendPlainText( u"Aucune information disponible" )
# Si on n'a pas d'image
if( urlImage == "" ):
# On met en place celle par defaut
self.logoFichier = self.logoFichierDefaut
self.labelLogo.setPixmap( self.logoFichier.scaled( QtCore.QSize( 150, 150 ), QtCore.Qt.KeepAspectRatio ) )
else: # Si on en a une
# Si elle est dans le cache des images
if( self.cacheImage.has_key( urlImage ) ):
self.mettreEnPlaceImage( self.cacheImage[ urlImage ] )
else: # Sinon
# On lance le thread pour la recuperer
threading.Thread( target = threadRecupererImage, args = ( self, urlImage ) ).start()
## Methode qui gere l'icone d'un fichier dans la liste des telechargements
# Il y a 3 icones possible :
# - C'est un fichier
# - C'est un fichier present dans l'historique (donc deja telecharge)
# - C'est un fichier present dans la liste des telechargements
# @param fichier Fichier a gerer
def gererIconeListeFichier( self, fichier ):
if( fichier in self.listeFichiers ):
ligneFichier = self.listeFichiers.index( fichier )
# On cherche quel icone mettre en place
if( fichier in self.listeFichiersATelecharger ):
icone = self.iconeAjoute
elif( self.historique.comparerHistorique( fichier ) ):
icone = self.iconeTelecharge
else:
icone = self.iconeFichier
# On met en place l'icone
self.tableWidgetFichier.item( ligneFichier, 0 ).setIcon( icone )
######################################################
# Methodes pour remplir la liste des telechargements #
######################################################
## Methode qui gere la liste des telechargements
# @param ligne Numero de la ligne (dans la liste des fichiers) de l'element a ajouter
# @param colonne Numero de colonne (inutile, juste pour le slot)
def gererTelechargement( self, ligne, colonne = 0 ):
fichier = self.listeFichiers[ ligne ]
# Si le fichier est deja dans la liste des telechargements
if( fichier in self.listeFichiersATelecharger ):
ligneTelechargement = self.listeFichiersATelecharger.index( fichier )
self.supprimerTelechargement( ligneTelechargement )
else: # S'il n'y est pas, on l'ajoute
self.listeFichiersATelecharger.append( fichier )
numLigne = self.tableWidgetTelechargement.rowCount()
# On insere une nouvelle ligne dans la liste des telechargements
self.tableWidgetTelechargement.insertRow( numLigne )
# On y insere les elements qui vont biens
self.tableWidgetTelechargement.setLigne( numLigne,
[ self.tableWidgetTelechargement.creerItem( getattr( fichier, "date" ) ),
self.tableWidgetTelechargement.creerItem( getattr( fichier, "nom" ) ),
self.tableWidgetTelechargement.creerItem( u"En attente de téléchargement" )
]
)
# On adapte la taille des colonnes
self.tableWidgetTelechargement.adapterColonnes()
# On modifie l'icone dans la liste des fichiers
self.gererIconeListeFichier( fichier )
## Methode qui ajoute tous les fichiers a la liste des telechargements
def ajouterTousLesFichiers( self ):
for i in range( self.tableWidgetFichier.rowCount() ):
self.gererTelechargement( i )
## Methode qui supprime un fichier de la liste des telechargements
# @param ligne Numero de la ligne a supprimer
# @param colonne Numero de colonne (inutile, juste pour le slot)
def supprimerTelechargement( self, ligne, colonne = 0 ):
fichier = self.listeFichiersATelecharger[ ligne ]
# On supprime l'element du tableWidgetTelechargement
self.tableWidgetTelechargement.removeRow( ligne )
# On supprime l'element de la liste des fichiers a telecharger
self.listeFichiersATelecharger.remove( fichier )
# On modifie l'icone dans la liste des fichiers
self.gererIconeListeFichier( fichier )
## Methode qui supprime tous les telechargement de la liste des telechargements
def supprimerTousLesTelechargements( self ):
for i in range( self.tableWidgetTelechargement.rowCount() -1, -1, -1 ):
self.supprimerTelechargement( i )
## Methode qui lance le telechargement des fichiers
def lancerTelechargement( self ):
# On liste les emissions a telecharger avec leurs numeros de ligne
listeFichiers = []
for i in range( self.tableWidgetTelechargement.rowCount() ): # Pour chaque ligne
fichier = self.listeFichiersATelecharger[ i ]
listeFichiers.append( [ i,
getattr( fichier, "lien" ),
getattr( fichier, "nomFichierSortie" ) ] )
nbATelecharger = len( listeFichiers )
# Si on a des elements a charger
if( nbATelecharger > 0 ):
# On met en place la valeur du progressBar
self.progressBarTelechargement.setMaximum( nbATelecharger )
self.progressBarTelechargement.setValue( 0 )
# On lance le telechargement
threading.Thread( target = self.downloader.lancerTelechargement, args = ( listeFichiers, ) ).start()
# On active/desactive ce qui va bien sur l'interface
self.activerDesactiverInterface( True )
## Methode qui stoppe le telechargement
def stopperTelechargement( self ):
# On stoppe le telechargement
self.downloader.stopperTelechargement()
############################################
# Methodes pour ouvrir les autres fenetres #
############################################
#
# Fenetre About
#
## Methode pour afficher la fenetre About
def ouvrirFenetreAPropos( self ):
if( self.aProposDialog == None ):
self.aProposDialog = AProposDialog()
self.aProposDialog.show()
#
# Fenetre de preference du logiciel
#
## Methode pour ouvrir les preferences du logiciel
def ouvrirPreferencesLogiciel( self ):
if( self.preferencesDialog == None ):
self.preferencesDialog = PreferencesDialog( self, self.signaux )
self.preferencesDialog.afficher()
#
# Fenetre de mise a jour des plugins
#
## Methode pour ouvrir la fenetre de mise a jour des plugins
def ouvrirFenetreMiseAJour( self ):
if( self.updateManagerDialog == None ):
self.updateManagerDialog = UpdateManagerDialog( self )
self.updateManagerDialog.afficher()
#
# Fenetre de preference des plugins
#
## Methode pour ouvrir les preferences du plugin courant
def ouvrirPreferencesPlugin( self ):
listeOptions = self.api.getPluginListeOptions( self.nomPluginCourant )
self.preferencesPluginDialog.ouvrirDialogPreferences( self.nomPluginCourant, listeOptions )
#########
# Slots #
#########
## Methode qui ouvre le repertoire de telechargement
def ouvrirRepertoireTelechargement( self ):
QtGui.QDesktopServices.openUrl( QtCore.QUrl.fromLocalFile( self.preferences.getPreference( "repertoireTelechargement" ) ) )
## Methode qui rafraichit le plugin courant
def rafraichirPlugin( self ):
def threadRafraichirPlugin( self, nomPlugin ):
self.signaux.signal( "debutActualisation", nomPlugin )
self.api.pluginRafraichir( nomPlugin )
self.signaux.signal( "finActualisation" )
threading.Thread( target = threadRafraichirPlugin, args = ( self, self.nomPluginCourant ) ).start()
## Methode qui rafraichit tous les plugins
# A utiliser au lancement du programme
def rafraichirTousLesPlugins( self ):
def threadRafraichirTousLesPlugins( self ):
self.signaux.signal( "debutActualisation", "TVDownloader" )
self.api.pluginRafraichirAuto()
self.signaux.signal( "finActualisation" )
self.signaux.signal( "actualiserListesDeroulantes" )
threading.Thread( target = threadRafraichirTousLesPlugins, args = ( self, ) ).start()
## Slot qui active/desactive des elements de l'interface pendant un telechargement
# @param telechargementEnCours Indique si on telecharge ou pas
def activerDesactiverInterface( self, telechargementEnCours = False ):
# Les boutons
self.pushButtonLancer.setEnabled( not telechargementEnCours )
self.pushButtonStop.setEnabled( telechargementEnCours )
self.pushButtonExtremiteMonter.setEnabled( not telechargementEnCours )
self.pushButtonMonter.setEnabled( not telechargementEnCours )
self.pushButtonDescendre.setEnabled( not telechargementEnCours )
self.pushButtonExtremiteDescendre.setEnabled( not telechargementEnCours )
self.pushButtonToutSupprimer.setEnabled( not telechargementEnCours )
self.pushButtonNettoyer.setEnabled( not telechargementEnCours )
# Le table widget
self.tableWidgetTelechargement.setEnabled( not telechargementEnCours )
## Slot appele lors ce qu'un le debut d'un telechargement commence
# @param numero Position dans la liste des telechargement du telechargement qui commence
def debutTelechargement( self, numero ):
self.tableWidgetTelechargement.item( numero, 2 ).setText( stringToQstring( u"Téléchargement en cours..." ) )
self.tableWidgetTelechargement.adapterColonnes()
self.progressBarTelechargementFichier.setValue( 0 )
## Slot appele lorsqu'un telechargement se finit
# @param numero Position dans la liste des telechargement du telechargement qui se finit
def finTelechargement( self, numero ):
fichier = self.listeFichiersATelecharger[ numero ]
# On ajoute le fichier a l'historique
self.historique.ajouterHistorique( fichier )
# On modifie l'icone dans la liste des fichiers
self.gererIconeListeFichier( fichier )
# On modifie l'interface
self.tableWidgetTelechargement.item( numero, 2 ).setText( stringToQstring( u"Fini !" ) )
self.progressBarTelechargement.setValue( self.progressBarTelechargement.value() + 1 )
self.tableWidgetTelechargement.adapterColonnes()
self.progressBarTelechargementFichier.setValue( 100 )
## Slot qui nettoie la liste des telechargements de tous les telechargements finis
def nettoyer( self ):
for i in range( self.tableWidgetTelechargement.rowCount() - 1, -1, -1 ): # [ nbLignes - 1, nbLignes - 2, ..., 1, 0 ]
if( self.tableWidgetTelechargement.item( i, 2 ).text() == u"Fini !" ): # Si c'est telecharge
self.supprimerTelechargement( i )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os.path
import pickle
import logging
logger = logging.getLogger( __name__ )
##########
# Classe #
##########
class Option():
def __init__(self, type, nom, description, valeur, choix=None):
self.type = type
self.nom= nom
self.description= description
self.valeur = valeur
if type == Option.TYPE_CHOIX_MULTIPLE and not isinstance(valeur, list):
raise Exception("La valeur doit être une liste pour le type spécifié.")
if choix != None:
if self.type != Option.TYPE_CHOIX_MULTIPLE and self.type != Option.TYPE_CHOIX_UNIQUE:
raise Exception("Liste des choix inutile pour le type d'option spécifié.")
elif not isinstance(choix, list):
raise Exception("La liste des choix doit être une liste.")
self.choix = choix
elif self.type == Option.TYPE_CHOIX_MULTIPLE or self.type == Option.TYPE_CHOIX_UNIQUE:
raise Exception("Liste des choix obligatoire pour le type d'option spécifié.")
#/*******************
# * CONSTANTES *
# *******************/
TYPE_TEXTE = "texte"
TYPE_BOULEEN = "bouleen"
TYPE_CHOIX_MULTIPLE = "choixmult"
TYPE_CHOIX_UNIQUE = "choixuniq"
def setValeur(self, valeur):
if self.type == Option.TYPE_TEXTE and not isinstance(valeur, str):
raise Exception("La valeur d'une option texte doit être une chaîne.")
elif self.type == Option.TYPE_BOULEEN and not isinstance(valeur, bool):
raise Exception("La valeur d'une option bouléen doit être un bouléen.")
elif self.type == Option.TYPE_CHOIX_MULTIPLE and not isinstance(valeur, list):
raise Exception("La valeur d'une option choix multiple doit être une liste.")
elif self.type == Option.TYPE_CHOIX_UNIQUE and not isinstance(valeur, str):
raise Exception("La valeur d'une option choix unique doit être une liste.")
self.valeur = valeur
def setChoix(self, choix):
if self.type == Option.TYPE_TEXTE:
raise Exception("Pas de choix pour les options de type texte.")
elif self.type == Option.TYPE_BOULEEN:
raise Exception("Pas de choix pour les options de type booléen.")
elif not isinstance(choix, list):
raise Exception("La liste des choix doit être une liste.")
self.choix = choix
def getType(self):
return self.type
def getNom(self):
return self.nom
def getDescription(self):
return self.description
def getValeur(self):
return self.valeur
def getChoix(self):
if self.type == Option.TYPE_TEXTE:
raise Exception("Pas de choix pour les options de type texte.")
elif self.type == Option.TYPE_BOULEEN:
raise Exception("Pas de choix pour les options de type booléen.")
return self.choix
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
# N.B. :
# La gestion des plugins s'appuie sur cet article :
# http://lucumr.pocoo.org/2006/7/3/python-plugin-system
###########
# Modules #
###########
import sys
import os.path
from string import find
import logging
logger = logging.getLogger( __name__ )
from API import API
from Plugin import Plugin
#############
# Variables #
#############
# Repertoires qui contiennent des plugins
repPlugins = [ os.path.expanduser( "~" ) + "/.tvdownloader/plugins",
"plugins" ]
##########
# Classe #
##########
## Classe qui gere les plugins
class PluginManager( object ):
# Instance de la classe (singleton)
instance = None
## Surcharge de la methode de construction standard (pour mettre en place le singleton)
def __new__( self, *args, **kwargs ):
if( self.instance is None ):
self.instance = super( PluginManager, self ).__new__( self )
return self.instance
## Constructeur
def __init__( self ):
self.api = API.getInstance()
self.listePlugins = {} # Clef : nomPlugin ; Valeur : classe du plugin (!= de son instance)
self.listeInstances = {} # Clef : nomPlugin ; Valeur : son instance
# On importe tous les plugins
for rep in repPlugins:
# On verifie que le repertoire des plugins existe bien
if( not os.path.isdir( rep ) ):
logger.warn( "le repertoire %s des plugins n'existe pas..." %( rep ) )
# On l'ajoute au path si necessaire
if not( rep in sys.path ):
sys.path.insert( 0, rep )
# On importe les plugins
self.importPlugins( rep )
# On liste les plugins
self.listerPlugins()
## Methode qui importe les plugins
# @param rep Repertoire dans lequel se trouvent les plugins a importer
def importPlugins( self, rep ):
for fichier in os.listdir( rep ):
# Tous les fichiers py autre que __init__.py sont des plugins a ajouter au programme
if( fichier [ -3 : ] == ".py" and fichier.find( "__init__.py" ) == -1 ):
# On suppose que c'est la derniere version du plugin
derniereVersion = True
# Pour les autres repertoires de plugins
for autreRep in ( set( repPlugins ).difference( set( [ rep ] ) ) ):
# Si le fichier existe dans l'autre repertoire
if( fichier in os.listdir( autreRep ) ):
# Si la version du plugin de l'autre repertoire est plus recente
if( os.stat( "%s/%s" %( autreRep, fichier ) ).st_mtime > os.stat( "%s/%s" %( rep, fichier ) ).st_mtime ):
derniereVersion = False
break # On arrete le parcourt des repertoires
# Si ce n'est pas la derniere version
if( not derniereVersion ):
continue # On passe au suivant
try :
__import__( fichier.replace( ".py", "" ), None, None, [ '' ] )
except ImportError :
logger.error( "impossible d'importer le fichier %s" %( fichier ) )
continue
## Methode qui retourne la liste des sites/plugins
# N.B. : On doit d'abord importer les plugins
# @return La liste des noms des plugins
def getListeSites( self ):
return self.listePlugins.keys()
## Methode qui liste les plugins
def listerPlugins( self ):
for plugin in Plugin.__subclasses__(): # Pour tous les plugins
# On l'instancie
inst = plugin()
# On recupere son nom
nom = getattr( inst, "nom" )
# On ajoute le plugin a la liste des plugins existants
self.listePlugins[ nom ] = plugin
## Methode pour activer un plugin
# @param nomPlugin Nom du plugin a activer
def activerPlugin( self, nomPlugin ):
if( self.listePlugins.has_key( nomPlugin ) ):
instance = self.listePlugins[ nomPlugin ]()
# On l'ajoute a la liste des instances
self.listeInstances[ nomPlugin ] = instance
# On l'ajoute a l'API
self.api.ajouterPlugin( instance )
self.api.activerPlugin( nomPlugin )
else:
logger.warn( "impossible d'activer le plugin %s" %( nomPlugin ) )
## Methode qui desactive un plugin
# @param nomPlugin Nom du plugin a desactiver
def desactiverPlugin( self, nomPlugin ):
# On le desactive dand l'API
self.api.desactiverPlugin( nomPlugin )
# On le supprime de la liste des instances
if( self.listeInstances.has_key( nomPlugin ) ):
self.listeInstances.pop( nomPlugin )
else:
logger.warn( "impossible de desactiver le plugin %s" %( nomPlugin ) )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
###########
# Modules #
###########
import unittest
import sys
if not( "../" in sys.path ):
sys.path.insert( 0, "../" )
from Historique import Historique
from Fichier import Fichier
##########
# Classe #
##########
## Classe qui gere les tests de la classe Historique
class HistoriqueTests( unittest.TestCase ):
## Initialisation
def setUp( self ):
self.historique = Historique()
## Fin
def tearDown( self ):
pass
def testSingleton( self ):
"""Test si le pattern singleton est bien en place"""
self.assertEqual( id( self.historique ), id( Historique() ) )
def testMauvaisType( self ):
"""Test si l'historique renvoit bien faux si on lui demande s'il contient une variable qui n'est pas un fichier"""
variable = "jeSuisUnString"
self.assertEqual( self.historique.comparerHistorique( variable ), False )
def testPresenceElement( self ):
"""Test si l'historique est capable de retrouver un element"""
element = Fichier( "Napoleon", "1804", "Notre Dame", "Sacre Napoleon" )
# On ajoute l'element a l'historique
self.historique.ajouterHistorique( element )
# On verifie si l'element y est present
self.assertEqual( self.historique.comparerHistorique( element ), True )
if __name__ == "__main__" :
unittest.main() | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
###########
# Modules #
###########
import unittest
from PreferencesTests import PreferencesTests
from HistoriqueTests import HistoriqueTests
#########
# Debut #
#########
unittest.main() | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
from API import API
from Navigateur import Navigateur
from time import time, sleep
urlsDifferentHost = ["http://www.google.fr/",
"http://fr.yahoo.com/",
"http://www.bing.com/",
"http://www.ubuntu-fr.org/",
"http://www.canalplus.fr/",
"http://www.m6.fr/",
"http://www.w9.fr/",
"http://www.tf1.fr/",
"http://www.france2.fr/",
"http://www.france3.fr/",
"http://www.france4.fr/",
"http://www.france5.fr/",
"http://www.franceo.fr/"]
urlsSameHost = ["http://www.canalplus.fr/c-divertissement/pid1784-les-guignols-de-l-info.html?",
"http://www.canalplus.fr/c-divertissement/pid1778-pepites-sur-le-net.html?",
"http://www.canalplus.fr/c-divertissement/pid3279-reperages-l-emission.html?",
"http://www.canalplus.fr/c-divertissement/pid2053-stephane-guillon.html?",
"http://www.canalplus.fr/c-divertissement/pid3591-une-minute-avant.html?",
"http://www.canalplus.fr/c-divertissement/pid3403-c-air-guitar-2010.html",
"http://www.canalplus.fr/c-divertissement/pid3299-album-de-la-semaine.html?",
"http://www.canalplus.fr/c-divertissement/pid3301-concert-prive.html?",
"http://www.canalplus.fr/c-divertissement/pid3535-c-la-musicale.html",
"http://www.canalplus.fr/c-divertissement/pid3308-la-radio-de-moustic.html?",
"http://www.canalplus.fr/c-divertissement/pid3298-coming-next.html?",
"http://www.canalplus.fr/c-divertissement/pid3522-u2-en-concert.html?",
"http://www.canalplus.fr/c-divertissement/pid3303-le-live-du-grand-journal.html?"]
navigateur = Navigateur()
api = API.getInstance()
def testeMechanize(urls):
reponses = {}
for url in urls:
reponses[ url ] = navigateur.getPage( url )
def testeGetPage(urls):
reponses = {}
for url in urls:
reponses[ url ] = api.getPage( url )
def testeGetPages(urls):
reponses = api.getPages(urls)
#~ t = time()
print "Url sur différent serveur:"
sleep(1)
t = time()
testeMechanize(urlsDifferentHost)
print "Mechanize:",time()-t,"secondes"
#~
sleep(1)
t = time()
testeGetPage(urlsDifferentHost)
print "getPage:",time()-t,"secondes"
#~
sleep(1)
t = time()
testeGetPages(urlsDifferentHost)
print "getPages:",time()-t,"secondes"
#~ print "\nUrl sur un même serveur:"
#~ sleep(1)
#~ t = time()
#~ testeMechanize(urlsSameHost)
#~ print "Mechanize:",time()-t,"secondes"
#~
#~ sleep(1)
#~ t = time()
#~ testeGetPage(urlsSameHost)
#~ print "getPage:",time()-t,"secondes"
#~
#~ sleep(1)
#~ t = time()
#~ testeGetPages(urlsSameHost)
#~ print "getPages:",time()-t,"secondes"
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
###########
# Modules #
###########
import unittest
import sys
if not( "../" in sys.path ):
sys.path.insert( 0, "../" )
from Preferences import Preferences
##########
# Classe #
##########
## Classe qui gere les tests de la classe Preferences
class PreferencesTests( unittest.TestCase ):
## Initialisation
def setUp( self ):
self.preferences = Preferences()
## Fin
def tearDown( self ):
pass
def testSingleton( self ):
"""Test si le pattern singleton est bien en place"""
self.assertEqual( id( self.preferences ), id( Preferences() ) )
def testSauvegarde( self ):
"""Test si les preferences sont bien sauvegardees"""
listePreferences = getattr( self.preferences, "preferences" )
nomPreference = listePreferences.keys()[ 0 ]
nouvelleValeur = "ValeurDeTest"
# On met en place la preference
self.preferences.setPreference( nomPreference, nouvelleValeur )
# On verifie qu'elle est bien en place
self.assertEqual( nouvelleValeur, self.preferences.getPreference( nomPreference ) )
if __name__ == "__main__" :
unittest.main() | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import sys
import os.path
import atexit
from lib.dialog import Dialog
from API import API
from Downloader import Downloader
from Historique import Historique
from Preferences import Preferences
##########
# Classe #
##########
## Classe qui gere la version CLI de TVDownloader
class CLIDialog():
## Constructeur
def __init__( self ):
# On cree l'instance de la classe dialog
self.dialog = Dialog()
self.dialog.setBackgroundTitle( "TVDownloader" )
# On recupere l'instance de API
self.api = API.getInstance()
# On instancie le gestionnaire de download
self.downloader = Downloader()
# On instancie le gestionnaire d'historique
self.historique = Historique()
# On instancie le gestionnaire de preferences
self.preferences = Preferences()
# Liste des telechargements
self.listeTelechargements = []
# Quand le programme se termine, on execute la fonction actionsAvantQuitter
atexit.register( self.actionsAvantQuitter )
# On commence
self.bouclePrincipale()
## Debut
def bouclePrincipale( self ):
choix = ( 1, "" )
while( choix != ( 0, "Quitter" ) ):
# On affiche le menu principal
choix = self.dialog.menu( text = "Menu Principal" ,
choices = [ [ "Commencer", "Afficher la liste des plugins" ],
[ "Téléchargements", "Gérer les téléchargements" ],
[ "Préférences", "Modifier les préférences" ],
[ "Quitter", "Quitter TVDownloader" ],
]
)
# On lance la methode qui va bien
if( choix == ( 0, "Commencer" ) ):
self.utilisationPlugins()
elif( choix == ( 0, "Téléchargements" ) ):
self.utlisationTelechargements()
elif( choix == ( 0, "Préférences" ) ):
pass
elif( choix == ( 0, "Quitter" ) ):
# Rien a faire, atexit gere cela
pass
## Methode pour selectionner les fichiers a telecharger avec les plugins
def utilisationPlugins( self ):
# Liste des plugins actifs
listePlugins = []
for nomPlugin in self.preferences.getPreference( "pluginsActifs" ):
listePlugins.append( [ nomPlugin, "" ] )
choixPlugin = ( 0, "" )
while( choixPlugin[ 0 ] != 1 ):
# On affiche le menu de selection de plugins
choixPlugin = self.dialog.menu( text = "De quelle plugin voulez-vous voir les chaines ?",
choices = listePlugins
)
if( choixPlugin[ 0 ] != 1 ):
# Liste des chaines du plugin
listeChaines = []
for nomChaine in self.api.getPluginListeChaines( choixPlugin[ 1 ] ):
listeChaines.append( [ nomChaine, "" ] )
choixChaine = ( 0, "" )
while( choixChaine[ 0 ] != 1 ):
# On affiche le menu de selection de la chaine
choixChaine = self.dialog.menu( text = "De quelle chaine voulez-vous voir les emissions ?",
choices = listeChaines
)
if( choixChaine[ 0 ] != 1 ):
# Liste des emissions de la chaine
listeEmissions = []
for nomEmission in self.api.getPluginListeEmissions( choixPlugin[ 1 ], choixChaine[ 1 ] ):
listeEmissions.append( [ nomEmission, "" ] )
choixEmission = ( 0, "" )
while( choixEmission[ 0 ] != 1 ):
# On affiche le menu de selection de l'emission
choixEmission = self.dialog.menu( text = "De quelle emission voulez-vous voir les fichiers ?",
choices = listeEmissions
)
if( choixEmission[ 0 ] != 1 ):
listeFichiersAAfficher = []
listeFichiersCoches = []
listeFichiersPrecedementCoches = []
listeFichiersAPI = self.api.getPluginListeFichiers( choixPlugin[ 1 ], choixEmission[ 1 ] )
i = 0
for fichier in listeFichiersAPI:
texteAAfficher = "(%s) %s" %( getattr( fichier, "date" ), getattr( fichier, "nom" ) )
if( fichier in self.listeTelechargements ):
listeFichiersPrecedementCoches.append( fichier )
cochee = 1
else:
cochee = 0
listeFichiersAAfficher.append( [ str( i ), texteAAfficher, cochee ] )
i+=1
choixFichiers = ( 0, [] )
while( choixFichiers[ 0 ] != 1 ):
choixFichiers = self.dialog.checklist( text = "Quels fichiers voulez-vous ajouter à la liste des téléchargements ?",
choices = listeFichiersAAfficher
)
if( choixFichiers[ 0 ] != 1 ):
for numeroFichier in choixFichiers[ 1 ]:
fichier = listeFichiersAPI[ int( numeroFichier ) ]
listeFichiersCoches.append( fichier )
for fichier in listeFichiersCoches:
if not ( fichier in listeFichiersPrecedementCoches ):
self.listeTelechargements.append( fichier )
for fichier in listeFichiersPrecedementCoches:
if not ( fichier in listeFichiersCoches ):
self.listeTelechargements.remove( fichier )
# On retourne au menu precedent
choixFichiers = ( 1, "" )
## Methode qui gere le gestionnaire de telechargement
def utlisationTelechargements( self ):
choix = ( 0, "" )
while( choix[ 0 ] != 1 ):
# On affiche le menu principal
choix = self.dialog.menu( text = "Gestionnaire de téléchargement" ,
choices = [ [ "Consulter", "Consulter la liste" ],
[ "Lancer", "Lancer les téléchargements" ]
]
)
# On lance la methode qui va bien
if( choix == ( 0, "Consulter" ) ):
if( len( self.listeTelechargements ) > 0 ):
texte = ""
for fichier in self.listeTelechargements:
texte += "(%s) %s\n" %( getattr( fichier, "date" ), getattr( fichier, "nom" ) )
else:
texte = "La liste des téléchargements est vide"
# On affiche la liste des fichiers a telecharger
self.dialog.msgbox( text = texte )
elif( choix == ( 0, "Lancer" ) ):
if( len( self.listeTelechargements ) > 0 ):
liste = []
for fichier in self.listeTelechargements:
lien = getattr( fichier , "lien" )
nomFichierSortie = getattr( fichier , "nomFichierSortie" )
if( nomFichierSortie == "" ): # Si le nom du fichier de sortie n'existe pas, on l'extrait de l'URL
nomFichierSortie = os.path.basename( lien )
liste.append( [ 0, lien, nomFichierSortie ] )
# On lance le telechargement
self.downloader.lancerTelechargement( liste )
self.dialog.msgbox( text = "Fin du téléchargement des fichiers" )
del self.listeTelechargements[ : ]
else:
self.dialog.msgbox( text = "Aucun fichier à télécharger" )
## Methode qui execute les actions necessaires avant de quitter le programme
def actionsAvantQuitter( self ):
print "Fermeture"
# On sauvegarde les options des plugins
self.api.fermeture()
# On sauvegarde l'historique
self.historique.sauverHistorique()
# On sauvegarde les options du logiciel
self.preferences.sauvegarderConfiguration() | Python |
# dialog.py --- A python interface to the Linux "dialog" utility
# Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov
# Copyright (C) 2002, 2003, 2004 Florent Rougon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Python interface to dialog-like programs.
This module provides a Python interface to dialog-like programs such
as `dialog', `Xdialog' and `whiptail'.
It provides a Dialog class that retains some parameters such as the
program name and path as well as the values to pass as DIALOG*
environment variables to the chosen program.
For a quick start, you should look at the demo.py file that comes
with pythondialog. It demonstrates a simple use of each widget
offered by the Dialog class.
See the Dialog class documentation for general usage information,
list of available widgets and ways to pass options to dialog.
Notable exceptions
------------------
Here is the hierarchy of notable exceptions raised by this module:
error
ExecutableNotFound
BadPythonDialogUsage
PythonDialogSystemError
PythonDialogIOError
PythonDialogOSError
PythonDialogErrorBeforeExecInChildProcess
PythonDialogReModuleError
UnexpectedDialogOutput
DialogTerminatedBySignal
DialogError
UnableToCreateTemporaryDirectory
PythonDialogBug
ProbablyPythonBug
As you can see, every exception `exc' among them verifies:
issubclass(exc, error)
so if you don't need fine-grained error handling, simply catch
`error' (which will probably be accessible as dialog.error from your
program) and you should be safe.
"""
from __future__ import nested_scopes
import sys, os, tempfile, random, string, re, types
# Python < 2.3 compatibility
if sys.hexversion < 0x02030000:
# The assignments would work with Python >= 2.3 but then, pydoc
# shows them in the DATA section of the module...
True = 0 == 0
False = 0 == 1
# Exceptions raised by this module
#
# When adding, suppressing, renaming exceptions or changing their
# hierarchy, don't forget to update the module's docstring.
class error(Exception):
"""Base class for exceptions in pythondialog."""
def __init__(self, message=None):
self.message = message
def __str__(self):
return "<%s: %s>" % (self.__class__.__name__, self.message)
def complete_message(self):
if self.message:
return "%s: %s" % (self.ExceptionShortDescription, self.message)
else:
return "%s" % self.ExceptionShortDescription
ExceptionShortDescription = "pythondialog generic exception"
# For backward-compatibility
#
# Note: this exception was not documented (only the specific ones were), so
# the backward-compatibility binding could be removed relatively easily.
PythonDialogException = error
class ExecutableNotFound(error):
"""Exception raised when the dialog executable can't be found."""
ExceptionShortDescription = "Executable not found"
class PythonDialogBug(error):
"""Exception raised when pythondialog finds a bug in his own code."""
ExceptionShortDescription = "Bug in pythondialog"
# Yeah, the "Probably" makes it look a bit ugly, but:
# - this is more accurate
# - this avoids a potential clash with an eventual PythonBug built-in
# exception in the Python interpreter...
class ProbablyPythonBug(error):
"""Exception raised when pythondialog behaves in a way that seems to \
indicate a Python bug."""
ExceptionShortDescription = "Bug in python, probably"
class BadPythonDialogUsage(error):
"""Exception raised when pythondialog is used in an incorrect way."""
ExceptionShortDescription = "Invalid use of pythondialog"
class PythonDialogSystemError(error):
"""Exception raised when pythondialog cannot perform a "system \
operation" (e.g., a system call) that should work in "normal" situations.
This is a convenience exception: PythonDialogIOError, PythonDialogOSError
and PythonDialogErrorBeforeExecInChildProcess all derive from this
exception. As a consequence, watching for PythonDialogSystemError instead
of the aformentioned exceptions is enough if you don't need precise
details about these kinds of errors.
Don't confuse this exception with Python's builtin SystemError
exception.
"""
ExceptionShortDescription = "System error"
class PythonDialogIOError(PythonDialogSystemError):
"""Exception raised when pythondialog catches an IOError exception that \
should be passed to the calling program."""
ExceptionShortDescription = "IO error"
class PythonDialogOSError(PythonDialogSystemError):
"""Exception raised when pythondialog catches an OSError exception that \
should be passed to the calling program."""
ExceptionShortDescription = "OS error"
class PythonDialogErrorBeforeExecInChildProcess(PythonDialogSystemError):
"""Exception raised when an exception is caught in a child process \
before the exec sytem call (included).
This can happen in uncomfortable situations like when the system is out
of memory or when the maximum number of open file descriptors has been
reached. This can also happen if the dialog-like program was removed
(or if it is has been made non-executable) between the time we found it
with _find_in_path and the time the exec system call attempted to
execute it...
"""
ExceptionShortDescription = "Error in a child process before the exec " \
"system call"
class PythonDialogReModuleError(PythonDialogSystemError):
"""Exception raised when pythondialog catches a re.error exception."""
ExceptionShortDescription = "'re' module error"
class UnexpectedDialogOutput(error):
"""Exception raised when the dialog-like program returns something not \
expected by pythondialog."""
ExceptionShortDescription = "Unexpected dialog output"
class DialogTerminatedBySignal(error):
"""Exception raised when the dialog-like program is terminated by a \
signal."""
ExceptionShortDescription = "dialog-like terminated by a signal"
class DialogError(error):
"""Exception raised when the dialog-like program exits with the \
code indicating an error."""
ExceptionShortDescription = "dialog-like terminated due to an error"
class UnableToCreateTemporaryDirectory(error):
"""Exception raised when we cannot create a temporary directory."""
ExceptionShortDescription = "unable to create a temporary directory"
# Values accepted for checklists
try:
_on_rec = re.compile(r"on", re.IGNORECASE)
_off_rec = re.compile(r"off", re.IGNORECASE)
_calendar_date_rec = re.compile(
r"(?P<day>\d\d)/(?P<month>\d\d)/(?P<year>\d\d\d\d)$")
_timebox_time_rec = re.compile(
r"(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)$")
except re.error, v:
raise PythonDialogReModuleError(v)
# This dictionary allows us to write the dialog common options in a Pythonic
# way (e.g. dialog_instance.checklist(args, ..., title="Foo", no_shadow=1)).
#
# Options such as --separate-output should obviously not be set by the user
# since they affect the parsing of dialog's output:
_common_args_syntax = {
"aspect": lambda ratio: ("--aspect", str(ratio)),
"backtitle": lambda backtitle: ("--backtitle", backtitle),
"beep": lambda enable: _simple_option("--beep", enable),
"beep_after": lambda enable: _simple_option("--beep-after", enable),
# Warning: order = y, x!
"begin": lambda coords: ("--begin", str(coords[0]), str(coords[1])),
"cancel": lambda string: ("--cancel-label", string),
"clear": lambda enable: _simple_option("--clear", enable),
"cr_wrap": lambda enable: _simple_option("--cr-wrap", enable),
"create_rc": lambda file: ("--create-rc", file),
"defaultno": lambda enable: _simple_option("--defaultno", enable),
"default_item": lambda string: ("--default-item", string),
"help": lambda enable: _simple_option("--help", enable),
"help_button": lambda enable: _simple_option("--help-button", enable),
"help_label": lambda string: ("--help-label", string),
"ignore": lambda enable: _simple_option("--ignore", enable),
"item_help": lambda enable: _simple_option("--item-help", enable),
"max_input": lambda size: ("--max-input", str(size)),
"no_kill": lambda enable: _simple_option("--no-kill", enable),
"no_cancel": lambda enable: _simple_option("--no-cancel", enable),
"nocancel": lambda enable: _simple_option("--nocancel", enable),
"no_shadow": lambda enable: _simple_option("--no-shadow", enable),
"ok_label": lambda string: ("--ok-label", string),
"print_maxsize": lambda enable: _simple_option("--print-maxsize",
enable),
"print_size": lambda enable: _simple_option("--print-size", enable),
"print_version": lambda enable: _simple_option("--print-version",
enable),
"separate_output": lambda enable: _simple_option("--separate-output",
enable),
"separate_widget": lambda string: ("--separate-widget", string),
"shadow": lambda enable: _simple_option("--shadow", enable),
"size_err": lambda enable: _simple_option("--size-err", enable),
"sleep": lambda secs: ("--sleep", str(secs)),
"stderr": lambda enable: _simple_option("--stderr", enable),
"stdout": lambda enable: _simple_option("--stdout", enable),
"tab_correct": lambda enable: _simple_option("--tab-correct", enable),
"tab_len": lambda n: ("--tab-len", str(n)),
"timeout": lambda secs: ("--timeout", str(secs)),
"title": lambda title: ("--title", title),
"trim": lambda enable: _simple_option("--trim", enable),
"version": lambda enable: _simple_option("--version", enable)}
def _simple_option(option, enable):
"""Turn on or off the simplest dialog Common Options."""
if enable:
return (option,)
else:
# This will not add any argument to the command line
return ()
def _find_in_path(prog_name):
"""Search an executable in the PATH.
If PATH is not defined, the default path ":/bin:/usr/bin" is
used.
Return a path to the file or None if no readable and executable
file is found.
Notable exception: PythonDialogOSError
"""
try:
# Note that the leading empty component in the default value for PATH
# could lead to the returned path not being absolute.
PATH = os.getenv("PATH", ":/bin:/usr/bin") # see the execvp(3) man page
for dir in string.split(PATH, ":"):
file_path = os.path.join(dir, prog_name)
if os.path.isfile(file_path) \
and os.access(file_path, os.R_OK | os.X_OK):
return file_path
return None
except os.error, v:
raise PythonDialogOSError(v.strerror)
def _path_to_executable(f):
"""Find a path to an executable.
Find a path to an executable, using the same rules as the POSIX
exec*p functions (see execvp(3) for instance).
If `f' contains a '/', it is assumed to be a path and is simply
checked for read and write permissions; otherwise, it is looked
for according to the contents of the PATH environment variable,
which defaults to ":/bin:/usr/bin" if unset.
The returned path is not necessarily absolute.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
"""
try:
if '/' in f:
if os.path.isfile(f) and \
os.access(f, os.R_OK | os.X_OK):
res = f
else:
raise ExecutableNotFound("%s cannot be read and executed" % f)
else:
res = _find_in_path(f)
if res is None:
raise ExecutableNotFound(
"can't find the executable for the dialog-like "
"program")
except os.error, v:
raise PythonDialogOSError(v.strerror)
return res
def _to_onoff(val):
"""Convert boolean expressions to "on" or "off"
This function converts every non-zero integer as well as "on",
"ON", "On" and "oN" to "on" and converts 0, "off", "OFF", etc. to
"off".
Notable exceptions:
PythonDialogReModuleError
BadPythonDialogUsage
"""
if type(val) == types.IntType:
if val:
return "on"
else:
return "off"
elif type(val) == types.StringType:
try:
if _on_rec.match(val):
return "on"
elif _off_rec.match(val):
return "off"
except re.error, v:
raise PythonDialogReModuleError(v)
else:
raise BadPythonDialogUsage("invalid boolean value: %s" % val)
def _compute_common_args(dict):
"""Compute the list of arguments for dialog common options.
Compute a list of the command-line arguments to pass to dialog
from a keyword arguments dictionary for options listed as "common
options" in the manual page for dialog. These are the options
that are not tied to a particular widget.
This allows to specify these options in a pythonic way, such as:
d.checklist(<usual arguments for a checklist>,
title="...",
backtitle="...")
instead of having to pass them with strings like "--title foo" or
"--backtitle bar".
Notable exceptions: None
"""
args = []
for key in dict.keys():
args.extend(_common_args_syntax[key](dict[key]))
return args
def _create_temporary_directory():
"""Create a temporary directory (securely).
Return the directory path.
Notable exceptions:
- UnableToCreateTemporaryDirectory
- PythonDialogOSError
- exceptions raised by the tempfile module (which are
unfortunately not mentioned in its documentation, at
least in Python 2.3.3...)
"""
find_temporary_nb_attempts = 5
for i in range(find_temporary_nb_attempts):
try:
# Using something >= 2**31 causes an error in Python 2.2...
tmp_dir = os.path.join(tempfile.gettempdir(),
"%s-%u" \
% ("pythondialog",
random.randint(0, 2**30-1)))
except os.error, v:
raise PythonDialogOSError(v.strerror)
try:
os.mkdir(tmp_dir, 0700)
except os.error:
continue
else:
break
else:
raise UnableToCreateTemporaryDirectory(
"somebody may be trying to attack us")
return tmp_dir
# DIALOG_OK, DIALOG_CANCEL, etc. are environment variables controlling
# dialog's exit status in the corresponding situation.
#
# Note:
# - 127 must not be used for any of the DIALOG_* values. It is used
# when a failure occurs in the child process before it exec()s
# dialog (where "before" includes a potential exec() failure).
# - 126 is also used (although in presumably rare situations).
_dialog_exit_status_vars = { "OK": 0,
"CANCEL": 1,
"ESC": 2,
"ERROR": 3,
"EXTRA": 4,
"HELP": 5 }
# Main class of the module
class Dialog:
"""Class providing bindings for dialog-compatible programs.
This class allows you to invoke dialog or a compatible program in
a pythonic way to build quicky and easily simple but nice text
interfaces.
An application typically creates one instance of the Dialog class
and uses it for all its widgets, but it is possible to use
concurrently several instances of this class with different
parameters (such as the background title) if you have the need
for this.
The exit code (exit status) returned by dialog is to be
compared with the DIALOG_OK, DIALOG_CANCEL, DIALOG_ESC,
DIALOG_ERROR, DIALOG_EXTRA and DIALOG_HELP attributes of the
Dialog instance (they are integers).
Note: although this class does all it can to allow the caller to
differentiate between the various reasons that caused a
dialog box to be closed, its backend, dialog 0.9a-20020309a
for my tests, doesn't always return DIALOG_ESC when the
user presses the ESC key, but often returns DIALOG_ERROR
instead. The exit codes returned by the corresponding
Dialog methods are of course just as wrong in these cases.
You've been warned.
Public methods of the Dialog class (mainly widgets)
---------------------------------------------------
The Dialog class has the following methods:
add_persistent_args
calendar
checklist
fselect
gauge_start
gauge_update
gauge_stop
infobox
inputbox
menu
msgbox
passwordbox
radiolist
scrollbox
tailbox
textbox
timebox
yesno
clear (obsolete)
setBackgroundTitle (obsolete)
Passing dialog "Common Options"
-------------------------------
Every widget method has a **kwargs argument allowing you to pass
dialog so-called Common Options (see the dialog(1) manual page)
to dialog for this widget call. For instance, if `d' is a Dialog
instance, you can write:
d.checklist(args, ..., title="A Great Title", no_shadow=1)
The no_shadow option is worth looking at:
1. It is an option that takes no argument as far as dialog is
concerned (unlike the "--title" option, for instance). When
you list it as a keyword argument, the option is really
passed to dialog only if the value you gave it evaluates to
true, e.g. "no_shadow=1" will cause "--no-shadow" to be
passed to dialog whereas "no_shadow=0" will cause this
option not to be passed to dialog at all.
2. It is an option that has a hyphen (-) in its name, which you
must change into an underscore (_) to pass it as a Python
keyword argument. Therefore, "--no-shadow" is passed by
giving a "no_shadow=1" keyword argument to a Dialog method
(the leading two dashes are also consistently removed).
Exceptions
----------
Please refer to the specific methods' docstrings or simply to the
module's docstring for a list of all exceptions that might be
raised by this class' methods.
"""
def __init__(self, dialog="dialog", DIALOGRC=None, compat="dialog",
use_stdout=None):
"""Constructor for Dialog instances.
dialog -- name of (or path to) the dialog-like program to
use; if it contains a '/', it is assumed to be a
path and is used as is; otherwise, it is looked
for according to the contents of the PATH
environment variable, which defaults to
":/bin:/usr/bin" if unset.
DIALOGRC -- string to pass to the dialog-like program as the
DIALOGRC environment variable, or None if no
modification to the environment regarding this
variable should be done in the call to the
dialog-like program
compat -- compatibility mode (see below)
The officially supported dialog-like program in pythondialog
is the well-known dialog program written in C, based on the
ncurses library. It is also known as cdialog and its home
page is currently (2004-03-15) located at:
http://dickey.his.com/dialog/dialog.html
If you want to use a different program such as Xdialog, you
should indicate the executable file name with the `dialog'
argument *and* the compatibility type that you think it
conforms to with the `compat' argument. Currently, `compat'
can be either "dialog" (for dialog; this is the default) or
"Xdialog" (for, well, Xdialog).
The `compat' argument allows me to cope with minor
differences in behaviour between the various programs
implementing the dialog interface (not the text or graphical
interface, I mean the "API"). However, having to support
various APIs simultaneously is a bit ugly and I would really
prefer you to report bugs to the relevant maintainers when
you find incompatibilities with dialog. This is for the
benefit of pretty much everyone that relies on the dialog
interface.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
"""
# DIALOGRC differs from the other DIALOG* variables in that:
# 1. It should be a string if not None
# 2. We may very well want it to be unset
if DIALOGRC is not None:
self.DIALOGRC = DIALOGRC
# After reflexion, I think DIALOG_OK, DIALOG_CANCEL, etc.
# should never have been instance attributes (I cannot see a
# reason why the user would want to change their values or
# even read them), but it is a bit late, now. So, we set them
# based on the (global) _dialog_exit_status_vars.keys.
for var in _dialog_exit_status_vars.keys():
varname = "DIALOG_" + var
setattr(self, varname, _dialog_exit_status_vars[var])
self._dialog_prg = _path_to_executable(dialog)
self.compat = compat
self.dialog_persistent_arglist = []
# Use stderr or stdout?
if self.compat == "Xdialog":
# Default to stdout if Xdialog
self.use_stdout = True
else:
self.use_stdout = False
if use_stdout != None:
# Allow explicit setting
self.use_stdout = use_stdout
if self.use_stdout:
self.add_persistent_args(["--stdout"])
def add_persistent_args(self, arglist):
self.dialog_persistent_arglist.extend(arglist)
# For compatibility with the old dialog...
def setBackgroundTitle(self, text):
"""Set the background title for dialog.
This method is obsolete. Please remove calls to it from your
programs.
"""
self.add_persistent_args(("--backtitle", text))
def _call_program(self, redirect_child_stdin, cmdargs, **kwargs):
"""Do the actual work of invoking the dialog-like program.
Communication with the dialog-like program is performed
through one or two pipes, depending on
`redirect_child_stdin'. There is always one pipe that is
created to allow the parent process to read what dialog
writes on its standard error stream.
If `redirect_child_stdin' is True, an additional pipe is
created whose reading end is connected to dialog's standard
input. This is used by the gauge widget to feed data to
dialog.
Beware when interpreting the return value: the length of the
returned tuple depends on `redirect_child_stdin'.
Notable exception: PythonDialogOSError (if pipe() or close()
system calls fail...)
"""
# We want to define DIALOG_OK, DIALOG_CANCEL, etc. in the
# environment of the child process so that we know (and
# even control) the possible dialog exit statuses.
new_environ = {}
new_environ.update(os.environ)
for var in _dialog_exit_status_vars:
varname = "DIALOG_" + var
new_environ[varname] = str(getattr(self, varname))
if hasattr(self, "DIALOGRC"):
new_environ["DIALOGRC"] = self.DIALOGRC
# Create:
# - a pipe so that the parent process can read dialog's output on
# stdout/stderr
# - a pipe so that the parent process can feed data to dialog's
# stdin (this is needed for the gauge widget) if
# redirect_child_stdin is True
try:
# rfd = File Descriptor for Reading
# wfd = File Descriptor for Writing
(child_rfd, child_wfd) = os.pipe()
if redirect_child_stdin:
(child_stdin_rfd, child_stdin_wfd) = os.pipe()
except os.error, v:
raise PythonDialogOSError(v.strerror)
child_pid = os.fork()
if child_pid == 0:
# We are in the child process. We MUST NOT raise any exception.
try:
# The child process doesn't need these file descriptors
os.close(child_rfd)
if redirect_child_stdin:
os.close(child_stdin_wfd)
# We want:
# - dialog's output on stderr/stdout to go to child_wfd
# - data written to child_stdin_wfd to go to dialog's stdin
# if redirect_child_stdin is True
if self.use_stdout:
os.dup2(child_wfd, 1)
else:
os.dup2(child_wfd, 2)
if redirect_child_stdin:
os.dup2(child_stdin_rfd, 0)
arglist = [self._dialog_prg] + \
self.dialog_persistent_arglist + \
_compute_common_args(kwargs) + \
cmdargs
# Insert here the contents of the DEBUGGING file if you want
# to obtain a handy string of the complete command line with
# arguments quoted for the shell and environment variables
# set.
os.execve(self._dialog_prg, arglist, new_environ)
except:
os._exit(127)
# Should not happen unless there is a bug in Python
os._exit(126)
# We are in the father process.
#
# It is essential to close child_wfd, otherwise we will never
# see EOF while reading on child_rfd and the parent process
# will block forever on the read() call.
# [ after the fork(), the "reference count" of child_wfd from
# the operating system's point of view is 2; after the child exits,
# it is 1 until the father closes it itself; then it is 0 and a read
# on child_rfd encounters EOF once all the remaining data in
# the pipe has been read. ]
try:
os.close(child_wfd)
if redirect_child_stdin:
os.close(child_stdin_rfd)
return (child_pid, child_rfd, child_stdin_wfd)
else:
return (child_pid, child_rfd)
except os.error, v:
raise PythonDialogOSError(v.strerror)
def _wait_for_program_termination(self, child_pid, child_rfd):
"""Wait for a dialog-like process to terminate.
This function waits for the specified process to terminate,
raises the appropriate exceptions in case of abnormal
termination and returns the exit status and standard error
output of the process as a tuple: (exit_code, stderr_string).
`child_rfd' must be the file descriptor for the
reading end of the pipe created by self._call_program()
whose writing end was connected by self._call_program() to
the child process's standard error.
This function reads the process's output on standard error
from `child_rfd' and closes this file descriptor once
this is done.
Notable exceptions:
DialogTerminatedBySignal
DialogError
PythonDialogErrorBeforeExecInChildProcess
PythonDialogIOError
PythonDialogBug
ProbablyPythonBug
"""
exit_info = os.waitpid(child_pid, 0)[1]
if os.WIFEXITED(exit_info):
exit_code = os.WEXITSTATUS(exit_info)
# As we wait()ed for the child process to terminate, there is no
# need to call os.WIFSTOPPED()
elif os.WIFSIGNALED(exit_info):
raise DialogTerminatedBySignal("the dialog-like program was "
"terminated by signal %u" %
os.WTERMSIG(exit_info))
else:
raise PythonDialogBug("please report this bug to the "
"pythondialog maintainers")
if exit_code == self.DIALOG_ERROR:
raise DialogError("the dialog-like program exited with "
"code %d (was passed to it as the DIALOG_ERROR "
"environment variable)" % exit_code)
elif exit_code == 127:
raise PythonDialogErrorBeforeExecInChildProcess(
"perhaps the dialog-like program could not be executed; "
"perhaps the system is out of memory; perhaps the maximum "
"number of open file descriptors has been reached")
elif exit_code == 126:
raise ProbablyPythonBug(
"a child process returned with exit status 126; this might "
"be the exit status of the dialog-like program, for some "
"unknown reason (-> probably a bug in the dialog-like "
"program); otherwise, we have probably found a python bug")
# We might want to check here whether exit_code is really one of
# DIALOG_OK, DIALOG_CANCEL, etc. However, I prefer not doing it
# because it would break pythondialog for no strong reason when new
# exit codes are added to the dialog-like program.
#
# As it is now, if such a thing happens, the program using
# pythondialog may receive an exit_code it doesn't know about. OK, the
# programmer just has to tell the pythondialog maintainer about it and
# can temporarily set the appropriate DIALOG_* environment variable if
# he wants and assign the corresponding value to the Dialog instance's
# DIALOG_FOO attribute from his program. He doesn't even need to use a
# patched pythondialog before he upgrades to a version that knows
# about the new exit codes.
#
# The bad thing that might happen is a new DIALOG_FOO exit code being
# the same by default as one of those we chose for the other exit
# codes already known by pythondialog. But in this situation, the
# check that is being discussed wouldn't help at all.
# Read dialog's output on its stderr
try:
child_output = os.fdopen(child_rfd, "rb").read()
# Now, since the file object has no reference anymore, the
# standard IO stream behind it will be closed, causing the
# end of the the pipe we used to read dialog's output on its
# stderr to be closed (this is important, otherwise invoking
# dialog enough times will eventually exhaust the maximum number
# of open file descriptors).
except IOError, v:
raise PythonDialogIOError(v)
return (exit_code, child_output)
def _perform(self, cmdargs, **kwargs):
"""Perform a complete dialog-like program invocation.
This function invokes the dialog-like program, waits for its
termination and returns its exit status and whatever it wrote
on its standard error stream.
Notable exceptions:
any exception raised by self._call_program() or
self._wait_for_program_termination()
"""
(child_pid, child_rfd) = \
self._call_program(False, *(cmdargs,), **kwargs)
(exit_code, output) = \
self._wait_for_program_termination(child_pid,
child_rfd)
return (exit_code, output)
def _strip_xdialog_newline(self, output):
"""Remove trailing newline (if any), if using Xdialog"""
if self.compat == "Xdialog" and output.endswith("\n"):
output = output[:-1]
return output
# This is for compatibility with the old dialog.py
def _perform_no_options(self, cmd):
"""Call dialog without passing any more options."""
return os.system(self._dialog_prg + ' ' + cmd)
# For compatibility with the old dialog.py
def clear(self):
"""Clear the screen. Equivalent to the dialog --clear option.
This method is obsolete. Please remove calls to it from your
programs.
"""
self._perform_no_options('--clear')
def calendar(self, text, height=6, width=0, day=0, month=0, year=0,
**kwargs):
"""Display a calendar dialog box.
text -- text to display in the box
height -- height of the box (minus the calendar height)
width -- width of the box
day -- inititial day highlighted
month -- inititial month displayed
year -- inititial year selected (0 causes the current date
to be used as the initial date)
A calendar box displays month, day and year in separately
adjustable windows. If the values for day, month or year are
missing or negative, the current date's corresponding values
are used. You can increment or decrement any of those using
the left, up, right and down arrows. Use tab or backtab to
move between windows. If the year is given as zero, the
current date is used as an initial value.
Return a tuple of the form (code, date) where `code' is the
exit status (an integer) of the dialog-like program and
`date' is a list of the form [day, month, year] (where `day',
`month' and `year' are integers corresponding to the date
chosen by the user) if the box was closed with OK, or None if
it was closed with the Cancel button.
Notable exceptions:
- any exception raised by self._perform()
- UnexpectedDialogOutput
- PythonDialogReModuleError
"""
(code, output) = self._perform(
*(["--calendar", text, str(height), str(width), str(day),
str(month), str(year)],),
**kwargs)
if code == self.DIALOG_OK:
try:
mo = _calendar_date_rec.match(output)
except re.error, v:
raise PythonDialogReModuleError(v)
if mo is None:
raise UnexpectedDialogOutput(
"the dialog-like program returned the following "
"unexpected date with the calendar box: %s" % output)
date = map(int, mo.group("day", "month", "year"))
else:
date = None
return (code, date)
def checklist(self, text, height=15, width=54, list_height=7,
choices=[], **kwargs):
"""Display a checklist box.
text -- text to display in the box
height -- height of the box
width -- width of the box
list_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a list of tuples (tag, item, status) where
`status' specifies the initial on/off state of
each entry; can be 0 or 1 (integers, 1 meaning
checked, i.e. "on"), or "on", "off" or any
uppercase variant of these two strings.
Return a tuple of the form (code, [tag, ...]) with the tags
for the entries that were selected by the user. `code' is the
exit status of the dialog-like program.
If the user exits with ESC or CANCEL, the returned tag list
is empty.
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
cmd = ["--checklist", text, str(height), str(width), str(list_height)]
for t in choices:
cmd.extend(((t[0], t[1], _to_onoff(t[2]))))
# The dialog output cannot be parsed reliably (at least in dialog
# 0.9b-20040301) without --separate-output (because double quotes in
# tags are escaped with backslashes, but backslashes are not
# themselves escaped and you have a problem when a tag ends with a
# backslash--the output makes you think you've encountered an embedded
# double-quote).
kwargs["separate_output"] = True
(code, output) = self._perform(*(cmd,), **kwargs)
# Since we used --separate-output, the tags are separated by a newline
# in the output. There is also a final newline after the last tag.
if output:
return (code, string.split(output, '\n')[:-1])
else: # empty selection
return (code, [])
def fselect(self, filepath, height, width, **kwargs):
"""Display a file selection dialog box.
filepath -- initial file path
height -- height of the box
width -- width of the box
The file-selection dialog displays a text-entry window in
which you can type a filename (or directory), and above that
two windows with directory names and filenames.
Here, filepath can be a file path in which case the file and
directory windows will display the contents of the path and
the text-entry window will contain the preselected filename.
Use tab or arrow keys to move between the windows. Within the
directory or filename windows, use the up/down arrow keys to
scroll the current selection. Use the space-bar to copy the
current selection into the text-entry window.
Typing any printable character switches focus to the
text-entry window, entering that character as well as
scrolling the directory and filename windows to the closest
match.
Use a carriage return or the "OK" button to accept the
current value in the text-entry window, or the "Cancel"
button to cancel.
Return a tuple of the form (code, path) where `code' is the
exit status (an integer) of the dialog-like program and
`path' is the path chosen by the user (whose last element may
be a directory or a file).
Notable exceptions:
any exception raised by self._perform()
"""
(code, output) = self._perform(
*(["--fselect", filepath, str(height), str(width)],),
**kwargs)
output = self._strip_xdialog_newline(output)
return (code, output)
def gauge_start(self, text="", height=8, width=54, percent=0, **kwargs):
"""Display gauge box.
text -- text to display in the box
height -- height of the box
width -- width of the box
percent -- initial percentage shown in the meter
A gauge box displays a meter along the bottom of the box. The
meter indicates a percentage.
This function starts the dialog-like program telling it to
display a gauge box with a text in it and an initial
percentage in the meter.
Return value: undefined.
Gauge typical usage
-------------------
Gauge typical usage (assuming that `d' is an instance of the
Dialog class) looks like this:
d.gauge_start()
# do something
d.gauge_update(10) # 10% of the whole task is done
# ...
d.gauge_update(100, "any text here") # work is done
exit_code = d.gauge_stop() # cleanup actions
Notable exceptions:
- any exception raised by self._call_program()
- PythonDialogOSError
"""
(child_pid, child_rfd, child_stdin_wfd) = self._call_program(
True,
*(["--gauge", text, str(height), str(width), str(percent)],),
**kwargs)
try:
self._gauge_process = {
"pid": child_pid,
"stdin": os.fdopen(child_stdin_wfd, "wb"),
"child_rfd": child_rfd
}
except os.error, v:
raise PythonDialogOSError(v.strerror)
def gauge_update(self, percent, text="", update_text=0):
"""Update a running gauge box.
percent -- new percentage to show in the gauge meter
text -- new text to optionally display in the box
update-text -- boolean indicating whether to update the
text in the box
This function updates the percentage shown by the meter of a
running gauge box (meaning `gauge_start' must have been
called previously). If update_text is true (for instance, 1),
the text displayed in the box is also updated.
See the `gauge_start' function's documentation for
information about how to use a gauge.
Return value: undefined.
Notable exception: PythonDialogIOError can be raised if there
is an I/O error while writing to the pipe
used to talk to the dialog-like program.
"""
if update_text:
gauge_data = "%d\nXXX\n%s\nXXX\n" % (percent, text)
else:
gauge_data = "%d\n" % percent
try:
self._gauge_process["stdin"].write(gauge_data)
self._gauge_process["stdin"].flush()
except IOError, v:
raise PythonDialogIOError(v)
# For "compatibility" with the old dialog.py...
gauge_iterate = gauge_update
def gauge_stop(self):
"""Terminate a running gauge.
This function performs the appropriate cleanup actions to
terminate a running gauge (started with `gauge_start').
See the `gauge_start' function's documentation for
information about how to use a gauge.
Return value: undefined.
Notable exceptions:
- any exception raised by
self._wait_for_program_termination()
- PythonDialogIOError can be raised if closing the pipe
used to talk to the dialog-like program fails.
"""
p = self._gauge_process
# Close the pipe that we are using to feed dialog's stdin
try:
p["stdin"].close()
except IOError, v:
raise PythonDialogIOError(v)
exit_code = \
self._wait_for_program_termination(p["pid"],
p["child_rfd"])[0]
return exit_code
def infobox(self, text, height=10, width=30, **kwargs):
"""Display an information dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
An info box is basically a message box. However, in this
case, dialog will exit immediately after displaying the
message to the user. The screen is not cleared when dialog
exits, so that the message will remain on the screen until
the calling shell script clears it later. This is useful
when you want to inform the user that some operations are
carrying on that may require some time to finish.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--infobox", text, str(height), str(width)],),
**kwargs)[0]
def inputbox(self, text, height=10, width=30, init='', **kwargs):
"""Display an input dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
init -- default input string
An input box is useful when you want to ask questions that
require the user to input a string as the answer. If init is
supplied it is used to initialize the input string. When
entering the string, the BACKSPACE key can be used to
correct typing errors. If the input string is longer than
can fit in the dialog box, the input field will be scrolled.
Return a tuple of the form (code, string) where `code' is the
exit status of the dialog-like program and `string' is the
string entered by the user.
Notable exceptions:
any exception raised by self._perform()
"""
(code, tag) = self._perform(
*(["--inputbox", text, str(height), str(width), init],),
**kwargs)
tag = self._strip_xdialog_newline(tag)
return (code, tag)
def menu(self, text, height=15, width=54, menu_height=7, choices=[],
**kwargs):
"""Display a menu dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
menu_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a sequence of (tag, item) or (tag, item, help)
tuples (the meaning of each `tag', `item' and
`help' is explained below)
Overview
--------
As its name suggests, a menu box is a dialog box that can be
used to present a list of choices in the form of a menu for
the user to choose. Choices are displayed in the order given.
Each menu entry consists of a `tag' string and an `item'
string. The tag gives the entry a name to distinguish it from
the other entries in the menu. The item is a short
description of the option that the entry represents.
The user can move between the menu entries by pressing the
UP/DOWN keys, the first letter of the tag as a hot-key, or
the number keys 1-9. There are menu-height entries displayed
in the menu at one time, but the menu will be scrolled if
there are more entries than that.
Providing on-line help facilities
---------------------------------
If this function is called with item_help=1 (keyword
argument), the option --item-help is passed to dialog and the
tuples contained in `choices' must contain 3 elements each :
(tag, item, help). The help string for the highlighted item
is displayed in the bottom line of the screen and updated as
the user highlights other items.
If item_help=0 or if this keyword argument is not passed to
this function, the tuples contained in `choices' must contain
2 elements each : (tag, item).
If this function is called with help_button=1, it must also
be called with item_help=1 (this is a limitation of dialog),
therefore the tuples contained in `choices' must contain 3
elements each as explained in the previous paragraphs. This
will cause a Help button to be added to the right of the
Cancel button (by passing --help-button to dialog).
Return value
------------
Return a tuple of the form (exit_info, string).
`exit_info' is either:
- an integer, being the the exit status of the dialog-like
program
- or the string "help", meaning that help_button=1 was
passed and that the user chose the Help button instead of
OK or Cancel.
The meaning of `string' depends on the value of exit_info:
- if `exit_info' is 0, `string' is the tag chosen by the
user
- if `exit_info' is "help", `string' is the `help' string
from the `choices' argument corresponding to the item
that was highlighted when the user chose the Help button
- otherwise (the user chose Cancel or pressed Esc, or there
was a dialog error), the value of `string' is undefined.
Notable exceptions:
any exception raised by self._perform()
"""
cmd = ["--menu", text, str(height), str(width), str(menu_height)]
for t in choices:
cmd.extend(t)
(code, output) = self._perform(*(cmd,), **kwargs)
output = self._strip_xdialog_newline(output)
if "help_button" in kwargs.keys() and output.startswith("HELP "):
return ("help", output[5:])
else:
return (code, output)
def msgbox(self, text, height=10, width=30, **kwargs):
"""Display a message dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
A message box is very similar to a yes/no box. The only
difference between a message box and a yes/no box is that a
message box has only a single OK button. You can use this
dialog box to display any message you like. After reading
the message, the user can press the ENTER key so that dialog
will exit and the calling program can continue its
operation.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--msgbox", text, str(height), str(width)],),
**kwargs)[0]
def passwordbox(self, text, height=10, width=60, init='', **kwargs):
"""Display an password input dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
init -- default input password
A password box is similar to an input box, except that the
text the user enters is not displayed. This is useful when
prompting for passwords or other sensitive information. Be
aware that if anything is passed in "init", it will be
visible in the system's process table to casual snoopers.
Also, it is very confusing to the user to provide them with a
default password they cannot see. For these reasons, using
"init" is highly discouraged.
Return a tuple of the form (code, password) where `code' is
the exit status of the dialog-like program and `password' is
the password entered by the user.
Notable exceptions:
any exception raised by self._perform()
"""
(code, password) = self._perform(
*(["--passwordbox", text, str(height), str(width), init],),
**kwargs)
password = self._strip_xdialog_newline(password)
return (code, password)
def radiolist(self, text, height=15, width=54, list_height=7,
choices=[], **kwargs):
"""Display a radiolist box.
text -- text to display in the box
height -- height of the box
width -- width of the box
list_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a list of tuples (tag, item, status) where
`status' specifies the initial on/off state
each entry; can be 0 or 1 (integers, 1 meaning
checked, i.e. "on"), or "on", "off" or any
uppercase variant of these two strings.
No more than one entry should be set to on.
A radiolist box is similar to a menu box. The main difference
is that you can indicate which entry is initially selected,
by setting its status to on.
Return a tuple of the form (code, tag) with the tag for the
entry that was chosen by the user. `code' is the exit status
of the dialog-like program.
If the user exits with ESC or CANCEL, or if all entries were
initially set to off and not altered before the user chose
OK, the returned tag is the empty string.
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
cmd = ["--radiolist", text, str(height), str(width), str(list_height)]
for t in choices:
cmd.extend(((t[0], t[1], _to_onoff(t[2]))))
(code, tag) = self._perform(*(cmd,), **kwargs)
tag = self._strip_xdialog_newline(tag)
return (code, tag)
def scrollbox(self, text, height=20, width=78, **kwargs):
"""Display a string in a scrollable box.
text -- text to display in the box
height -- height of the box
width -- width of the box
This method is a layer on top of textbox. The textbox option
in dialog allows to display file contents only. This method
allows you to display any text in a scrollable box. This is
simply done by creating a temporary file, calling textbox and
deleting the temporary file afterwards.
Return the dialog-like program's exit status.
Notable exceptions:
- UnableToCreateTemporaryDirectory
- PythonDialogIOError
- PythonDialogOSError
- exceptions raised by the tempfile module (which are
unfortunately not mentioned in its documentation, at
least in Python 2.3.3...)
"""
# In Python < 2.3, the standard library does not have
# tempfile.mkstemp(), and unfortunately, tempfile.mktemp() is
# insecure. So, I create a non-world-writable temporary directory and
# store the temporary file in this directory.
try:
# We want to ensure that f is already bound in the local
# scope when the finally clause (see below) is executed
f = 0
tmp_dir = _create_temporary_directory()
# If we are here, tmp_dir *is* created (no exception was raised),
# so chances are great that os.rmdir(tmp_dir) will succeed (as
# long as tmp_dir is empty).
#
# Don't move the _create_temporary_directory() call inside the
# following try statement, otherwise the user will always see a
# PythonDialogOSError instead of an
# UnableToCreateTemporaryDirectory because whenever
# UnableToCreateTemporaryDirectory is raised, the subsequent
# os.rmdir(tmp_dir) is bound to fail.
try:
fName = os.path.join(tmp_dir, "text")
# No race condition as with the deprecated tempfile.mktemp()
# since tmp_dir is not world-writable.
f = open(fName, "wb")
f.write(text)
f.close()
# Ask for an empty title unless otherwise specified
if not "title" in kwargs.keys():
kwargs["title"] = ""
return self._perform(
*(["--textbox", fName, str(height), str(width)],),
**kwargs)[0]
finally:
if type(f) == types.FileType:
f.close() # Safe, even several times
os.unlink(fName)
os.rmdir(tmp_dir)
except os.error, v:
raise PythonDialogOSError(v.strerror)
except IOError, v:
raise PythonDialogIOError(v)
def tailbox(self, filename, height=20, width=60, **kwargs):
"""Display the contents of a file in a dialog box, as in "tail -f".
filename -- name of the file whose contents is to be
displayed in the box
height -- height of the box
width -- width of the box
Display the contents of the specified file, updating the
dialog box whenever the file grows, as with the "tail -f"
command.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--tailbox", filename, str(height), str(width)],),
**kwargs)[0]
# No tailboxbg widget, at least for now.
def textbox(self, filename, height=20, width=60, **kwargs):
"""Display the contents of a file in a dialog box.
filename -- name of the file whose contents is to be
displayed in the box
height -- height of the box
width -- width of the box
A text box lets you display the contents of a text file in a
dialog box. It is like a simple text file viewer. The user
can move through the file by using the UP/DOWN, PGUP/PGDN
and HOME/END keys available on most keyboards. If the lines
are too long to be displayed in the box, the LEFT/RIGHT keys
can be used to scroll the text region horizontally. For more
convenience, forward and backward searching functions are
also provided.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
# This is for backward compatibility... not that it is
# stupid, but I prefer explicit programming.
if not "title" in kwargs.keys():
kwargs["title"] = filename
return self._perform(
*(["--textbox", filename, str(height), str(width)],),
**kwargs)[0]
def timebox(self, text, height=3, width=30, hour=-1, minute=-1,
second=-1, **kwargs):
"""Display a time dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
hour -- inititial hour selected
minute -- inititial minute selected
second -- inititial second selected
A dialog is displayed which allows you to select hour, minute
and second. If the values for hour, minute or second are
negative (or not explicitely provided, as they default to
-1), the current time's corresponding values are used. You
can increment or decrement any of those using the left-, up-,
right- and down-arrows. Use tab or backtab to move between
windows.
Return a tuple of the form (code, time) where `code' is the
exit status (an integer) of the dialog-like program and
`time' is a list of the form [hour, minute, second] (where
`hour', `minute' and `second' are integers corresponding to
the time chosen by the user) if the box was closed with OK,
or None if it was closed with the Cancel button.
Notable exceptions:
- any exception raised by self._perform()
- PythonDialogReModuleError
- UnexpectedDialogOutput
"""
(code, output) = self._perform(
*(["--timebox", text, str(height), str(width),
str(hour), str(minute), str(second)],),
**kwargs)
if code == self.DIALOG_OK:
try:
mo = _timebox_time_rec.match(output)
if mo is None:
raise UnexpectedDialogOutput(
"the dialog-like program returned the following "
"unexpected time with the --timebox option: %s" % output)
time = map(int, mo.group("hour", "minute", "second"))
except re.error, v:
raise PythonDialogReModuleError(v)
else:
time = None
return (code, time)
def yesno(self, text, height=10, width=30, **kwargs):
"""Display a yes/no dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
A yes/no dialog box of size `height' rows by `width' columns
will be displayed. The string specified by `text' is
displayed inside the dialog box. If this string is too long
to fit in one line, it will be automatically divided into
multiple lines at appropriate places. The text string can
also contain the sub-string "\\n" or newline characters to
control line breaking explicitly. This dialog box is useful
for asking questions that require the user to answer either
yes or no. The dialog box has a Yes button and a No button,
in which the user can switch between by pressing the TAB
key.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--yesno", text, str(height), str(width)],),
**kwargs)[0]
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
import pickle
from Fichier import Fichier
##########
# Classe #
##########
## Classe qui gere l'historique des telechargements
class Historique( object ):
# Instance de la classe (singleton)
instance = None
## Surcharge de la methode de construction standard (pour mettre en place le singleton)
def __new__( self, *args, **kwargs ):
if( self.instance is None ):
self.instance = super( Historique, self ).__new__( self )
return self.instance
# Historique : les fichiers sont d'abord hashes selon leur date pour diminuer le temps de recherche
# Ainsi, l'historique est de la forme { date1, [ Fichiers a date1 ], date2, [ Fichiers a date2 ], ... }
## Constructeur
def __init__( self ):
self.home = os.path.expanduser( "~" )
self.fichierHistorique = self.home + "/.tvdownloader/logs/historique"
self.chargerHistorique()
## Methode qui charge l'historique existant
def chargerHistorique( self ):
if os.path.exists( self.fichierHistorique ): # Si le fichier existe, on le charge
fichier = open( self.fichierHistorique, "r" )
self.historique = pickle.load( fichier )
fichier.close()
else: # Sinon, on creee un historique vide
self.historique = {}
## Methode qui ajoute un fichier a l'historique
# @param nouveauFichier Fichier a ajouter a l'historique
def ajouterHistorique( self, nouveauFichier ):
if( isinstance( nouveauFichier, Fichier ) ):
date = getattr( nouveauFichier, "date" )
if( self.historique.has_key( date ) ):
self.historique[ date ].append( nouveauFichier )
else:
self.historique[ date ] = [ nouveauFichier ]
## Methode qui sauvegarde l'historique
def sauverHistorique( self ):
# On enregistre l'historique
fichier = open( self.fichierHistorique, "w" )
pickle.dump( self.historique, fichier )
fichier.close()
## Methode qui verifie si un fichier se trouve dans l'historique
# @param fichier Fichier a chercher dans l'historique
# @return Si le fichier est present ou non dans l'historique
def comparerHistorique( self, fichier ):
if( isinstance( fichier, Fichier ) ):
date = getattr( fichier, "date" )
if( self.historique.has_key( date ) ):
return fichier in self.historique[ date ]
else:
return False
else:
return False
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
import sys
#############
# Variables #
#############
# du programme
TVD_NOM = "TVDownloader"
TVD_VERSION = "0.8"
# du systeme
OS_UNIX = False
OS_WINDOWS = False
if( sys.platform.lower()[ : 3 ] == "win" ):
OS_WINDOWS = True
else:
OS_UNIX = True
# des chemins
if( "TVDOWNLOADER_HOME" in os.environ ):
REPERTOIRE_HOME = os.path.join( os.environ[ "TVDOWNLOADER_HOME" ] )
REPERTOIRE_CACHE = os.path.join( REPERTOIRE_HOME, "cache" )
REPERTOIRE_CONFIGURATION = os.path.join( REPERTOIRE_HOME, "config" )
elif( "APPDATA" in os.environ ):
REPERTOIRE_HOME = os.path.join( os.environ[ "APPDATA" ], "tvdownloader" )
REPERTOIRE_CACHE = os.path.join( REPERTOIRE_HOME, "cache" )
REPERTOIRE_CONFIGURATION = os.path.join( REPERTOIRE_HOME, "config" )
else:
REPERTOIRE_HOME = os.path.expanduser( "~" )
REPERTOIRE_CACHE = os.path.join( REPERTOIRE_HOME, ".cache", "tvdownloader" )
REPERTOIRE_CONFIGURATION = os.path.join( REPERTOIRE_HOME, ".config", "tvdownloader" )
REPERTOIRE_LOGS = os.path.join( REPERTOIRE_CONFIGURATION, "logs" )
REPERTOIRE_PLUGIN_PERSO = os.path.join( REPERTOIRE_CONFIGURATION, "plugins" )
REPERTOIRE_TELECHARGEMENT_DEFAUT = os.path.join( os.path.expanduser( "~" ), "Videos_TVDownloader" )
# des plugins
REPERTOIRES_PLUGINS = [ REPERTOIRE_PLUGIN_PERSO,
"plugins" ]
# des fichiers
FICHIER_CONFIGURATION_TVD = os.path.join( REPERTOIRE_CONFIGURATION, "tvdownloader" )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import datetime
import os.path
import re
import unicodedata
import logging
logger = logging.getLogger( __name__ )
##########
# Classe #
##########
## Classe qui contient les informations d'un fichier
class Fichier:
## @var nom
# Nom du fichier (tel qu'affiché à l'utilisateur)
## @var date
# Date du fichier sous forme d'une chaîne
## @var lien
# Url où se trouve le fichier
## @var nomFichierSortie
# Nom du fichier en sortie
## @var urlImage
# URL de l'image a afficher avec le Fichier
## @var descriptif
# Texte descriptif du fichier
## Contructeur.
# @param self L'objet courant
# @param nom Le nom du fichier (tel qu'affiché à l'utilisateur)
# @param date La date du fichier sous forme d'une chaîne
# @param lien L'url où se trouve le fichier
# @param nomFichierSortie Nom du fichier de sortie
# @param urlImage URL de l'image a afficher
# @param descriptif Texte descriptif a afficher
def __init__( self, nom = "", date = "", lien = "", nomFichierSortie = "", urlImage = "", descriptif = "" ):
self.nom = nom
self.lien = lien
self.urlImage = urlImage
self.descriptif = self.supprimeBaliseHTML( descriptif )
if( nomFichierSortie == "" ):
self.nomFichierSortie = self.stringToFileName( os.path.basename( self.lien ) )
else:
self.nomFichierSortie = self.stringToFileName( nomFichierSortie )
if( isinstance( date, datetime.date ) ):
self.date = date.isoformat()
else:
self.date = date
## Surcharge de la methode ==
# @param other L'autre Fichier a comparer
# @return Si les 2 Fichiers sont egaux
def __eq__( self, other ):
if not isinstance( other, Fichier ):
return False
else:
return ( self.nom == getattr( other, "nom" ) and \
self.date == getattr( other, "date" ) and \
self.lien == getattr( other, "lien" ) )
## Surcharge de la methode !=
# @param other L'autre Fichier a comparer
# @return Si les 2 Fichiers sont differents
def __ne__( self, other ):
return not self.__eq__( other )
## Methode qui transforme une chaine de caracteres en chaine de caracteres utilisable comme nom de fichiers
# @param chaine Chaine de caracteres a transformer
# @return Chaine de caracteres utilisable en nom de fichiers
def stringToFileName( self, chaine ):
if( isinstance( chaine, str ) ):
chaine = unicode( chaine, "utf8" )
# On supprime les accents
chaineNettoyee = unicodedata.normalize( 'NFKD', chaine ).encode( 'ASCII', 'ignore' )
# On supprimes les espaces
chaineSansEspaces = chaineNettoyee.replace( " ", "_" )
# On supprime les caracteres speciaux
return "".join( [ x for x in chaineSansEspaces if x.isalpha() or x.isdigit() or x == "." ] )
## Methode qui supprime les balises HTML courantes d'une chaine de caractere
# @param chaine Chaine de caracteres a transformer
# @return Chaine de caracteres utilisable en nom de fichiers
def supprimeBaliseHTML( self, chaine ):
p = re.compile( r'<.*?>' )
return p.sub( '', chaine ) | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import urllib
import urllib2
import mechanize
import random
import re
import threading
import time
import xml.sax.saxutils
import logging
logger = logging.getLogger( __name__ )
#
# Liste d'user agent
#
listeUserAgents = [ 'Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; fr; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; fr; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.1b2) Gecko/20081201 Firefox/3.1b2',
'Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.2) Gecko/20100115 Firefox/3.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Opera/8.50 (Windows NT 5.1; U; en)',
'Opera/9.80 (X11; Linux x86_64; U; fr) Presto/2.2.15 Version/10.00',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312' ]
##########
# Classe #
##########
## Classe Navigateur pour charger les pages web
class Navigateur( object ):
timeOut = 5
maxThread = 10
## Constructeur
def __init__( self ):
# Navigateur
self.navigateur = mechanize.Browser()
#
# Options du Navigateur
#
# User Agent
self.navigateur.addheaders = [ ('User-agent', random.choice( listeUserAgents ) ) ]
#
self.navigateur.set_handle_equiv( True )
# Active compression gzip
#~ self.navigateur.set_handle_gzip( True )
#
self.navigateur.set_handle_redirect( True )
# N'ajoute pas le referer a l'en-tete
self.navigateur.set_handle_referer( False )
# Ne prend pas en compte les robots.txt
self.navigateur.set_handle_robots( False )
# Ne doit pas gerer les cookies
self.navigateur.set_cookiejar( None )
## Methode pour recuperer une page web
# @param URLPage URL de la page web a charger
# @return Code de la page
def getPage( self, URLPage ):
logger.info( "acces a la page %s" %( URLPage ) )
try:
# Page a charger
page = self.navigateur.open( URLPage, timeout = self.timeOut )
# Si le fichier est un XML
if( URLPage[ -4 : ] == ".xml" ):
# On la page telle quelle, sans aucun traitement
return page.read()
else: # Sinon, on va cherche a determiner son encodage
# Donnees de la page
donnees = self.unescape( page.read() )
# On recupere si possible l'encodage de la page
contentType = page.info()[ "Content-type" ]
# Type d'encodage de la page
encodagePage = ""
# On extrait l'encodage
res = re.findall( "charset=(.+)", contentType )
if( len( res ) != 0 ):
encodagePage = res[ 0 ].lower()
# Si on a trouve un encodage et qui n'est pas de l'utf-8
if( encodagePage != "" and encodagePage != "utf-8" ):
# On retourne la page dans le bon encodage
return unicode( donnees, encodagePage ).encode( 'utf-8', 'replace' )
else:
return donnees
except urllib2.URLError, erreur:
try:
logger.error( erreur.reason )
except :
pass
return ""
except:
return ""
## Methode pour recuperer plusieurs pages web
# @param listeURL Liste des URLs des pages web a charger
# @return La liste (dictionnaire) des pages web recuperees { URLPage : Page }
def getPages( self, listeURL ):
## Sous methode qui gere le telechargement d'une page (thread)
# @param URLPage URL de la page a charger
def ajoutPage( self, URLPage ):
# On a un thread lance de plus
self.lock.acquire()
self.nbThreadLances += 1
self.lock.release()
# On recupere la page web
try:
page = self.getPage( URLPage )
except:
page = ""
#~ print "DL de %s fini" %( URLPage )
# On ajoute la page a la liste et on a un thread lance de moins
self.lock.acquire()
self.listePage[ URLPage ] = page
self.nbThreadLances -= 1
self.lock.release()
self.listePage = {}
self.nbThreadLances = 0
indiceActuelListe = 0
tailleListe = len( listeURL )
self.lock = threading.Lock()
# Boucle pour lancer les threads
self.lock.acquire()
while( indiceActuelListe < tailleListe ): # Tant qu'on a pas fini de parcourir la liste
if( self.nbThreadLances < self.maxThread ): # Si on peut encore lance des threads
#~ print "Indice = %d" %( indiceActuelListe )
self.lock.release()
# On en lance un
threading.Thread( target = ajoutPage,
args = ( self, listeURL[ indiceActuelListe ] )
).start()
indiceActuelListe += 1
#~ self.lock.release()
#~ time.sleep( 0.01 ) # Legere attente pour que le thread ait le temps d'incrementer le nombre de threads lances
else: # Sinon,
# On attend un peu avant de reessayer
self.lock.release()
time.sleep( 0.1 )
#~ print self.nbThreadLances
self.lock.acquire()
self.lock.release()
# Boucle pour attendre la fin de tous les threads
self.lock.acquire()
while( self.nbThreadLances > 0 ): # Si des threads ne sont pas finis
#~ print self.nbThreadLances
# On attend un peu
self.lock.release()
time.sleep( 0.1 )
self.lock.acquire()
self.lock.release()
return self.listePage
## Methode pour recuperer une image
# @param URLPicture URL de l'image a charger
# @return Image
def getPicture( self, URLPicture ):
logger.info( "acces a l'image %s" %( URLPicture ) )
try:
# Image a charger
page = self.navigateur.open( URLPicture, timeout = self.timeOut )
# Donnees de l'image
donnees = page.read()
return donnees
except urllib2.URLError, erreur:
try:
logger.error( erreur.reason )
except :
pass
return ""
def unescape( self, texte ):
#~ def ent2chr( m ):
#~ code = m.group( 1 )
#~ if( code.isdigit() ):
#~ code = int( code )
#~ else:
#~ code = int( code[ 1 : ], 16 )
#~ if( code < 256 ):
#~ return chr( code )
#~ else:
#~ return '?'
#~
#~ texte = texte.replace( "<", "<" )
#~ texte = texte.replace( ">", ">" )
#~ texte = texte.replace( "&", "&" )
#~ texte = texte.replace( """, '"' )
#~ texte = texte.replace( "'", "'" )
#~ texte = re.sub( r'\&\#(x?[0-9a-fA-F]+);', ent2chr, texte )
return xml.sax.saxutils.unescape( texte )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
import os.path
import threading
import subprocess
import shlex
import re
import fcntl
import select
import time
import sys
import unicodedata
import logging
logger = logging.getLogger( __name__ )
from Preferences import Preferences
from fonctions.urlToRtmpdump import urlToRtmpdump
##########
# Classe #
##########
## Classe qui gere le telechargement des fichiers
class Downloader( object ):
# Instance de la classe (singleton)
instance = None
## Surcharge de la methode de construction standard (pour mettre en place le singleton)
def __new__( self, *args, **kwargs ):
if( self.instance is None ):
self.instance = super( Downloader, self ).__new__( self )
return self.instance
## Constructeur
# @param signaux Lanceur de signaux. Si on le precise pas, aucun signal n'est lance (mode CLI).
def __init__( self, signaux = None ):
self.preferences = Preferences()
self.signaux = signaux
self.arreter = True
self.process = None
## Methode pour afficher un pourcentage à l'ecran
# @param pourcentage Pourcentage actuel a afficher
def afficherPourcentage( self, pourcentage ):
# On s'assure que le pourcentage soit bien entre 0 et 100
if( pourcentage < 0 ):
pourcentage = 0
elif( pourcentage > 100 ):
pourcentage = 100
message = str( pourcentage ) + " %"
print '\r', # Permet d'écrire au même endroit
sys.stdout.write( message )
sys.stdout.flush()
## Methode pour lancer le telecharger des fichiers
# @param listeFichiers Liste des fichiers a telecharger
def lancerTelechargement( self, listeFichiers ):
self.arreter = False
for ( numero, fichier, nomFichierSortie ) in listeFichiers:
logger.info( u"téléchargement de %s" %( fichier ) )
# Si on demande de s'arreter, on sort
if self.arreter:
break
# Si on a le lanceur de signal
if self.signaux :
# On envoie le signal de debut de telechargement d'un fichier
self.signaux.signal( "debutTelechargement", numero )
else:
print "Debut telechargement", nomFichierSortie
# On ajoute le repertoire de destination au nom du fichier
fichierSortie = self.preferences.getPreference( "repertoireTelechargement" ) + "/" + nomFichierSortie
# On telecharge de differentes manieres selon le protocole
if( fichier[ :4 ] == "rtmp" ):
commande = urlToRtmpdump( fichier )
self.telecharger( commande + " -o \"" + fichierSortie + "\"" )
elif( fichier[ :4 ] == "http" or fichier[ :3 ] == "ftp" or fichier[ :3 ] == "mms" ):
self.telecharger( "msdl -c " + fichier + " -o \"" + fichierSortie + "\"" )
else:
logger.warn( "le protocole du fichier %s n'est pas gere" %( fichier ) )
# Si on a le lanceur de signal
if self.signaux :
# On envoie le signal de fin de telechargement d'un fichier
self.signaux.signal( "finTelechargement", numero )
else:
print "\n\tFin telechargement"
# Si on a le lanceur de signal
if self.signaux :
# On envoie le signal de fin de telechargement des fichiers
self.signaux.signal( "finDesTelechargements" )
## Methode qui telecharge un fichier
# @param commande Commande a lancer pour telecharger le fichier
def telecharger( self, commande ):
# Commande mise au bon format pour Popen
if( not isinstance( commande, str ) ):
commande = str( commande )
arguments = shlex.split( commande )
# On lance la commande en redirigeant stdout et stderr (stderr va dans stdout)
self.process = subprocess.Popen( arguments, stdout = subprocess.PIPE, stderr = subprocess.STDOUT )
# On recupere le flux stdout
stdoutF = self.process.stdout
# On recupere le descripteur de fichier de stdout
stdoutFD = stdoutF.fileno()
# On recupere les flags existants
stdoutFlags = fcntl.fcntl( stdoutFD, fcntl.F_GETFL )
# On modifie les flags existants en ajoutant le flag NoDelay
fcntl.fcntl( stdoutFD, fcntl.F_SETFL, stdoutFlags | os.O_NDELAY )
# Tant que le subprocess n'est pas fini
while( self.process.poll() == None ):
# On attent que stdout soit lisible
if( stdoutFD in select.select( [ stdoutFD ],[],[] )[ 0 ] ):
# On lit stdout
ligne = stdoutF.read()
# On affiche que les textes non vides
if ligne:
pourcentListe = re.findall( "(\d{1,3}\.{0,1}\d{0,1})%", ligne )
if( pourcentListe != [] ):
pourcent = int( float( pourcentListe[ -1 ] ) )
if( pourcent >= 0 and pourcent <= 100 ):
# Si on a le lanceur de signal
if not self.signaux :
self.afficherPourcentage( pourcent )
elif self.signaux :
# On envoit le pourcentage d'avancement a l'interface
self.signaux.signal( "pourcentageFichier", pourcent )
# On attent avant de recommencer a lire
time.sleep( 3 )
## Methode pour stopper le telechargement des fichiers
def stopperTelechargement( self ):
if not self.arreter:
# On sort de la boucle principale
self.arreter = True
# On stop le process s'il est lance
if( self.process.poll() == None ):
self.process.terminate()
#~ self.process.kill()
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os,os.path,pickle
from API import API
from Option import Option
import logging
logger = logging.getLogger( __name__ )
import Constantes
##########
# Classe #
##########
## Classe abstraite Plugin dont doit heriter chacun des plugins.
#
# Les plugins doivent hériter de cette classe et redéfinir les méthodes #listerChaines, #listerEmissions et #listerFichiers.
# La méthode #listerOptions est optionnellement à redéfinir (dans le cas où il y aurai des options).
class Plugin(object):
## @var API
# Instance de l'API à utilisé pour l'accès au méthode de l'API.
## @var nom
# Nom du plugin
## @var url
# Url du site internet du plugin
## @var frequence
# Nombre de jour avant le rafraichissement automatique du plugin
## @var fichierConfiguration
# Chemin du fichier de configuration
## @var fichierCache
# Chemin du fichier de cache
## Constructeur
# @param self le plugin courant
# @param nom le nom du plugin
# @param url l'url du site internet
# @param frequence la fréquence (en jour) de rafraichissement, 0 pour ne jamais rafraichir
def __init__(self, nom=None, url=None, frequence=7):
self.API = API.getInstance()
self.pluginDatas = {"chaines":[],
"emissions":{},
"fichiers":{}}
self.pluginOptions = []
if nom == None:
logger.warn("DEPRECATED: il faut préciser le nom du plugin au constructeur")
else:
self.nom = nom
if url == None:
logger.warn("DEPRECATED: il faut préciser l'url du site du plugin au constructeur")
else:
self.url = url
self.frequence = frequence
self.fichierConfiguration = os.path.join( Constantes.REPERTOIRE_CONFIGURATION, self.nom.replace( " ", "_" )+ ".conf" )
self.fichierCache = os.path.join( Constantes.REPERTOIRE_CACHE, self.nom.replace( " ", "_" ) + ".cache" )
## Efface les informations mémorisées.
# @param self l'objet courant
def vider(self):
self.pluginDatas = {"chaines":[],
"emissions":{},
"fichiers":{}}
self.pluginOptions = []
## Effectue le listage des options.
# Utiliser #optionTexte, #optionCheckbox, #optionListeMultiple et #optionListeUnique pour ajouter des options
# @param self le plugin courant
# @return rien
def listerOptions(self):
pass
## Rafraichie les informations durable du plugins comme la liste des émissions.
# Y placer les traitements lourd n'ayant pas besoin d'être fait souvent.
# @param self le plugin courant
# @return Rien
def rafraichir( self ):
pass
## Effectue le listage des chaînes.
# Utiliser #ajouterChaine pour ajouter une chaîne à la liste.
# @param self le plugin courant
# @return rien
def listerChaines( self ):
pass
## Effectue le listage des émissions.
# Utiliser #ajouterEmission pour ajouter une émission à la liste.
# @param self le plugin courant
# @param chaine la chaine
# @return rien
def listerEmissions( self, chaine ):
pass
## Effectue le listage des fichiers.
# Utiliser #ajouterFichier pour ajouter un fichier à la liste.
# @param self le plugin courant
# @param emission l'emission
# @return Rien
def listerFichiers( self, emission ):
pass
## Ajoute une chaine à celle disponible pour ce plugin.
# A utiliser dans #listerChaines et en remplacement d'un retour de paramètre.
# @param self le plugin courant
# @param chaine le nom de la chaine
# @return Rien
def ajouterChaine(self, chaine):
self.pluginDatas["chaines"].append(chaine)
## Ajoute une émission à celle disponible pour ce plugin.
# A utiliser dans #listerEmissions et en remplacement d'un retour de paramètre.
# @param self le plugin courant
# @param chaine le nom de la chaine de l'émission
# @param emission le nom de l'émission
# @return Rien
def ajouterEmission(self, chaine, emission):
if not self.pluginDatas["emissions"].has_key(chaine):
self.pluginDatas["emissions"][chaine] = []
self.pluginDatas["emissions"][chaine].append(emission)
## Ajoute un fichier à ceux disponible pour ce plugin.
# A utiliser dans #listerFichiers et en remplacement d'un retour de paramètre.
# @param self le plugin courant
# @param emission l'emission du fichier
# @param fichier le fichier
# @return Rien
def ajouterFichier(self, emission, fichier):
if not self.pluginDatas["fichiers"].has_key(emission):
self.pluginDatas["fichiers"][emission] = []
self.pluginDatas["fichiers"][emission].append(fichier)
## Affiche le texte "text" dans la console avec en préfixe le nom du plugin.
# Facilite le déboguage, utilisé cette méthode plutôt que "print".
# @param self le plugin courant
# @param text le texte à afficher en console
# @param ligne paramètre inutile, conservé par rétrocompatibilité
# @return Rien
def afficher(self, text, ligne=None):
if ligne != None:
logger.warn("Le paramètre ligne n'a plus aucun effet.")
logger.info(self.nom+":"+text)
## Sauvegarde les options.
#
# Sauvegarde les options dans le fichier de configuration, ne pas utiliser.
# Les options sont sauvegardées automatiquement.
# @param self le plugin courant
# @return Rien
# @deprecated Ne fait plus rien. Ne pas uiliser.
def sauvegarderPreference(self):
logger.warn("Plugin.sauvegarderPreference(): DEPRECATED: ne fait plus rien.")
return
try:
file = open(self.fichierConfiguration, "w")
pickle.dump(self.pluginOptions, file)
file.close()
except:
print "Plugin.sauvegarderPreference(): Erreur de sauvegarde"
## Charge les préférences.
#
# Charge les préférences du fichier de configuration, ne pas utiliser.
# Les options sont chargées automatiquement.
# @param self le plugin courant
# @return Rien
# @deprecated Ne fait plus rien. Ne pas uiliser.
def chargerPreference(self):
logger.warn("Plugin.chargerPreference(): DEPRECATED: ne fait plus rien.")
return
if os.path.exists(self.fichierConfiguration):
try:
file = open(self.fichierConfiguration, "r")
tmp = pickle.load(file)
file.close()
self.pluginOptions = tmp
except:
print "Plugin.chargerPreference(): Erreur de chargement"
## Sauvegarde un objet dans le cache.
#
# Attention, cette méthode écrase le cache déjà enregistré.
# @param self le plugin courant
# @param objet l'objet à sauvegarder
# @return Rien
def sauvegarderCache(self, objet):
try:
file = open(self.fichierCache, "w")
pickle.dump(objet, file)
file.close()
except:
logger.error("Plugin.sauvegarderCache(): Erreur de sauvegarde")
## Charge le fichier de cache.
# @param self le plugin courant
# @return l'objet sauvegardé dans le cache ou None en cas d'échec
def chargerCache(self):
if os.path.exists(self.fichierCache):
try:
file = open(self.fichierCache, "r")
tmp = pickle.load(file)
file.close()
return tmp
except:
return None
else:
return None
## Renvoie la valeur d'une option
#
# L'option doit être ajouter dans #listerOptions pour que cela renvoie une valeur.
# @param self le plugin courant
# @param nom le nom de l'option
# @return la valeur de l'option, None en cas d'échec
def getOption(self, nom):
for option in self.pluginOptions:
if option.getNom() == nom:
return option.getValeur()
return None
## Ajoute une option texte.
# @param self le plugin courant
# @param nom le nom de l'option (sert d'identifiant)
# @param description la description de l'option
# @param defaut la valeur par défaut (celle qui sera présente lors de l'affichage des options)
# @return rien
def optionTexte(self, nom, description, defaut):
self.pluginOptions.append(Option(Option.TYPE_TEXTE, nom, description, defaut))
## Ajoute une option bouléen.
# @param self le plugin courant
# @param nom le nom de l'option (sert d'identifiant)
# @param description la description de l'option
# @param defaut la valeur par défaut, True pour coché, faut pour décoché
# @return rien
def optionBouleen(self, nom, description, defaut):
self.pluginOptions.append(Option(Option.TYPE_BOULEEN, nom, description, defaut))
## Ajoute une option liste (choix multiple).
# @param self le plugin courant
# @param nom le nom de l'option (sert d'identifiant)
# @param description la description de l'option
# @param valeurs les valeurs possibles (liste)
# @param defauts les valeurs sélectionnées (liste)
# @return rien
def optionChoixMultiple(self, nom, description, defauts, valeurs):
self.pluginOptions.append(Option(Option.TYPE_CHOIX_MULTIPLE, nom, description, defauts, valeurs))
## Ajoute une option liste (choix unique).
# @param self le plugin courant
# @param nom le nom de l'option (sert d'identifiant)
# @param description la description de l'option
# @param valeurs les valeurs possibles (liste)
# @param defaut la valeur par défaut
# @return rien
def optionChoixUnique(self, nom, description, defaut, valeurs):
self.pluginOptions.append(Option(Option.TYPE_CHOIX_UNIQUE, nom, description, defaut, valeurs))
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
import pickle
import logging
logger = logging.getLogger( __name__ )
import Constantes
from GUI.Downloader import Downloader
from Navigateur import Navigateur
from PluginManager import PluginManager
##########
# Classe #
##########
## Classe qui gere les preferences du logiciel
class Preferences( object ):
# Instance de la classe (singleton)
instance = None
## Surcharge de la methode de construction standard (pour mettre en place le singleton)
def __new__( self, *args, **kwargs ):
if( self.instance is None ):
self.instance = super( Preferences, self ).__new__( self )
return self.instance
## Constructeur
def __init__( self ):
self.pluginManager = PluginManager()
self.fichierConfiguration = Constantes.FICHIER_CONFIGURATION_TVD
self.chargerConfiguration()
## Methode qui charge les preferences du logiciel
def chargerConfiguration( self ):
# Parametres par defaut
self.preferencesParDefault = { "repertoireTelechargement" : Constantes.REPERTOIRE_TELECHARGEMENT_DEFAUT,
"pluginsActifs" : [],
"pluginParDefaut" : "",
"tailleFenetre" : [ 500, 500 ],
"timeOut" : 15,
"nbThreadMax" : 20
}
if os.path.exists( self.fichierConfiguration ): # Si le fichier existe, on le charge
# On recupere les preferences dans le fichier
fichier = open( self.fichierConfiguration, "r" )
self.preferences = pickle.load( fichier )
fichier.close()
# On verifie qu'il ne nous manque pas une preference
# Si c'est le cas, on prend sa valeur par defaut
for elmt in self.preferencesParDefault.keys():
if not self.preferences.has_key( elmt ):
self.preferences[ elmt ] = self.preferencesParDefault[ elmt ]
else: # Sinon, on utilise les parametres par defaut
self.preferences = self.preferencesParDefault
# On active les plugins qui doivent etre actifs
for plugin in self.preferences[ "pluginsActifs" ]:
self.pluginManager.activerPlugin( plugin )
# On cree le repertoire de telechargement s'il n'existe pas
if( not os.path.isdir( self.preferences[ "repertoireTelechargement" ] ) ):
os.makedirs( self.preferences[ "repertoireTelechargement" ] )
# On applique les preferences
self.appliquerPreferences()
## Methode qui applique les preferences
def appliquerPreferences( self ):
Downloader.repertoireTelechargement = self.preferences[ "repertoireTelechargement" ]
Navigateur.timeOut = self.preferences[ "timeOut" ]
Navigateur.maxThread = self.preferences[ "nbThreadMax" ]
## Methode qui sauvegarde les preferences du logiciel
def sauvegarderConfiguration( self ):
# On applique les preferences
self.appliquerPreferences()
# On sauvegarde les preferences dans le fichier de configuration
fichier = open( self.fichierConfiguration, "w" )
pickle.dump( self.preferences, fichier )
fichier.close()
## Methode qui renvoit une preference du logiciel
# @param nomPreference Nom de la preference a renvoyer
# @return Valeur de cette preference
def getPreference( self, nomPreference ):
try:
return self.preferences[ nomPreference ]
except KeyError:
logger.warn( "preference %s inconnue" %( nomPreference ) )
return None
## Methode qui met en place la valeur d'une preference
# @param nomPreference Nom de la preference dont on va mettre en place la valeur
# @param valeur Valeur a mettre en place
def setPreference( self, nomPreference, valeur ):
# Si on sauvegarde une nouvelle liste de plugin
if( nomPreference == "pluginsActifs" ):
nouvelleListe = valeur
ancienneListe = self.preferences[ "pluginsActifs" ]
# Pour chaque element dans l'union des 2 listes
for elmt in ( set( nouvelleListe ).union( set( ancienneListe ) ) ):
if( ( elmt in ancienneListe ) and not ( elmt in nouvelleListe ) ):
self.pluginManager.desactiverPlugin( elmt )
elif( ( elmt in nouvelleListe ) and not ( elmt in ancienneListe ) ):
self.pluginManager.activerPlugin( elmt )
# Dans tous les cas, on sauvegarde la preference
self.preferences[ nomPreference ] = valeur
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import logging
import optparse
import os
import sys
import Constantes
#
# Entree du programme
#
if __name__ == "__main__" :
# On se deplace dans le repertoire de travail (pas necessaire sous Windows)
if( not Constantes.OS_WINDOWS ):
# On se deplace dans le repertoire de travail du logciel
repertoireTravail = os.path.dirname( os.path.abspath( __file__ ) )
sys.path.insert( 0, repertoireTravail )
os.chdir( repertoireTravail )
# Options a parser
parser = optparse.OptionParser()
parser.add_option( "-v", "--verbose",
action = "store_true", dest = "verbose", default = False,
help = "Affiche informations dans le terminal" )
parser.add_option( "-c", "--cli",
action = "store_true", dest = "cli", default = False,
help = "Affiche la version CLI" )
parser.add_option( "-d", "--dialog",
action = "store_true", dest = "dialog", default = False,
help = u"Affiche la version Dialog (en cours de développement)" )
parser.add_option( "-g", "--genererXML",
action = "store_true", dest = "genererXML", default = False,
help = u"Génère le fichier XML qui decrit les plugins" )
options, args = parser.parse_args()
# On a active le mode verbeux ?
logger = logging.getLogger( __name__ )
console = logging.StreamHandler( sys.stdout )
if( options.verbose ):
logger.setLevel( logging.DEBUG )
console.setLevel( logging.DEBUG )
else:
logger.setLevel( logging.ERROR )
console.setLevel( logging.ERROR )
console.setFormatter( logging.Formatter( '%(levelname)-7s %(name)s : %(message)s' ) )
logger.addHandler( console )
# On veut generer le fichier XML qui decrit les plugins
if( options.genererXML ):
import UpdateManager
UpdateManager.UpdateManager.creerXML()
sys.exit( 0 )
# On met en place les repertoires de travail du logiciel
repertoires = [ Constantes.REPERTOIRE_CACHE, \
Constantes.REPERTOIRE_CONFIGURATION, \
Constantes.REPERTOIRE_LOGS, \
Constantes.REPERTOIRE_PLUGIN_PERSO ]
for repertoire in repertoires:
if( not os.path.isdir( repertoire ) ):
logger.info( "création du répertoire %s" %( repertoire ) )
os.makedirs( repertoire )
# On demarre le CLI ou le GUI ?
if( options.cli == False and options.dialog == False ):
# On importe les fichiers necessaires pour le GUI
try:
from PyQt4 import QtGui
except ImportError:
logger.critical( "ouuupppss : il vous faut PyQt4 pour pouvoir utiliser ce programme..." )
sys.exit( 1 )
from GUI.MainWindow import MainWindow
# On creer l'interface graphique
app = QtGui.QApplication( sys.argv )
window = MainWindow()
window.show()
sys.exit( app.exec_() )
elif( options.cli == True ):
from CLI.cli import cli
cli()
else:
from CLIDialog.CLIDialog import CLIDialog
CLIDialog()
| Python |
#/usr/bin/python
# -*- coding: utf-8 -*-
import os
#classe qui affiche la barre en haut de l'ecran
# @param self l'objet courant
# @param plugin le nom du plugin choisi
# @param chaine le nom de la chaine choisie
# @param program le nom du programme choisi
# @param program le nom du programme choisi ou de l'ecran d'option affiche
# @return Rien
def header(plugin,chaine,program):
print ""
#on efface l'affichage en cours
os.system(['clear','cls'][os.name == 'nt'])
#formatte le nom du plugin (entre 0 et 14 caracteres)
if len(plugin)<7:plugin+="\t"
#formatte le nom de la chaine (entre 0 et 14 caracteres)
if len(chaine)<7:chaine+="\t"
#formatte le nom du programme selon le nombre de caracteres
#if len(program)==0:program+="\t\t\t\t "
if len(program)<=7:program+= "\t\t\t\t "
elif len(program)<=14:program+="\t\t\t "
elif len(program)<=21:program+= "\t\t "
elif len(program)<=28:program+= "\t "
elif len(program)<=36:program+= " "
elif len(program)>36:
program=program[:33]
program+="..."
#affiche la barre avec les parametres recus
print " ##############################################################################"
print " ## TVDownloader 0.4 ##"
print " ## Command-Line Interface ##"
print " ## ##"
print " ## ##"
print " ##\t",plugin,"\t",chaine,"\t",program,"##"
print " ## ##"
print " ##############################################################################"
print ""
#classe qui affiche la barre de menu en bas de l'ecran, avant l'invite de saisie
# @param self l'objet courant
# @param Rien
# @return Rien
def footer():
print " q:quitter p:preferences t:telechargements r:retour a:actualiser",
#classe qui affiche les plugins, avec defilement +/- si plus de 15 plugins
# @param self l'objet courant
# @param plugins la liste des plugins
# @param current le numero de defilement dans la liste (0 pour la premiere page, 1 pour la page suivantee, etc)
# @return Rien
def plugin(plugins,current):
for i in range(10) :
if i+10*current<len(plugins): print " ",i,":",plugins[i+10*current]
else: print ""
print "\n\n"
if len(plugins)>10:print " +:plugins suivants -:plugins precedents (page",current+1,"/",len(plugins)/10+1,",",len(plugins),"plugins)"
else:print""
#classe qui affiche les chaines, avec defilement +/- si plus de 15 chaines
# @param self l'objet courant
# @param chaines la liste des chaines
# @param current le numero de defilement dans la liste (0 pour la premiere page, 1 pour la page suivantee, etc)
# @return Rien
def chaine(chaines,current):
for i in range(10) :
if i+10*current<len(chaines): print " ",i,":",chaines[i+10*current]
else: print ""
print "\n\n"
if len(chaines)>10:print " +:chaines suivantes -:chaines precedentes (page",current+1,"/",len(chaines)/10+1,",",len(chaines),"chaines)"
else:print""
#classe qui affiche les programmes, avec defilement +/- si plus de 15 programmes
# @param self l'objet courant
# @param programs la liste des programmes
# @param current le numero de defilement dans la liste (0 pour la premiere page, 1 pour la page suivantee, etc)
# @return Rien
def program(programs,current):
for i in range(10) :
if i+10*current<len(programs): print " ",i,":",programs[i+10*current]
else: print ""
print "\n\n"
if len(programs)>10:print " +:programmes suivants -:programmes precedents (page",current+1,"/",len(programs)/10+1,",",len(programs),"programmes)"
else:print""
#classe qui affiche les fichiers, avec defilement +/- si plus de 15 fichiers
# @param self l'objet courant
# @param fichiers la liste des fichiers
# @param current le numero de defilement dans la liste (0 pour la premiere page, 1 pour la page suivantee, etc)
# @return Rien
def fichier(fichiers,current):
for i in range(10) :
if i+10*current<len(fichiers):
if len(fichiers[i+10*current].nom)>74:print " ",i,":",fichiers[i+10*current].nom[:71]+"..."
elif len(fichiers[i+10*current].nom)<=74: print " ",i,":",fichiers[i+10*current].nom
else: print ""
print "\n\n"
if len(fichiers)>10:print " +:fichiers suivants -:fichiers precedents (page",current+1,"/",len(fichiers)/10+1,",",len(fichiers),"fichiers)"
else:print""
print " *:tous ",
| Python |
#/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
from CLI.Option import dl,prefs,quitter,wait,info
from CLI.Screen import header,footer,plugin,chaine,program,fichier
from getch import getch
from API import API
from APIPrive import APIPrive
from PluginManager import PluginManager
from Preferences import Preferences
from Downloader import Downloader
class show:
def __init__(self,selectedPlugin,selectedChaine,selectedProgram,temp):
#affichage de la barre du programme en haut de l'ecran
header(selectedPlugin,selectedChaine,selectedProgram)
#selon l'avancement dans la navigation on affichage les plugins, chaines, programmes ou fichiers
if len(selectedPlugin)==0:
plugin(plugins,temp)
elif len(selectedChaine)==0:
chaine(chaines,temp)
elif len(selectedProgram)==0:
program(programs,temp)
elif len(selectedPlugin)!=0 and len(selectedChaine)!=0 and len(selectedProgram)!=0:
fichier(fichiers,temp)
footer()
class cli:
def __init__(self):
#declaration des variables
global choice, temp, plugins, chaines, programs, fichiers, DLlist
chaines=''
programs=''
fichiers=''
temp = 0
choice = ""
selectedPlugin =''
selectedChaine =''
selectedProgram = ''
DLlist=[]
################################################
# Instanciations + initialisation de variables #
################################################
# On instancie le plugin manager
self.pluginManager = PluginManager()
# On instancie le gestionnaire de preferences
self.preferences = Preferences()
# On instancie le gestionnaire de download
self.downloader = Downloader()
# On recupere l'instance de API
self.api = API.getInstance()
# # On instancie le gestionnaire d'historique
# self.historique = Historique()
# Si aucun plugin n'est active, on ouvre la fenetre des preferences
if( len( self.preferences.getPreference( "pluginsActifs" ) ) == 0 ):
choice = 'p'
self.api.pluginRafraichirAuto()
# On met en place la liste des plugins dans API
plugins = self.preferences.getPreference( "pluginsActifs" )
plugins.sort()
# On actualise tous les plugins
self.api.pluginRafraichirAuto()
#boucle qui raffraichit l'affichage apres chaque interaction utilisateur
while choice != 'exit':
#ouverture du menu de preferences
if choice == 'p' or choice == 'P':
prefs()
# On met en place la liste des plugins dans API
plugins = self.preferences.getPreference( "pluginsActifs" )
plugins.sort()
# On actualise tous les plugins
self.api.pluginRafraichirAuto()
#ouverture du menu de telechargement
elif choice == 't' or choice == 'T': dl(DLlist)
#ouverture de l'invite de fermeture
elif choice == 'q' or choice == 'Q': quitter()
#actualisation de l'affichage ecran
elif choice == 'i' or choice == 'I': info()
#actualisation de l'affichage ecran
elif choice == 'a' or choice == 'A':
header(selectedPlugin,selectedChaine,selectedProgram)
print "\n\n\n\n\t\tRafraichissement\n\n\n"
self.api.pluginRafraichirAuto()
#recharger les listes
if len(selectedProgram)!=0:
fichiers = self.api.getPluginListeFichiers(selectedPlugin,selectedProgram)
elif len(selectedChaine)!=0:
programs = self.api.getPluginListeEmissions(selectedPlugin,selectedChaine)
elif len(selectedPlugin)!=0:
chaines = self.api.getPluginListeChaines(selectedPlugin)
elif len(selectedPlugin)==0 and len(selectedChaine)==0 and len(selectedProgram)==0:
plugins = self.preferences.getPreference( "pluginsActifs" )
plugins.sort()
#mise a jour de l'affichage
header(selectedPlugin,selectedChaine,selectedProgram)
print "\n\n\n\n\t\tVeuillez patientez pendant la mise a jour des informations\n\n\n"
time.sleep(1)
show(selectedPlugin,selectedChaine,selectedProgram,temp)
elif choice == 'r' or choice == 'R':
temp=0
if len(selectedProgram)!=0:
selectedProgram=""
elif len(selectedChaine)!=0:
selectedChaine=""
if len(chaines)==1:
selectedPlugin=""
elif len(selectedPlugin)!=0:
selectedPlugin=""
elif choice.isdigit() and int(choice)>=0:
choice=10*temp+int(choice)
if len(selectedPlugin)==0 and len(plugins)>choice:
temp=0
selectedPlugin = plugins[choice]
chaines = self.api.getPluginListeChaines(selectedPlugin)
if len(chaines)==1:
header(selectedPlugin,'','')
print "Une seule chaine :",chaines
time.sleep (0.5)
selectedChaine=chaines[0]
programs = self.api.getPluginListeEmissions(selectedPlugin,selectedChaine)
elif len(selectedChaine)==0 and len(chaines)>choice:
temp=0
selectedChaine=chaines[choice]
programs = self.api.getPluginListeEmissions(selectedPlugin,selectedChaine)
elif len(selectedProgram)==0 and len(programs)>choice:
selectedProgram=programs[choice]
header(selectedPlugin,selectedChaine,selectedProgram)
print "\n\n\n\n\t\tVeuillez patientez pendant le chargement des informations\n\n\n"
fichiers = self.api.getPluginListeFichiers(selectedPlugin,selectedProgram)
if len(fichiers)==0:
header (selectedPlugin,selectedChaine,selectedProgram)
print "\n\n\n\n\n\n\n\t\tAucun fichier dans le programme :",selectedProgram
time.sleep (1)
selectedProgram=''
else:temp=0
elif len(selectedPlugin)!=0 and len(selectedChaine)!=0 and len(selectedProgram)!=0 and len(fichiers)>choice:
header(selectedPlugin,selectedChaine,selectedProgram)
if fichiers[choice] not in DLlist:
print "\n\n\n\n\n\n\najout",fichiers[choice].nom,"a la liste de telechargement\n\n\n\n\n\n\n\n\n"
DLlist.append(fichiers[choice])
else: print "\n\n\n\n\n\n\n\t\tFichier deja dans la liste de telechargement\n\n\n\n\n\n\n\n\n"
time.sleep(1)
os.system(['clear','cls'][os.name == 'nt'])
elif choice=='*':
# if len(selectedPlugin)==0:
# temp=0
# selectedPlugin = 'None'
# chaines = self.api.getPluginListeChaines()
# elif len(selectedChaine)==0:
# temp=0
# selectedChaine='None'
# programs = self.api.getPluginListeEmissions(selectedPlugin,selectedChaine)
# el
if len(selectedProgram)==0:
selectedProgram='Tous'
header(selectedPlugin,selectedChaine,selectedProgram)
print "\n\n\n\n\t\tVeuillez patientez pendant le chargement des informations\n\n\n"
# for choice in range(len(programs)) :
fichiers = self.api.getPluginListeFichiers(selectedPlugin,None)#programs[choice])
elif len(selectedPlugin)!=0 and len(selectedChaine)!=0 and len(selectedProgram)!=0:
header(selectedPlugin,selectedChaine,selectedProgram)
for choice in range(len(fichiers)) :
if fichiers[int(choice)] not in DLlist:
header(selectedPlugin,selectedChaine,selectedProgram)
print "\n\n\n\n\t\tajout",fichiers[int(choice)].nom,"a la liste de telechargement"
DLlist.append(fichiers[int(choice)])
else: print "\t\tFichier deja dans la liste de telechargement"
time.sleep(0.5)
#afficher la suite de la liste
elif choice=='+':
if len(selectedPlugin) == 0:
if len(plugins)>temp*10+10: temp+=1
elif len(selectedChaine) == 0:
if len(chaines)>temp*10+10: temp+=1
elif len(selectedProgram) == 0:
if len(programs)>temp*10+10: temp+=1
elif len(selectedPlugin) != 0 and len(selectedChaine) != 0 and len(selectedProgram) != 0:
if len(fichiers)>temp*10+10: temp+=1
#afficher le debut de la liste
elif choice=='-':
if temp!=0: temp-=1
show(selectedPlugin,selectedChaine,selectedProgram,temp)
choice=''
# if not choice:choice=raw_input("\n\t\tEntrez votre choix : ")
if not choice:choice=getch()
# if len(choice)>1:choice=choice[0]
# if choice:print choice[0]
#split
if __name__=="__main__":
main()
| Python |
#/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
from CLI.Screen import header,footer
from Downloader import Downloader
from Preferences import Preferences
from Historique import Historique
from getch import getch
class dl:
def __init__(self, DLlist):
# On instancie le gestionnaire de preferences et sa fenetre
self.preferences = Preferences()
# On instancie le gestionnaire de download
self.downloader = Downloader()
# On instancie le gestionnaire d'historique et sa fenetre
self.historique = Historique()
current=0
global choice
choice=''
while choice!='r' and choice!='R':
if choice=='s' or choice=='S':
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\tSupprimer tous les fichiers de la liste de telchargement"
#pour chaque fichier de la liste ***(len(DLlist))!=0
while len(DLlist)>0:
print "Supprimer le fichier :",DLlist[0].nom
#supprimer le fichier de la liste
DLlist.remove(DLlist[0])
#ajouter le fichier au log
time.sleep (1)
if choice=='t' or choice=='T':
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\ttelecharger tous les fichiers"
#pour chaque fichier de la liste ***(len(DLlist))!=0
while len(DLlist)>0:
if not self.historique.comparerHistorique(DLlist[0]):
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\ttelecharger le fichier :",DLlist[0].nom
if(DLlist[0].nomFichierSortie=="" ):
DLlist[0].nomFichierSortie=os.path.basename(getattr(DLlist[0],"lien" ))
#telecharger le fichier
self.downloader.lancerTelechargement([[0,DLlist[0].lien,DLlist[0].nomFichierSortie]])
#ajouter le fichier a l'historique de telechargement
self.historique.ajouterHistorique(DLlist[0])
else:
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\tFichier deja telecharge"
#supprimer le fichier de la liste
DLlist.remove(DLlist[0])
time.sleep (1)
elif choice=='q' or choice=='Q':
quitter()
elif choice.isdigit() and len(DLlist)>int(choice)+10*current and int(choice)>=0:
value=''
while (value!='r' and value!='t' and value!='s'):
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\tFichier :",DLlist[int(choice)+10*current].nom,"\n\n\tQue voulez vous faire?\n\n\t\tt:telecharger le fichier\n\t\ts:supprimer le fichier de la liste de telechargement\n\t\tr:retour a liste de telechargement\n\n\n\n\n"
value=getch()
if value=='t':
if not self.historique.comparerHistorique(DLlist[int(choice)+10*current]):
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\ttelecharger le fichier :",DLlist[int(choice)].nom
# Si le nom du fichier de sortie n'existe pas, on l'extrait de l'URL
if(DLlist[int(choice)+10*current].nomFichierSortie=="" ):
DLlist[int(choice)+10*current].nomFichierSortie=os.path.basename(getattr(DLlist[int(choice)+10*current],"lien" ))
#telecharger le fichier
self.historique.ajouterHistorique(DLlist[int(choice)+10*current])
self.downloader.lancerTelechargement([[0,DLlist[int(choice)].lien,DLlist[int(choice)].nomFichierSortie]])
#ajouter le fichier a l'historique de telechargement
else:
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\tFichier deja telecharge"
time.sleep(1)
#supprimer le fichier de la liste
DLlist.remove(DLlist[int(choice)])
elif value=='s':
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\tSuppression de la liste de telechargement du fichier :\n\n\t\t",DLlist[int(choice)].nom
#supprimer le fichier de la liste
DLlist.remove(DLlist[int(choice)])
elif value=='r':
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\tRetour a la liste de telechargement"
#ajouter le fichier au log
time.sleep(1)
elif choice=='*' :
value=''
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\n\n\tQue voulez vous faire?\n\n\t\tt:telecharger les fichiers\n\t\ts:supprimer les fichiers de la liste de telechargement\n\n\n\n\n\n"
value=getch()
while len(DLlist)>0:
if value=='t':
if not self.historique.comparerHistorique(DLlist[0]):
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\ttelecharger le fichier :",DLlist[0].nom
# Si le nom du fichier de sortie n'existe pas, on l'extrait de l'URL
if(DLlist[0].nomFichierSortie=="" ):
DLlist[0].nomFichierSortie=os.path.basename(getattr(DLlist[0],"lien" ))
#telecharger le fichier
self.downloader.lancerTelechargement([[0,DLlist[0].lien,DLlist[0].nomFichierSortie]])
#ajouter le fichier a l'historique de telechargement
self.historique.ajouterHistorique(DLlist[0])
else:
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\tFichier deja telecharge"
time.sleep(0.5)
#supprimer le fichier de la liste
DLlist.remove(DLlist[0])
#ajouter le fichier au log
elif choice=='+':
if len(DLlist)>current*10+10: current+=1
elif choice=='-':
if current!=0: current-=1
choice=''
#sauvegarder l'historique de telechargement
self.historique.sauverHistorique()
#affichage a l'ecran de la liste
header ('','','Liste de telechargement\t')
for i in range(10):
if len(DLlist)>i+10*current:
if len(DLlist[int(i+10*current)].nom)>74: print " ",i,":",DLlist[int(i+10*current)].nom[:71]+"..."
elif len(DLlist[int(i+10*current)].nom)<=74: print " ",i,":",DLlist[int(i+10*current)].nom
else: print ""
if len(DLlist)>10:print "\n\t+:fichiers suivants\t-:fichiers precedents (page",current+1,"/",len(DLlist)/10+1,",",len(DLlist),"chaines)"
else:print"\n"
print "\n\tt:telecharger tous les fichiers s:supprimer tous les fichiers"
footer()
if len(DLlist)==0:
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Liste de telechargement\t')
print "\n\n\n\n\n\t\tAucun fichier dans la liste"
footer()
choice='r'
time.sleep(1)
if not choice:choice=getch()
class prefs:
def __init__(self):
from API import API
from APIPrive import APIPrive
from PluginManager import PluginManager
################################################
# Instanciations + initialisation de variables #
################################################
# On instancie le plugin manager
self.pluginManager = PluginManager()
# On instancie le gestionnaire de preferences et sa fenetre
self.preferences = Preferences()
# On instancie le gestionnaire de download
self.downloader = Downloader()
# On instancie seulement les plugins qui sont selectionnes dans les preferences
#~ self.pluginManager.activerPlugins( self.preferences.getPreference( "pluginsActifs" ) )
# On recupere l'instance de API
self.api = API.getInstance()
# On met en place la liste des plugins dans API
current=0
global choice
choice=''
while choice!='r' and choice!='R':
# self.api.setListeInstance( getattr( self.pluginManager, "listeInstances" ) )
pluginsActifs = self.pluginManager.listeInstances
plugins = self.pluginManager.getListeSites()
plugins.sort()
rep= self.preferences.getPreference( "repertoireTelechargement" )
# if choice.isdigit() and int(choice) < int(len(plugins)-10*current): print int(choice)+int(10*current)
# elif choice.isdigit() and int(choice) > int(len(plugins)-10*current): print int(choice)+int(10*current)
if choice=='q' or choice=='Q':
quitter()
elif choice.isdigit() and int(choice) < int(len(plugins)-10*current):
if plugins[int(choice)+10*current] in pluginsActifs:
self.pluginManager.desactiverPlugin(plugins[int(choice)+10*current])
print int(choice)+10*current,
else:
self.pluginManager.activerPlugin(plugins[int(choice)+10*current])
print int(choice)+10*current,
elif choice=='m' or choice =='M':
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Repertoire de telechargement')
choice=raw_input('\n\n\n\n\n\n\n\tVeuillez saisir un repertoire valide\n\n\t\t')
if not os.path.isdir(choice):
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Repertoire de telechargement')
print "\n\n\n\n\n\n\n\trepertoire ",choice," inexistant\n\n\t\tRepertoire courant:",rep
else :
os.system(['clear','cls'][os.name == 'nt'])
header ('','','Repertoire de telechargement')
rep=choice
print "\n\n\n\n\n\n\n\tModification du repertoire de telechargement :\n\n\t\tNouveau repertoire :",choice
self.preferences.setPreference( "repertoireTelechargement", str(rep))
time.sleep(1)
elif choice=='+':
if len(plugins)>current*15+15: current+=1
elif choice=='-':
if current!=0: current-=1
#affichage a l'ecran de la liste
header ('','','Menus des options')
print " Repertoire de telechargement :",rep
for i in range(10) :
if i+10*current<len(plugins):
print "\n ",i,":",plugins[i+10*current],
if len(plugins[i+10*current])<=8:print"\t\t",
elif len(plugins[i+10*current])<=15:print"\t",
for j in pluginsActifs:
if j==plugins[i+10*current]:
print "actif",
else: print ""
print "\n\n m:modifier le repertoire de telechargement +/-:afficher les autres plugins"
footer()
choice=getch()
liste=[]
for instance in pluginsActifs:
liste.append(instance)
self.preferences.setPreference( "pluginsActifs", liste)
self.preferences.sauvegarderConfiguration()
def info():
choice=''
while choice!='r' and choice!='R':
header ('','','Credits & license')
print "\t\t\tGNU GENERAL PUBLIC LICENSE"
print "\t\t\tVersion 2, June 1991"
print ""
print ""
print ""
print "\t\t\tDéveloppeurs :"
print "\t\t\t\t- chaoswizard"
print "\t\t\t\t- ggauthier.ggl"
print "\t\t\t\t"
print "\t\t\tDéveloppeur CLI :"
print "\t\t\t\ttvelter"
print ""
print "\t\t\tPlugins :"
print "\t\t\t\tBmD_Online"
print ""
print ""
footer()
if choice=='q' or choice=='Q':
quitter()
choice=getch()
def quitter():
#quitter program apres confirmation utilisateur
choice = ""
if not choice :
os.system(['clear','cls'][os.name == 'nt'])
sys.exit()
header ('','Quitter ?','')
print "\n\n\n\n\n\t\tAre you sure you want to quit ? (y/n)"
choice=getch()
if choice=='y' or choice=='Y':
os.system(['clear','cls'][os.name == 'nt'])
sys.exit()
elif choice!='y' and choice!='Y':
os.system(['clear','cls'][os.name == 'nt'])
header ('','Quitter ?','')
print "\n\n\n\n\n\t\tRetour a l'interface du programme"
print "#"
time.sleep(1)
print "#"
os.system(['clear','cls'][os.name == 'nt'])
# @param time: duree d'affichage du message d'attente
def wait(duree):
#Affichage d'un message d'attente pendant le chargement des infos ou le telechargmeent des fichiers
# Fenetre d'attente
os.system(['clear','cls'][os.name == 'nt'])
print "Patientez pendant l'actualisation des informations"
#while get info not finished
for i in range(duree):
time.sleep(1)
print "#",
#os.system(['clear','cls'][os.name == 'nt'])
| Python |
class getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = getch()
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
########
# Code #
########
# RegEx de decoupage d'un lien RTMP
RTMP_URL_PATTERN = re.compile("(?P<scheme>[^:]*)://(?P<host>[^/^:]*):{0,1}(?P<port>[^/]*)/(?P<app>.*?)/(?P<playpath>\w*?\:.*)", re.DOTALL)
## Fonction qui transforme un lien RTMP en commande rtmpdump
# @param url URL RTMP a transformer
# @return Commande rtmpdump obtenue
def urlToRtmpdump( url ):
match = re.match( RTMP_URL_PATTERN, url )
comand = ""
if match != None:
comand = "rtmpdump --host %host% --port %port% --protocol %scheme% --app %app% --playpath %playpath%"
comand = comand.replace( "%scheme%", match.group( "scheme" ) ).replace( "%host%", match.group( "host" ) ).replace( "%app%", match.group( "app" ) ).replace( "%playpath%", match.group( "playpath" ) )
if( match.group( "port" ) != "" ):
comand = comand.replace( "%port%", match.group( "port" ) )
elif( url[ :6 ] == "rtmpte" ):
comand = comand.replace( "%port%", "80" )
elif( url[ :5 ] == "rtmpe" ):
comand = comand.replace( "%port%", "1935" )
elif( url[ :5 ] == "rtmps" ):
comand = comand.replace( "%port%", "443" )
elif( url[ :5 ] == "rtmpt" ):
comand = comand.replace( "%port%", "80" )
else:
comand = comand.replace( "%port%", "1935" )
else:
comand = "rtmpdump -r " + url
return comand
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'TvDownloaderPluzzWidget.ui'
#
# Created: Thu Jan 13 22:07:19 2011
# by: PyQt4 UI code generator 4.7.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_TvDownloaderPluzzWidget(object):
def setupUi(self, TvDownloaderPluzzWidget):
TvDownloaderPluzzWidget.setObjectName("TvDownloaderPluzzWidget")
TvDownloaderPluzzWidget.resize(760, 540)
self.gridLayoutWidget = QtGui.QWidget(TvDownloaderPluzzWidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 741, 521))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout_TV = QtGui.QGridLayout(self.gridLayoutWidget)
self.gridLayout_TV.setObjectName("gridLayout_TV")
self.pushButton_France2 = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_France2.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_France2.setMouseTracking(False)
self.pushButton_France2.setFocusPolicy(QtCore.Qt.TabFocus)
self.pushButton_France2.setAutoFillBackground(False)
self.pushButton_France2.setText("France 2")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("img/02_France2_256x256.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_France2.setIcon(icon)
self.pushButton_France2.setIconSize(QtCore.QSize(128, 128))
self.pushButton_France2.setObjectName("pushButton_France2")
self.gridLayout_TV.addWidget(self.pushButton_France2, 0, 0, 1, 1)
self.pushButton_France3 = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_France3.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_France3.setMouseTracking(False)
self.pushButton_France3.setFocusPolicy(QtCore.Qt.TabFocus)
self.pushButton_France3.setAutoFillBackground(False)
self.pushButton_France3.setText("France 3")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("img/03_France3_256x256.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_France3.setIcon(icon1)
self.pushButton_France3.setIconSize(QtCore.QSize(128, 128))
self.pushButton_France3.setObjectName("pushButton_France3")
self.gridLayout_TV.addWidget(self.pushButton_France3, 0, 1, 1, 1)
self.pushButton_France5 = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_France5.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_France5.setMouseTracking(False)
self.pushButton_France5.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_France5.setAutoFillBackground(False)
self.pushButton_France5.setText("France 5")
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("img/05_France5_256x256.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_France5.setIcon(icon2)
self.pushButton_France5.setIconSize(QtCore.QSize(128, 128))
self.pushButton_France5.setObjectName("pushButton_France5")
self.gridLayout_TV.addWidget(self.pushButton_France5, 1, 0, 1, 1)
self.pushButton_FranceO = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_FranceO.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_FranceO.setMouseTracking(False)
self.pushButton_FranceO.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_FranceO.setAutoFillBackground(False)
self.pushButton_FranceO.setText("France O")
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap("img/19_FranceO_256x256.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_FranceO.setIcon(icon3)
self.pushButton_FranceO.setIconSize(QtCore.QSize(128, 128))
self.pushButton_FranceO.setObjectName("pushButton_FranceO")
self.gridLayout_TV.addWidget(self.pushButton_FranceO, 1, 1, 1, 1)
self.pushButton_France4 = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_France4.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_France4.setMouseTracking(False)
self.pushButton_France4.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_France4.setAutoFillBackground(False)
self.pushButton_France4.setText("France 4")
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap("img/14_France4_256x256.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_France4.setIcon(icon4)
self.pushButton_France4.setIconSize(QtCore.QSize(128, 128))
self.pushButton_France4.setObjectName("pushButton_France4")
self.gridLayout_TV.addWidget(self.pushButton_France4, 0, 2, 1, 1)
self.pushButton_Back = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_Back.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_Back.setMouseTracking(False)
self.pushButton_Back.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_Back.setAutoFillBackground(False)
self.pushButton_Back.setText("Retour")
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap("ico/gtk-go-back.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_Back.setIcon(icon5)
self.pushButton_Back.setIconSize(QtCore.QSize(128, 128))
self.pushButton_Back.setObjectName("pushButton_Back")
self.gridLayout_TV.addWidget(self.pushButton_Back, 1, 2, 1, 1)
self.retranslateUi(TvDownloaderPluzzWidget)
QtCore.QObject.connect(self.pushButton_Back, QtCore.SIGNAL("clicked()"), TvDownloaderPluzzWidget.close)
QtCore.QMetaObject.connectSlotsByName(TvDownloaderPluzzWidget)
def retranslateUi(self, TvDownloaderPluzzWidget):
TvDownloaderPluzzWidget.setWindowTitle(QtGui.QApplication.translate("TvDownloaderPluzzWidget", "Form", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
TvDownloaderPluzzWidget = QtGui.QWidget()
ui = Ui_TvDownloaderPluzzWidget()
ui.setupUi(TvDownloaderPluzzWidget)
TvDownloaderPluzzWidget.show()
sys.exit(app.exec_())
| Python |
from PyQt4 import QtGui, QtCore
from TvDownloaderSitesWidgetView import Ui_TvDownloaderSitesWidget
class TvDownloaderSitesWidgetController(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self)
self.mainWindow = parent
self.ui = Ui_TvDownloaderSitesWidget()
self.ui.setupUi(self)
# Connect the events
self.connect(self.ui.pushButton_Arte, QtCore.SIGNAL('clicked()'), self.arteClicked)
self.connect(self.ui.pushButton_Canal, QtCore.SIGNAL('clicked()'), self.canalClicked)
self.connect(self.ui.pushButton_M6Replay, QtCore.SIGNAL('clicked()'), self.m6Clicked)
self.connect(self.ui.pushButton_Pluzz, QtCore.SIGNAL('clicked()'), self.pluzzClicked)
self.connect(self.ui.pushButton_W9Replay, QtCore.SIGNAL('clicked()'), self.w9Clicked)
def arteClicked(self):
print 'TvDownloaderSitesWidgetController>> arteClicked'
def canalClicked(self):
print 'TvDownloaderSitesWidgetController>> canalClicked'
def m6Clicked(self):
print 'TvDownloaderSitesWidgetController>> m6Clicked'
def pluzzClicked(self):
print 'TvDownloaderSitesWidgetController>> pluzzClicked'
self.mainWindow.updateCentralWidget('site_pluzz')
def w9Clicked(self):
print 'TvDownloaderSitesWidgetController>> w9Clicked' | Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'TvDownloaderMainWindow.ui'
#
# Created: Thu Jan 13 22:07:18 2011
# by: PyQt4 UI code generator 4.7.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_TvDownloaderMainWindow(object):
def setupUi(self, TvDownloaderMainWindow):
TvDownloaderMainWindow.setObjectName("TvDownloaderMainWindow")
TvDownloaderMainWindow.resize(800, 600)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("ico/TVDownloader.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
TvDownloaderMainWindow.setWindowIcon(icon)
self.centralwidget = QtGui.QWidget(TvDownloaderMainWindow)
self.centralwidget.setObjectName("centralwidget")
self.widget = QtGui.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(20, 5, 760, 540))
self.widget.setObjectName("widget")
TvDownloaderMainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(TvDownloaderMainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
self.menubar.setObjectName("menubar")
self.menuFichier = QtGui.QMenu(self.menubar)
self.menuFichier.setObjectName("menuFichier")
self.menuEdition = QtGui.QMenu(self.menubar)
self.menuEdition.setObjectName("menuEdition")
self.menuAide = QtGui.QMenu(self.menubar)
self.menuAide.setObjectName("menuAide")
TvDownloaderMainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(TvDownloaderMainWindow)
self.statusbar.setObjectName("statusbar")
TvDownloaderMainWindow.setStatusBar(self.statusbar)
self.actionQuit = QtGui.QAction(TvDownloaderMainWindow)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("ico/gtk-quit.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionQuit.setIcon(icon1)
self.actionQuit.setMenuRole(QtGui.QAction.QuitRole)
self.actionQuit.setIconVisibleInMenu(True)
self.actionQuit.setObjectName("actionQuit")
self.actionAbout = QtGui.QAction(TvDownloaderMainWindow)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("ico/gtk-about.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionAbout.setIcon(icon2)
self.actionAbout.setIconVisibleInMenu(True)
self.actionAbout.setObjectName("actionAbout")
self.actionUpdatePlugins = QtGui.QAction(TvDownloaderMainWindow)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap("ico/gtk-refresh.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionUpdatePlugins.setIcon(icon3)
self.actionUpdatePlugins.setIconVisibleInMenu(True)
self.actionUpdatePlugins.setObjectName("actionUpdatePlugins")
self.actionPreferences = QtGui.QAction(TvDownloaderMainWindow)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap("ico/gtk-preferences.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionPreferences.setIcon(icon4)
self.actionPreferences.setIconVisibleInMenu(True)
self.actionPreferences.setObjectName("actionPreferences")
self.menuFichier.addAction(self.actionQuit)
self.menuEdition.addAction(self.actionUpdatePlugins)
self.menuEdition.addAction(self.actionPreferences)
self.menuAide.addAction(self.actionAbout)
self.menubar.addAction(self.menuFichier.menuAction())
self.menubar.addAction(self.menuEdition.menuAction())
self.menubar.addAction(self.menuAide.menuAction())
self.retranslateUi(TvDownloaderMainWindow)
QtCore.QMetaObject.connectSlotsByName(TvDownloaderMainWindow)
def retranslateUi(self, TvDownloaderMainWindow):
TvDownloaderMainWindow.setWindowTitle(QtGui.QApplication.translate("TvDownloaderMainWindow", "TvDownloader", None, QtGui.QApplication.UnicodeUTF8))
self.menuFichier.setTitle(QtGui.QApplication.translate("TvDownloaderMainWindow", "Fichier", None, QtGui.QApplication.UnicodeUTF8))
self.menuEdition.setTitle(QtGui.QApplication.translate("TvDownloaderMainWindow", "Edition", None, QtGui.QApplication.UnicodeUTF8))
self.menuAide.setTitle(QtGui.QApplication.translate("TvDownloaderMainWindow", "Aide", None, QtGui.QApplication.UnicodeUTF8))
self.actionQuit.setText(QtGui.QApplication.translate("TvDownloaderMainWindow", "Quitter", None, QtGui.QApplication.UnicodeUTF8))
self.actionQuit.setShortcut(QtGui.QApplication.translate("TvDownloaderMainWindow", "Ctrl+Q", None, QtGui.QApplication.UnicodeUTF8))
self.actionAbout.setText(QtGui.QApplication.translate("TvDownloaderMainWindow", "A propos", None, QtGui.QApplication.UnicodeUTF8))
self.actionUpdatePlugins.setText(QtGui.QApplication.translate("TvDownloaderMainWindow", "Mise à jour des plugins", None, QtGui.QApplication.UnicodeUTF8))
self.actionUpdatePlugins.setShortcut(QtGui.QApplication.translate("TvDownloaderMainWindow", "Ctrl+U", None, QtGui.QApplication.UnicodeUTF8))
self.actionPreferences.setText(QtGui.QApplication.translate("TvDownloaderMainWindow", "Préférences", None, QtGui.QApplication.UnicodeUTF8))
self.actionPreferences.setShortcut(QtGui.QApplication.translate("TvDownloaderMainWindow", "Ctrl+P", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
TvDownloaderMainWindow = QtGui.QMainWindow()
ui = Ui_TvDownloaderMainWindow()
ui.setupUi(TvDownloaderMainWindow)
TvDownloaderMainWindow.show()
sys.exit(app.exec_())
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'TvDownloaderSitesWidget.ui'
#
# Created: Thu Jan 13 22:07:19 2011
# by: PyQt4 UI code generator 4.7.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_TvDownloaderSitesWidget(object):
def setupUi(self, TvDownloaderSitesWidget):
TvDownloaderSitesWidget.setObjectName("TvDownloaderSitesWidget")
TvDownloaderSitesWidget.resize(760, 540)
self.gridLayoutWidget = QtGui.QWidget(TvDownloaderSitesWidget)
self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 741, 521))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout_TV = QtGui.QGridLayout(self.gridLayoutWidget)
self.gridLayout_TV.setObjectName("gridLayout_TV")
self.pushButton_Arte = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_Arte.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_Arte.setMouseTracking(False)
self.pushButton_Arte.setFocusPolicy(QtCore.Qt.TabFocus)
self.pushButton_Arte.setAutoFillBackground(False)
self.pushButton_Arte.setText("Arte")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("img/07_ARTE_256x256.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_Arte.setIcon(icon)
self.pushButton_Arte.setIconSize(QtCore.QSize(128, 128))
self.pushButton_Arte.setObjectName("pushButton_Arte")
self.gridLayout_TV.addWidget(self.pushButton_Arte, 0, 0, 1, 1)
self.pushButton_Canal = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_Canal.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_Canal.setMouseTracking(False)
self.pushButton_Canal.setFocusPolicy(QtCore.Qt.TabFocus)
self.pushButton_Canal.setAutoFillBackground(False)
self.pushButton_Canal.setText("Canal+")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("img/04_Canal+_256x256.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_Canal.setIcon(icon1)
self.pushButton_Canal.setIconSize(QtCore.QSize(128, 128))
self.pushButton_Canal.setObjectName("pushButton_Canal")
self.gridLayout_TV.addWidget(self.pushButton_Canal, 0, 1, 1, 1)
self.pushButton_Pluzz = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_Pluzz.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_Pluzz.setMouseTracking(False)
self.pushButton_Pluzz.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_Pluzz.setAutoFillBackground(False)
self.pushButton_Pluzz.setText("Pluzz")
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("img/Pluzz_470x318.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_Pluzz.setIcon(icon2)
self.pushButton_Pluzz.setIconSize(QtCore.QSize(128, 128))
self.pushButton_Pluzz.setObjectName("pushButton_Pluzz")
self.gridLayout_TV.addWidget(self.pushButton_Pluzz, 1, 0, 1, 1)
self.pushButton_W9Replay = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_W9Replay.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_W9Replay.setMouseTracking(False)
self.pushButton_W9Replay.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_W9Replay.setAutoFillBackground(False)
self.pushButton_W9Replay.setText("W9 Replay")
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap("img/W9_Replay_220x122.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_W9Replay.setIcon(icon3)
self.pushButton_W9Replay.setIconSize(QtCore.QSize(128, 128))
self.pushButton_W9Replay.setObjectName("pushButton_W9Replay")
self.gridLayout_TV.addWidget(self.pushButton_W9Replay, 1, 1, 1, 1)
self.pushButton_M6Replay = QtGui.QPushButton(self.gridLayoutWidget)
self.pushButton_M6Replay.setCursor(QtCore.Qt.PointingHandCursor)
self.pushButton_M6Replay.setMouseTracking(False)
self.pushButton_M6Replay.setFocusPolicy(QtCore.Qt.NoFocus)
self.pushButton_M6Replay.setAutoFillBackground(False)
self.pushButton_M6Replay.setText("M6 Replay")
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap("img/M6_Replay_450x295.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_M6Replay.setIcon(icon4)
self.pushButton_M6Replay.setIconSize(QtCore.QSize(128, 128))
self.pushButton_M6Replay.setObjectName("pushButton_M6Replay")
self.gridLayout_TV.addWidget(self.pushButton_M6Replay, 0, 2, 1, 1)
self.retranslateUi(TvDownloaderSitesWidget)
QtCore.QMetaObject.connectSlotsByName(TvDownloaderSitesWidget)
def retranslateUi(self, TvDownloaderSitesWidget):
TvDownloaderSitesWidget.setWindowTitle(QtGui.QApplication.translate("TvDownloaderSitesWidget", "Form", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
TvDownloaderSitesWidget = QtGui.QWidget()
ui = Ui_TvDownloaderSitesWidget()
ui.setupUi(TvDownloaderSitesWidget)
TvDownloaderSitesWidget.show()
sys.exit(app.exec_())
| Python |
from PyQt4 import QtGui, QtCore
from TvDownloaderPluzzWidgetView import Ui_TvDownloaderPluzzWidget
class TvDownloaderPluzzWidgetController(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self)
self.mainWindow = parent
self.ui = Ui_TvDownloaderPluzzWidget()
self.ui.setupUi(self)
# Connect the events
self.connect(self.ui.pushButton_France2, QtCore.SIGNAL('clicked()'), self.france2Clicked)
self.connect(self.ui.pushButton_France3, QtCore.SIGNAL('clicked()'), self.france3Clicked)
self.connect(self.ui.pushButton_France4, QtCore.SIGNAL('clicked()'), self.france4Clicked)
self.connect(self.ui.pushButton_France5, QtCore.SIGNAL('clicked()'), self.france5Clicked)
self.connect(self.ui.pushButton_FranceO, QtCore.SIGNAL('clicked()'), self.franceOClicked)
self.connect(self.ui.pushButton_Back, QtCore.SIGNAL('clicked()'), self.backClicked)
def france2Clicked(self):
print 'TvDownloaderPluzzWidgetController>> france2 clicked'
def france3Clicked(self):
print 'TvDownloaderPluzzWidgetController>> france3 clicked'
def france4Clicked(self):
print 'TvDownloaderPluzzWidgetController>> france4 clicked'
def france5Clicked(self):
print 'TvDownloaderPluzzWidgetController>> france5 clicked'
def franceOClicked(self):
print 'TvDownloaderPluzzWidgetController>> franceO clicked'
def backClicked(self):
print 'TvDownloaderPluzzWidgetController>> franceO clicked'
self.mainWindow.updateCentralWidget('back') | Python |
from PyQt4 import QtGui, QtCore
from GUI.AProposDialog import AProposDialog
from GUI.PreferencesDialog import PreferencesDialog
from GUI.UpdateManagerDialog import UpdateManagerDialog
from TvDownloaderMainWindowView import Ui_TvDownloaderMainWindow
from TvDownloaderSitesWidgetController import TvDownloaderSitesWidgetController
from TvDownloaderPluzzWidgetController import TvDownloaderPluzzWidgetController
class TvDownloaderMainWindowController(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# Load the View
self.ui = Ui_TvDownloaderMainWindow()
self.ui.setupUi(self)
# Connect the HMI Events
self.connect(self.ui.actionQuit, QtCore.SIGNAL('triggered()'), self.close)
self.connect(self.ui.actionUpdatePlugins, QtCore.SIGNAL('triggered()'), self.openUpdatePluginsWindow)
self.connect(self.ui.actionPreferences, QtCore.SIGNAL('triggered()'), self.openPreferencesWindow)
self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'), self.openAboutDialog)
# Define the other dialogs
self.updatePluginsDlg = None
self.preferencesDlg = None
self.aboutDlg = None
# Init the main widget
self.previousWidgetID = 'main_menu'
self.updateCentralWidget(self.previousWidgetID)
def updateCentralWidget(self, strWidgetID):
if strWidgetID == 'main_menu':
self.setCentralWidget(TvDownloaderSitesWidgetController(self))
elif strWidgetID == "site_arte":
print 'TvDownloaderMainWindowController>> display site Arte'
elif strWidgetID == "site_canal":
print 'TvDownloaderMainWindowController>> display site Canal+'
elif strWidgetID == "site_m6replay":
print 'TvDownloaderMainWindowController>> display site M6Replay'
elif strWidgetID == "site_pluzz":
print 'TvDownloaderMainWindowController>> display site Pluzz'
self.setCentralWidget(TvDownloaderPluzzWidgetController(self))
elif strWidgetID == "site_w9replay":
print 'TvDownloaderMainWindowController>> display site W9'
elif strWidgetID == 'back':
print 'TvDownloaderMainWindowController>> back'
self.updateCentralWidget(self.previousWidgetID)
def openUpdatePluginsWindow(self):
if self.updatePluginsDlg == None:
self.updatePluginsDlg = UpdateManagerDialog(self)
self.updatePluginsDlg.afficher()
def openPreferencesWindow(self):
if self.preferencesDlg == None:
self.preferencesDlg = PreferencesDialog(self)
self.preferencesDlg.afficher()
def openAboutDialog(self):
if self.aboutDlg == None:
self.aboutDlg = AProposDialog()
self.aboutDlg.show()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
win = TvDownloaderMainWindowController()
win.show()
sys.exit(app.exec_()) | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import logging
import optparse
import os
import sys
import Constantes
#
# Entree du programme
#
if __name__ == "__main__" :
# On se deplace dans le repertoire de travail (pas necessaire sous Windows)
if( not Constantes.OS_WINDOWS ):
# On se deplace dans le repertoire de travail du logciel
repertoireTravail = os.path.dirname( os.path.abspath( __file__ ) )
sys.path.insert( 0, repertoireTravail )
os.chdir( repertoireTravail )
# Options a parser
parser = optparse.OptionParser()
parser.add_option( "-v", "--verbose",
action = "store_true", dest = "verbose", default = False,
help = "Affiche informations dans le terminal" )
parser.add_option( "-c", "--cli",
action = "store_true", dest = "cli", default = False,
help = "Affiche la version CLI" )
parser.add_option( "-d", "--dialog",
action = "store_true", dest = "dialog", default = False,
help = u"Affiche la version Dialog (en cours de développement)" )
parser.add_option( "-g", "--genererXML",
action = "store_true", dest = "genererXML", default = False,
help = u"Génère le fichier XML qui decrit les plugins" )
options, args = parser.parse_args()
# On a active le mode verbeux ?
logger = logging.getLogger( __name__ )
console = logging.StreamHandler( sys.stdout )
if( options.verbose ):
logger.setLevel( logging.DEBUG )
console.setLevel( logging.DEBUG )
else:
logger.setLevel( logging.ERROR )
console.setLevel( logging.ERROR )
console.setFormatter( logging.Formatter( '%(levelname)-7s %(name)s : %(message)s' ) )
logger.addHandler( console )
# On veut generer le fichier XML qui decrit les plugins
if( options.genererXML ):
import UpdateManager
UpdateManager.UpdateManager.creerXML()
sys.exit( 0 )
# On met en place les repertoires de travail du logiciel
repertoires = [ Constantes.REPERTOIRE_CACHE, \
Constantes.REPERTOIRE_CONFIGURATION, \
Constantes.REPERTOIRE_LOGS, \
Constantes.REPERTOIRE_PLUGIN_PERSO ]
for repertoire in repertoires:
if( not os.path.isdir( repertoire ) ):
logger.info( "création du répertoire %s" %( repertoire ) )
os.makedirs( repertoire )
# On demarre le CLI ou le GUI ?
if( options.cli == False and options.dialog == False ):
# On importe les fichiers necessaires pour le GUI
try:
from PyQt4 import QtGui, QtCore
except ImportError:
logger.critical( "ouuupppss : il vous faut PyQt4 pour pouvoir utiliser ce programme..." )
sys.exit( 1 )
# from GUI.MainWindow import MainWindow
from GUINextGen.PyQt.TvDownloaderMainWindowController import TvDownloaderMainWindowController
# On creer l'interface graphique
# app = QtGui.QApplication( sys.argv )
# window = MainWindow()
# window.show()
# sys.exit( app.exec_() )
app = QtGui.QApplication(sys.argv)
MainWindow = TvDownloaderMainWindowController()
MainWindow.show()
sys.exit(app.exec_())
elif( options.cli == True ):
from CLI.cli import cli
cli()
else:
from CLIDialog.CLIDialog import CLIDialog
CLIDialog()
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import httplib,re
from random import choice
from APIPrive import APIPrive
from urlparse import urlparse
from traceback import print_exc
from Navigateur import Navigateur
##########
# Classe #
##########
## Classe rassemblant des méthodes utils et nécessaire aux plugins.
#
# Cette classe fournis des méthodes permattant de facilité la création d'un plugin. Elle est pour l'instant peu fournis mais a pour but d'être étoffé avec le temps et la possible augmentation de fonctionnalité possible des plugins.
# Elle contient aussi des méthodes permettant de dialoguer avec le programme.
class API(APIPrive):
## Instance utilisé par le programme
INSTANCE = None
## Constructeur.
# Ne pas utiliser.
# @param self l'objet courant
def __init__( self ):
self.navigateur = Navigateur()
APIPrive.__init__( self )
if API.INSTANCE != None:
raise Exception("API est déjà instancier")
## Renvoie l'instance d'API
# @return l'instance d'API
@staticmethod
def getInstance():
"""Renvoie l'instance de l'API"""
return API.INSTANCE
## Récupère une page web sur internet et remplace les caractères spéciaux (code HTML ou ISO).
# @param self le plugin courant
# @param url l'url de la page web
# @return la page web sous forme d'une chaîne ou la chaîne vide en cas d'échec
def getPage(self, url):
return self.navigateur.getPage( url )
#~
#~ #Vérification de l'url
#~ match = re.match(API.PATTERN_URL, url)
#~ if match == None:
#~ print "API.getPage(): url invalide."
#~ return ""
#~
#~ #Téléchargement et décompression si néscessaire
#~ try:
#~ connexion = httplib.HTTPConnection(match.group(1), timeout=APIPrive.HTTP_TIMEOUT)
#~
#~ heads = {"Accept-Encoding":"deflate,gzip",
#~ "Accept-Charset":"iso-8859-5, utf-8",
#~ "User-Agent":choice(APIPrive.USER_AGENT)}
#~ connexion.request("GET", match.group(2), headers=heads)
#~ reponse = connexion.getresponse()
#~ if reponse == None:
#~ print "API.getPage(): erreur de téléchargement."
#~ return ""
#~ return self.reponseHttpToUTF8(reponse)
#~ except Exception, ex:
#~ print "API.getPage(): erreur de téléchargement.",ex
#~ print_exc()
#~ return ""
def getPicture( self, url ):
return self.navigateur.getPicture( url )
## Récupère des pages webs sur internet et remplace les caractères spéciaux (code HTML ou ISO). Cette méthode reste connecté au serveur si il y a plusieurs page à y télécharger, elle est plus rapide que plusieurs appel à #getPage.
# @param self le plugin courant
# @param urls une liste d'url des pages à télécharger
# @return un dictionnaire avec comme clé les urls et comme valeur les pages sous forme de chaîne
def getPages(self, urls):
reponses = self.navigateur.getPages( urls )
return reponses
#~ reponses = {}
#~ for url in urls:
#~ reponses[ url ] = self.navigateur.getPage( url )
#~ reponses = {}
#~ connexions = {}
#~ user = choice(APIPrive.USER_AGENT)
#~ for url in urls:
#~ parse = urlparse(url)
#~ query = parse.query
#~ if query != "":
#~ query = "?"+query
#~ path = parse.path
#~ if path == "":
#~ path = "/"
#~
#~ requette = path+query
#~ serveur= parse.netloc
#~
#~ try:
#~ connexion = None
#~ if not connexions.has_key(serveur):
#~ connexion = httplib.HTTPConnection(serveur, timeout=APIPrive.HTTP_TIMEOUT)
#~ connexion.connect()
#~ connexions[serveur] = connexion
#~ else:
#~ connexion = connexions[serveur]
#~ connexion.putrequest("GET", requette)
#~ connexion.putheader("Connexion", "Keep-alive")
#~ connexion.putheader("Accept-Encoding", "deflate,gzip")
#~ connexion.putheader("Accept-Charset", "iso-8859-5, utf-8")
#~ connexion.putheader("User-Agent", user)
#~ connexion.endheaders()
#~
#~ reponse = connexion.getresponse()
#~ if reponse == None:
#~ print "API.getPages(): erreur de téléchargement de",url
#~ reponses[url] = ""
#~ else:
#~ reponses[url] = self.reponseHttpToUTF8(reponse)
#~ except Exception, ex:
#~ print "API.getPages(): erreur de téléchargement.",ex
#~ print_exc()
#~ for serveur in connexions.keys():
#~ connexions[serveur].close()
#~ return reponses
API.INSTANCE = API()
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
import pickle
import urllib
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class RTL( Plugin ):
listeEmissionsRegEx = re.compile( "<h4>(.+?)</h4>.*?podcast.rtl.fr/(.+?).xml", re.DOTALL )
def __init__( self):
Plugin.__init__( self, "RTL", "http://www.rtl.fr", 7 )
self.listeChaines = {} # Clef = nom chaine ; Valeur = { nom emission : lien fichier XML qui contient la liste des emissions }
self.derniereChaine = ""
if os.path.exists( self.fichierCache ):
self.listeChaines = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des chaines et des émissions..." )
# On remet a zero la liste des chaines
self.listeChaines.clear()
# On recupere la page qui contient les emissions
page = self.API.getPage( "http://www.rtl.fr/podcast.html" )
# On decoupe la page selon le nom des chaines
resultats = re.split( "<h3>([^<]+)</h3>", page )[ 1 : ]
for ( chaine, texteChaine ) in ( zip( resultats[ 0::2 ], resultats[ 1::2 ] ) ):
# On ajoute la chaine
self.listeChaines[ chaine ] = {}
# On extrait le nom des emissions et les liens des fichiers XML correspondants
resultatsEmissions = re.findall( self.listeEmissionsRegEx, texteChaine )
for res in resultatsEmissions:
nom = res[ 0 ]
lien = "http://podcast.rtl.fr/" + res[ 1 ] + ".xml"
self.listeChaines[ chaine ][ nom ] = lien
self.sauvegarderCache( self.listeChaines )
self.afficher( str( len( self.listeChaines ) ) + " chaines concervées." )
def listerChaines( self ):
print self.listeChaines
for chaine in self.listeChaines.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeChaines.has_key( chaine ) ):
self.derniereChaine = chaine
for emission in self.listeChaines[ chaine ].keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeChaines.has_key( self.derniereChaine ) ):
if( self.listeChaines[ self.derniereChaine ].has_key( emission ) ):
# On recupere le lien de la page de l'emission
lienPage = self.listeChaines[ self.derniereChaine ][ emission ]
# On recupere la page de l'emission
page = self.API.getPage( lienPage )
# On recupere le lien de l'image de l'emission
try :
urlImage = re.findall( '<image><url>([^<]+?)</url>', page )[ 0 ]
except :
urlImage = ""
# On extrait les emissions
resultats = re.findall( "media_url=([^\"]*)\"", page )
for res in resultats:
lien = urllib.unquote( res )
listeDates = re.findall( "(\d{4})/(\d{4})", lien )
if( listeDates == [] ): # Si on n'a pas pu extraire une date
date = "Inconnue"
else: # Si on a extrait une date
date = listeDates[ 0 ][ 1 ][ 2:4 ] + "-" + listeDates[ 0 ][ 1 ][ 0:2 ] + "-" + listeDates[ 0 ][ 0 ]
self.ajouterFichier( emission, Fichier( emission + " (" + date + ")", date, lien, urlImage = urlImage ) )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
import xml.sax
from Podcasts import PodcastsHandler
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class Europe1( Plugin ):
listeEmissionsRegEx = re.compile( "<td class=\"programme\">.+?<a href=\".+?>(.+?)</a>.+?podcasts/(.+?)\.xml", re.DOTALL )
listeFichiersRegEx = re.compile( 'media_url=([^"]*)".+?<!\[CDATA\[(.+?)\]\]>', re.DOTALL )
def __init__( self):
Plugin.__init__( self, "Europe1", "http://www.europe1.fr", 1 )
# On instancie la classe qui permet de charger les pages web
self.listeEmissions = {} # Clef = nom emission ; Valeur = lien fichier XML qui contient la liste des emissions
if os.path.exists( self.fichierCache ):
self.listeEmissions = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions..." )
# On remet a zero la liste des emissions
self.listeEmissions.clear()
# On recupere la page qui contient les emissions
for page in [ "http://www.europe1.fr/Radio/Podcasts/Semaine/", "http://www.europe1.fr/Radio/Podcasts/Samedi/", "http://www.europe1.fr/Radio/Podcasts/Dimanche/" ]:
pageEmissions = self.API.getPage( page )
# On extrait le nom des emissions et les liens des fichiers XML correspondants
resultats = re.findall( self.listeEmissionsRegEx, pageEmissions )
for res in resultats:
nom = res[ 0 ]
lien = "http://www.europe1.fr/podcasts/" + res[ 1 ] + ".xml"
self.listeEmissions[ nom ] = lien
self.sauvegarderCache( self.listeEmissions )
self.afficher( str( len( self.listeEmissions ) ) + " émissions concervées." )
def listerChaines( self ):
self.ajouterChaine(self.nom)
def listerEmissions( self, chaine ):
# On renvoit le resulat
liste = self.listeEmissions.keys()
liste.sort()
for emission in liste:
self.ajouterEmission(chaine, emission)
def listerFichiers( self, emission ):
if( emission != "" ):
if( emission in self.listeEmissions ):
# On recupere le lien de la page de l'emission
lienPage = self.listeEmissions[ emission ]
# On recupere la page de l'emission
page = self.API.getPage( lienPage )
# On extrait les fichiers
listeFichiers = []
handler = PodcastsHandler( listeFichiers )
try:
xml.sax.parseString( page, handler )
except:
return
# On ajoute les fichiers
for fichier in listeFichiers:
self.ajouterFichier( emission, fichier )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
# Coucou les amis
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import xml.sax
from xml.sax.handler import ContentHandler
import urllib
import unicodedata
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class Podcasts( Plugin ):
listePodcasts = { "Allo Cine" : { "Bandes Annonces" : "http://rss.allocine.fr/bandesannonces/ipod" },
"Casse Croute" : { "Recettes" : "http://www.casse-croute.fr/media/cassecroute.xml" },
"Game One" : { u"E-NEWS JEUX VIDEO" : "http://podcast13.streamakaci.com/xml/GAMEONE2.xml",
u"NEWS DU JT" : "http://podcast13.streamakaci.com/xml/GAMEONE6.xml",
u"LE TEST" : "http://podcast13.streamakaci.com/xml/GAMEONE3.xml",
u"PLAY HIT" : "http://podcast13.streamakaci.com/xml/GAMEONE9.xml",
u"RETRO GAME ONE" : "http://podcast13.streamakaci.com/xml/GAMEONE11.xml",
u"Funky Web" : "http://podcast13.streamakaci.com/xml/GAMEONE26.xml"
},
"No Watch" : { u"CINEFUZZ" : "http://feeds.feedburner.com/CineFuzz?format=xml",
u"GEEK Inc (SD)" : "http://feeds.feedburner.com/GeekInc?format=xml",
u"GEEk Inc (HD)" : "http://feeds.feedburner.com/GeekIncHD?format=xml",
u"S.C.U.D.S tv (SD)" : "http://feeds2.feedburner.com/scudstv?format=xml",
u"S.C.U.D.S tv (HD)" : "http://feeds2.feedburner.com/scudshd?format=xml",
u"Tonight On Mars (SD)" : "http://feeds2.feedburner.com/tonightonmars?format=xml",
u"Zapcast tv (SD)" : "http://feeds.feedburner.com/Zapcasttv?format=xml",
u"Zapcast tv (HD)" : "http://feeds.feedburner.com/Zapcasthd?format=xml"},
"i>TELE" : { "Le Journal" : "http://podcast12.streamakaci.com/iTELE/iTELElejournal.xml" },
"RMC" : { u"Bourdin & CO" : "http://podcast.rmc.fr/channel30/RMCInfochannel30.xml",
u"Coach Courbis" : "http://podcast.rmc.fr/channel33/RMCInfochannel33.xml",
u"De quoi je me mail" : "http://podcast.rmc.fr/channel35/RMCInfochannel35.xml",
u"Intégrale Foot Made in Di Meco" : "http://podcast.rmc.fr/channel192/RMCInfochannel192.xml",
u"JO Live du jour" : "http://podcast.rmc.fr/channel196/RMCInfochannel196.xml",
u"L'Afterfoot" : "http://podcast.rmc.fr/channel59/RMCInfochannel59.xml",
u"Lahaie, l'amour et vous" : "http://podcast.rmc.fr/channel51/RMCInfochannel51.xml",
u"La politique " : "http://podcast.rmc.fr/channel179/RMCInfochannel179.xml",
u"La quotidienne courses hippiques" : "http://podcast.rmc.fr/channel197/RMCInfochannel197.xml",
u"Larqué Foot" : "http://podcast.rmc.fr/channel53/RMCInfochannel53.xml",
u"Le Billet de Guimard" : "http://podcast.rmc.fr/channel210/RMCInfochannel210.xml",
u"L'économie" : "http://podcast.rmc.fr/channel178/RMCInfochannel178.xml",
u"Le Débat du jour" : "http://podcast.rmc.fr/channel211/RMCInfochannel211.xml",
u"Le Journal du jour" : "http://podcast.rmc.fr/channel39/RMCInfochannel39.xml",
u"Le Mercato Show" : "http://podcast.rmc.fr/channel213/RMCInfochannel213.xml",
u"Le Monde Hi-Tech" : "http://podcast.rmc.fr/channel31/RMCInfochannel31.xml",
u"Les courses RMC" : "http://podcast.rmc.fr/channel193/RMCInfochannel193.xml",
u"Les Experts F1" : "http://podcast.rmc.fr/channel191/RMCInfochannel191.xml",
u"Les GG et vous" : "http://podcast.rmc.fr/channel181/RMCInfochannel181.xml",
u"Les Grandes Gueules" : "http://podcast.rmc.fr/channel36/RMCInfochannel36.xml",
u"Les Paris RMC du samedi" : "http://podcast.rmc.fr/channel160/RMCInfochannel160.xml",
u"Le Top de l'After Foot" : "http://podcast.rmc.fr/channel174/RMCInfochannel174.xml",
u"Le top de Sportisimon" : "http://podcast.rmc.fr/channel188/RMCInfochannel188.xml",
u"Le Top rugby " : "http://podcast.rmc.fr/channel176/RMCInfochannel176.xml",
u"Le Tour du jour" : "http://podcast.rmc.fr/channel209/RMCInfochannel209.xml",
u"L'invité de Bourdin & Co" : "http://podcast.rmc.fr/channel38/RMCInfochannel38.xml",
u"L'invité de Captain Larqué" : "http://podcast.rmc.fr/channel175/RMCInfochannel175.xml",
u"L'invité de Luis" : "http://podcast.rmc.fr/channel170/RMCInfochannel170.xml",
u"Love conseil " : "http://podcast.rmc.fr/channel183/RMCInfochannel183.xml",
u"Luis Attaque" : "http://podcast.rmc.fr/channel40/RMCInfochannel40.xml",
u"Moscato Show" : "http://podcast.rmc.fr/channel131/RMCInfochannel131.xml",
u"Moscato Show " : "http://podcast.rmc.fr/channel190/RMCInfochannel190.xml",
u"Motors" : "http://podcast.rmc.fr/channel42/RMCInfochannel42.xml",
u"RMC première Le 5/7" : "http://podcast.rmc.fr/channel32/RMCInfochannel32.xml",
u"RMC Sport matin" : "http://podcast.rmc.fr/channel77/RMCInfochannel77.xml",
u"Sportisimon" : "http://podcast.rmc.fr/channel186/RMCInfochannel186.xml",
u"Vos Animaux" : "http://podcast.rmc.fr/channel48/RMCInfochannel48.xml",
u"Votre Auto" : "http://podcast.rmc.fr/channel50/RMCInfochannel50.xml",
u"Votre Jardin" : "http://podcast.rmc.fr/channel52/RMCInfochannel52.xml",
u"Votre Maison" : "http://podcast.rmc.fr/channel54/RMCInfochannel54.xml"
}
}
derniereChaine = ""
listeFichiers = []
def __init__( self):
Plugin.__init__( self, "Podcasts", "", 30 )
def rafraichir( self ):
pass # Rien a rafraichir ici...
def listerChaines( self ):
listeChaines = self.listePodcasts.keys()
listeChaines.sort()
for chaine in listeChaines:
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listePodcasts.has_key( chaine ) ):
self.derniereChaine = chaine
listeEmissions = self.listePodcasts[ chaine ].keys()
listeEmissions.sort()
for emission in listeEmissions:
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listePodcasts.has_key( self.derniereChaine ) ):
listeEmission = self.listePodcasts[ self.derniereChaine ]
if( listeEmission.has_key( emission ) ):
# On remet a 0 la liste des fichiers
del self.listeFichiers[ : ]
# On recupere la page de l'emission
page = urllib.urlopen( listeEmission[ emission ] )
page = page.read()
#~ page = self.API.getPage( listeEmission[ emission ] )
# Handler
handler = PodcastsHandler( self.listeFichiers )
# On parse le fichier xml
xml.sax.parseString( page, handler )
# On ajoute les fichiers
for fichier in self.listeFichiers:
self.ajouterFichier( emission, fichier )
#
# Parser XML pour les podcasts
#
## Classe qui permet de lire les fichiers XML de podcasts
class PodcastsHandler( ContentHandler ):
# Constructeur
# @param listeFichiers Liste des fichiers que le parser va remplir
def __init__( self, listeFichiers ):
# Liste des fichiers
self.listeFichiers = listeFichiers
# Url de l'image globale
self.urlImageGlobale = ""
# Initialisation des variables a Faux
self.isItem = False
self.isTitle = False
self.isDescription = False
self.isPubDate = False
self.isGuid = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "item" ):
self.isItem = True
self.titre = ""
self.date = ""
self.urlFichier = ""
self.urlImage = ""
self.description = ""
elif( name == "title" and self.isItem ):
self.isTitle = True
elif( name == "description" and self.isItem ):
self.isDescription = True
elif( name == "pubDate" and self.isItem ):
self.isPubDate = True
elif( name == "media:thumbnail" and self.isItem ):
self.urlImage = attrs.get( "url", "" )
elif( name == "media:content" and self.isItem ):
self.urlFichier = attrs.get( "url", "" )
elif( name == "guid" and self.isItem ):
self.isGuid = True
elif( name == "itunes:image" and not self.isItem ):
self.urlImageGlobale = attrs.get( "href", "" )
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
if( self.isTitle ):
self.titre += data
#~ self.isTitle = False
elif( self.isDescription ):
if( data.find( "<" ) == -1 ):
self.description += data
else:
self.isDescription = False
elif( self.isPubDate ):
self.date = data
self.isPubDate = False
elif( self.isGuid ):
self.urlFichier = data
self.isGuid = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "item" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( self.urlFichier )
# Si le fichier n'a pas d'image, on prend l'image globale
if( self.urlImage == "" ):
self.urlImage = self.urlImageGlobale
# On ajoute le fichier
self.listeFichiers.append( Fichier ( self.titre, self.date, self.urlFichier, self.titre + extension, self.urlImage, self.description ) )
self.isTitle = False
elif( name == "description" ):
self.isDescription = False
elif( name == "title" ):
self.isTitle = False
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
from Plugin import Plugin
from Fichier import Fichier
from urllib import quote
import re,unicodedata,datetime
##########
# Classe #
##########
class Pluzz( Plugin ):
"""Classe abstraite Plugin dont doit heriter chacun des plugins"""
listeChainesEmissionsUrl = "http://www.pluzz.fr/appftv/webservices/video/catchup/getListeAutocompletion.php?support=1"
listeChainesEmissionsPattern = re.compile("chaine_principale=\"(.*?)\".*?.\[CDATA\[(.*?)\]\]")
lienEmissionBaseUrl = "http://www.pluzz.fr/"
videoInfosBaseUrl = "http://www.pluzz.fr/appftv/webservices/video/getInfosVideo.php?src=cappuccino&video-type=simple&template=ftvi&template-format=complet&id-externe="
videoTitrePattern = re.compile("titre.public><.\[CDATA\[(.*?)]]>", re.DOTALL)
videoNomPattern = re.compile("nom><.\[CDATA\[(.*?)]]>", re.DOTALL)
videoCheminPattern = re.compile("chemin><!\[CDATA\[(.*?)]]>", re.DOTALL)
videoDatePattern = re.compile("date><!\[CDATA\[(.*?)]]>", re.DOTALL)
def __init__( self):
Plugin.__init__( self, "Pluzz", "http://www.pluzz.fr/")
cache = self.chargerCache()
if cache:
self.listeChaines = cache
else:
self.listeChaines = {}
def listerOptions(self):
self.optionBouleen("france2", "Afficher France 2", True)
t = []
if self.listeChaines.has_key("france2"):
t = self.listeChaines["france2"]
t.sort()
self.optionChoixMultiple("emissionsfrance2", "Liste des émissions à afficher pour France 2", t, t)
self.optionBouleen("france3", "Afficher France 3", True)
t = []
if self.listeChaines.has_key("france3"):
t = self.listeChaines["france3"]
t.sort()
self.optionChoixMultiple("emissionsfrance3", "Liste des émissions à afficher pour France 3", t, t)
self.optionBouleen("france4", "Afficher France 4", True)
t = []
if self.listeChaines.has_key("france4"):
t = self.listeChaines["france4"]
t.sort()
self.optionChoixMultiple("emissionsfrance4", "Liste des émissions à afficher pour France 4", t, t)
self.optionBouleen("france5", "Afficher France 5", True)
t = []
if self.listeChaines.has_key("france5"):
t = self.listeChaines["france5"]
t.sort()
self.optionChoixMultiple("emissionsfrance2", "Liste des émissions à afficher pour France 5", t, t)
self.optionBouleen("franceo", "Afficher France O", True)
t = []
if self.listeChaines.has_key("franceo"):
t = self.listeChaines["franceo"]
t.sort()
self.optionChoixMultiple("emissionsfranceo", "Liste des émissions à afficher pour France O", t, t)
def rafraichir( self ):
self.listeChaines = {}
self.afficher("Récupération de la liste des émissions...")
for item in re.findall(self.listeChainesEmissionsPattern, self.API.getPage(self.listeChainesEmissionsUrl)):
if not(self.listeChaines.has_key(item[0])):
self.listeChaines[item[0]] = []
self.listeChaines[item[0]].append(item[1])
self.sauvegarderCache(self.listeChaines)
def getLienEmission(self, emission):
s = re.sub("[,: !/'\.]+", "-", emission).replace( ',', '' ).lower()
s = unicode( s, "utf8", "replace" )
s = unicodedata.normalize( 'NFD',s )
#~ return self.lienEmissionBaseUrl+unicodedata.normalize( 'NFD', s).encode( 'ascii','ignore' )+".html"
return self.lienEmissionBaseUrl+quote(s.encode( 'ascii','ignore' ))+".html"
def listerChaines( self ):
t = self.listeChaines.keys()
t.sort()
for chaine in t:
if self.getOption(chaine) == True:
self.ajouterChaine(chaine)
def listerEmissions( self, chaine ):
#~ t = []
#~ if self.listeChaines.has_key(chaine):
#~ t = self.listeChaines[chaine]
#~ t.sort()
t = self.getOption("emissions"+chaine)
if not(t):
t = []
if self.listeChaines.has_key(chaine):
t = self.listeChaines[chaine]
t.sort()
for emission in t:
self.ajouterEmission(chaine, emission)
def listerFichiers( self, emission ):
lien = self.getLienEmission(emission)
base = lien.replace(".html", "")
self.afficher("Récupération de la liste des fichiers pour \""+emission+"\"...")
dejaVue = []
nombre = 0
videos = re.findall("("+base+".+?.html)", self.API.getPage(lien));
if videos == None:
return
videos.append(lien)
for fichier in videos:
fichierInfosUrl_match = re.search(re.compile("info.francetelevisions.fr/\?id-video=(.+?)\"", re.DOTALL), self.API.getPage(fichier))
if fichierInfosUrl_match == None:
continue
fichierInfos = self.API.getPage(self.videoInfosBaseUrl+fichierInfosUrl_match.group(1))
titre = re.search(self.videoTitrePattern, fichierInfos)
if titre != None:
titre = titre.group(1)
else:
continue
nom = re.search(self.videoNomPattern, fichierInfos)
if nom != None:
nom = nom.group(1)
else:
continue
chemin = re.search(self.videoCheminPattern, fichierInfos)
if chemin != None:
chemin = chemin.group(1)
else:
continue
date = re.search(self.videoDatePattern, fichierInfos)
if date != None:
date = datetime.date.fromtimestamp(int(date.group(1))).strftime("%d/%m/%Y")
else:
continue
if titre in dejaVue:
continue
else:
dejaVue.append(titre)
lien = None
if( chemin.find( 'http' ) != -1 ):
lien = chemin + titre
elif( nom.find( 'wmv' ) != -1 ):
lien = "mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication" + chemin + nom
elif( nom.find( 'mp4' ) != -1 ):
lien = "rtmp://videozones-rtmp.francetv.fr/ondemand/mp4:cappuccino/publication" + chemin + nom
if not(lien):
continue
self.ajouterFichier(emission, Fichier( titre, date, lien ) )
nombre = nombre+1
self.afficher(str(nombre)+" fichiers trouvés.")
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class RadioFrance( Plugin ):
listeFichiersRegEx = re.compile( '<description>([^<]+?)</description>.+?podcast09/([^"]*\.mp3)"', re.DOTALL )
listeEmissionsFranceInter = { u"Allo la planète" : "http://radiofrance-podcast.net/podcast09/rss_10121.xml",
u"Au detour du monde" : "http://radiofrance-podcast.net/podcast09/rss_10039.xml",
u"Bons baisers de Manault" : "http://radiofrance-podcast.net/podcast09/rss_11160.xml",
u"Carnet de campagne" : "http://radiofrance-podcast.net/podcast09/rss_10205.xml",
u"carrefour de l'Eco" : "http://radiofrance-podcast.net/podcast09/rss_11292.xml",
u"C'est demain la veille" : "http://radiofrance-podcast.net/podcast09/rss_11264.xml",
u"CO2 mon Amour" : "http://radiofrance-podcast.net/podcast09/rss_10006.xml",
u"Comme on nous parle" : "http://radiofrance-podcast.net/podcast09/rss_11242.xml",
u"Daniel Morin" : "http://radiofrance-podcast.net/podcast09/rss_10906.xml",
u"Didier Porte" : "http://radiofrance-podcast.net/podcast09/rss_10907.xml",
u"ECLECTIK (dimanche)" : "http://radiofrance-podcast.net/podcast09/rss_10946.xml",
u"Eclectik (samedi)" : "http://radiofrance-podcast.net/podcast09/rss_17621.xml",
u"Esprit critique" : "http://radiofrance-podcast.net/podcast09/rss_10240.xml",
u"Et pourtant elle tourne" : "http://radiofrance-podcast.net/podcast09/rss_10269.xml",
u"Histoire de..." : "http://radiofrance-podcast.net/podcast09/rss_10919.xml",
u"LA BAS, SI J'Y SUIS" : "http://radiofrance-podcast.net/podcast09/rss_14288.xml",
u"La cellule de dégrisement" : "http://radiofrance-podcast.net/podcast09/rss_11259.xml",
u"la chronique anglaise de David LOWE" : "http://radiofrance-podcast.net/podcast09/rss_11345.xml",
u"La chronique de régis Mailhot" : "http://radiofrance-podcast.net/podcast09/rss_11335.xml",
u"La chronique de Vincent Roca" : "http://radiofrance-podcast.net/podcast09/rss_11336.xml",
u"La librairie francophone" : "http://radiofrance-podcast.net/podcast09/rss_18647.xml",
u"La nuit comme si" : "http://radiofrance-podcast.net/podcast09/rss_11254.xml",
u"La presse étrangère" : "http://radiofrance-podcast.net/podcast09/rss_11331.xml",
u"Le Cinq Six Trente" : "http://radiofrance-podcast.net/podcast09/rss_10915.xml",
u"L'économie autrement" : "http://radiofrance-podcast.net/podcast09/rss_11081.xml",
u"Le débat économique" : "http://radiofrance-podcast.net/podcast09/rss_18783.xml",
u"Le jeu des mille euros" : "http://radiofrance-podcast.net/podcast09/rss_10206.xml",
u"Le journal de l'économie" : "http://radiofrance-podcast.net/podcast09/rss_10980.xml",
u"le sept neuf du dimanche" : "http://radiofrance-podcast.net/podcast09/rss_10982.xml",
u"le sept neuf du samedi" : "http://radiofrance-podcast.net/podcast09/rss_10981.xml",
u"Les grandes nuits et les petits ..." : "http://radiofrance-podcast.net/podcast09/rss_11257.xml",
u"Les savanturiers" : "http://radiofrance-podcast.net/podcast09/rss_10908.xml",
u"Le Zapping de France Inter" : "http://radiofrance-podcast.net/podcast09/rss_10309.xml",
u"L'humeur de Didier Porte" : "http://radiofrance-podcast.net/podcast09/rss_11078.xml",
u"L'humeur de François Morel" : "http://radiofrance-podcast.net/podcast09/rss_11079.xml",
u"L'humeur de Stéphane Guillon" : "http://radiofrance-podcast.net/podcast09/rss_10692.xml",
u"L'humeur vagabonde" : "http://radiofrance-podcast.net/podcast09/rss_10054.xml",
u"Noctiluque" : "http://radiofrance-podcast.net/podcast09/rss_10208.xml",
u"Nocturne" : "http://radiofrance-podcast.net/podcast09/rss_10268.xml",
u"Nonobstant" : "http://radiofrance-podcast.net/podcast09/rss_10615.xml",
u"Nous autres" : "http://radiofrance-podcast.net/podcast09/rss_18633.xml",
u"Panique au Mangin palace" : "http://radiofrance-podcast.net/podcast09/rss_10128.xml",
u"panique au ministère psychique" : "http://radiofrance-podcast.net/podcast09/rss_10905.xml",
u"Parking de nuit" : "http://radiofrance-podcast.net/podcast09/rss_10136.xml",
u"Périphéries" : "http://radiofrance-podcast.net/podcast09/rss_10040.xml",
u"Service public" : "http://radiofrance-podcast.net/podcast09/rss_10207.xml",
u"Sous les étoiles exactement" : "http://radiofrance-podcast.net/podcast09/rss_10218.xml",
u"Studio théatre" : "http://radiofrance-podcast.net/podcast09/rss_10629.xml",
u"Système disque" : "http://radiofrance-podcast.net/podcast09/rss_10093.xml",
u"Un jour sur la toile" : "http://radiofrance-podcast.net/podcast09/rss_10274.xml",
u"Un livre sous le bras" : "http://radiofrance-podcast.net/podcast09/rss_10664.xml" }
listeEmissionsFranceInfo = { u"Il était une mauvaise foi" : "http://radiofrance-podcast.net/podcast09/rss_10951.xml",
u"La vie et vous, Le chemin de l'école" : "http://radiofrance-podcast.net/podcast09/rss_11077.xml",
u"Le bruit du net" : "http://radiofrance-podcast.net/podcast09/rss_11064.xml",
u"Le droit d'info" : "http://radiofrance-podcast.net/podcast09/rss_10986.xml",
u"Le sens de l'info" : "http://radiofrance-podcast.net/podcast09/rss_10586.xml",
u"Question d'argent" : "http://radiofrance-podcast.net/podcast09/rss_10556.xml",
u"Tout comprendre" : "http://radiofrance-podcast.net/podcast09/rss_11313.xml",
u"Tout et son contraire" : "http://radiofrance-podcast.net/podcast09/rss_11171.xml" }
listeEmissionsFranceBleu = { u"1999" : "http://radiofrance-podcast.net/podcast09/rss_11325.xml",
u"C'est bon à savoir" : "http://radiofrance-podcast.net/podcast09/rss_10337.xml",
u"Chanson d'Aqui" : "http://radiofrance-podcast.net/podcast09/rss_11298.xml",
u"Club Foot Marseille" : "http://radiofrance-podcast.net/podcast09/rss_11201.xml",
u"Côté Mer" : "http://radiofrance-podcast.net/podcast09/rss_10890.xml",
u"France Bleu Midi " : "http://radiofrance-podcast.net/podcast09/rss_11204.xml",
u"Histoire en Bretagne" : "http://radiofrance-podcast.net/podcast09/rss_10638.xml",
u"La science en question" : "http://radiofrance-podcast.net/podcast09/rss_10336.xml",
u"Les défis du Professeur Gersal" : "http://radiofrance-podcast.net/podcast09/rss_11263.xml",
u"Les Français parlent aux Français" : "http://radiofrance-podcast.net/podcast09/rss_11351.xml",
u"Les nouvelles archives de l étrange" : "http://radiofrance-podcast.net/podcast09/rss_11265.xml",
u"L'horoscope" : "http://radiofrance-podcast.net/podcast09/rss_10020.xml",
u"L'humeur de Fred Ballard" : "http://radiofrance-podcast.net/podcast09/rss_11317.xml",
u"Ligne d'expert" : "http://radiofrance-podcast.net/podcast09/rss_11023.xml",
u"On repeint la musique" : "http://radiofrance-podcast.net/podcast09/rss_11268.xml",
u"Planète Bleu" : "http://radiofrance-podcast.net/podcast09/rss_11031.xml",
u"Sul gouel ha bembez..." : "http://radiofrance-podcast.net/podcast09/rss_10312.xml",
u"Tour de France 2010" : "http://radiofrance-podcast.net/podcast09/rss_11355.xml" }
listeEmissionsFranceCulture = { u"Affinités électives" : "http://radiofrance-podcast.net/podcast09/rss_10346.xml",
u"A plus d'un titre" : "http://radiofrance-podcast.net/podcast09/rss_10466.xml",
u"avec ou sans rdv" : "http://radiofrance-podcast.net/podcast09/rss_10180.xml",
u"A voix nue" : "http://radiofrance-podcast.net/podcast09/rss_10351.xml",
u"Ca rime à quoi" : "http://radiofrance-podcast.net/podcast09/rss_10897.xml",
u"Carnet Nomade" : "http://radiofrance-podcast.net/podcast09/rss_10237.xml",
u"Caroline FOUREST" : "http://radiofrance-podcast.net/podcast09/rss_10725.xml",
u"Chanson boum" : "http://radiofrance-podcast.net/podcast09/rss_10975.xml",
u"Chronique de Caroline Eliacheff" : "http://radiofrance-podcast.net/podcast09/rss_10477.xml",
u"Chronique de Cécile Ladjali" : "http://radiofrance-podcast.net/podcast09/rss_11270.xml",
u"Chronique de Clémentine Autain" : "http://radiofrance-podcast.net/podcast09/rss_10714.xml",
u"CONCORDANCE DES TEMPS" : "http://radiofrance-podcast.net/podcast09/rss_16278.xml",
u"Conférences de Michel Onfray" : "http://radiofrance-podcast.net/podcast09/rss_11141.xml",
u"Continent sciences" : "http://radiofrance-podcast.net/podcast09/rss_16256.xml",
u"Controverses du progrès (les)" : "http://radiofrance-podcast.net/podcast09/rss_11055.xml",
u"Cultures D'Islam" : "http://radiofrance-podcast.net/podcast09/rss_10073.xml",
u"Des histoires à ma façon" : "http://radiofrance-podcast.net/podcast09/rss_11181.xml",
u"Des papous dans la tête" : "http://radiofrance-podcast.net/podcast09/rss_13364.xml",
u"Divers aspects de la pensée (...)" : "http://radiofrance-podcast.net/podcast09/rss_10344.xml",
u"Du grain à moudre" : "http://radiofrance-podcast.net/podcast09/rss_10175.xml",
u"Du jour au Lendemain" : "http://radiofrance-podcast.net/podcast09/rss_10080.xml",
u"En toute franchise" : "http://radiofrance-podcast.net/podcast09/rss_10898.xml",
u"'EPOPEE DE LA FRANCE LIBRE" : "http://radiofrance-podcast.net/podcast09/rss_11365.xml",
u"Foi et tradition" : "http://radiofrance-podcast.net/podcast09/rss_10492.xml",
u"For interieur" : "http://radiofrance-podcast.net/podcast09/rss_10266.xml",
u"HORS" : "http://radiofrance-podcast.net/podcast09/rss_11189.xml",
u"Jeux d'épreuves" : "http://radiofrance-podcast.net/podcast09/rss_10083.xml",
u"La chronique d'Alexandre Adler" : "http://radiofrance-podcast.net/podcast09/rss_18810.xml",
u"La chronique de d'Alain" : "http://radiofrance-podcast.net/podcast09/rss_18809.xml",
u"La chronique d'Olivier Duhamel" : "http://radiofrance-podcast.net/podcast09/rss_18811.xml",
u"LA FABRIQUE DE L'HUMAIN" : "http://radiofrance-podcast.net/podcast09/rss_11188.xml",
u"LA MARCHE DES SCIENCES" : "http://radiofrance-podcast.net/podcast09/rss_11193.xml",
u"La messe" : "http://radiofrance-podcast.net/podcast09/rss_10272.xml",
u"La nelle fabrique de l'histoire" : "http://radiofrance-podcast.net/podcast09/rss_10076.xml",
u"La rumeur du monde" : "http://radiofrance-podcast.net/podcast09/rss_10234.xml",
u"LA SUITE DANS LES IDEES" : "http://radiofrance-podcast.net/podcast09/rss_16260.xml",
u"L'ATELIER LITTERAIRE" : "http://radiofrance-podcast.net/podcast09/rss_11185.xml",
u"LA VIGNETTE" : "http://radiofrance-podcast.net/podcast09/rss_11199.xml",
u"Le bien commun" : "http://radiofrance-podcast.net/podcast09/rss_16279.xml",
u"L'économie en question o" : "http://radiofrance-podcast.net/podcast09/rss_10081.xml",
u"Le journal de 12h30" : "http://radiofrance-podcast.net/podcast09/rss_10059.xml",
u"Le journal de 18h" : "http://radiofrance-podcast.net/podcast09/rss_10060.xml",
u"Le journal de 22h" : "http://radiofrance-podcast.net/podcast09/rss_10061.xml",
u"Le journal de 7h" : "http://radiofrance-podcast.net/podcast09/rss_10055.xml",
u"Le journal de 8h" : "http://radiofrance-podcast.net/podcast09/rss_10057.xml",
u"Le magazine de la rédaction" : "http://radiofrance-podcast.net/podcast09/rss_10084.xml",
u"LE MARDI DES AUTEURS" : "http://radiofrance-podcast.net/podcast09/rss_11194.xml",
u"Le portrait du jour par Marc Krav" : "http://radiofrance-podcast.net/podcast09/rss_18812.xml",
u"Le regard d'Albert Jacquard" : "http://radiofrance-podcast.net/podcast09/rss_16496.xml",
u"Le rendez" : "http://radiofrance-podcast.net/podcast09/rss_10082.xml",
u"Le salon noir" : "http://radiofrance-podcast.net/podcast09/rss_10267.xml",
u"Les ateliers de création radio." : "http://radiofrance-podcast.net/podcast09/rss_10185.xml",
u"Les enjeux internationaux" : "http://radiofrance-podcast.net/podcast09/rss_13305.xml",
u"LES JEUDIS DE L'EXPO" : "http://radiofrance-podcast.net/podcast09/rss_11196.xml",
u"Les lundis de l'histoire" : "http://radiofrance-podcast.net/podcast09/rss_10193.xml",
u"Les matins de France Culture" : "http://radiofrance-podcast.net/podcast09/rss_10075.xml",
u"LES MERCREDIS DU THEATRE" : "http://radiofrance-podcast.net/podcast09/rss_11195.xml",
u"Les nv chemins de la connaissance" : "http://radiofrance-podcast.net/podcast09/rss_10467.xml",
u"LES PASSAGERS DE LA NUIT" : "http://radiofrance-podcast.net/podcast09/rss_11190.xml",
u"Les Pieds sur Terre" : "http://radiofrance-podcast.net/podcast09/rss_10078.xml",
u"L'esprit public" : "http://radiofrance-podcast.net/podcast09/rss_16119.xml",
u"LES RACINES DU CIEL" : "http://radiofrance-podcast.net/podcast09/rss_11200.xml",
u"LES RETOURS DU DIMANCHE" : "http://radiofrance-podcast.net/podcast09/rss_11186.xml",
u"LES VENDREDIS DE LA MUSIQUE" : "http://radiofrance-podcast.net/podcast09/rss_11197.xml",
u"L'oeil du larynx" : "http://radiofrance-podcast.net/podcast09/rss_10311.xml",
u"MACADAM PHILO" : "http://radiofrance-podcast.net/podcast09/rss_11198.xml",
u"Maison d'études" : "http://radiofrance-podcast.net/podcast09/rss_10182.xml",
u"Masse critique" : "http://radiofrance-podcast.net/podcast09/rss_10183.xml",
u"Mauvais Genres" : "http://radiofrance-podcast.net/podcast09/rss_10070.xml",
u"MEGAHERTZ" : "http://radiofrance-podcast.net/podcast09/rss_11182.xml",
u"METROPOLITAINS" : "http://radiofrance-podcast.net/podcast09/rss_16255.xml",
u"Orthodoxie" : "http://radiofrance-podcast.net/podcast09/rss_10491.xml",
u"Place de la toile" : "http://radiofrance-podcast.net/podcast09/rss_10465.xml",
u"PLACE DES PEUPLES" : "http://radiofrance-podcast.net/podcast09/rss_11207.xml",
u"Planète terre" : "http://radiofrance-podcast.net/podcast09/rss_10233.xml",
u"POST FRONTIERE" : "http://radiofrance-podcast.net/podcast09/rss_11191.xml",
u"Projection privée" : "http://radiofrance-podcast.net/podcast09/rss_10198.xml",
u"Question d'éthique" : "http://radiofrance-podcast.net/podcast09/rss_10201.xml",
u"RADIO LIBRE" : "http://radiofrance-podcast.net/podcast09/rss_11183.xml",
u"Répliques" : "http://radiofrance-podcast.net/podcast09/rss_13397.xml",
u"Revue de presse internationale" : "http://radiofrance-podcast.net/podcast09/rss_10901.xml",
u"RUE DES ECOLES" : "http://radiofrance-podcast.net/podcast09/rss_11192.xml",
u"Science publique" : "http://radiofrance-podcast.net/podcast09/rss_10192.xml",
u"Service protestant" : "http://radiofrance-podcast.net/podcast09/rss_10297.xml",
u"Sur les docks" : "http://radiofrance-podcast.net/podcast09/rss_10177.xml",
u"Terre à terre" : "http://radiofrance-podcast.net/podcast09/rss_10867.xml",
u"TIRE TA LANGUE" : "http://radiofrance-podcast.net/podcast09/rss_11184.xml",
u"Tout arrive" : "http://radiofrance-podcast.net/podcast09/rss_10077.xml",
u"Tout un monde" : "http://radiofrance-podcast.net/podcast09/rss_10191.xml",
u"Vivre sa ville" : "http://radiofrance-podcast.net/podcast09/rss_10878.xml" }
listeEmissionsFranceMusique = { u"Histoire de..." : "http://radiofrance-podcast.net/podcast09/rss_10977.xml",
u"Le mot musical du jour" : "http://radiofrance-podcast.net/podcast09/rss_10976.xml",
u"Miniatures" : "http://radiofrance-podcast.net/podcast09/rss_10978.xml",
u"Sonnez les matines" : "http://radiofrance-podcast.net/podcast09/rss_10979.xml" }
listeEmissionsLeMouv = { u"Buzz de la semaine" : "http://radiofrance-podcast.net/podcast09/rss_10924.xml",
u"Cette année là" : "http://radiofrance-podcast.net/podcast09/rss_11280.xml",
u"Chez Francis" : "http://radiofrance-podcast.net/podcast09/rss_11285.xml",
u"Compression de Cartier" : "http://radiofrance-podcast.net/podcast09/rss_11279.xml",
u"Fausse Pub" : "http://radiofrance-podcast.net/podcast09/rss_11309.xml",
u"La BD de Philippe Audoin" : "http://radiofrance-podcast.net/podcast09/rss_11278.xml",
u"La minute culturelle de Cug et Westrou" : "http://radiofrance-podcast.net/podcast09/rss_10914.xml",
u"La minute numérique" : "http://radiofrance-podcast.net/podcast09/rss_11277.xml",
u"La mode de Samyjoe" : "http://radiofrance-podcast.net/podcast09/rss_11048.xml",
u"La Revue de Presse" : "http://radiofrance-podcast.net/podcast09/rss_11281.xml",
u"Le cinema de Jean Z" : "http://radiofrance-podcast.net/podcast09/rss_11045.xml",
u"Le Comedy Club Live" : "http://radiofrance-podcast.net/podcast09/rss_11314.xml",
u"Le meilleur du Mouv'" : "http://radiofrance-podcast.net/podcast09/rss_11274.xml",
u"L'Environnement" : "http://radiofrance-podcast.net/podcast09/rss_11041.xml",
u"Le pire de la semaine" : "http://radiofrance-podcast.net/podcast09/rss_11276.xml",
u"Le Reportage de la Redaction" : "http://radiofrance-podcast.net/podcast09/rss_11311.xml",
u"Les bons plans" : "http://radiofrance-podcast.net/podcast09/rss_11273.xml",
u"Les lectures de Clementine" : "http://radiofrance-podcast.net/podcast09/rss_11051.xml",
u"Les séries TV de Pierre Langlais" : "http://radiofrance-podcast.net/podcast09/rss_11288.xml",
u"Le Top 3 d'Emilie" : "http://radiofrance-podcast.net/podcast09/rss_11287.xml",
u"Le tour du Web" : "http://radiofrance-podcast.net/podcast09/rss_10926.xml",
u"L'invité du Mouv'" : "http://radiofrance-podcast.net/podcast09/rss_11330.xml",
u"L'invité matinal" : "http://radiofrance-podcast.net/podcast09/rss_11286.xml",
u"Revue de Web" : "http://radiofrance-podcast.net/podcast09/rss_11310.xml",
u"Un grand verre d'Orangeade" : "http://radiofrance-podcast.net/podcast09/rss_11282.xml",
u"Un tir dans la lucarne" : "http://radiofrance-podcast.net/podcast09/rss_11289.xml",
u"Zebra" : "http://radiofrance-podcast.net/podcast09/rss_11308.xml" }
listeEmissions = { "France Inter" : listeEmissionsFranceInter,
"France Info" : listeEmissionsFranceInfo,
"France Bleu" : listeEmissionsFranceBleu,
"France Culture" : listeEmissionsFranceCulture,
"France Musique" : listeEmissionsFranceMusique,
"Le Mouv'" : listeEmissionsLeMouv }
def __init__( self):
Plugin.__init__( self, "Radio France", "http://www.radiofrance.fr/", 30 )
def rafraichir( self ):
pass # Rien a rafraichir ici...
def listerChaines( self ):
liste = self.listeEmissions.keys()
liste.sort()
for chaine in liste:
self.ajouterChaine(chaine)
def listerEmissions( self, chaine ):
self.derniereChaine = chaine
liste = []
if( chaine != "" ):
liste = self.listeEmissions[ chaine ].keys()
liste.sort()
for emission in liste:
self.ajouterEmission(chaine, emission)
def listerFichiers( self, emission ):
if( emission != "" ):
if( emission in self.listeEmissions[ self.derniereChaine ] ):
# On recupere le lien de la page de l'emission
lienPage = self.listeEmissions[ self.derniereChaine ][ emission ]
# On recupere la page de l'emission
page = self.API.getPage( lienPage )
# On recupere le lien de l'image de l'emission
try :
urlImage = re.findall( '<itunes:image href="([^"]+?)"', page )[ 0 ]
except :
urlImage = ""
# On extrait les emissions
resultats = re.findall( self.listeFichiersRegEx, page )
for ( descriptif, fichier ) in resultats:
lien = "http://media.radiofrance-podcast.net/podcast09/" + fichier
listeDates = re.findall( "\d{2}\.\d{2}\.\d{2}", fichier )
if( listeDates == [] ): # Si on n'a pas pu extraire une date
date = "Inconnue"
else: # Si on a extrait une date
date = listeDates[ 0 ]
self.ajouterFichier(emission, Fichier( emission + " (" + date + ")", date, lien, urlImage = urlImage, descriptif = descriptif ) )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
from Plugin import Plugin
from Fichier import Fichier
from urllib import quote,unquote
import re,unicodedata
import time,rfc822 # for RFC822 datetime format (rss feed)
from datetime import datetime
from htmlentitydefs import name2codepoint
##########
# Classe #
##########
class Arte(Plugin):
##
## Arte Live Web
##
configArteLiveWeb = {
'nom' : "Arte Live Web",
'qualite' : ['SD', 'HD', 'Live'],
'regexEmissions' : {
'url' : "http://liveweb.arte.tv/",
# Attention à bien nommer les zones de recherche "lien" et "nom"
'pattern' : re.compile("<li><a href=\"http://liveweb.arte.tv/fr/cat/(?P<lien>.*?)\" class=\"accueil\">(?P<nom>.*?)</a></li>", re.DOTALL)
},
'regexListeFichiers' : {
0 : {
# %emission% représente l'émission à lister
'url' : "http://liveweb.arte.tv/fr/cat/%emission%",
'pattern' : re.compile("<a href=\"(http://download.liveweb.arte.tv/o21/liveweb/rss/home.*?\.rss)\"", re.DOTALL)
},
1 : {
# %pattern% représente le résultat de l'expression régulière précédente
'url' : "%pattern%",
# Expression régulière pour extraire les blocs descriptifs de chaque fichier
'pattern' : re.compile("(<item>.*?</item>)", re.DOTALL)
},
},
'regexInfosFichiers' : {
0 : {
# Premère regex, ne se base pas sur une URL mais sur les données extraites par regexListeFichiers
# Liste des informations à récupérer
'patterns' : {
'titre' : re.compile("<title>(.*?)</title>", re.DOTALL),
'lien' : re.compile("<link>(http://liveweb.arte.tv/fr/video/.*?)</link>", re.DOTALL),
'date' : re.compile("<pubDate>(.*?)</pubDate>", re.DOTALL),
'description' : re.compile("<description>(.*?)</description>", re.DOTALL),
#'eventid' : re.compile("<enclosure.*?/event/(.*?)/.*?/>", re.DOTALL),
'eventid' : re.compile("<enclosure.*?/event/.*?/(.*?)-.*?/>", re.DOTALL)
}
},
1 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "%lien%",
# optional = 1, cette étape n'est pas exécutée en mode TURBO
'optional' : 1,
# Liste des informations à récupérer
'patterns' : {
'eventid_html': re.compile("new LwEvent\('(.*?)', ''\);", re.DOTALL)
},
},
2 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "http://arte.vo.llnwd.net/o21/liveweb/events/event-%eventid%.xml",
# Liste des informations à récupérer
'patterns' : {
'titre' : re.compile("<nameFr>(.*?)</nameFr>", re.DOTALL),
'lien.HD': re.compile("<urlHd>(.*?)</urlHd>", re.DOTALL),
'lien.SD': re.compile("<urlSd>(.*?)</urlSd>", re.DOTALL),
'lien.Live': re.compile("<liveUrl>(.*?)</liveUrl>", re.DOTALL)
},
},
},
'infosFichier' : {
'nom' : "[%qualite%] %titre%",
'date' : "%date%",
'lien' : "%lien%",
#'nomFichierSortieStd' : "%lien%",
#'nomFichierSortieRen' : "%titre%",
#~ 'urlImage' : "http://download.liveweb.arte.tv/o21/liveweb/media/event/%eventid%/%eventid%-visual-cropcropcrop-small.jpg",
'urlImage' : "http://download.liveweb.arte.tv/o21/liveweb/media/event/%eventid%/%eventid%-visual.jpg",
'descriptif' : "%description%"
}
}
##
## Arte+7
##
# En cas de souci, on pourrait utiliser la page RSS de chaque chaine
# Pour récupérer la liste des chaines (càd la liste des flux RSS)
# http://videos.arte.tv/fr/videos/meta/index-3188674-3223978.html
# Pour récupérer la liste des émissions d'une chaine
# http://videos.arte.tv/fr/do_delegate/videos/programmes/360_geo/index-3188704,view,rss.xml
configArtePlusSept = {
'nom' : "Arte+7",
'qualite' : ['SD', 'HD'],
'regexEmissions' : {
'url' : "http://videos.arte.tv/fr/videos",
# Attention à bien nommer les zones de recherche "lien" et "nom"
'pattern' : re.compile("<input type=\"checkbox\" value=\"(?P<lien>.*?)\"/>.*?<a href=\"#\">(?P<nom>.*?)</a>", re.DOTALL)
},
'regexListeFichiers' : {
0 : {
# %emission% représente l'émission à lister
'url' : "http://videos.arte.tv/fr/do_delegate/videos/index-%emission%-3188698,view,asList.html?hash=fr/list/date//1/250/",
# Expression régulière pour extraire les blocs descriptifs de chaque vidéo
'pattern' : re.compile("(<tr.*?>.*?</tr>)", re.DOTALL)
},
},
'regexInfosFichiers' : {
0 : {
# Premère regex, ne se base pas sur une URL mais sur les données extraites par regexListeFichiers
# Liste des informations à récupérer
# Les expressions de type texte %xxx% sont remplacées par les options du plugin (choix arbitraire pour l'instant)
'patterns' : {
'titre' : re.compile("title=\"(.*?)\|\|", re.DOTALL),
'lien' : re.compile("<a href=\"/(fr/videos/.*?\.html)\">", re.DOTALL),
'date' : re.compile("<em>(.*?)</em>", re.DOTALL),
'description' : re.compile("\|\|(.*?)\">", re.DOTALL),
'guid' : re.compile("{ajaxUrl:'.*-(.*?).html", re.DOTALL),
'player_swf' : "%default_playerSWF%",
}
},
1 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "http://videos.arte.tv/%lien%",
# optional = 1, cette étape n'est pas exécutée en mode TURBO
'optional' : 1,
# Liste des informations à récupérer
'patterns' : {
'player_swf' : re.compile("<param name=\"movie\" value=\"(.*?\.swf)", re.DOTALL),
'titre' : re.compile("<div class=\"recentTracksMast\">.*?<h3>(.*?)</h3>.*?</div>", re.DOTALL),
'image' : re.compile("<link rel=\"image_src\" href=\"(.*?)\"/>", re.DOTALL),
'description' : re.compile("<div class=\"recentTracksCont\">.*?<div>(.*?)</div>", re.DOTALL),
'guid': re.compile("addToPlaylistOpen {ajaxUrl:'/fr/do_addToPlaylist/videos/.*?-(.*?)\.html'}", re.DOTALL)
},
},
2 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "http://videos.arte.tv/fr/do_delegate/videos/-%guid%,view,asPlayerXml.xml",
# Liste des informations à récupérer
'patterns' : {
'titre' : re.compile("<name>(.*?)</name>", re.DOTALL),
'date' : re.compile("<dateVideo>(.*?)</dateVideo>", re.DOTALL),
'image' : re.compile("<firstThumbnailUrl>(.*?)</firstThumbnailUrl>", re.DOTALL),
'lien.HD': re.compile("<url quality=\"hd\">(.*?)</url>", re.DOTALL),
'lien.SD': re.compile("<url quality=\"sd\">(.*?)</url>", re.DOTALL),
},
},
},
'infosFichier' : {
'nom' : "[%qualite%] %titre%",
'date' : "%date%",
'lien' : "%lien% -W %player_swf%",
#'nomFichierSortieStd' : "%lien%.mp4",
#'nomFichierSortieRen' : "%titre%",
'urlImage' : "%image%",
'descriptif' : "%description%"
}
}
##
## Options du plugin
##
listeOptions = {
0: {
# Qualité à rechercher SD ou HD ?
'type' : "ChoixUnique",
'nom' : "qualite",
'description' : "Qualité des vidéos",
'defaut' : "HD",
'valeurs' : ["HD", "SD","HD & SD"],
},
1: {
# Nombre maximum de fichiers à rechercher (0 = aucune limite)
'type' : "Texte",
'nom' : "max_files",
'description' : "Nombre d'enregistrements à analyser\n(0=pas de limite)",
'defaut' : "20",
},
2: {
# Renommer les fichiers à partir du titre de l'émission
'type' : "Bouleen",
'nom' : "rename_files",
'description' : "Renommer les fichiers à partir du titre de l'émission\nATTENTION : plusieurs enregistrements peuvent avoir le même nom",
'defaut' : False,
},
3: {
# Mode turbo : charge moins de pages, donc plus rapide, mais moins de détails
'type' : "Bouleen",
'nom' : "turbo_mode",
'description' : "Mode TURBO\nChargement plus rapide mais informations moins détaillées",
'defaut' : False,
},
4: {
# PlayerSWF par default pour Arte+7
'type' : "Texte",
'nom' : "default_playerSWF",
'description' : "Player Arte+7 à utiliser par défaut (en mode TURBO)\nATTENTION : Réservé aux utilisateurs avancés",
'defaut' : "http://videos.arte.tv/blob/web/i18n/view/player_11-3188338-data-4785094.swf",
}
}
nom = "Arte"
url = "http://www.arte.tv/"
listeChaines = {} # Clef = Nom Chaine, Valeur = { Nom emission : Lien }
# Supprime les caractères spéciaux HTML du tyle &#nn;
# http://www.w3.org/QA/2008/04/unescape-html-entities-python.html
# http://bytes.com/topic/python/answers/21074-unescaping-xml-escape-codes
def htmlent2chr(self, s):
def ent2chr(m):
code = m.group(1)
if code.isdigit(): code = int(code)
else: code = int(code[1:], 16)
if code<256: return chr(code)
else: return '?' #XXX unichr(code).encode('utf-16le') ??
return re.sub(r'\&\#(x?[0-9a-fA-F]+);', ent2chr, s)
# Supprime les caractères spéciaux HTML
# http://wiki.python.org/moin/EscapingHtml
def htmlentitydecode(self, s):
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
# Supprime les caractères spéciaux pour obtenir un nom de fichier correct
def cleanup_filename (self, s):
nouvNom = s
nouvNom = nouvNom.replace(" ","_")
nouvNom = nouvNom.replace(":","_")
nouvNom = nouvNom.replace("/","_")
nouvNom = nouvNom.replace("\\","_")
nouvNom = nouvNom.replace("?","_")
return nouvNom
# Fonction parse_date recopiée de l'application arte+7recorder
# Permet de convertir une date issue d'Arte+7 (hier, aujourd'hui...) en vrai date
def parse_date(self, date_str):
time_re = re.compile("^\d\d[h:]\d\d$")
fr_monthesL = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]
fr_monthesC = ["janv.", "fevr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."]
de_monthes = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]
date_array = date_str.split(",")
if time_re.search(date_array[-1].strip()) is None:
return ""
time_ = date_array[-1].strip()
if date_array[0].strip() in ("Aujourd'hui", "Heute"):
date_ = time.strftime("%Y/%m/%d")
elif date_array[0].strip() in ("Hier", "Gestern"):
date_ = time.strftime("%Y/%m/%d", time.localtime(time.time() - (24*60*60)))
else:
array = date_array[1].split()
day = array[0].strip(".")
month = array[1]
for arr in (fr_monthesL, fr_monthesC, de_monthes):
if array[1] in arr:
month = "%02d" % (arr.index(array[1])+1)
year = array[2]
date_ = "%s/%s/%s" % (year, month, day)
return date_ + ", " + time_
def __init__(self):
Plugin.__init__(self, self.nom, self.url, 7) #7 = fréquence de rafraichissement
if os.path.exists(self.fichierCache):
self.listeChaines = self.chargerCache()
def debug_savefile (self, buffer):
path = os.path.expanduser( "~" )
fichierDebug = path+"/.tvdownloader/"+self.nom.replace( " ", "_" )+".log"
file = open(fichierDebug, "w")
file.write (buffer)
file.close()
def debug_print (self, variable):
#~ print str(variable).replace("},", "},\n\n").replace("',", "',\n").replace("\",", "\",\n")
print str(variable).replace("{", "\n\n{").replace(", ", ",\n")
def listerOptions(self):
for option in self.listeOptions.values():
if option['type']=="ChoixUnique":
self.optionChoixUnique(option['nom'], option['description'], option['defaut'], option['valeurs'])
elif option['type']=="ChoixMultiple":
self.optionChoixMultiple(option['nom'], option['description'], option['defaut'], option['valeurs'])
elif option['type']=="Texte":
self.optionTexte(option['nom'], option['description'], option['defaut'])
elif option['type']=="Bouleen":
self.optionBouleen(option['nom'], option['description'], option['defaut'])
def rafraichir(self):
self.afficher("Global : Création de la liste des chaines...")
# On remet a 0 la liste des chaines
self.listeChaines.clear()
# On boucle sur chaque "chaine" à analyser
for chaineActuelle in [self.configArteLiveWeb, self.configArtePlusSept]:
self.afficher (chaineActuelle['nom']+" Récupération de la liste des catégories "+chaineActuelle['nom']+"...")
listeEmissions = {}
# On recherche toutes les catégories
for item in re.finditer(chaineActuelle['regexEmissions']['pattern'], self.API.getPage(chaineActuelle['regexEmissions']['url'])):
self.afficher (chaineActuelle['nom']+" ... Catégorie "+item.group('nom')+" : "+item.group('lien')+".")
listeEmissions[item.group('nom')]=item.group('lien')
self.listeChaines[chaineActuelle['nom']] = listeEmissions
# On sauvegarde les chaines trouvées
self.listerOptions()
self.sauvegarderCache(self.listeChaines)
self.afficher("Global : Emissions conservées.")
def listerChaines(self):
liste = self.listeChaines.keys()
liste.sort()
for chaine in liste:
self.ajouterChaine(chaine)
def listerEmissions(self, chaine):
if(self.listeChaines.has_key(chaine)):
self.derniereChaine = chaine
liste = self.listeChaines[chaine].keys()
liste.sort()
for emission in liste:
self.ajouterEmission(chaine, emission)
def getLienEmission(self, emission):
# Cherche dans quelle chaine se trouve l'émission
if(self.listeChaines.has_key(self.derniereChaine)):
listeEmissions = self.listeChaines[ self.derniereChaine ]
if(listeEmissions.has_key(emission)):
return listeEmissions[ emission ]
def chargeListeEnregistrements(self, emission, chaineActuelle):
emissionID = self.getLienEmission(emission)
if emissionID == None:
self.afficher (chaineActuelle['nom']+" Erreur de recherche du lien pour \""+emission+"\"")
return None
else:
self.afficher (chaineActuelle['nom']+" Liste des enregistrements pour \""+emission+"\"...")
pattern = ""
for unItem in chaineActuelle['regexListeFichiers'].values():
#~ print str(chaineActuelle['regexListeFichiers'])
# Construction du lien contenant toutes les émissions de cette catégorie
lienPage = unItem['url'].replace("%emission%", emissionID).replace("%pattern%", pattern)
self.afficher (chaineActuelle['nom']+" ... lecture de la page "+lienPage)
laPage = self.API.getPage(lienPage)
if len(laPage)>0:
foundItems = re.findall(unItem['pattern'], laPage)
pattern = foundItems[0]
self.afficher (chaineActuelle['nom']+" On a listé " + str(len(foundItems)) + " enregistrements.")
else:
self.afficher (chaineActuelle['nom']+" Impossible de charger la page. Aucun enregistrement trouvé !")
foundItems = None
return foundItems
def ajouteFichiers (self, emission, listeEnregistrement, chaineActuelle):
self.afficher (chaineActuelle['nom']+" On ajoute les enregitrements trouvés.")
opt_renameFiles = self.getOption("rename_files")
opt_qual = self.getOption("qualite")
nbLiens = 0
for keyEnregistrement in listeEnregistrement.keys():
# on supprime l'enregistrement avec son index actuel
unEnregistrement = listeEnregistrement.copy()[keyEnregistrement]
for infosQualite in chaineActuelle['qualite']:
infosFichier = {}
if opt_qual.find(infosQualite)>=0:
# Lien dans la qualité voulue
unEnregistrement['lien'] = unEnregistrement.get('lien.'+infosQualite, None)
if unEnregistrement['lien'] == None:
self.afficher (chaineActuelle['nom']+" ... Pas de lien "+infosQualite+" trouvé.")
continue
# Date, mise en forme
rfc_date = rfc822.parsedate(unEnregistrement['date'])
# Format année/mois/jour hh:mm, mieux pour effectuer un tri
unEnregistrement['date'] = time.strftime("%Y/%m/%d %H:%M", rfc_date)
lesInfos = {}
for keyInfo in chaineActuelle['infosFichier'].keys():
uneInfo = chaineActuelle['infosFichier'][keyInfo]
# On effectue les remplacements selon les informations collectées
for unTag in unEnregistrement.keys():
if unEnregistrement[unTag] != None:
uneInfo = uneInfo.replace("%"+unTag+"%", unEnregistrement[unTag])
else:
uneInfo = uneInfo.replace("%"+unTag+"%", "")
# Qualité de la video
uneInfo = uneInfo.replace("%qualite%", infosQualite)
lesInfos[keyInfo] = uneInfo
# Nom fichier
if opt_renameFiles:
nomFichierSortie = self.cleanup_filename(unEnregistrement['titre'])
else:
nomFichierSortie = unEnregistrement['lien'].split('/')[-1]
if nomFichierSortie.find('?')>0:
nomFichierSortie = nomFichierSortie.split('?')[0]
if not re.match(".*\.mp4", nomFichierSortie):
nomFichierSortie = nomFichierSortie+".mp4"
# Ajout du fichier
nbLiens += 1
self.afficher (chaineActuelle['nom']+" Ajoute dans la liste...")
self.afficher (chaineActuelle['nom']+" ... Date : "+ lesInfos['date'])
self.afficher (chaineActuelle['nom']+" ... Nom : "+ lesInfos['nom'])
self.afficher (chaineActuelle['nom']+" ... Lien : " + lesInfos['lien'])
self.afficher (chaineActuelle['nom']+" ... Image : " + lesInfos['urlImage'])
self.afficher (chaineActuelle['nom']+" ... Nom fichier : " + nomFichierSortie)
leFichier = Fichier(
lesInfos['nom'],
lesInfos['date'],
lesInfos['lien'],
nomFichierSortie,
lesInfos['urlImage'],
lesInfos['descriptif']
)
self.ajouterFichier(emission, leFichier)
return nbLiens
def listerEnregistrements(self, emission, chaineActuelle):
opt_maxFiles = int(self.getOption("max_files"))
opt_turbo = self.getOption("turbo_mode")
nbLiens = 0
# Charge la page contenant la liste des émissions
videosList = self.chargeListeEnregistrements(emission, chaineActuelle)
# A-t-on une liste d'enregistrements ?
if videosList != None:
listeEnregistrement = {}
# Boucle sur chaque traitement de recherche
for unItem in chaineActuelle['regexInfosFichiers'].values():
optional = unItem.get('optional',0)
if not (opt_turbo and optional):
if unItem.get('url', None) == None:
# On n'a pas d'url, on travaille sur videoList
# C'est la première passe
nbFichiers = 0
lesPages = {}
for infosVideo in videosList:
lesPages[nbFichiers] = infosVideo
# On crée, et on indexe listeEnregistrement en phase avec videosList
listeEnregistrement[nbFichiers] = {}
nbFichiers += 1
if (opt_maxFiles>0 and nbFichiers>=opt_maxFiles):
break
else:
# Chargement des pages HTML sur lesquelles on va devoir travailler
self.afficher (chaineActuelle['nom']+" Chargement des pages nécessaires...")
listeURL = []
# On boucle sur chaque enregistrement à travailler
for keyEnregistrement in listeEnregistrement.keys():
# on supprime l'enregistrement avec son index actuel
unEnregistrement = listeEnregistrement.pop (keyEnregistrement)
lienHTML = unItem['url']
# On effectue les remplacements des paramètres dans l'url
for unTag in unEnregistrement.keys():
if unEnregistrement[unTag] != None:
lienHTML = lienHTML.replace("%"+unTag+"%", unEnregistrement[unTag])
else:
lienHTML = lienHTML.replace("%"+unTag+"%", "")
listeURL.append(lienHTML)
# on recrée l'enregistrement avec son nouvel index
listeEnregistrement[lienHTML] = unEnregistrement
# On charge les pages désirées
lesPages = self.API.getPages(listeURL)
# On boucle et exécute les expressions régulières
for pageNum in lesPages.keys():
unePage = lesPages[pageNum]
if len(unePage)==0:
self.afficher (chaineActuelle['nom']+" ERREUR : La page "+pageNum+" n'a pas été chargée !")
#~ print "Page : "+repr(unePage)
unEnregistrement = listeEnregistrement[pageNum]
for unTag in unItem['patterns'].keys():
if type(unItem['patterns'][unTag]).__name__==type(re.compile("foo")).__name__:
reFound = re.search(unItem['patterns'][unTag], unePage)
if reFound != None:
unEnregistrement[unTag] = reFound.group(1)
else:
unEnregistrement[unTag] = None
else:
texte = unItem['patterns'][unTag]
for option in self.listeOptions.values():
texte = texte.replace("%"+option['nom']+"%", str(self.getOption(option['nom'])))
unEnregistrement[unTag] = texte
# On ajoute enfin la liste des fichiers à télécharger
nbLiens = self.ajouteFichiers(emission, listeEnregistrement, chaineActuelle)
def listerFichiers(self, emission):
for chaineActuelle in [self.configArteLiveWeb, self.configArtePlusSept]:
if (self.derniereChaine == chaineActuelle['nom']):
self.listerEnregistrements (emission, chaineActuelle) | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
import pickle
import base64
from Crypto.Cipher import DES
import xml.sax
from xml.sax.handler import ContentHandler
import unicodedata
from Fichier import Fichier
from Plugin import Plugin
###########
# Classes #
###########
class M6Replay( Plugin ):
def __init__( self ):
Plugin.__init__( self, "M6Replay", "www.m6replay.fr/", 1 )
self.listeFichiers = {} # Clefs = nomChaine, Valeurs = { nomEmission, [ [ Episode 1, Date1, URL1 ], ... ] }
if os.path.exists( self.fichierCache ):
self.listeFichiers = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions..." )
# On remet a 0 la liste des fichiers
self.listeFichiers.clear()
# On recupere la page qui contient les donnees chiffrees
pageEmissionsChiffree = self.API.getPage( "http://www.m6replay.fr/catalogue/catalogueWeb3.xml" )
#
# N.B. : La page http://www.m6replay.fr/catalogue/catalogueWeb4.xml semble contenir
# des videos non presentent sur le site...
# Il faudrait voir ce qu'il en retourne (pourquoi ne sont-elles pas sur le site ? les liens fonctionnent-ils ?)
#
# Classe pour dechiffrer la page
decryptor = DES.new( "ElFsg.Ot", DES.MODE_ECB )
# Page des emissions dechiffree
pageEmissions = decryptor.decrypt( base64.decodestring( pageEmissionsChiffree ) )
# On cherche la fin du fichier XML
finXML = pageEmissions.find( "</template_exchange_WEB>" ) + len( "</template_exchange_WEB>" )
# On enleve ce qui est apres la fin du fichier XML
pageEmissions = pageEmissions[ : finXML ]
# Handler
handler = M6ReplayHandler( self.listeFichiers )
# On parse le fichier xml
xml.sax.parseString( pageEmissions, handler )
self.sauvegarderCache( self.listeFichiers )
self.afficher( "Fichier sauvegarde" )
def listerChaines( self ):
for chaine in self.listeFichiers.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeFichiers.has_key( chaine ) ):
self.listeEmissionsCourantes = self.listeFichiers[ chaine ]
for emission in self.listeFichiers[ chaine ].keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeEmissionsCourantes.has_key( emission ) ):
listeFichiers = self.listeEmissionsCourantes[ emission ]
for ( nom, date, lien, urlImage, descriptif ) in listeFichiers:
lienValide = "rtmpe://m6dev.fcod.llnwd.net:443/a3100/d1/mp4:production/regienum/" + lien
urlImage = "http://images.m6replay.fr" + urlImage
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lien )
self.ajouterFichier( emission, Fichier( nom, date, lienValide, nom + extension, urlImage, descriptif ) )
#
# Parser XML pour M6Replay
#
## Classe qui permet de lire les fichiers XML de M6Replay
class M6ReplayHandler( ContentHandler ):
# Constructeur
# @param listeFichiers Liste des fichiers que le parser va remplir
def __init__( self, listeFichiers ):
# Liste des fichiers
self.listeFichiers = listeFichiers
# Liste des emissions (temporaire, ajoute au fur et a mesure dans listeFichiers)
self.listeEmissions = {}
# Liste des videos (temporaire, ajoute au fur et a mesure dans listeEmissions)
self.listeVideos = []
# Initialisation des variables a Faux
self.nomChaineConnu = False
self.nomEmissionConnu = False
self.nomEpisodeConnu = False
self.nomVideoConnu = False
self.isNomChaine = False
self.isNomEmission = False
self.isNomEpisode = False
self.isNomVideo = False
self.isResume = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "categorie" ):
if( self.nomChaineConnu ):
# On commence une nouvelle emission
pass
else:
# On commence une nouvelle chaine
pass
elif( name == "nom" ):
# Si on a nom, cela peut etre (toujours dans cet ordre) :
# - Le nom de la chaine
# - Le nom de l'emission
# - Le nom d'un episode de cette emission
# - Le nom de la vidéo de cet episode
# De plus, si on ne connait pas la nom de la chaine, alors le 1er nom rencontre est le nom de la chaine
if( self.nomChaineConnu ):
if( self.nomEmissionConnu ):
if( self.nomEpisodeConnu ): # Alors on a le nom de la video
self.isNomVideo = True
else: # Alors on a le nom de l'episode
self.isNomEpisode = True
else: # Alors on a le nom de l'emission
self.isNomEmission = True
else: # Alors on a le nom de la chaine
self.isNomChaine = True
elif( name == "diffusion" ):
self.dateEpisode = attrs.get( "date", "" )
elif( name == "resume" ):
self.isResume = True
elif( name == "produit" ):
self.image = attrs.get( "sml_img_url", "" )
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
data = unicodedata.normalize( 'NFKD', data ).encode( 'ascii','ignore' )
if( self.isNomChaine ):
self.nomChaine = data
self.nomChaineConnu = True
self.isNomChaine = False
elif( self.isNomEmission ):
self.nomEmission = data
self.nomEmissionConnu = True
self.isNomEmission = False
elif( self.isNomEpisode ):
self.nomEpisode = data
self.nomEpisodeConnu = True
self.isNomEpisode = False
elif( self.isNomVideo ):
self.nomVideo = data
self.nomVideoConnu = True
self.isNomVideo = False
elif( self.isResume ):
self.resume = data
self.isResume = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "categorie" ):
if( self.nomEmissionConnu ): # On a fini de traiter une emission
self.listeEmissions[ self.nomEmission.title() ] = self.listeVideos
self.listeVideos = []
self.nomEmissionConnu = False
else: # On a fini de traiter une chaine
self.listeFichiers[ self.nomChaine.title() ] = self.listeEmissions
self.listeEmissions = {}
self.nomChaineConnu = False
elif( name == "nom" ):
pass
elif( name == "diffusion" ):
self.listeVideos.append( [ self.nomEpisode.title(), self.dateEpisode, self.nomVideo, self.image, self.resume ] )
self.nomEpisodeConnu = False
self.nomVideoConnu = False
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
import pickle
import xml.sax
from xml.sax.handler import ContentHandler
import urllib
import unicodedata
from Fichier import Fichier
from Plugin import Plugin
###########
# Classes #
###########
class W9Replay( Plugin ):
urlFichierXML = "http://data.w9replay.fr/catalogue/120-w9.xml"
listeFichiers = {} # Clefs = nomChaine, Valeurs = { nomEmission, [ [ Episode 1, Date1, URL1 ], ... ] }
def __init__( self ):
Plugin.__init__( self, "W9Replay", "http://www.w9replay.fr/", 1 )
self.listeEmissionsCourantes = {}
if os.path.exists( self.fichierCache ):
self.listeFichiers = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions et des fichiers..." )
# On remet a 0 la liste des fichiers
self.listeFichiers.clear()
# On recupere la page qui contient les infos
page = urllib.urlopen( self.urlFichierXML )
pageXML = page.read()
#~ pageXML = self.API.getPage( self.urlFichierXML )
# Handler
handler = W9ReplayHandler( self.listeFichiers )
# On parse le fichier xml
xml.sax.parseString( pageXML, handler )
self.sauvegarderCache( self.listeFichiers )
self.afficher( u"Liste sauvegardée" )
def listerChaines( self ):
for chaine in self.listeFichiers.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeFichiers.has_key( chaine ) ):
self.listeEmissionsCourantes = self.listeFichiers[ chaine ]
for emission in self.listeEmissionsCourantes.keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeEmissionsCourantes.has_key( emission ) ):
listeFichiers = self.listeEmissionsCourantes[ emission ]
for ( nom, date, lien, urlImage, descriptif ) in listeFichiers:
lienValide = "rtmpe://m6dev.fcod.llnwd.net:443/a3100/d1/mp4:production/w9replay/" + lien
urlImage = "http://images.w9replay.fr" + urlImage
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lien )
self.ajouterFichier( emission, Fichier( nom, date, lienValide, nom + extension, urlImage, descriptif ) )
#
# Parser XML pour W9Replay
#
## Classe qui permet de lire les fichiers XML de W9Replay
class W9ReplayHandler( ContentHandler ):
# Constructeur
# @param listeFichiers Liste des fichiers que le parser va remplir
def __init__( self, listeFichiers ):
# Liste des fichiers
self.listeFichiers = listeFichiers
# Liste des emissions (temporaire, ajoute au fur et a mesure dans listeFichiers)
self.listeEmissions = {}
# Liste des videos (temporaire, ajoute au fur et a mesure dans listeEmissions)
self.listeVideos = []
# Initialisation des variables a Faux
self.nomChaineConnu = False
self.nomEmissionConnu = False
self.nomEpisodeConnu = False
self.nomVideoConnu = False
self.isNomChaine = False
self.isNomEmission = False
self.isNomEpisode = False
self.isNomVideo = False
self.isResume = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "categorie" ):
if( self.nomChaineConnu ):
# On commence une nouvelle emission
pass
else:
# On commence une nouvelle chaine
pass
elif( name == "nom" ):
# Si on a nom, cela peut etre (toujours dans cet ordre) :
# - Le nom de l'emission
# - Le nom d'un episode de cette emission
# - Le nom de la vidéo de cet episode
# De plus, si on ne connait pas la nom de la chaine, alors le 1er nom rencontre est le nom de la chaine
if( self.nomChaineConnu ):
if( self.nomEmissionConnu ):
if( self.nomEpisodeConnu ): # Alors on a le nom de la video
self.isNomVideo = True
else: # Alors on a le nom de l'episode
self.isNomEpisode = True
else: # Alors on a le nom de l'emission
self.isNomEmission = True
else: # Alors on a le nom de la chaine
self.isNomChaine = True
elif( name == "diffusion" ):
self.dateEpisode = attrs.get( "date", "" )
elif( name == "resume" ):
self.isResume = True
elif( name == "produit" ):
self.image = attrs.get( "sml_img_url", "" )
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
data = unicodedata.normalize( 'NFKD', data ).encode( 'ascii','ignore' )
if( self.isNomChaine ):
self.nomChaine = data
self.nomChaineConnu = True
self.isNomChaine = False
elif( self.isNomEmission ):
self.nomEmission = data
self.nomEmissionConnu = True
self.isNomEmission = False
elif( self.isNomEpisode ):
self.nomEpisode = data
self.nomEpisodeConnu = True
self.isNomEpisode = False
elif( self.isNomVideo ):
self.nomVideo = data
self.nomVideoConnu = True
self.isNomVideo = False
elif( self.isResume ):
self.resume = data
self.isResume = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "categorie" ):
if( self.nomEmissionConnu ): # On a fini de traiter une emission
self.listeEmissions[ self.nomEmission.title() ] = self.listeVideos
self.listeVideos = []
self.nomEmissionConnu = False
else: # On a fini de traiter une chaine
self.listeFichiers[ self.nomChaine.title() ] = self.listeEmissions
self.listeEmissions = {}
self.nomChaineConnu = False
elif( name == "nom" ):
pass
elif( name == "diffusion" ):
self.listeVideos.append( [ self.nomEpisode.title(), self.dateEpisode, self.nomVideo, self.image, self.resume ] )
self.nomEpisodeConnu = False
self.nomVideoConnu = False
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class Gulli( Plugin ):
urlListeProgrammes = "http://replay.gulli.fr/"
listeEmissionsRegEx = re.compile( '<a href="([^<]+?)".*?alt="([^<]+?)"' )
lienVideoRegEx = re.compile( "URL_RTMP[^,]+?'([^,]+?)'," )
def __init__( self ):
Plugin.__init__( self, "Gulli", "http://www.gulli.fr", 1 )
# Liste des programmes sous la forme
# { Chaine : [ Nom, Lien ] }
self.listeProgrammes = {}
if os.path.exists( self.fichierCache ):
self.listeProgrammes = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions..." )
# On remet a 0 la liste des programmes
self.listeProgrammes.clear()
# On recupere la page qui contient toutes les informations
pageProgrammes = self.API.getPage( self.urlListeProgrammes )
# On decoupe la page selon les chaines ( Dessins Animes, ... )
resultats = re.split( "<h2>([^<]+)</h2>", pageProgrammes )[ 1 : ]
for ( chaine, texteChaine ) in ( zip( resultats[ 0::2 ], resultats[ 1::2 ] ) ):
# On ajoute la chaine
chaine = chaine.title()
self.listeProgrammes[ chaine ] = []
# On extrait les noms des programmes avec le lien vers la page qui contient la video
resultatsEmissions = re.findall( self.listeEmissionsRegEx, texteChaine )
for res in resultatsEmissions:
lienPage = self.url + res[ 0 ]
nom = res[ 1 ]
# On va recuperer la page qui contient le lien vers la video
pageVideo = self.API.getPage( lienPage )
# On en extrait le lien de la video
lienVideo = re.findall( self.lienVideoRegEx, pageVideo )[ 0 ]
# On l'ajoute a la liste
self.listeProgrammes[ chaine ].append( [ nom, lienVideo ] )
self.sauvegarderCache( self.listeProgrammes )
self.afficher( u"Liste sauvegardée" )
def listerChaines( self ):
for chaine in self.listeProgrammes.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
self.chaineCourante = chaine
self.ajouterEmission( chaine, chaine )
def listerFichiers( self, emission ):
if( self.listeProgrammes.has_key( self.chaineCourante ) ):
for( nom, lien ) in self.listeProgrammes[ self.chaineCourante ]:
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lien )
self.ajouterFichier( self.chaineCourante, Fichier( nom, "Inconnue", lien, nom + extension ) )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
from Plugin import Plugin
from Fichier import Fichier
import re,unicodedata,datetime
##########
# Classe #
##########
class TF1( Plugin ):
"""Classe abstraite Plugin dont doit heriter chacun des plugins"""
videoBaseUrl = "http://videos.tf1.fr/"
listeEmissionBaseUrl = "http://videos.tf1.fr/videos-en-integralite/"
listeEmissionPage1Pattern = re.compile("<a onmousedown=\"[^\"]*integralite.([^']*?)@html[^>]*>De A à Z", re.DOTALL)
listeEmissionPagePattern = re.compile("<a href=\"/videos-en-integralite/([^\"]*.html)\" class=\"c2 t3\">", re.DOTALL)
emissionInfosPattern = re.compile("<a href=\"/([^/]+?)/.*?.html\" class=\"c2\"><strong class=\"t4\">([^<]+)</strong>", re.DOTALL)
infosFichierPattern = re.compile("<a href=\"/([^\"]*-\d+.html)\" class=\"t3\">([^<]*)</a></h4>", re.DOTALL)
listeEmissions = {}
listeFichiers = {}
def __init__( self):
Plugin.__init__( self, "TF1", "http://www.tf1.fr/")
def rafraichir( self ):
pass
def listerChaines( self ):
self.ajouterChaine("TF1")
def listerEmissions( self, chaine ):
match = re.search(self.listeEmissionPage1Pattern, self.API.getPage(self.listeEmissionBaseUrl))
if match == None:
return []
urls = [self.listeEmissionBaseUrl+match.group(1)+".html"]
for index in re.findall(self.listeEmissionPagePattern, self.API.getPage(urls[0])):
urls.append(self.listeEmissionBaseUrl+index)
for page in self.API.getPages(urls).values():
for emission in re.findall(self.emissionInfosPattern, page):
if not self.listeEmissions.has_key(emission[1]):
self.listeEmissions[emission[1]] = self.videoBaseUrl+emission[0]+"/"
liste = self.listeEmissions.keys()
liste.sort()
for emission in liste:
self.ajouterEmission(chaine, emission)
def listerFichiers( self, emission ):
if not self.listeEmissions.has_key(emission):
return
#~ print self.listeEmissions[emission]+"video-integrale/"
for fichier in re.findall( self.infosFichierPattern, self.API.getPage(self.listeEmissions[emission]+"video-integrale/")):
print fichier
return
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#~ import sys
#~ sys.path[ :0 ] = [ '../', '../lib/' ] # On ajoute des repertoires au path
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
#~ import pickle
import xml.sax
from Podcasts import PodcastsHandler
from Fichier import Fichier
from Plugin import Plugin
###########
# Classes #
###########
class FranceInter( Plugin ):
urlListesEmissions = [ [ "Du lundi au vendredi", "http://sites.radiofrance.fr/franceinter/pod/index.php?page=chrono&jd=sem" ],
[ "Le samedi", "http://sites.radiofrance.fr/franceinter/pod/index.php?page=chrono&jd=sam" ],
[ "Le dimanche", "http://sites.radiofrance.fr/franceinter/pod/index.php?page=chrono&jd=dim" ]
]
listeEmissions = {} # { Nom chaine : { Nom emission : URL fichier XML } }
urlPageDescriptive = "http://sites.radiofrance.fr/_c/php/popcast.php?chaine=1&cid="
pageDescriptiveRegEx = re.compile( '<h2>(.+?)</h2>.+?<p class="rssLink">(.+?)</p>' , re.DOTALL )
derniereChaine = ""
def __init__( self ):
Plugin.__init__( self, "France Inter", "http://sites.radiofrance.fr/franceinter/accueil/", 30 )
if os.path.exists( self.fichierCache ):
self.listeEmissions = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions..." )
# On remet a 0 la liste des emissions
self.listeEmissions.clear()
# Pour chaque page
for ( nom, urlPage ) in self.urlListesEmissions:
# On cree la chaine dans la liste des programmes
self.listeEmissions[ nom ] = {}
# On recupere la page web
page = self.API.getPage( urlPage )
# On extrait les numeros de chacune des pages des podcasts
listeNumeros = re.findall( '<h6><a href="javascript:popcast\(([0-9]+?), 1\);"', page )
# On cree la liste de toutes les pages que l'on doit recuperer
listeURL = []
for numero in listeNumeros:
listeURL.append( self.urlPageDescriptive + numero )
# On recupere toutes ces pages
listePages = self.API.getPages( listeURL )
# Pour chaque page = emission
for pageEmission in listePages.values():
# On recupere les informations
infos = re.findall( self.pageDescriptiveRegEx, pageEmission )
for ( nomEmission, urlFichierXML ) in infos:
nomEmission = nomEmission.replace( "»", "" ).title()
self.listeEmissions[ nom ][ nomEmission ] = urlFichierXML
self.sauvegarderCache( self.listeEmissions )
self.afficher( u"Liste des émissions sauvegardées" )
def listerChaines( self ):
for chaine in self.listeEmissions.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeEmissions.has_key( chaine ) ):
self.derniereChaine = chaine
for emission in self.listeEmissions[ chaine ].keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeEmissions.has_key( self.derniereChaine ) ):
if( self.listeEmissions[ self.derniereChaine ].has_key( emission ) ):
# On recupere la page web qui liste les fichiers
pageXML = self.API.getPage( self.listeEmissions[ self.derniereChaine ][ emission ] )
# On extrait les fichiers
listeFichiers = []
handler = PodcastsHandler( listeFichiers )
try:
xml.sax.parseString( pageXML, handler )
except:
return
# On ajoute les fichiers
for fichier in listeFichiers:
self.ajouterFichier( emission, fichier )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class MediciTV( Plugin ):
# Liens
urlPageEmissions = "http://www.medici.tv/api/menu/playlist/"
urlPageFichiers = "http://www.medici.tv/api/playlist/_ID_/_PAGE_/"
urlPageFichiersLien = "http://www.medici.tv/api/_PATH_"
lienRTMPFichier = "rtmp://fms033.lo1.hwcdn.net/v4m4b2s4/_definst_/mp4:fms/_LIEN_?FLVPlaybackVersion=2.1&doppl=d4b9dc3598d53667&dopsig=400d0e45687214d4f95eaf4be6791054"
# RegEx
listeEmissionsRegEx = re.compile( "<id>([^<]+)</id>.*?<title>([^<]+)</title>", re.DOTALL )
listeFichiersRegEx = re.compile( "<path>([^<]+)</path>.*?<title>([^<]+)</title>.*?<line2>([^<]+)</line2>", re.DOTALL )
listeFichiersDernierePageRegEx = re.compile( "<last_page>\d</last_page>" )
listeFichiersNomFichierRegEx = re.compile( "<stream>([^<]+)</stream>" )
# Listes
listeEmissions = {} # Clef = nom emission, Valeur = id de l'emission
def __init__( self):
Plugin.__init__( self, "Medici TV", "http://www.medici.tv", 30 )
def rafraichir( self ):
pass
def listerChaines( self ):
self.ajouterChaine( self.nom )
def listerEmissions( self, chaine ):
# On recupere la page qui liste les emissions
pageEmissions = self.API.getPage( self.urlPageEmissions )
# On extrait les emissions
resultats = re.findall( self.listeEmissionsRegEx, pageEmissions )
for res in resultats:
idEmission = res[ 0 ]
nomEmission = res[ 1 ]
# On enregistre l'emission et son id
self.listeEmissions[ nomEmission ] = idEmission
# On ajoute l'emission
self.ajouterEmission( chaine, nomEmission )
def listerFichiers( self, emission ):
# On recupere l'id de l'emission dont on veut les fichiers
if( self.listeEmissions.has_key( emission ) ):
idEmission = self.listeEmissions[ emission ]
# On va commencer a la premier page qui liste les fichiers
urlPageCourante = self.urlPageFichiers.replace( "_ID_", idEmission ).replace( "_PAGE_", "0" )
dernierePage = self.extraireFichierPage( emission, urlPageCourante )
# On continue sur les autres pages s'il y en a
if( dernierePage != 1 ):
for page in range( 2, dernierePage + 1 ):
urlPageCourante = self.urlPageFichiers.replace( "_ID_", idEmission ).replace( "_PAGE_", str( page ) )
self.extraireFichierPage( emission, urlPageCourante )
def extraireFichierPage( self, emission, urlPageCourante ):
pageCourante = self.API.getPage( urlPageCourante )
# On extrait le numero de la derniere page
try :
dernierePage = int( re.findall( self.listeFichiersDernierePageRegEx )[ 0 ] )
except :
dernierePage = 1
# On extrait les fichiers
resultatsFichiers = re.findall( self.listeFichiersRegEx, pageCourante )
for resFichiers in resultatsFichiers:
pathFichier = resFichiers[ 0 ]
nomFichier = resFichiers[ 1 ]
try :
dateFichier = resFichiers[ 2 ].split( "-" )[ 1 ]
except :
dateFichier = "Inconnue"
# On doit maintenant recuperer le lien du fichier sur une autre page
urlPageLienFichier = self.urlPageFichiersLien.replace( "_PATH_", pathFichier )
pageLienFichier = self.API.getPage( urlPageLienFichier )
if( pageLienFichier.find( "Please come back later" ) != -1 ): # S'il y a une erreur sur la page
continue
lienFichier = re.findall( self.listeFichiersNomFichierRegEx, pageLienFichier )[ 0 ]
lienBonFormat = self.lienRTMPFichier.replace( "_LIEN_", str( lienFichier.split( "/" )[ -1 ] ) )
# On ajoute le fichier
self.ajouterFichier( emission, Fichier( nomFichier, dateFichier, lienBonFormat ) )
# On renvoit le numero de la derniere page
return dernierePage
#~ rtmp://fms033.lo1.hwcdn.net/v4m4b2s4/_definst_/mp4:fms/VERBIER-1-20100716-combins-medici-hi.mp4?FLVPlaybackVersion=2.1&doppl=d4b9dc3598d53667&dopsig=400d0e45687214d4f95eaf4be6791054
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
# Modules Python
import datetime
import os.path
import re
import xml.sax
from xml.sax.handler import ContentHandler
# Modules de TVD
from Fichier import Fichier
from Plugin import Plugin
# Logger de TVD
import logging
logger = logging.getLogger( __name__ )
###########
# Classes #
###########
class CanalPlus( Plugin ):
urlFichierXMLListeProgrammes = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/initPlayer"
urlFichierXMLEmissions = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getMEAs/"
urlFichierXMLFichiers = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getVideos/"
def __init__( self ):
Plugin.__init__( self, "Canal+", "http://www.canalplus.fr/", 7 )
self.listeProgrammes = {} # { Nom chaine : { Nom emission : ID emission } }
self.derniereChaine = ""
if os.path.exists( self.fichierCache ):
self.listeProgrammes = self.chargerCache()
def rafraichir( self ):
logger.info( "récupération de la liste des chaines et des émissions" )
# On remet a 0 la liste des programmes
self.listeProgrammes.clear()
# On recupere la page qui contient les infos
pageXML = self.API.getPage( self.urlFichierXMLListeProgrammes )
# Handler
handler = CanalPlusListeProgrammesHandler( self.listeProgrammes )
# On parse le fichier xml
try:
xml.sax.parseString( pageXML, handler )
except:
logger.error( "impossible de parser le fichier XML de la liste des programmes" )
return
# On sauvegarde la liste dans le cache
self.sauvegarderCache( self.listeProgrammes )
logger.info( "liste des programmes sauvegardée" )
def listerChaines( self ):
for chaine in self.listeProgrammes.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeProgrammes.has_key( chaine ) ):
self.derniereChaine = chaine
for emission in self.listeProgrammes[ chaine ].keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeProgrammes.has_key( self.derniereChaine ) ):
listeEmissions = self.listeProgrammes[ self.derniereChaine ]
if( listeEmissions.has_key( emission ) ):
IDEmission = listeEmissions[ emission ]
# On recupere la page qui contient les ids des fichiers
pageXML = self.API.getPage( self.urlFichierXMLEmissions + IDEmission )
# On extrait les ids
listeIDs = re.findall( "<ID>(.+?)</ID>", pageXML )
# On construit la liste des liens a recuperer
listeURL = []
for IDFichier in listeIDs:
listeURL.append( self.urlFichierXMLFichiers + IDFichier )
# On recupere les pages correspondantes
pagesXML = self.API.getPages( listeURL )
# On parse chacune de ces pages
for URL in listeURL:
pageXMLFichier = pagesXML[ URL ]
# Handler
infosFichier = []
handler = CanalPlusListeFichierHandler( infosFichier )
# On parse le fichier xml
try:
xml.sax.parseString( pageXMLFichier, handler )
except:
logger.error( "impossible de parser le fichier XML de la liste des fichiers" )
continue
# On ajoute le fichier
nom, date, lienLD, lienMD, lienHD, urlImage, descriptif = infosFichier
# On transforme la date en type datetime.date
try:
dateDecoupee = map( int, date.split( "/" ) )
dateBonFormat = datetime.date( dateDecoupee[ 2 ], dateDecoupee[ 1 ], dateDecoupee[ 0 ] )
except:
dateBonFormat = date
if( lienHD != "" and lienHD[ : 4 ] == "rtmp" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lienHD )
self.ajouterFichier( emission, Fichier( "[HD]" + nom, dateBonFormat, lienHD, nom + extension, urlImage, descriptif ) )
elif( lienMD != "" and lienMD[ : 4 ] == "rtmp" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lienMD )
self.ajouterFichier( emission, Fichier( "[MD]" + nom, dateBonFormat, lienMD, nom + extension, urlImage, descriptif ) )
elif( lienLD != "" and lienLD[ : 4 ] == "rtmp" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lienLD )
self.ajouterFichier( emission, Fichier( "[LD]" + nom, dateBonFormat, lienLD, nom + extension, urlImage, descriptif ) )
#
# Parsers XML pour Canal+
#
## Classe qui permet de lire le fichier XML de Canal qui liste les emissions
class CanalPlusListeProgrammesHandler( ContentHandler ):
# Constructeur
# @param listeProgrammes Liste des programmes que le parser va remplir
def __init__( self, listeProgrammes ):
# Liste des programmes
self.listeProgrammes = listeProgrammes
# Liste des emissions d'un programme (temporaire)
# Clef : nom emission, Valeur : ID
self.listeEmissions = {}
# Initialisation des variables a Faux
self.nomChaineConnu = False
self.isNomChaine = False
self.isIDEmission = False
self.nomEmissionConnu = False
self.isNomEmission = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "THEMATIQUE" ):
pass
elif( name == "NOM" and self.nomChaineConnu == False ):
self.isNomChaine = True
elif( name == "ID" and self.nomChaineConnu == True ):
self.isIDEmission = True
elif( name == "NOM" and self.nomChaineConnu == True ):
self.isNomEmission = True
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
if( self.isNomChaine ):
self.nomChaine = data
self.nomChaineConnu = True
self.isNomChaine = False
elif( self.isIDEmission ):
self.IDEmission = data
self.isIDEmission = False
elif( self.isNomEmission ):
self.nomEmission = data
self.nomEmissionConnu = True
self.isNomEmission = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "THEMATIQUE" ):
self.listeProgrammes[ self.nomChaine.title() ] = self.listeEmissions
self.listeEmissions = {}
self.nomChaineConnu = False
elif( name == "NOM" and self.nomEmissionConnu ):
self.listeEmissions[ self.nomEmission.title() ] = self.IDEmission
self.nomEmissionConnu = False
## Classe qui permet de lire le fichier XML d'un fichier de Canal
class CanalPlusListeFichierHandler( ContentHandler ):
# Constructeur
# @param infosFichier Infos du fichier que le parser va remplir
def __init__( self, infosFichier ):
# Liste des programmes
self.infosFichier = infosFichier
# On n'a pas forcement les 3 liens
self.lienLD = ""
self.lienMD = ""
self.lienHD = ""
# Initialisation des variables a Faux
self.isTitre = False
self.isDate = False
self.isLienLD = False
self.isLienMD = False
self.isLienHD = False
self.isLienImage = False
self.isDescriptif = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "DESCRIPTION" ):
self.descriptif = ""
self.isDescriptif = True
elif( name == "DATE" ):
self.isDate = True
elif( name == "TITRAGE" ):
self.titre = ""
elif( name == "TITRE" or name == "SOUS_TITRE" ):
self.isTitre = True
elif( name == "PETIT" ):
self.isLienImage = True
elif( name == "BAS_DEBIT" ):
self.isLienLD = True
elif( name == "HAUT_DEBIT" ):
self.isLienMD = True
elif( name == "HD" ):
self.isLienHD = True
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
if( self.isDescriptif ):
self.descriptif += data
elif( self.isDate ):
self.date = data
self.isDate = False
elif( self.isTitre ):
self.titre += " %s" %( data )
self.isTitre = False
elif( self.isLienImage ):
self.urlImage = data
self.isLienImage = False
elif( self.isLienLD ):
self.lienLD = data
self.isLienLD = False
elif( self.isLienHD ):
self.lienHD = data
self.isLienHD = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "DESCRIPTION" ):
self.isDescriptif = False
elif( name == "VIDEO" ):
self.infosFichier[:] = self.titre, self.date, self.lienLD, self.lienMD, self.lienHD, self.urlImage, self.descriptif
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import hashlib
import os
import os.path
import xml.sax
from xml.sax.handler import ContentHandler
from Navigateur import Navigateur
import logging
logger = logging.getLogger( __name__ )
#############
# Variables #
#############
# Repertoires qui contiennent des plugins
repPlugins = [ os.path.expanduser( "~" ) + "/.tvdownloader/plugins",
"plugins" ]
##########
# Classe #
##########
## Classe qui gere les plugins
class UpdateManager( object ):
# Liste des sites qui disposent des mises a jour
listeSites = [ "http://tvdownloader.googlecode.com/hg/plugins" ]
# Instance de la classe (singleton)
instance = None
## Surcharge de la methode de construction standard (pour mettre en place le singleton)
def __new__( self, *args, **kwargs ):
if( self.instance is None ):
self.instance = super( UpdateManager, self ).__new__( self )
return self.instance
## Constructeur
def __init__( self ):
self.navigateur = Navigateur()
## Methode pour generer le fichier XML de description des plugins
@staticmethod
def creerXML():
# On ouvre le fichier XML
try:
fichierXML = open( "versionsPlugins.xml", "wt" )
except:
logger.error( "impossible d'ouvrir le fichier XML en ecriture" )
return
fichierXML.write( '<?xml version="1.0" encoding="UTF-8"?>\n' )
fichierXML.write( "<plugins>\n" )
# Pour chaque fichier de plugin
for fichier in os.listdir( "plugins" ):
# Tous les fichiers .py autre que __init__.py sont des plugins
if( fichier [ -3 : ] == ".py" and fichier.find( "__init__.py" ) == -1 ):
fichierCheminComplet = "plugins/%s" %( fichier )
# Nom du fichier
nom = fichier
# Date de la derniere modification
date = os.stat( fichierCheminComplet ).st_mtime
# Somme de controle SHA1
fichierPlugin = open( fichierCheminComplet, "rt" )
sha1 = hashlib.sha1( fichierPlugin.read() ).hexdigest()
fichierPlugin.close()
# On ajoute l'element au fichier XML
fichierXML.write( '\t<plugin nom="%s" dateModification="%s" sha1="%s"></plugin>\n' %( nom, date, sha1 ) )
# On ferme le fichier XML
fichierXML.write( "</plugins>\n" )
fichierXML.close()
## Methode qui verifie si les plugins disposent d'une mise a jour
# @param site Sites sur lesquel aller chercher la mise a jour
# @return Liste des plugins a mettre a jour [ Nom du plugin, URL ou charger le plugin, SHA1 du plugin ]
def verifierMiseAjour( self, site ):
listePluginsXML = [] # [ Nom, date derniere modification, SHA1 ]
listePluginAMettreAJour = [] # [ Nom du plugin, URL ou charger le plugin, SHA1 du plugin ]
handler = UpdateManagerHandler( listePluginsXML )
# On recupere le fichier XML de description des plugins
fichierXML = self.navigateur.getPage( "%s/versionsPlugins.xml" %( site ) )
if( fichierXML == "" ): # Si on n'a rien recupere, on essaye un autre site
logger.warn( "aucune information disponible sur le site %s" %( site ) )
return []
# On vide la liste
del listePluginsXML[ : ]
# On parse le fichier XML
try:
xml.sax.parseString( fichierXML, handler )
except:
logger.error( "impossible de parser le fichier XML du site %s" %( site ) )
return []
# Pour chaque plugin decrit dans le fichier XML
for( nom, dateModification, sha1 ) in listePluginsXML:
# On n'a pas une nouvelle version du plugin
nouvelleVersion = False
# Dans chacun des repertoires qui contiennent des plugins
for rep in repPlugins:
pluginCheminComplet = "%s/%s" %( rep, nom )
# Si le plugin est present
if( os.path.isfile( pluginCheminComplet ) ):
# Si la version dont l'on dispose est moins recente que celle du site
if( os.stat( pluginCheminComplet ).st_mtime < dateModification ):
nouvelleVersion = True
else:
nouvelleVersion = False
break # On peut arrete de chercher, on a deja le plus recent
# S'il y a une nouvelle version
if( nouvelleVersion ):
listePluginAMettreAJour.append( [ nom, "%s/%s" %( site, nom ), sha1 ] )
# On a fini de lire les infos sur ce site, pas besoin de parcourir les autres
return listePluginAMettreAJour
# Methode pour installer la mise a jour d'un plugin
# @param nomPlugin Nom du fichier du plugin a mettre a jour
# @param urlPlugin URL ou charger le plugin
# @param sha1 Somme de controle SHA1 du plugin
# @return Si le plugin a ete correctement installe
def mettreAJourPlugin( self, nomPlugin, urlPlugin, sha1 ):
logger.info( "mise a jour du plugin %s" %( nomPlugin ) )
# On telecharge le plugin
codePlugin = self.navigateur.getPage( urlPlugin )
if( codePlugin == "" ):
return False
# On verifie la somme de controle du plugin
if( hashlib.sha1( codePlugin ).hexdigest() != sha1 ):
logger.warn( "somme de controle incorrecte pour le fichier %s" %( urlPlugin ) )
return False
# On met en place le plugin
fichier = open( "%s/%s" %( repPlugins[ 0 ], nomPlugin ), 'wt' )
fichier.write( codePlugin )
fichier.close()
return True
#
# Parser XML pour le fichier versionsPlugins.xml
#
## Classe qui permet de lire le fichier XML versionsPlugins.xml
class UpdateManagerHandler( ContentHandler ):
# Constructeur
# @param listePluginsXML Liste des plugins que l'on va remplir
def __init__( self, listePluginsXML ):
self.listePluginsXML = listePluginsXML # [ Nom, date derniere modification, SHA1 ]
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "plugin" ):
nom = attrs.get( "nom", "" )
dateModification = attrs.get( "dateModification", "" )
sha1 = attrs.get( "sha1", "" )
self.listePluginsXML.append( [ nom, float( dateModification ), sha1 ] )
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
pass
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
pass
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import httplib,re,zlib, os.path, time, pickle
from random import choice
from traceback import print_exc
import logging
logger = logging.getLogger( __name__ )
from htmlentitydefs import codepoint2name
SPECCAR_CODE = {}
type = []
for code in codepoint2name:
SPECCAR_CODE[codepoint2name[code]] = unicode(unichr(code)).encode("UTF-8", "replace")
from Fichier import Fichier
from Option import Option
##########
# Classe #
##########
class APIPrive():
## Contructeur
# @param self l'objet courant
def __init__(self):
self.listePluginActif = {}
self.listePlugin = {}
## Active un plugin (il faut qu'il ait déjà été ajouté).
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @return Rien
def activerPlugin(self, nomPlugin):
if self.listePlugin.has_key(nomPlugin):
self.listePluginActif[nomPlugin] = self.listePlugin[nomPlugin]
## Désactive un plugin (il faut qu'il ait déjà été ajouté).
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @return Rien
def desactiverPlugin(self, nomPlugin):
if self.listePluginActif.has_key(nomPlugin):
self.listePluginActif.pop(nomPlugin)
## Ajoute un plugin.
# @param self l'objet courant
# @param instance l'instance du plugin
# @return Rien
def ajouterPlugin(self, instance):
if not self.listePlugin.has_key(instance.nom):
self.listePluginActif[instance.nom] = instance
self.listePlugin[instance.nom] = instance
## Spécifie la liste des instances des plugins.
# @param self l'objet courant
# @param liste la liste des instances
# @return Rien
# @deprecated Utiliser #ajouterPlugin à la place.
def setListeInstance(self, liste):
logger.warn("DEPRECATED: APIPrive.setListeInstance: utilisez #ajouterPlugin")
self.listePluginActif = {}
for instance in liste:
self.ajouterPlugin(instance)
#/*******************
# * CONSTANTES *
# *******************/
DATA_CHAINE = "chaines"
DATA_EMISSION = "emissions"
DATA_FICHIER = "fichiers"
#/**************
# * GETTERS *
# **************/
## Renvoie la liste des plugins (leur nom)
# @param self l'objet courant
# @return la liste des noms des plugins
def getPluginListe(self):
return self.listePluginActif.keys()
## Renvoie la liste des chaînes.
#
# Si nomPlugin est égal à None, la liste des chaînes de tout les plugins est renvoyée, sinon c'est celle du plugin portant le nom passé en paramètre.
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @return la liste des chaînes du plugin
def getPluginListeChaines(self, nomPlugin=None):
if nomPlugin != None and not self.listePluginActif.has_key(nomPlugin):
return []
liste = []
if nomPlugin == None:
for nom in self.listePluginActif.keys():
plugin = self.listePluginActif[nom]
if len(plugin.pluginDatas[APIPrive.DATA_CHAINE]) == 0:
plugin.listerChaines()
liste+=plugin.pluginDatas[APIPrive.DATA_CHAINE]
else:
plugin = self.listePluginActif[nomPlugin]
if len(plugin.pluginDatas[APIPrive.DATA_CHAINE]) == 0:
plugin.listerChaines()
liste+=plugin.pluginDatas[APIPrive.DATA_CHAINE]
return liste
## Renvoie la liste des émissions pour un plugin et une chaîne donné.
#
# Si nomPlugin est égal à None, la liste des émissions de tout les plugins est renvoyée, sinon c'est celle du plugin portant le nom passé en paramètre. Si chaine est égal à None, la liste des émissions de toute les chaines du plugin est renvoyée.
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @param chaine le nom de la chaîne
# @return la liste des émissions
def getPluginListeEmissions(self, nomPlugin=None, chaine=None):
if nomPlugin != None and not self.listePluginActif.has_key(nomPlugin):
return []
liste= []
if nomPlugin == None:
for nom in self.listePluginActif.keys():
plugin = self.listePluginActif[nom]
for chaine in self.getPluginListeChaines(nom):
if not plugin.pluginDatas[APIPrive.DATA_EMISSION].has_key(chaine):
plugin.pluginDatas[APIPrive.DATA_EMISSION][chaine] = []
plugin.listerEmissions(chaine)
liste+=plugin.pluginDatas[APIPrive.DATA_EMISSION][chaine]
elif chaine == None:
plugin = self.listePluginActif[nomPlugin]
for chaine in self.getPluginListeChaines(nomPlugin):
if not plugin.pluginDatas[APIPrive.DATA_EMISSION].has_key(chaine):
plugin.pluginDatas[APIPrive.DATA_EMISSION][chaine] = []
plugin.listerEmissions(chaine)
liste+=plugin.pluginDatas[APIPrive.DATA_EMISSION][chaine]
else:
plugin = self.listePluginActif[nomPlugin]
if not plugin.pluginDatas[APIPrive.DATA_EMISSION].has_key(chaine):
plugin.pluginDatas[APIPrive.DATA_EMISSION][chaine] = []
plugin.listerEmissions(chaine)
liste+=plugin.pluginDatas[APIPrive.DATA_EMISSION][chaine]
return liste
## Renvoie la liste des fichiers pour un plugin et une émission donné
#
# Si nomPlugin est égal à None, la liste des fichiers de tout les plugins est renvoyée, sinon c'est celle du plugin portant le nom passé en paramètre. Si emission est égal à None, la liste des fichiers de toute les émissions du plugin est renvoyée.
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @param emission le nom de l'émission
# @return la liste des fichiers
def getPluginListeFichiers(self, nomPlugin=None, emission=None):
if nomPlugin != None and not self.listePluginActif.has_key(nomPlugin):
return []
liste= []
if nomPlugin == None:
for nom in self.listePluginActif.keys():
plugin = self.listePluginActif[nom]
for emission in self.getPluginListeEmissions(nom):
if not plugin.pluginDatas[APIPrive.DATA_FICHIER].has_key(emission):
plugin.pluginDatas[APIPrive.DATA_FICHIER][emission] = []
plugin.listerFichiers(emission)
liste+=plugin.pluginDatas[APIPrive.DATA_FICHIER][emission]
elif emission == None:
plugin = self.listePluginActif[nomPlugin]
for emission in self.getPluginListeEmissions(nomPlugin):
if not plugin.pluginDatas[APIPrive.DATA_FICHIER].has_key(emission):
plugin.pluginDatas[APIPrive.DATA_FICHIER][emission] = []
plugin.listerFichiers(emission)
liste+=plugin.pluginDatas[APIPrive.DATA_FICHIER][emission]
else:
plugin = self.listePluginActif[nomPlugin]
if not plugin.pluginDatas[APIPrive.DATA_FICHIER].has_key(emission):
plugin.pluginDatas[APIPrive.DATA_FICHIER][emission] = []
plugin.listerFichiers(emission)
liste+=plugin.pluginDatas[APIPrive.DATA_FICHIER][emission]
return liste
## Renvoie la liste des options pour un plugin donné
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @return la liste des options
def getPluginListeOptions(self, nomPlugin):
if not self.listePluginActif.has_key(nomPlugin):
return []
return self.listePluginActif[nomPlugin].pluginOptions
## Renvoie l'option d'un plugin
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @param nomOption le nom de l'option
# @return la valeur de l'option, None en cas d'échec
def getPluginOption(self, nomPlugin, nomOption):
if nomPlugin != None and not self.listePluginActif.has_key(nomPlugin):
return None
plugin = self.listePluginActif[nomPlugin]
for option in plugin.pluginOptions:
if option.getNom() == nomOption:
return option
return None
#/**************
# * SETTERS *
# **************/
## Change la valeur d'une option d'un plugin.
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @param valeur la valeur de l'option
# @return Rien
def setPluginOption(self, nomPlugin, nomOption, valeur):
if nomPlugin != None and not self.listePluginActif.has_key(nomPlugin):
return None
plugin = self.listePluginActif[nomPlugin]
plugin.pluginDatas = {"chaines":[],
"emissions":{},
"fichiers":{}}
for option in plugin.pluginOptions:
if option.getNom() == nomOption:
option.setValeur(valeur)
#/************
# * DIVERS *
# ************/
## Rafraichie un plugin (appel à Plugin.rafraichir)
# @param self l'objet courant
# @param nomPlugin le nom du plugin
# @return Rien
def pluginRafraichir(self, nomPlugin):
try:
if self.listePluginActif.has_key(nomPlugin):
self.listePluginActif[nomPlugin].vider()
self.listePluginActif[nomPlugin].rafraichir()
except Exception, ex:
logger.error("Erreur lors du rafraichissement du plugin",self.listePlugin[nomPlugin].nom+":"+str(ex))
print_exc()
## Rafraichie tous les plugins qui ont besoin de l'être.
#
# Doit être appelé obligatoirement après l'ajout des plugins.
# @param self l'objet courant
# @return Rien
def pluginRafraichirAuto(self):
t = time.time()
for instance in self.listePlugin.values():
if instance.frequence >= 0:
if os.path.isfile(instance.fichierCache):
delta = t-os.path.getmtime(instance.fichierCache)
if delta > instance.frequence*86400:
self.pluginRafraichir(instance.nom)
else:
self.pluginRafraichir(instance.nom)
#~ instance.chargerPreference()
#~ if len(instance.pluginOptions) == 0:
#~ instance.listerOptions()
instance.listerOptions()
if os.path.exists(instance.fichierConfiguration):
try:
file = open(instance.fichierConfiguration, "r")
tmp = pickle.load(file)
file.close()
for k in tmp.keys():
self.setPluginOption(instance.nom, k, tmp[k])
except:
logger.error( u"impossible de charger les préférences de %s" %( instance.nom ) )
## Effectue les tâches de sauvegarde avant la fermeture.
#
# Doit être absolument appelé avant la fermeture.
# @param self l'objet courant
def fermeture(self):
for instance in self.listePluginActif.values():
if len(instance.pluginOptions) > 0:
try:
pref = {}
for o in instance.pluginOptions:
pref[o.getNom()] = o.getValeur()
file = open(instance.fichierConfiguration, "w")
pickle.dump(pref, file)
file.close()
except:
logger.error("Erreur de sauvegarde des préférences de"+instance.nom)
#/*************
# * AUTRES *
# *************/
USER_AGENT = [ 'Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; fr; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; fr; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.1b2) Gecko/20081201 Firefox/3.1b2',
'Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.2) Gecko/20100115 Firefox/3.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Opera/8.50 (Windows NT 5.1; U; en)',
'Opera/9.80 (X11; Linux x86_64; U; fr) Presto/2.2.15 Version/10.00',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312' ]
PATTERN_CHARSET = re.compile("charset=(.*?)$", re.IGNORECASE)
PATTERN_SPECCAR= re.compile("&(.+?);")
PATTERN_URL = re.compile("http://(.+?)(/.*)|(.+?)(/.*)")
TAILLE_BLOCK = 1000#essayé avec 8k mais plante :/
HTTP_TIMEOUT = 5
def reponseHttpToUTF8(self, reponse):
"""Renvoie le corp d'une réponse HTTP en UTF8, décompressé et débarassé des caractères spéciaux html.
Renvoie la chaîne vide en cas d'échec."""
data = ""
if reponse.getheader('Content-Encoding', '').find('gzip') >= 0:
try:
decomp = zlib.decompressobj(16+zlib.MAX_WBITS)#chiffre "magic" apparemment
while True:
buff = reponse.read(APIPrive.TAILLE_BLOCK)
if not(buff):
break
data = data+decomp.decompress(buff)
except:
logger.warn("APIPrive.reponseHttpToUTF8(): erreur de décompression")
return ""
else:
data = reponse.read()
#Vérification de l'encodage et conversion si néscessaire
encoding = reponse.getheader("Content-Type", "")
if encoding != "":
try:
match = re.search(APIPrive.PATTERN_CHARSET, encoding)
if match != None and encoding != "utf-8":
data = unicode(data, match.group(1), "replace").encode("utf-8", "replace")
else:
logger.info("APIPrive.reponseHttpToUTF8(): encodage inconnu.")
except:
logger.error("APIPrive.reponseHttpToUTF8(): erreur de décodage.")
iters = []
for match in re.finditer(APIPrive.PATTERN_SPECCAR, data):
iters.insert(0, match)
for match in iters:
if match.group(1)[0] == "#":
try:
car = chr(int(match.group(1)[1:]))
data = data[:match.start()] + car + data[match.end():]
except:
#Rien
rien = None
elif SPECCAR_CODE.has_key(match.group(1)):
data = data[:match.start()] + SPECCAR_CODE[match.group(1)] + data[match.end():]
return data
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import threading
from PyQt4 import QtGui, QtCore
from GUI.Qt.MyQTableWidget import MyQTableWidget
from GUI.Qt.MyQPushButton import MyQPushButton
from UpdateManager import UpdateManager
from GUI.ConvertQString import *
##########
# Classe #
##########
## Classe qui gere le dialog du gestionnaire de mise a jour
class UpdateManagerDialog( QtGui.QDialog ):
## Constructeur
def __init__( self, parent ):
# Appel au constructeur de la classe mere
QtGui.QDialog.__init__( self, parent )
self.updateManager = UpdateManager()
###########
# Fenetre #
###########
###
# Reglages de la fenetre principale
###
# Nom de la fenetre
self.setWindowTitle( u"Mise à jour des plugins" )
# Dimensions la fenetre
self.resize( 1, 190 )
# Mise en place de son icone
self.setWindowIcon( QtGui.QIcon( "ico/gtk-refresh.svg" ) )
###
# Mise en place des widgets dans la fenetre
###
# Layout de grille principal
self.gridLayout = QtGui.QGridLayout( self )
# Font pour les titres
fontTitres = QtGui.QFont()
fontTitres.setPointSize( 11 )
fontTitres.setWeight( 75 )
fontTitres.setBold( True )
#
# Choix du miroir pour la mise a jour
#
# Label
self.labelMiroir = QtGui.QLabel( self )
self.labelMiroir.setFont( fontTitres )
self.labelMiroir.setText( u"Miroir :" )
# Choix du miroir
self.comboBoxMiroir = QtGui.QComboBox( self )
self.comboBoxMiroir.setEditable( True )
for miroir in UpdateManager.listeSites:
self.comboBoxMiroir.addItem( stringToQstring( miroir ) )
# Bouton pour lancer la recherche
self.pushButtonRecherche = QtGui.QPushButton( self )
self.pushButtonRecherche.setIcon( QtGui.QIcon( "ico/gtk-refresh.svg" ) )
self.pushButtonRecherche.setToolTip( u"Rechercher les mises à jour des plugins" )
# Label info
self.labelInfo = QtGui.QLabel( self )
self.labelInfo.setText( u"(il faut redémarer le logiciel pour que les mises à jour soient prises en compte)" )
#
# Affichage des plugins a mettre a jour
#
# Table widget qui contient la liste des plugins a mettre a jour
self.tableWidgetPlugins = MyQTableWidget( self )
# Il a 2 colonnes et 0 ligne (pour l'instant)
self.tableWidgetPlugins.setColumnCount( 2 )
self.tableWidgetPlugins.setRowCount( 0 )
# On ajoute les titres
self.tableWidgetPlugins.setHorizontalHeaderItem( 0,
self.tableWidgetPlugins.creerItem( "" ) )
self.tableWidgetPlugins.setHorizontalHeaderItem( 1,
self.tableWidgetPlugins.creerItem( "Nom du plugin" ) )
# Icones du tableWidget
self.iconeMAJ = QtGui.QIcon( "ico/gtk-add.svg" )
self.iconeMAJReussie = QtGui.QIcon( "ico/gtk-apply.svg" )
self.iconeMAJEchouee = QtGui.QIcon( "ico/gtk-cancel.svg" )
# Bouton pour lancer l'installation des plugins a mettre a jour
self.pushButtonLancerInstallation = MyQPushButton( self )
self.pushButtonLancerInstallation.setIcon( QtGui.QIcon( "ico/gtk-media-play-ltr.svg" ) )
self.pushButtonLancerInstallation.setToolTip( u"Installer les mises à jour des plugins" )
# Bouton pour redemarrer/fermer la fenetre
self.buttonBox = QtGui.QDialogButtonBox( self )
#~ self.buttonBox.addButton( "Redemmarer programme", QtGui.QDialogButtonBox.AcceptRole )
self.buttonBox.addButton( "Fermer", QtGui.QDialogButtonBox.RejectRole )
# On ajoute le tout au layout
self.gridLayout.addWidget( self.labelMiroir, 0, 0, 1, 1 )
self.gridLayout.addWidget( self.comboBoxMiroir, 0, 1, 1, 1 )
self.gridLayout.addWidget( self.pushButtonRecherche, 0, 2, 1, 1 )
self.gridLayout.addWidget( self.labelInfo, 1, 0, 1, 3 )
self.gridLayout.addWidget( self.tableWidgetPlugins, 2, 0, 1, 2 )
self.gridLayout.addWidget( self.pushButtonLancerInstallation, 2, 2, 1, 1 )
self.gridLayout.addWidget( self.buttonBox, 3, 0, 1, 3 )
###
# Signaux
###
QtCore.QObject.connect( self.pushButtonRecherche, QtCore.SIGNAL( "clicked()" ), self.rechercheMiseAJour )
QtCore.QObject.connect( self.pushButtonLancerInstallation, QtCore.SIGNAL( "clicked()" ), self.mettreAJourPlugins )
#~ QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "accepted()" ), self.??? )
QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "rejected()" ), self.reject )
QtCore.QObject.connect( self, QtCore.SIGNAL( "finRechercheMAJ(PyQt_PyObject)" ), self.afficherMiseAJour )
self.listePluginAMettreAJour = []
## Methode pour afficher la fenetre des preferences
def afficher( self ):
# On n'active pas le bouton d'installation
self.pushButtonLancerInstallation.setEnabled( False )
# On affiche la fenetre
self.exec_()
## Methode qui va lancer la recherche de mise a jour sur le site actuellement selectionne
def rechercheMiseAJour( self ):
def threadRechercheMiseAJour( self, site ):
listePluginAMettreAJour = self.updateManager.verifierMiseAjour( site )
self.emit( QtCore.SIGNAL( "finRechercheMAJ(PyQt_PyObject)" ), listePluginAMettreAJour )
site = qstringToString( self.comboBoxMiroir.currentText() )
threading.Thread( target = threadRechercheMiseAJour, args = ( self, site ) ).start()
## Methode qui affiche les mise a jour
# @param listePluginAMettreAJour Liste des plugins a mettre a jour [ Nom du plugin, URL ou charger le plugin, SHA1 du plugin ]
def afficherMiseAJour( self, listePluginAMettreAJour ):
self.listePluginAMettreAJour = listePluginAMettreAJour
self.tableWidgetPlugins.toutSupprimer()
# Si on n'a rien recuperer
if( len( listePluginAMettreAJour ) == 0 ):
QtGui.QMessageBox.information( self,
u"Mise à jour des plugins",
u"Aucune mise à jour disponible."
)
# On n'active pas le bouton d'installation
self.pushButtonLancerInstallation.setEnabled( False )
else:
ligneCourante = 0
for( nom, url, sha1 ) in self.listePluginAMettreAJour:
# On ajoute une ligne
self.tableWidgetPlugins.insertRow( ligneCourante )
self.tableWidgetPlugins.setLigne( ligneCourante, [ self.tableWidgetPlugins.creerItem( "" ),
self.tableWidgetPlugins.creerItem( stringToQstring( nom ) )
]
)
self.tableWidgetPlugins.item( ligneCourante, 0 ).setIcon( self.iconeMAJ )
ligneCourante += 1
# On active le bouton d'installation
self.pushButtonLancerInstallation.setEnabled( True )
## Methode qui met a jour tous les plugins
def mettreAJourPlugins( self ):
def threadMettreAJour( self ):
ligne = 0
for( nom, url, sha1 ) in self.listePluginAMettreAJour:
retour = self.updateManager.mettreAJourPlugin( nom, url, sha1 )
if( retour ):
self.tableWidgetPlugins.item( ligne, 0 ).setIcon( self.iconeMAJReussie )
else:
self.tableWidgetPlugins.item( ligne, 0 ).setIcon( self.iconeMAJEchouee )
ligne += 1
# On n'active pas le bouton d'installation
self.pushButtonLancerInstallation.setEnabled( False )
threading.Thread( target = threadMettreAJour, args = ( self, ) ).start()
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
import re
import shlex
import subprocess
import time
from fonctions.urlToRtmpdump import urlToRtmpdump
from PyQt4 import QtGui, QtCore
import logging
logger = logging.getLogger( __name__ )
##########
# Classe #
##########
## Classe qui gere le telechargement des fichiers
class Downloader( QtCore.QObject ):
repertoireTelechargement = ""
# Instance de la classe (singleton)
instance = None
def __new__( cls, *args, **kwargs ):
if( cls.instance is None ):
cls.instance = super( Downloader, cls ).__new__( cls, *args, **kwargs )
return cls.instance
## Constructeur
def __init__( self ):
QtCore.QObject.__init__( self )
self.arreter = True
self.process = None
## Methode pour telecharger un fichier
# @param fichier Fichier a telecharger
# @return Booleen qui indique si le telechargement a reussi
def telecharger( self, fichier ):
# Chemin complet du fichier de sortie
fichierSortie = os.path.join( self.repertoireTelechargement, getattr( fichier, "nomFichierSortie" ) )
# URL du fichier
urlFichier = str( getattr( fichier, "lien" ) )
logger.info( u"téléchargement de %s" %( urlFichier ) )
# On va creer la commande a executer pour telecharger le fichier
# L'outil va dependre du protocol
if( urlFichier[ :4 ] == "rtmp" ):
commande = '%s -o "%s"' %( urlToRtmpdump( urlFichier ), fichierSortie )
elif( urlFichier[ :4 ] == "http" or urlFichier[ :3 ] == "ftp" or urlFichier[ :3 ] == "mms" ):
commande = "msdl -c " + urlFichier + ' -o "' + fichierSortie + '"'
else:
logger.warn( u"le protocole du fichier %s n'est pas géré" %( urlFichier ) )
return False
# Commande mise au bon format pour Popen
if( not isinstance( commande, str ) ):
commande = str( commande )
# Arguments a donner a Popen
arguments = shlex.split( commande )
# On commence
self.arreter = False
# On lance la commande en redirigeant stdout et stderr (stderr va dans stdout)
self.process = subprocess.Popen( arguments, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, universal_newlines = True )
# On recupere le flux stdout
stdoutF = self.process.stdout
# Tant que le subprocess n'est pas fini
while( self.process.poll() == None ):
# On lit stdout
ligne = stdoutF.readline()
# On recupere le pourcentage (s'il est affiche)
pourcentListe = re.findall( "(\d{1,3}\.{0,1}\d{0,1})%", ligne )
if( pourcentListe != [] ):
pourcent = int( float( pourcentListe[ -1 ] ) )
if( pourcent >= 0 and pourcent <= 100 ):
# On envoit le pourcentage d'avancement a l'interface
self.emit( QtCore.SIGNAL( "pourcentageFichier(int)" ), pourcent )
# On attent avant de recommencer a lire
time.sleep( 1 )
# On a fini
self.arreter = True
self.process = None
# Le telechargement s'est bien passe
return True
## Methode pour stopper le telechargement d'un fichier
def stopperTelechargement( self ):
if not self.arreter:
self.arreter = True
# On stop le process s'il est lance
if( self.process != None and self.process.poll() == None ):
self.process.terminate()
#~ self.process.kill()
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
from PyQt4 import QtGui, QtCore
from Preferences import Preferences
from PluginManager import PluginManager
from GUI.ConvertQString import *
##########
# Classe #
##########
## Classe qui gere le dialog des preferences du logiciel
class PreferencesDialog( QtGui.QDialog ):
## Constructeur
def __init__( self, parent ):
# Appel au constructeur de la classe mere
QtGui.QDialog.__init__( self, parent )
self.preferences = Preferences()
self.pluginManager = PluginManager()
###########
# Fenetre #
###########
###
# Reglages de la fenetre principale
###
# Nom de la fenetre
self.setWindowTitle( u"Préférences" )
# Dimensions la fenetre
self.resize( 325, 510 )
# Mise en place de son icone
self.setWindowIcon( QtGui.QIcon( "ico/gtk-preferences.svg" ) )
###
# Mise en place des widgets dans la fenetre
###
# Layout du dialog (il ne contiendra que la scroll area)
self.layoutPrincipal = QtGui.QVBoxLayout( self )
# Scroll Area (elle ne contiendra que le widget central)
self.scrollArea = QtGui.QScrollArea( self )
self.layoutPrincipal.addWidget( self.scrollArea )
# Widget central
self.widgetCentral = QtGui.QWidget( self.scrollArea )
# Layout de grillequi contient les elements
self.gridLayout = QtGui.QGridLayout( self.widgetCentral )
# Font pour les titres
fontTitres = QtGui.QFont()
fontTitres.setPointSize( 11 )
fontTitres.setWeight( 75 )
fontTitres.setBold( True )
#
# Choix du repertoire telechargement
#
# Label
self.labelRepertoire = QtGui.QLabel( self )
self.labelRepertoire.setFont( fontTitres )
self.labelRepertoire.setText( u"Répertoire de téléchargement :" )
# Repertoire de telechargement
self.lineEditRepertoireTelechargement = QtGui.QLineEdit( self )
# Bouton pour ouvrir la fenetre de selection de repertoire
self.pushButtonSelectionDossier = QtGui.QPushButton( self )
self.pushButtonSelectionDossier.setIcon( QtGui.QIcon( "ico/gtk-folder.svg" ) )
#
# Choix du plugin par defaut
#
# Label
self.labelPluginDefaut = QtGui.QLabel( self )
self.labelPluginDefaut.setFont( fontTitres )
self.labelPluginDefaut.setText( u"Plugin par défaut :" )
# Liste de choix du plugin par defaut
self.comboBoxPluginDefaut = QtGui.QComboBox( self )
#
# Choix des plugins a activer
#
# Label
self.labelPlugins = QtGui.QLabel( self )
self.labelPlugins.setFont( fontTitres )
self.labelPlugins.setText( "Plugins actifs :" )
# Liste des plugins
self.listWidgetPlugin = QtGui.QListWidget( self )
#
# Choix des parametres Internet
#
# Label
self.labelInternet = QtGui.QLabel( self )
self.labelInternet.setFont( fontTitres )
self.labelInternet.setText( u"Paramètres Internet :" )
# Layout formulaire
self.layoutInternet = QtGui.QFormLayout()
# SpinBox pour choisir le timeOut
self.spinBoxTimeOut = QtGui.QSpinBox()
self.spinBoxTimeOut.setMinimum( 1 )
self.spinBoxTimeOut.setMaximum( 60 )
self.layoutInternet.addRow( u"Time out (en s) :", self.spinBoxTimeOut )
# SpinBox pour choisir le nombre de threads max
self.spinBoxNbThread = QtGui.QSpinBox()
self.spinBoxNbThread.setMinimum( 1 )
self.spinBoxNbThread.setMaximum( 100 )
self.layoutInternet.addRow( u"Nombre de threads max :", self.spinBoxNbThread )
# Bouton pour enregistrer/annuler les preferences
self.buttonBox = QtGui.QDialogButtonBox( self )
self.buttonBox.addButton( "Enregistrer", QtGui.QDialogButtonBox.AcceptRole )
self.buttonBox.addButton( "Fermer", QtGui.QDialogButtonBox.RejectRole )
# On ajoute le tout au layout
self.gridLayout.addWidget( self.labelRepertoire, 0, 0, 1, 2 )
self.gridLayout.addWidget( self.lineEditRepertoireTelechargement, 1, 0, 1, 1 )
self.gridLayout.addWidget( self.pushButtonSelectionDossier, 1, 1, 1, 1 )
self.gridLayout.addWidget( self.labelPluginDefaut, 2, 0, 1, 2 )
self.gridLayout.addWidget( self.comboBoxPluginDefaut, 3, 0, 1, 2 )
self.gridLayout.addWidget( self.labelPlugins, 4, 0, 1, 2 )
self.gridLayout.addWidget( self.listWidgetPlugin, 5, 0, 1, 2 )
self.gridLayout.addWidget( self.labelInternet, 6, 0, 1, 2 )
self.gridLayout.addLayout( self.layoutInternet, 7, 0, 1, 2 )
# Les boutons sont ajoutes au layout principal
self.layoutPrincipal.addWidget( self.buttonBox )
# On adapte la taille du widget
self.widgetCentral.adjustSize()
# On ajoute le widget central a la scroll area
self.scrollArea.setWidget( self.widgetCentral )
###
# Signaux provenants de l'interface
###
QtCore.QObject.connect( self.pushButtonSelectionDossier, QtCore.SIGNAL( "clicked()" ), self.afficherSelecteurDossier )
QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "accepted()" ), self.enregistrerPreferences )
QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "rejected()" ), self.reject )
## Methode pour afficher la fenetre des preferences
def afficher( self ):
# On met en place dans le textEdit le repertoire
self.lineEditRepertoireTelechargement.setText( stringToQstring( self.preferences.getPreference( "repertoireTelechargement" ) ) )
# On met en place le plugin par defaut
self.remplirPluginParDefaut()
# On met en place la liste des plugins
self.afficherPlugins()
# On met en place les valeurs des SpinBox
self.spinBoxTimeOut.setValue( self.preferences.getPreference( "timeOut" ) )
self.spinBoxNbThread.setValue( self.preferences.getPreference( "nbThreadMax" ) )
# On affiche la fenetre
self.exec_()
## Methode pour enregistrer les preferences du logiciel
def enregistrerPreferences( self ):
# On sauvegarde les valeurs des SpinBox
self.preferences.setPreference( "nbThreadMax", self.spinBoxNbThread.value() )
self.preferences.setPreference( "timeOut", self.spinBoxTimeOut.value() )
# On sauvegarde les plugins actifs
self.sauvegarderPlugins()
# On sauvegarde le plugin par defaut
self.preferences.setPreference( "pluginParDefaut", qstringToString( self.comboBoxPluginDefaut.currentText() ) )
# On sauvegarde le repertoire de telechargement
self.preferences.setPreference( "repertoireTelechargement", qstringToString( self.lineEditRepertoireTelechargement.text() ) )
# On sauvegarde dans le fichier
self.preferences.sauvegarderConfiguration()
# On masque la fenetre
self.hide()
####################################################################
# Methodes qui gerent l'emplacement de telechargement des fichiers #
####################################################################
## Methode qui affiche le selecteur de dossier
def afficherSelecteurDossier( self ):
rep = QtGui.QFileDialog.getExistingDirectory( None,
u"Sélectionnez le répertoire de téléchargement",
self.lineEditRepertoireTelechargement.text(),
QtGui.QFileDialog.ShowDirsOnly
)
# Si le repertoire existe
if( os.path.isdir( qstringToString( rep ) ) ):
self.lineEditRepertoireTelechargement.setText( rep ) # On modifie la zone de texte qui affiche le repertoire
################################################
# Methodes qui gerent la partie plugins actifs #
################################################
## Methode qui liste les plugins actif dans le listWidgetPlugin
def afficherPlugins( self ):
# On recupere les listes de plugins
listePluginsDisponibles = self.pluginManager.getListeSites()
listePluginsDisponibles.sort() # On trie cette liste
listePluginsActives = self.preferences.getPreference( "pluginsActifs" )
# On remet a 0 le listWidget
self.listWidgetPlugin.clear()
# On affiche les plugins
for plugin in listePluginsDisponibles:
# On met en place l'item
self.listWidgetPlugin.addItem( self.creerItem( plugin, plugin in listePluginsActives ) )
## Methode qui remplie la combo box du plugin par defaut
def remplirPluginParDefaut( self ):
# On efface la liste
self.comboBoxPluginDefaut.clear()
# On ajoute les plugins actifs
for plugin in self.preferences.getPreference( "pluginsActifs" ):
self.comboBoxPluginDefaut.addItem( stringToQstring( plugin ) )
# On selectionne le plugin par defaut
index = self.comboBoxPluginDefaut.findText( stringToQstring( self.preferences.getPreference( "pluginParDefaut" ) ) )
if( index != -1 ):
self.comboBoxPluginDefaut.setCurrentIndex( index )
## Methode qui sauvegarde les plugins actifs
def sauvegarderPlugins( self ):
# On liste les plugins actifs
liste = []
for i in range( self.listWidgetPlugin.count() ): # Pour chaque ligne
if( self.listWidgetPlugin.item( i ).checkState() == QtCore.Qt.Checked ): # Si elle est selectionnee
liste.append( qstringToString( self.listWidgetPlugin.item( i ).text() ) )
# On met cela en place dans les preferences
self.preferences.setPreference( "pluginsActifs", liste )
# On relance l'actualisation de l'affichage
self.emit( QtCore.SIGNAL( "actualiserListesDeroulantes()" ) )
####################
# Autres methodes #
####################
## Methode qui creer une element pour un listeWidget
# @param texte Texte de l'element
# @param checkBox Si la checkBox de l'element est cochee ou non
# @return L'element cree
def creerItem( self, texte, checkBox = False ):
# On cree l'item avec le texte
item = QtGui.QListWidgetItem( stringToQstring( texte ) )
# On centre le texte
item.setTextAlignment( QtCore.Qt.AlignCenter )
# L'item ne doit pas etre modifiable
item.setFlags( item.flags() & ~QtCore.Qt.ItemIsEditable )
# L'item doit avoir sa checkBox cochee ?
if( checkBox ):
item.setCheckState( QtCore.Qt.Checked )
else:
item.setCheckState( QtCore.Qt.Unchecked )
# On renvoie l'item
return item
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import logging
logger = logging.getLogger( __name__ )
from PyQt4 import QtGui, QtCore
from GUI.ConvertQString import *
from API import API
from Option import Option
##########
# Classe #
##########
## Classe qui gere l'affichage des fenetres de dialog pour les preferences des plugins
class PreferencePluginDialog:
OPTION_TEXTE = 0
OPTION_CHECKBOX = 1
OPTION_LISTE = 2
OPTION_COMBOBOX = 3
## Constructeur
# @param parent Fenetre parent (MainWindow)
def __init__( self, parent ):
self.parent = parent # Dans ce cas, parent = MainWindow
self.api = API.getInstance()
##########################################################################
# Fonctions pour creer le dialog, l'afficher et en recuperer les valeurs #
##########################################################################
## Methode qui ouvre la fenetre de preference d'un plugin
# @param nomPlugin Nom du plugin pour lequel on va ouvrir la fenetre
# @param listeOptions Listes des options du plugin
def ouvrirDialogPreferences( self, nomPlugin, listeOptions ):
self.nomPluginCourant = nomPlugin
self.initDialogPreferences( nomPlugin, listeOptions )
self.dialogPreferences.exec_()
## Methode pour creer la fenetre de preference d'un plugin
# @param nomPlugin Nom du plugin pour lequel on va creer la fenetre
# @param listeOptions Listes des options du plugin
def initDialogPreferences( self, nomPlugin, listeOptions ):
# On cree un nouveau dialog
self.dialogPreferences = QtGui.QDialog( self.parent )
# On met le nom du plugin dans le titre de la fenetre
self.dialogPreferences.setWindowTitle( stringToQstring( u"Préférences de %s" %( nomPlugin ) ) )
# Change la taille
self.dialogPreferences.resize( 500, 350 )
# La liste des widgets est vide
self.listeWidget = []
# Layout du dialog (il ne contiendra que la scroll area)
self.layoutPrincipal = QtGui.QVBoxLayout( self.dialogPreferences )
# Scroll Area (elle ne contiendra que le widget central)
self.scrollArea = QtGui.QScrollArea( self.dialogPreferences )
self.layoutPrincipal.addWidget( self.scrollArea )
# Widget central
self.widgetCentral = QtGui.QWidget( self.scrollArea )
# On cree un layout de grille (layout du widget central)
self.layoutGrille = QtGui.QGridLayout( self.widgetCentral )
# On ajoute les options
for option in listeOptions:
typeOption = getattr( option, "type" )
nomOption = getattr( option, "nom" )
texteDescriptif = getattr( option, "description" )
valeurParDefaut = getattr( option, "valeur" )
valeurs = getattr( option, "choix", None )
if( typeOption == Option.TYPE_TEXTE ):
self.ajoutTexte( nomOption, texteDescriptif, valeurParDefaut )
elif( typeOption == Option.TYPE_BOULEEN ):
self.ajoutCheckBox( nomOption, texteDescriptif, valeurParDefaut )
elif( typeOption == Option.TYPE_CHOIX_MULTIPLE ):
valeursBonFormat = []
for val in valeurs:
valeursBonFormat.append( [ val, val in valeurParDefaut ] )
self.ajoutListe( nomOption, texteDescriptif, valeursBonFormat )
elif( typeOption == Option.TYPE_CHOIX_UNIQUE ):
self.ajoutComboBox( nomOption, texteDescriptif, valeurs, valeurParDefaut )
else:
logger.warn( "type d'option inconnu" )
# On ajoute les bouton Sauvegarder et Annuler
buttonBox = QtGui.QDialogButtonBox( self.dialogPreferences )
buttonBox.addButton( "Sauvegarder", QtGui.QDialogButtonBox.AcceptRole )
buttonBox.addButton( "Annuler", QtGui.QDialogButtonBox.RejectRole )
self.layoutPrincipal.addWidget( buttonBox )
# On connecte les signaux
QtCore.QObject.connect( buttonBox, QtCore.SIGNAL( "accepted()" ), self.sauvegarderPreferences )
QtCore.QObject.connect( buttonBox, QtCore.SIGNAL( "rejected()" ), self.dialogPreferences.reject )
# On adapte la taille du widget
#~ self.widgetCentral.adjustSize()
# On ajoute le widget central a la scroll area
self.scrollArea.setWidget( self.widgetCentral )
## Methode pour envoyer les nouvelles valeurs des options du plugin a API
def sauvegarderPreferences( self ):
# Pour chaque widget
for( typeWidget, widget ) in self.listeWidget:
# On recupere le nom de la preference
nomPreference = qstringToString( widget.objectName() )
# On recupere l'information qui nous interesse dans le widget et on la retourne
if( typeWidget == self.OPTION_TEXTE ):
valeurWidget = qstringToString( widget.text() )
elif( typeWidget == self.OPTION_CHECKBOX ):
valeurWidget = ( widget.checkState() == QtCore.Qt.Checked )
elif( typeWidget == self.OPTION_LISTE ):
liste = []
for i in range( widget.count() ): # Pour chaque ligne
if( widget.item( i ).checkState() == QtCore.Qt.Checked ): # Si elle est selectionnee
liste.append( qstringToString( widget.item( i ).text() ) )
valeurWidget = liste
elif( typeWidget == self.OPTION_COMBOBOX ):
valeurWidget = qstringToString( widget.currentText() )
else:
logger.warn( "type d'option inconnu" )
continue
# On envoit la nouvelle valeur
self.api.setPluginOption( self.nomPluginCourant, nomPreference, valeurWidget )
# On ferme la fenetre
self.dialogPreferences.hide()
###############################################
# Fonctions pour creer les elements du dialog #
###############################################
## Methode pour ajouter une zone de texte
# A ne pas appeler implicitement
# @param nom Nom unique de la preference
# @param texteDescriptif Texte qui presente la preference
# @param texteParDefaut Valeur par defaut du texte
def ajoutTexte( self, nom, texteDescriptif, texteParDefaut ):
# On cree le widget
widget = QtGui.QLineEdit( self.dialogPreferences )
# On met en place son nom
widget.setObjectName( stringToQstring( nom ) )
# On met en place son texte par defaut
widget.setText( stringToQstring( texteParDefaut ) )
# On l'ajoute a la liste des widgets du dialog
self.listeWidget.append( [ self.OPTION_TEXTE, widget ] )
# On cree le label qui le decrit
label = QtGui.QLabel( stringToQstring( texteDescriptif ), self.dialogPreferences )
# On ajoute le texte et le widget au layout
numeroLigne = self.layoutGrille.rowCount()
self.layoutGrille.addWidget( label, numeroLigne, 0, 1, 1 )
self.layoutGrille.addWidget( widget, numeroLigne, 1, 1, 1 )
## Methode pour ajouter une case a cocher
# A ne pas appeler implicitement
# @param nom Nom unique de la preference
# @param texteDescriptif Texte qui presente la preference
# @param valeurParDefaut Valeur par defaut (True ou False)
def ajoutCheckBox( self, nom, texteDescriptif, valeurParDefaut ):
# On cree le widget
widget = QtGui.QCheckBox( self.dialogPreferences )
#~ widget = QtGui.QCheckBox( u"Activer ?", self.dialogPreferences )
# On met en place son nom
widget.setObjectName( stringToQstring( nom ) )
# On met en place sa valeur par defaut (cochee ou non)
if( valeurParDefaut ):
widget.setCheckState( QtCore.Qt.Checked )
else:
widget.setCheckState( QtCore.Qt.Unchecked )
# On l'ajoute a la liste des widgets du dialog
self.listeWidget.append( [ self.OPTION_CHECKBOX, widget ] )
# On cree le label qui le decrit
label = QtGui.QLabel( stringToQstring( texteDescriptif ), self.dialogPreferences )
# On ajoute le texte et le widget au layout
numeroLigne = self.layoutGrille.rowCount()
self.layoutGrille.addWidget( label, numeroLigne, 0, 1, 1 )
self.layoutGrille.addWidget( widget, numeroLigne, 1, 1, 1 )
## Methode pour ajouter une liste
# A ne pas appeler implicitement
# @param nom Nom unique de la preference
# @param texteDescriptif Texte qui presente la preference
# @param valeurs Valeurs par defaut [ [ Element1, Cochee1 ? ], [ ... ] , ... ]
def ajoutListe( self, nom, texteDescriptif, valeurs ):
# On cree le widget
widget = QtGui.QListWidget( self.dialogPreferences )
# On met en place son nom
widget.setObjectName( stringToQstring( nom ) )
# On met en place ses valeurs
for( nom, cochee ) in valeurs:
widget.addItem( self.creerItem( nom, cochee ) )
# On l'ajoute a la liste des widgets du dialog
self.listeWidget.append( [ self.OPTION_LISTE, widget ] )
# On cree le label qui le decrit
label = QtGui.QLabel( stringToQstring( texteDescriptif ), self.dialogPreferences )
# On ajoute le texte et le widget au layout
numeroLigne = self.layoutGrille.rowCount()
self.layoutGrille.addWidget( label, numeroLigne, 0, 1, 2 )
self.layoutGrille.addWidget( widget, numeroLigne + 1, 0, 1, 2 )
## Methode pour ajouter une liste deroulante
# A ne pas appeler implicitement
# @param nom Nom unique de la preference
# @param texteDescriptif Texte qui presente la preference
# @param elements Element de la liste
# @param valeurParDefaut Element selectionne dans la liste
def ajoutComboBox( self, nom, texteDescriptif, elements, valeurParDefaut ):
# On cree le widget
widget = QtGui.QComboBox( self.dialogPreferences )
# On met en place son nom
widget.setObjectName( stringToQstring( nom ) )
# On ajoute tous les elements a la combo box
for elmt in elements:
widget.addItem( stringToQstring( elmt ) )
# On met en place la valeur par defaut
if not( valeurParDefaut in elements ): # Si on a pas deja la valeur par defaut dans la liste
# On l'ajoute
widget.addItem( stringToQstring( valeurParDefaut ) )
# On selectionne la valeur par defaut
widget.setCurrentIndex( widget.findText( stringToQstring( valeurParDefaut ) ) )
# On l'ajoute a la liste des widgets du dialog
self.listeWidget.append( [ self.OPTION_COMBOBOX, widget ] )
# On cree le label qui le decrit
label = QtGui.QLabel( stringToQstring( texteDescriptif ), self.dialogPreferences )
# On ajoute le texte et le widget au layout
numeroLigne = self.layoutGrille.rowCount()
self.layoutGrille.addWidget( label, numeroLigne, 0, 1, 1 )
self.layoutGrille.addWidget( widget, numeroLigne, 1, 1, 1 )
####################
# Autres fonctions #
####################
## Fonction qui creer un item pour un QListWidget
# @param texte Texte de l'element
# @param checkBox La checkbox doit-elle etre cochee ?
# @return L'element cree
def creerItem( self, texte, checkBox ):
# On cree l'item avec le texte
item = QtGui.QListWidgetItem( stringToQstring( texte ) )
# On centre le texte
item.setTextAlignment( QtCore.Qt.AlignCenter )
# L'item ne doit pas etre modifiable
item.setFlags( item.flags() & ~QtCore.Qt.ItemIsEditable )
# L'item doit avoir sa checkBox cochee ?
if( checkBox ):
item.setCheckState( QtCore.Qt.Checked )
else:
item.setCheckState( QtCore.Qt.Unchecked )
# On renvoie l'item
return item
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
from PyQt4 import QtCore
import re
import unicodedata
#############
# Fonctions #
#############
## Fonction qui transforme un string Python en QString
# @param texte Le string a transformer
# @return Le string transforme en QString
def stringToQstring( texte ):
if( isinstance( texte, str ) ):
return QtCore.QString( unicode( texte, "utf-8", "replace" ) )
else:
return QtCore.QString( texte )
## Fonction qui transforme un QString en string Python
# @param texte Le QString a transformer
# @return Le QString tranforme en string
def qstringToString( texte ):
try:
return str( texte.toUtf8() )
except UnicodeDecodeError:
return unicode( texte.toUtf8(), "utf-8" )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
from PyQt4 import QtGui, QtCore
from GUI.ConvertQString import *
#########
# Texte #
#########
texteCredits = \
u"""Développeurs :
- chaoswizard
- ggauthier.ggl
Développeur CLI :
tvelter
Plugins :
BmD_Online : Arte
Remerciements :
- wido (packager Archlinux)
- devil505 (packager Frugalware)
- paulk (packager Fedora)
- Thierry Thomas (packager FreeBSD)
"""
##########
# Classe #
##########
## Dialog A propos du programme
class AProposDialog( QtGui.QDialog ):
## Constructeur
def __init__( self ):
# Appel au constructeur de la classe mere
QtGui.QDialog.__init__( self )
###########
# Fenetre #
###########
###
# Reglages de la fenetre principale
###
# Nom de la fenetre
self.setWindowTitle( "A propos de TVDownloader" )
# Dimensions la fenetre
self.resize( 430, 360 )
# Mise en place de son icone
self.setWindowIcon( QtGui.QIcon( "ico/gtk-about.svg" ) )
###
# Mise en place des widgets dans la fenetre
###
# Layout de grille principal
self.gridLayout = QtGui.QGridLayout( self )
# Banniere
self.labelBanniere = QtGui.QLabel()
self.labelBanniere.setPixmap( QtGui.QPixmap( "img/banniere.png" ) )
# Onglets
self.tabWidget = QtGui.QTabWidget( self )
# Onglet Infos
#~ self.tabInfos = QtGui.QWidget()
#~ self.tabWidget.addTab( self.tabInfos, "Infos" )
#
# Onglet Crédits
#
self.tabCredits = QtGui.QWidget()
# On ajoute une zone de texte dans laquelle on ajoute les credits
self.gridLayoutCredits = QtGui.QGridLayout( self.tabCredits )
self.plainTextEditCredits = QtGui.QPlainTextEdit( self.tabCredits )
self.plainTextEditCredits.appendPlainText( texteCredits )
self.gridLayoutCredits.addWidget( self.plainTextEditCredits, 0, 0, 1, 1 )
self.tabWidget.addTab( self.tabCredits, u"Crédits" )
#
# Onglet Licence
#
self.tabLicence = QtGui.QWidget()
# On ajoute une zone de texte dans laquelle on ajoute la licence
self.gridLayoutLicence = QtGui.QGridLayout( self.tabLicence )
self.plainTextEditLicence = QtGui.QPlainTextEdit( self.tabLicence )
fichier = open( "COPYING", "rt" )
self.plainTextEditLicence.appendPlainText( fichier.read() )
fichier.close()
self.gridLayoutLicence.addWidget( self.plainTextEditLicence, 0, 0, 1, 1 )
self.tabWidget.addTab( self.tabLicence, "Licence" )
# Bouton pour fermer la fenetre
self.buttonBox = QtGui.QDialogButtonBox( self )
self.buttonBox.addButton( "Fermer", QtGui.QDialogButtonBox.AcceptRole )
# On ajoute le tout au layout
self.gridLayout.addWidget( self.labelBanniere, 0, 0, 1, 1 )
self.gridLayout.addWidget( self.tabWidget , 1, 0, 1, 1 )
self.gridLayout.addWidget( self.buttonBox , 2, 0, 1, 1 )
###
# Signaux provenants de l'interface
###
QtCore.QObject.connect( self.buttonBox, QtCore.SIGNAL( "accepted()" ), self.accept )
# On selectionne le premier onglet
self.tabWidget.setCurrentIndex( 0 )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
from PyQt4 import QtGui, QtCore
from GUI.ConvertQString import *
import logging
logger = logging.getLogger( __name__ )
##########
# Classe #
##########
## Classe heritant de QTableWidget a laquelle on va rajouter des methode specifiques
class MyQTableWidget( QtGui.QTableWidget ):
## Constructeur
# @param parent Parent (le plus souvent, c'est une fenetre ou un layout)
# @param dragndropEnable Autorise ou pas le drag n drop sur le QTableWidget
def __init__( self, parent = None, dragndropEnable = False ):
# Appel au constructeur de la classe mere
QtGui.QTableWidget.__init__( self, parent )
# On masque le numero des lignes
self.verticalHeader().setVisible( False )
# On masque le quadrillage
self.setShowGrid( False )
# Lorsque qu'on clique sur une ligne, on selectionne toute la ligne
self.setSelectionBehavior( QtGui.QAbstractItemView.SelectRows )
# On ne peut selectionner qu'une ligne a la fois
self.setSelectionMode( QtGui.QAbstractItemView.SingleSelection )
# La derniere colonne visible prend toute la place restante
self.horizontalHeader().setStretchLastSection( True )
# On alterne les couleurs des lignes
self.setAlternatingRowColors( True )
# Gestion du drag n drop
if( dragndropEnable ):
# Accepte le drag n drop
self.setDragEnabled( True )
self.viewport().setAcceptDrops( True )
# Le drag n drop ne prend en compte que les deplacements a l'interieur d'un meme QTableWidget
self.setDragDropMode( QtGui.QAbstractItemView.InternalMove )
# Affiche un indicateur visuel lors d'un drag n drop
self.setDropIndicatorShown( True )
# Gestion des lignes
# Chaque ligne va contenir dans une liste la reference de la classe qu'elle represente
self.listeClasse = []
## Methode pour creer un item
# @param texte Texte de l'item
# @param modifiable Indique si le texte peut etre modifiable
# @param checkBox Indique si l'item doit comprendre une checkbox
# @param cochee Indique si la checkbox doit etre cochee par defaut
# @return L'item cree
def creerItem( self, texte, modifiable = False, checkBox = False, cochee = False ):
# On cree l'item avec le texte
item = QtGui.QTableWidgetItem( stringToQstring( texte ) )
# On centre le texte
item.setTextAlignment( QtCore.Qt.AlignCenter )
# L'item peut etre modifiable ?
if not modifiable:
item.setFlags( item.flags() & ~QtCore.Qt.ItemIsEditable )
# L'item doit comprendre une checkbox ?
if( checkBox ):
# La checkBox doit etre cochee ?
if( cochee ):
item.setCheckState( QtCore.Qt.Checked )
else:
item.setCheckState( QtCore.Qt.Unchecked )
# On renvoie l'item
return item
##########################
# Gestion du drag n drop #
##########################
## Surcharge de la methode qui gere l'entree des drags dans le QTableWidget
# @param event Evenement
def dragEnterEvent( self, event ):
# On laisse le comportement par defaut
event.acceptProposedAction()
## Surcharge de la methode qui gere la sortie des drags du QTableWidget
# @param event Evenement
def dragLeaveEvent( self, event ):
# On ne laisse sortir aucun drag
event.ignore()
def dragMoveEvent( self, event ):
event.setDropAction( QtCore.Qt.MoveAction )
# On laisse le comportement par defaut
event.acceptProposedAction()
## Surcharge de la methode qui gere les drops
# @param event Evenement
def dropEvent( self, event ):
try:
ligneElementSelectionne = self.selectedItems()[ 0 ].row()
ligneOuDeplacerSelection = self.itemAt( event.pos() ).row()
# On recupere l'element a deplacer
#~ elementADeplacer = self.getLigne( ligneElementSelectionne )
# Si on veut descendre l'element
if( ligneOuDeplacerSelection > ligneElementSelectionne ):
# On remonte toutes les autres lignes entre l'element et sa future position
for ligne in range( ligneElementSelectionne, ligneOuDeplacerSelection ):
self.echangerLignes( ligne + 1, ligne )
# Si on veut monter l'element
elif( ligneOuDeplacerSelection < ligneElementSelectionne ):
# On descend toutes les autres lignes entre l'element et sa future position
for ligne in range( ligneElementSelectionne, ligneOuDeplacerSelection, -1 ):
self.echangerLignes( ligne, ligne - 1 )
# On met en place la ligne a deplacer
#~ self.setLigne( ligneOuDeplacerSelection, elementADeplacer )
except:
pass
# On a gere a la main le deplacement, on ignore donc l'event
event.ignore()
######################
# Gestion des lignes #
######################
## Methode pour renvoyer une ligne (a utiliser avec #setLigne)
# @param numeroLigne Numero de la ligne a renvoyer
# @return La liste des elements de la ligne + reference de la classe qu'elle represente
def getLigne( self, numeroLigne ):
liste = []
for i in range( self.columnCount() ):
liste.append( self.takeItem( numeroLigne, i ) )
return [ liste, self.listeClasse[ numeroLigne ] ]
## Methode pour copier une ligne (a utiliser avec #setLigne)
# @param numeroLigne Numero de la ligne a copier
# @return La liste des elements de la ligne + reference de la classe qu'elle represente
def copierLigne( self, numeroLigne ):
liste = []
for i in range( self.columnCount() ):
liste.append( self.item( numeroLigne, i ).clone() )
return [ liste, self.listeClasse[ numeroLigne ] ]
## Methode pour mettre en place une ligne (a utiliser avec #getLigne)
# @param numeroLigne Numero de la ligne que l'on va mettre en place
# @param listeElementsClasse Liste des elements a mettre en place sur cette ligne + reference de la classe qu'elle represente
def setLigne( self, numeroLigne, listeElementsClasse ):
nbColonnes = self.columnCount()
listeElements, classe = listeElementsClasse
# Les lignes ont le meme nombre d'elements ?
if( len( listeElements ) == nbColonnes ):
for i in range( nbColonnes ):
self.setItem( numeroLigne, i, listeElements[ i ] )
if( numeroLigne < len( self.listeClasse ) ):
self.listeClasse[ numeroLigne ] = classe
else:
self.listeClasse.append( classe )
else:
logger.warn( "probleme avec les tailles des colonnes" )
## Methode pour echanger 2 lignes
# @param numeroLigne1 Numero de la 1ere ligne
# @param numeroLigne2 Numero de la 2eme ligne
def echangerLignes( self, numeroLigne1, numeroLigne2 ):
# On s'assure qu'on essaye pas d'echanger les memes lignes
if( numeroLigne1 != numeroLigne2 ):
ligne1 = self.getLigne( numeroLigne1 )
self.setLigne( numeroLigne1, self.getLigne( numeroLigne2 ) )
self.setLigne( numeroLigne2, ligne1 )
else:
logger.warn( u"pourquoi vouloir échanger une ligne avec elle meme ?!" )
## Methode pour renvoyer la reference de la classe qui represente une ligne
# @param numeroLigne Numero de la ligne dont on veut la classe
# @return Reference sur cette classe
def getClasse( self, numeroLigne ):
return self.listeClasse[ numeroLigne ]
def getListeClasse( self ):
return self.listeClasse
## Methode pour supprimer une ligne
# @param numeroLigne Numero de la ligne a supprimer
def supprimerLigne( self, numeroLigne ):
self.removeRow( numeroLigne )
del self.listeClasse[ numeroLigne ]
## Methode pour supprimer tous les elements
def toutSupprimer( self ):
for i in range( self.rowCount() - 1, -1, -1 ): # [ nbLignes - 1, nbLignes - 2, ..., 1, 0 ]
self.removeRow( i )
del self.listeClasse[ : ]
self.adapterColonnes()
## Methode pour deplacer une ligne
# La ligne est deplacee d'un element ou a une extremite de la liste
# @param versLeHaut Indique si la ligne doit etre deplacee vers le haut ou vers le bas
# @param extremite Indique si la ligne doit etre deplacee a une extremite de la liste
def deplacerLigne( self, versLeHaut = False, extremite = False ):
# Si on a au moin un element selectionne
if( len( self.selectedItems() ) > 0 ):
numeroLigne = self.currentRow()
nbLignes = self.rowCount()
if( versLeHaut ):
# On test si un deplacement est utile
if( numeroLigne != 0 or not versLeHaut ):
if extremite:
for i in range( numeroLigne, 0, -1 ): # [ numeroLigne - 1, numeroLigne - 2, ..., 1 ]
self.echangerLignes( i, i - 1 )
self.selectRow( 0 )
else:
self.echangerLignes( numeroLigne, numeroLigne - 1 )
self.selectRow( numeroLigne - 1 )
else:
# On test si un deplacement est utile
if( numeroLigne != nbLignes - 1 or versLeHaut ):
if extremite:
for i in range( numeroLigne, nbLignes - 1 ):
self.echangerLignes( i, i + 1 )
self.selectRow( nbLignes - 1 )
else:
self.echangerLignes( numeroLigne, numeroLigne + 1 )
self.selectRow( numeroLigne + 1 )
## Methode qui adapte la taille des colonnes
def adapterColonnes( self ):
# On adapte la taille des colonnes
self.resizeColumnsToContents()
# Si on n'a pas la scroll bar
if not self.isHorizontalScrollBarVisible():
# La derniere colonne visible prend toute la place restante
self.horizontalHeader().setStretchLastSection( True )
## Methode qui determine si la scroll bar horizontale est visible
# @return Si la scroll bar horizontale est visible
def isHorizontalScrollBarVisible( self ):
isVisible = False
tailleColonnes = 0
for i in range( self.columnCount() ):
tailleColonnes += self.columnWidth( i )
tailleWidget = self.width()
if( tailleColonnes > tailleWidget ):
isVisible = True
return isVisible
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
from PyQt4 import QtGui, QtCore
##########
# Classe #
##########
## Classe heritant de QPushButton
class MyQPushButton( QtGui.QPushButton ):
## Constructeur
# @param parent Parent (le plus souvent, c'est une fenetre ou un layout)
def __init__( self, *args ):
# Appel au constructeur de la classe mere
nb = len( args )
if( nb == 1 ):
QtGui.QPushButton.__init__( self, args[ 0 ] )
elif( nb == 2 ):
QtGui.QPushButton.__init__( self, args[ 0 ], args[ 1 ] )
else:
QtGui.QPushButton.__init__( self, args[ 0 ], args[ 1 ], args[ 2 ] )
# On fait en sorte que la taille du bouton s'adapte toute seule
sizePolicy = self.sizePolicy()
sizePolicy.setVerticalPolicy( QtGui.QSizePolicy.Expanding )
self.setSizePolicy( sizePolicy )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
from PyQt4 import QtGui, QtCore
import threading
import time
##########
# Classe #
##########
## Fenetre d'attente du programme
class FenetreAttenteProgressDialog( QtGui.QProgressDialog ):
## Constructeur
# @param parent Fenetre parent
def __init__( self, parent ):
# Appel au constructeur de la classe mere
QtGui.QProgressDialog.__init__( self,
"Patientez pendant l'actualisation des informations de ",
"Fermer",
0,
0,
parent )
# La fenetre est modale
self.setModal( True )
# Titre de la fenetre
self.setWindowTitle( u"Merci de patienter..." )
# La fenetre ne peut pas changer de taille
self.setFixedSize( self.size() )
# On masque le bouton annuler
self.setCancelButton( None )
# Signaux
QtCore.QObject.connect( self,
QtCore.SIGNAL( "ouvrirFenetre(PyQt_PyObject)" ),
self.ouvrirSiNecessaire )
# Etat dans lequel on veut que soit la fenetre
# !!! : L'etat dans lequel on veut qu'elle soit n'est pas forcement l'etat dans lequel elle est
self.etatOuvert = False
# Mutex
self.lock = threading.Lock()
## Surcharge de la methode appelee lors de la fermeture du dialog
# Ne doit pas etre appele explicitement
# @param evenement Evenement qui a provoque la fermeture
def closeEvent( self, evenement ):
# Si la fenetre est masquee
if( self.isHidden() ):
# On accept la fermeture
evenement.accept()
else:
# On refuse la fermeture
evenement.ignore()
## Methode pour afficher la fenetre d'attente
# @param nomSite Nom du plugin (site) qui demande la fenetre d'attente
def ouvrirFenetreAttente( self, nomSite ):
self.lock.acquire()
# On veut que la fenetre soit ouverte
self.etatOuvert = True
self.lock.release()
# On attent un peu puis on ouvre la fenetre si necessaire
threading.Timer( 0.5, self.emit, ( QtCore.SIGNAL( "ouvrirFenetre(PyQt_PyObject)" ), nomSite ) ).start()
## Methode lancee par le timer apres X seconde qui ouvre la fenetre d'attente si c'est necessaire
# @param nomSite Nom du plugin (site) qui demande la fenetre d'attente
def ouvrirSiNecessaire( self, nomSite ):
self.lock.acquire()
# Si on veut toujours que la fenetre soit ouverte, on l'ouvre !
if( self.etatOuvert ):
self.setLabelText( "Patientez pendant l'actualisation des informations de %s" %( nomSite ) )
self.show()
self.lock.release()
## Methode pour fermer la fenetre d'attente
def fermerFenetreAttente( self ):
self.lock.acquire()
self.etatOuvert = False
# Si la fenetre est affiche, on la masque apres avoir un peu attendu
if not ( self.isHidden() ):
self.hide()
self.lock.release()
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import threading
import Constantes
from PyQt4 import QtGui, QtCore
from GUI.Qt.MyQPushButton import MyQPushButton
from GUI.Qt.MyQTableWidget import MyQTableWidget
from API import API
from Fichier import Fichier
from GUI.AProposDialog import AProposDialog
from GUI.ConvertQString import *
from GUI.Downloader import Downloader
from GUI.FenetreAttenteProgressDialog import FenetreAttenteProgressDialog
from GUI.PreferencePluginDialog import PreferencePluginDialog
from GUI.PreferencesDialog import PreferencesDialog
from GUI.UpdateManagerDialog import UpdateManagerDialog
from Historique import Historique
from PluginManager import PluginManager
from Preferences import Preferences
import logging
logger = logging.getLogger( __name__ )
##########
# Classe #
##########
## Fenetre principale de l'application
class MainWindow( QtGui.QMainWindow ):
## Constructeur
# Le constructeur va creer la fenetre principale en y ajoutant tous les widgets necessaires au programme
def __init__( self ):
# Appel au constructeur de la classe mere
QtGui.QMainWindow.__init__( self )
###########
# Fenetre #
###########
###
# Reglages de la fenetre principale
###
# Nom de la fenetre
self.setWindowTitle( "%s %s" %( Constantes.TVD_NOM, Constantes.TVD_VERSION ) )
# Mise en place de son icone
self.setWindowIcon( QtGui.QIcon( "ico/TVDownloader.png" ) )
###
# Mise en place des widgets dans la fenetre
###
# Widget central qui contiendra tout
self.centralWidget = QtGui.QWidget( self )
#
# Barre du haut
#
# Layout horizontal qui contiendra les listes deroulantes
self.horizontalLayoutBarreHaut = QtGui.QHBoxLayout()
# Liste deroulante pour choisir le site (plugin)
self.comboBoxSite = QtGui.QComboBox( self.centralWidget )
self.horizontalLayoutBarreHaut.addWidget( self.comboBoxSite )
# Liste deroulante pour choisir une chaine du site courant
self.comboBoxChaine = QtGui.QComboBox( self.centralWidget)
self.horizontalLayoutBarreHaut.addWidget( self.comboBoxChaine )
# Liste deroulante pour choisir une emission de la chaine courante
self.comboBoxEmission = QtGui.QComboBox( self.centralWidget )
self.horizontalLayoutBarreHaut.addWidget( self.comboBoxEmission )
#
# Onglets
#
# Gestionnaire onglets
self.tabWidget = QtGui.QTabWidget( self.centralWidget )
# Onglet Fichiers
self.tabFichiers = QtGui.QSplitter( self.centralWidget ) # L'onglet Fichier contient un splitter
self.tabWidget.addTab( self.tabFichiers, u"Choix des fichiers" )
# Onglet Telechargements
self.tabTelechargements = QtGui.QWidget( self.centralWidget )
self.tabWidget.addTab( self.tabTelechargements, u"Téléchargements" )
#
# Liste des fichiers
#
# Layout de grille qui contient le tableau qui liste les fichiers et ses boutons
self.gridLayoutFichiers = QtGui.QGridLayout( self.tabFichiers )
# Tableau qui contient la liste des fichiers disponibles pour l'emission courante
self.tableWidgetFichier = MyQTableWidget( self.tabFichiers )
# Il a 4 colonnes et 0 ligne (pour l'instant)
self.tableWidgetFichier.setColumnCount( 3 )
self.tableWidgetFichier.setRowCount( 0 )
# On ajoute les titres
self.tableWidgetFichier.setHorizontalHeaderItem( 0,
self.tableWidgetFichier.creerItem( "" ) )
self.tableWidgetFichier.setHorizontalHeaderItem( 1,
self.tableWidgetFichier.creerItem( "Date" ) )
self.tableWidgetFichier.setHorizontalHeaderItem( 2,
self.tableWidgetFichier.creerItem( "Emission" ) )
# La liste est triable
#~ self.tableWidgetFichier.setSortingEnabled( True )
# On l'ajoute au layout
self.gridLayoutFichiers.addWidget( self.tableWidgetFichier, 0, 1, 6, 1 )
# Icones du tableWidget
self.iconeFichier = QtGui.QIcon( "ico/gtk-file.svg" )
self.iconeAjoute = QtGui.QIcon( "ico/gtk-add.svg" )
self.iconeTelecharge = QtGui.QIcon( "ico/gtk-apply.svg" )
# Bouton pour ajouter tous les fichiers a la liste des telechargements
self.pushButtonToutAjouter = MyQPushButton( self.tabFichiers )
self.pushButtonToutAjouter.setIcon( QtGui.QIcon( "ico/gtk-add.svg" ) )
self.pushButtonToutAjouter.setToolTip( u"Ajouter tous les fichiers à la liste des téléchargements" )
self.gridLayoutFichiers.addWidget( self.pushButtonToutAjouter, 0, 0, 2, 1 )
# Bouton pour rafraichir le plugin courant
self.pushButtonRafraichirPlugin = MyQPushButton( self.tabFichiers )
self.pushButtonRafraichirPlugin.setIcon( QtGui.QIcon( "ico/gtk-refresh.svg" ) )
self.pushButtonRafraichirPlugin.setToolTip( "Rafraichir le plugin" )
self.gridLayoutFichiers.addWidget( self.pushButtonRafraichirPlugin, 2, 0, 2, 1 )
# Bouton pour ouvrir la fenetre des preferences du plugin courant
self.pushButtonPreferencesPlugin = MyQPushButton( self.tabFichiers )
self.pushButtonPreferencesPlugin.setIcon( QtGui.QIcon( "ico/gtk-preferences.svg" ) )
self.pushButtonPreferencesPlugin.setToolTip( u"Ouvrir les préférences du plugin" )
self.gridLayoutFichiers.addWidget( self.pushButtonPreferencesPlugin, 4, 0, 2, 1 )
# On met en place ce layout sur un widget (pour le splitter)
self.widgetFichiers = QtGui.QWidget( self.tabFichiers )
self.widgetFichiers.setLayout( self.gridLayoutFichiers )
#
# Descriptif des fichiers
#
# Splitter pour separer image et texte
self.splitterDescriptif = QtGui.QSplitter( self.tabFichiers )
# Label pour afficher un logo
self.logoFichierDefaut = QtGui.QPixmap()
self.logoFichierDefaut.load( "img/gtk-dialog-question.svg" )
self.labelLogo = QtGui.QLabel( self.tabFichiers )
self.labelLogo.setScaledContents( True )
self.labelLogo.setPixmap( self.logoFichierDefaut.scaled( QtCore.QSize( 150, 150 ), QtCore.Qt.KeepAspectRatio ) )
self.splitterDescriptif.addWidget( self.labelLogo )
# Zone de texte pour afficher un descriptif
self.plainTextEdit = QtGui.QPlainTextEdit( self.tabFichiers )
self.splitterDescriptif.addWidget( self.plainTextEdit )
# Onrientation verticale du splitter
self.tabFichiers.setOrientation( QtCore.Qt.Vertical )
# On ajoute les 2 elements au splitter (qui est notre onglet)
self.tabFichiers.addWidget( self.widgetFichiers )
self.tabFichiers.addWidget( self.splitterDescriptif )
#
# Liste des telechargements
#
# Layout de grille qui contient le tableau qui liste les fichiers a telecharger + les boutons pour le controller
self.gridLayoutTelechargement = QtGui.QGridLayout( self.tabTelechargements )
# Tableau qui contient la liste des fichiers a telecharger
self.tableWidgetTelechargement = MyQTableWidget( self.tabTelechargements, True )
# Il a 3 colonnes et 0 ligne (pour l'instant)
self.tableWidgetTelechargement.setColumnCount( 3 )
self.tableWidgetTelechargement.setRowCount( 0 )
# On ajoute le titre des 3 colonnes
self.tableWidgetTelechargement.setHorizontalHeaderItem( 0,
self.tableWidgetTelechargement.creerItem( "Date" ) )
self.tableWidgetTelechargement.setHorizontalHeaderItem( 1,
self.tableWidgetTelechargement.creerItem( "Emission" ) )
self.tableWidgetTelechargement.setHorizontalHeaderItem( 2,
self.tableWidgetTelechargement.creerItem( "Etat" ) )
# On l'ajoute au layout
self.gridLayoutTelechargement.addWidget( self.tableWidgetTelechargement, 0, 1, 2, 1 )
# Bouton pour supprimer tous les elements de la liste
self.pushButtonToutSupprimer = MyQPushButton( self.tabTelechargements )
self.pushButtonToutSupprimer.setIcon( QtGui.QIcon( "ico/gtk-cancel.svg" ) )
self.pushButtonToutSupprimer.setToolTip( u"Supprimer tous les téléchargements de la liste" )
self.gridLayoutTelechargement.addWidget( self.pushButtonToutSupprimer, 0, 0, 1, 1 )
# Bouton pour ouvrir le dossier des telechargements
self.pushButtonOuvrirDossierTelechargement = MyQPushButton( self.tabTelechargements )
self.pushButtonOuvrirDossierTelechargement.setIcon( QtGui.QIcon( "ico/gtk-folder.svg" ) )
self.pushButtonOuvrirDossierTelechargement.setToolTip( u"Ouvrir le dossier des téléchargements" )
self.gridLayoutTelechargement.addWidget( self.pushButtonOuvrirDossierTelechargement, 1, 0, 1, 1 )
#
# Barre progression de telechargement d'un fichier
#
self.progressBarTelechargementFichier = QtGui.QProgressBar( self.centralWidget )
self.progressBarTelechargementFichier.setProperty( "value", 0 )
#
# Barre de progression de telechargement des fichiers
#
self.progressBarTelechargement = QtGui.QProgressBar( self.centralWidget )
self.progressBarTelechargement.setProperty( "value", 0 )
#
# Boutons du bas pour gerer ajouter/supprimer/lancer telechargements
#
# Layout horizontal qui contiendra les boutons
self.horizontalLayoutBarreBas = QtGui.QHBoxLayout()
# Bouton pour lancer les telechargements
self.pushButtonLancer = QtGui.QPushButton( QtGui.QIcon( "ico/gtk-media-play-ltr.svg" ), u"Lancer téléchargement", self.centralWidget )
self.horizontalLayoutBarreBas.addWidget( self.pushButtonLancer )
# Bouton pour stopper les telechargements
self.pushButtonStop = QtGui.QPushButton( QtGui.QIcon( "ico/gtk-media-stop.svg" ), u"Stopper le téléchargement", self.centralWidget )
self.pushButtonStop.setEnabled( False )
self.horizontalLayoutBarreBas.addWidget( self.pushButtonStop )
###
# Positionnement des differents widgets/layouts sur le layout de grille
###
# Layout de grille dans lequel on va placer nos widgets/layouts
self.gridLayout = QtGui.QGridLayout( self.centralWidget )
# On ajoute la barre du haut
self.gridLayout.addLayout( self.horizontalLayoutBarreHaut, 0, 0, 1, 3 )
# On ajoute le gestionnaire d'onglets
self.gridLayout.addWidget( self.tabWidget, 1, 0, 1, 3 )
# On ajoute la barre de progression de telechargement d'un fichier
self.gridLayout.addWidget( self.progressBarTelechargementFichier, 2, 0, 1, 3 )
# On ajoute la barre de progression de telechargement des fichiers
self.gridLayout.addWidget( self.progressBarTelechargement, 3, 0, 1, 3 )
# On ajoute les boutons ajouter/supprimer/lancer
self.gridLayout.addLayout( self.horizontalLayoutBarreBas, 4, 0, 1, 3 )
###
# Mise en place du central widget dans la fenetre
###
self.setCentralWidget( self.centralWidget )
###
# Mise en place du menu
###
# Menu barre
self.menubar = QtGui.QMenuBar( self )
self.menubar.setGeometry( QtCore.QRect( 0, 0, 480, 25 ) )
# Menu Fichier
self.menuFichier = QtGui.QMenu( "&Fichier", self.menubar )
self.menubar.addAction( self.menuFichier.menuAction() )
# Action Fichier -> Quitter
self.actionQuitter = QtGui.QAction( QtGui.QIcon( "ico/gtk-quit.svg" ), "&Quitter", self.menuFichier )
self.actionQuitter.setIconVisibleInMenu( True )
self.menuFichier.addAction( self.actionQuitter )
# Menu Edition
self.menuEdition = QtGui.QMenu( "&Edition", self.menubar )
self.menubar.addAction( self.menuEdition.menuAction() )
# Action Edition -> Mise a jour
self.actionMAJ = QtGui.QAction( QtGui.QIcon( "ico/gtk-refresh.svg" ), u"&Mise à jour des plugins", self.menuEdition )
self.actionMAJ.setIconVisibleInMenu( True )
self.menuEdition.addAction( self.actionMAJ )
# Action Edition -> Preferences
self.actionPreferences = QtGui.QAction( QtGui.QIcon( "ico/gtk-preferences.svg" ), u"&Préférences", self.menuEdition )
self.actionPreferences.setIconVisibleInMenu( True )
self.menuEdition.addAction( self.actionPreferences )
# Menu Aide
self.menuAide = QtGui.QMenu( "&Aide", self.menubar )
self.menubar.addAction( self.menuAide.menuAction() )
# Action Aide -> A propos
self.actionAPropos = QtGui.QAction( QtGui.QIcon( "ico/gtk-about.svg" ), u"À p&ropos", self.menuAide )
self.actionAPropos.setIconVisibleInMenu( True )
self.menuAide.addAction( self.actionAPropos )
# Ajout du menu a l'interface
self.setMenuBar( self.menubar )
################################################
# Instanciations + initialisation de variables #
################################################
# Fenetre About
self.aProposDialog = None
# Fenetre des preferences du logiciel
self.preferencesDialog = None
# Fenetre de mise a jour des plugins
self.updateManagerDialog = None
# Nom plugin courant
self.nomPluginCourant = ""
# Cache des images descriptive
# Clef : urlImage Valeur : image (binaire)
self.cacheImage = {}
# On instancie le gestionnaire de preferences
self.preferences = Preferences()
# On instancie le gestionnaire de preferences des plugins
self.preferencesPluginDialog = PreferencePluginDialog( self )
# On instancie le gestionnaire de download
self.downloader = Downloader()
# On recupere l'instance de API
self.api = API.getInstance()
# On instancie le gestionnaire d'historique
self.historique = Historique()
# On instancie la fenetre d'attente
self.fenetreAttenteProgressDialog = FenetreAttenteProgressDialog( self )
# On instancie le gest
#
# Fenetre de confirmation pour quitter le logiciel
#
self.quitterMessageBox = QtGui.QMessageBox( self )
self.quitterMessageBox.setWindowTitle( "Fermeture de TVDownloader" )
self.quitterMessageBox.setText( u"Voulez-vous réellement quitter TVDownloader ?" )
self.quitterMessageBox.setInformativeText( u"Votre liste de téléchargement sera perdue" )
self.quitterMessageBox.addButton( "Oui", QtGui.QMessageBox.AcceptRole )
self.quitterMessageBox.addButton( "Non", QtGui.QMessageBox.RejectRole )
###########
# Signaux #
###########
QtCore.QObject.connect( self.comboBoxSite,
QtCore.SIGNAL( "activated(QString)" ),
self.listerChaines )
QtCore.QObject.connect( self.comboBoxChaine,
QtCore.SIGNAL( "activated(QString)" ),
self.listerEmissions )
QtCore.QObject.connect( self.comboBoxEmission,
QtCore.SIGNAL( "activated(QString)" ),
self.listerFichiers )
QtCore.QObject.connect( self.tableWidgetFichier,
QtCore.SIGNAL( "cellClicked(int,int)" ),
self.afficherInformationsFichier )
QtCore.QObject.connect( self.tableWidgetFichier,
QtCore.SIGNAL( "cellDoubleClicked(int,int)" ),
self.gererTelechargement )
QtCore.QObject.connect( self.pushButtonToutAjouter,
QtCore.SIGNAL( "clicked()" ),
self.ajouterTousLesFichiers )
QtCore.QObject.connect( self.pushButtonRafraichirPlugin,
QtCore.SIGNAL( "clicked()" ),
self.rafraichirPlugin )
QtCore.QObject.connect( self.pushButtonPreferencesPlugin,
QtCore.SIGNAL( "clicked()" ),
self.ouvrirPreferencesPlugin )
QtCore.QObject.connect( self.tableWidgetTelechargement,
QtCore.SIGNAL( "cellDoubleClicked(int,int)" ),
self.supprimerTelechargement )
QtCore.QObject.connect( self.pushButtonToutSupprimer,
QtCore.SIGNAL( "clicked()" ),
self.supprimerTousLesTelechargements )
QtCore.QObject.connect( self.pushButtonOuvrirDossierTelechargement,
QtCore.SIGNAL( "clicked()" ),
self.ouvrirRepertoireTelechargement )
QtCore.QObject.connect( self.pushButtonLancer,
QtCore.SIGNAL( "clicked()" ),
self.lancerTelechargement )
QtCore.QObject.connect( self.pushButtonStop,
QtCore.SIGNAL( "clicked()" ),
self.stopperTelechargement )
QtCore.QObject.connect( self.actionQuitter,
QtCore.SIGNAL( "triggered()" ),
self.close )
QtCore.QObject.connect( self.actionMAJ,
QtCore.SIGNAL( "triggered()" ),
self.ouvrirFenetreMiseAJour )
QtCore.QObject.connect( self.actionPreferences,
QtCore.SIGNAL( "triggered()" ),
self.ouvrirPreferencesLogiciel )
QtCore.QObject.connect( self.actionAPropos,
QtCore.SIGNAL( "triggered()" ),
self.ouvrirFenetreAPropos )
QtCore.QObject.connect( self, QtCore.SIGNAL( "listeChaines(PyQt_PyObject)" ) , self.ajouterChaines )
QtCore.QObject.connect( self, QtCore.SIGNAL( "listeEmissions(PyQt_PyObject)" ) , self.ajouterEmissions )
QtCore.QObject.connect( self, QtCore.SIGNAL( "listeFichiers(PyQt_PyObject)" ) , self.ajouterFichiers )
QtCore.QObject.connect( self, QtCore.SIGNAL( "nouvelleImage(PyQt_PyObject)" ) , self.mettreEnPlaceImage )
QtCore.QObject.connect( self, QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ) , self.fenetreAttenteProgressDialog.ouvrirFenetreAttente )
QtCore.QObject.connect( self, QtCore.SIGNAL( "finActualisation()" ) , self.fenetreAttenteProgressDialog.fermerFenetreAttente )
QtCore.QObject.connect( self, QtCore.SIGNAL( "actualiserListesDeroulantes()" ) , self.actualiserListesDeroulantes )
QtCore.QObject.connect( self, QtCore.SIGNAL( "debutTelechargement(PyQt_PyObject)" ) , self.debutTelechargement )
QtCore.QObject.connect( self, QtCore.SIGNAL( "finTelechargement(PyQt_PyObject,bool)" ) , self.finTelechargement )
QtCore.QObject.connect( self, QtCore.SIGNAL( "finDesTelechargements()" ) , self.activerDesactiverInterface )
QtCore.QObject.connect( self.downloader, QtCore.SIGNAL( "pourcentageFichier(int)" ) , self.progressBarTelechargementFichier.setValue )
#########
# Début #
#########
# La fenetre prend la dimension qu'elle avait a sa fermeture
taille = self.preferences.getPreference( "tailleFenetre" )
self.resize( taille[ 0 ], taille[ 1 ] )
# Si aucun plugin n'est active, on ouvre la fenetre des preferences
if( len( self.preferences.getPreference( "pluginsActifs" ) ) == 0 ):
self.ouvrirPreferencesLogiciel()
# On actualise tous les plugins
self.rafraichirTousLesPlugins()
## Methode qui execute les actions necessaires avant de quitter le programme
def actionsAvantQuitter( self ):
# On sauvegarde les options des plugins
self.api.fermeture()
# On sauvegarde la taille de la fenetre
taille = self.size()
self.preferences.setPreference( "tailleFenetre", [ taille.width(), taille.height() ] )
# On sauvegarde les options du logiciel
self.preferences.sauvegarderConfiguration()
# On sauvegarde l'historique
self.historique.sauverHistorique()
# On stoppe les telechargements
self.stopperTelechargement()
#########################################
# Surcharge des methodes de QMainWindow #
#########################################
## Surcharge de la methode appelee lors de la fermeture de la fenetre
# Ne doit pas etre appele explicitement
# @param evenement Evenement qui a provoque la fermeture
def closeEvent( self, evenement ):
# On affiche une fenetre pour demander la fermeture si des fichiers sont dans la liste de telechargement
if( self.tableWidgetTelechargement.rowCount() > 0 ):
# On affiche une fenetre qui demande si on veut quitter
retour = self.quitterMessageBox.exec_()
# Si on veut quitter
if( retour == 0 ):
# On execute les actions necessaires
self.actionsAvantQuitter()
# On accept la fermeture
evenement.accept()
else:
# On refuse la fermeture
evenement.ignore()
else: # S'il n'y a pas de fichier
# On execute les actions necessaires
self.actionsAvantQuitter()
# On accept la fermeture
evenement.accept()
##############################################
# Methodes pour remplir les menus deroulants #
##############################################
## Methode qui actualise les listes deroulantes
def actualiserListesDeroulantes( self ):
# On lance juste l'ajout des sites en se basant sur les plugins actifs
self.ajouterSites( self.preferences.getPreference( "pluginsActifs" ) )
## Methode qui lance le listage des chaines
# @param site Nom du plugin/site pour lequel on va lister les chaines
def listerChaines( self, site ):
def threadListerChaines( self, nomPlugin ):
self.emit( QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ), nomPlugin )
try:
listeChaines = self.api.getPluginListeChaines( nomPlugin )
except:
listeChaines = []
logger.error( u"impossible de récupérer la liste des chaines de %s" %( nomPlugin ) )
self.emit( QtCore.SIGNAL( "listeChaines(PyQt_PyObject)" ), listeChaines )
self.emit( QtCore.SIGNAL( "finActualisation()" ) )
if( site != "" ):
self.nomPluginCourant = qstringToString( site )
threading.Thread( target = threadListerChaines, args = ( self, self.nomPluginCourant ) ).start()
# On active (ou pas) le bouton de preference du plugin
self.pushButtonPreferencesPlugin.setEnabled( self.api.getPluginListeOptions( self.nomPluginCourant ) != [] )
## Methode qui lance le listage des emissions
# @param chaine Nom de la chaine pour laquelle on va lister les emissions
def listerEmissions( self, chaine ):
def threadListerEmissions( self, nomPlugin, chaine ):
self.emit( QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ), nomPlugin )
try:
listeEmissions = self.api.getPluginListeEmissions( nomPlugin, chaine )
except:
listeEmissions = []
logger.error( u"impossible de récupérer la liste des emissions de %s" %( nomPlugin ) )
self.emit( QtCore.SIGNAL( "listeEmissions(PyQt_PyObject)" ), listeEmissions )
self.emit( QtCore.SIGNAL( "finActualisation()" ) )
if( chaine != "" ):
threading.Thread( target = threadListerEmissions, args = ( self, self.nomPluginCourant, qstringToString( chaine ) ) ).start()
## Methode qui lance le listage des fichiers
# @param emission Nom de l'emission pour laquelle on va lister les fichiers
def listerFichiers( self, emission ):
def threadListerFichiers( self, nomPlugin, emission ):
self.emit( QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ), nomPlugin )
try:
listeFichiers = self.api.getPluginListeFichiers( nomPlugin, emission )
except:
listeFichiers = []
logger.error( u"impossible de récupérer la liste des fichiers de %s" %( nomPlugin ) )
self.emit( QtCore.SIGNAL( "listeFichiers(PyQt_PyObject)" ), listeFichiers )
self.emit( QtCore.SIGNAL( "finActualisation()" ) )
if( emission != "" ):
threading.Thread( target = threadListerFichiers, args = ( self, self.nomPluginCourant, qstringToString( emission ) ) ).start()
## Methode qui met en place une liste de sites sur l'interface
# @param listeSites Liste des sites a mettre en place
def ajouterSites( self, listeSites ):
# On efface la liste des sites
self.comboBoxSite.clear()
# On met en place les sites
for site in listeSites:
self.comboBoxSite.addItem( stringToQstring( site ) )
# On selectionne par defaut celui choisis dans les preference
index = self.comboBoxSite.findText( stringToQstring( self.preferences.getPreference( "pluginParDefaut" ) ) )
if( index != -1 ):
self.comboBoxSite.setCurrentIndex( index )
# On lance l'ajout des chaines
self.listerChaines( self.comboBoxSite.currentText() )
## Methode qui met en place une liste de chaines sur l'interface
# @param listeChaines Liste des chaines a mettre en place
def ajouterChaines( self, listeChaines ):
# On trie la liste des chaines
listeChaines.sort()
# On efface la liste des chaines
self.comboBoxChaine.clear()
# On efface la liste des emissions
self.comboBoxEmission.clear()
# On efface la liste des fichiers
self.tableWidgetFichier.toutSupprimer()
# On met en place les chaines
for chaine in listeChaines:
self.comboBoxChaine.addItem( stringToQstring( chaine ) )
# Si on a juste une seule chaine
if( self.comboBoxChaine.count() == 1 ):
# On lance l'ajout des emissions
self.listerEmissions( self.comboBoxChaine.currentText() )
else:
# On ne selectionne pas de chaine
self.comboBoxChaine.setCurrentIndex( -1 )
## Methode qui met en place une liste d'emissions sur l'interface
# @param listeEmissions Liste des emissions a mettre en place
def ajouterEmissions( self, listeEmissions ):
# On trie la liste des emissions
listeEmissions.sort()
# On efface la liste des emissions
self.comboBoxEmission.clear()
# On efface la liste des fichiers
self.tableWidgetFichier.toutSupprimer()
# On met en place la liste des emissions
for emission in listeEmissions:
self.comboBoxEmission.addItem( stringToQstring( emission ) )
# Si on a juste une seule emission
if( self.comboBoxEmission.count() == 1 ):
# On lance l'ajout des fichiers
self.listerFichiers( self.comboBoxEmission.currentText() )
else:
# On ne selectionne pas d'emission
self.comboBoxEmission.setCurrentIndex( -1 )
###############################################
# Methodes pour remplir la liste des fichiers #
###############################################
## Methode pour ajouter des fichiers a l'interface
# @param listeFichiers Liste des fichiers a ajouter
def ajouterFichiers( self, listeFichiers ):
# On efface la liste des fichiers
self.tableWidgetFichier.toutSupprimer()
# On commence au depart
ligneCourante = 0
# On met en place chacun des fichiers
for fichier in listeFichiers:
# On ajoute une ligne
self.tableWidgetFichier.insertRow( ligneCourante )
# On ajoute les informations au tableWidgetFichier
liste = []
liste.append( self.tableWidgetFichier.creerItem( "" ) )
liste.append( self.tableWidgetFichier.creerItem( getattr( fichier, "date" ) ) )
liste.append( self.tableWidgetFichier.creerItem( getattr( fichier, "nom" ) ) )
self.tableWidgetFichier.setLigne( ligneCourante, [ liste, fichier ] )
# On met en place l'icone qui va bien
self.gererIconeListeFichier( fichier )
ligneCourante += 1
# On adapte la taille des colonnes
self.tableWidgetFichier.adapterColonnes()
## Methode qui rafraichit le plugin courant
def rafraichirPlugin( self ):
def threadRafraichirPlugin( self, nomPlugin ):
self.emit( QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ), nomPlugin )
try:
self.api.pluginRafraichir( nomPlugin )
except:
logger.error( "impossible de rafraichir le plugin %s" %( nomPlugin ) )
self.emit( QtCore.SIGNAL( "finActualisation()" ) )
threading.Thread( target = threadRafraichirPlugin, args = ( self, self.nomPluginCourant ) ).start()
## Methode qui met en place l'image de la description d'un fichier
# @param image Image a mettre en place (binaire)
def mettreEnPlaceImage( self, image ):
logoFichier = QtGui.QPixmap()
logoFichier.loadFromData( image )
self.labelLogo.setPixmap( logoFichier.scaled( QtCore.QSize( 150, 150 ), QtCore.Qt.KeepAspectRatio ) )
## Methode qui affiche des informations sur le fichier selectionne
def afficherInformationsFichier( self, ligne, colonne ):
def threadRecupererImage( self, urlImage ):
image = self.api.getPicture( urlImage )
if( image != "" ):
self.cacheImage[ urlImage ] = image
self.emit( QtCore.SIGNAL( "nouvelleImage(PyQt_PyObject)" ), image )
else:
# Afficher image par defaut
pass
fichier = self.tableWidgetFichier.getClasse( ligne )
# On recupere le lien de l'image et le texte descriptif
urlImage = getattr( fichier, "urlImage" )
texteDescriptif = getattr( fichier, "descriptif" )
self.plainTextEdit.clear()
# Si on a un texte descriptif, on l'affiche
if( texteDescriptif != "" ):
self.plainTextEdit.appendPlainText( stringToQstring( texteDescriptif ) )
else:
self.plainTextEdit.appendPlainText( u"Aucune information disponible" )
# Si on n'a pas d'image
if( urlImage == "" ):
# On met en place celle par defaut
self.logoFichier = self.logoFichierDefaut
self.labelLogo.setPixmap( self.logoFichier.scaled( QtCore.QSize( 150, 150 ), QtCore.Qt.KeepAspectRatio ) )
else: # Si on en a une
# Si elle est dans le cache des images
if( self.cacheImage.has_key( urlImage ) ):
self.mettreEnPlaceImage( self.cacheImage[ urlImage ] )
else: # Sinon
# On lance le thread pour la recuperer
threading.Thread( target = threadRecupererImage, args = ( self, urlImage ) ).start()
## Methode qui gere l'icone d'un fichier dans la liste des telechargements
# Il y a 3 icones possible :
# - C'est un fichier
# - C'est un fichier present dans l'historique (donc deja telecharge)
# - C'est un fichier present dans la liste des telechargements
# @param fichier Fichier a gerer
def gererIconeListeFichier( self, fichier ):
if( fichier in self.tableWidgetFichier.getListeClasse() ):
ligneFichier = self.tableWidgetFichier.getListeClasse().index( fichier )
# On cherche quel icone mettre en place
if( fichier in self.tableWidgetTelechargement.getListeClasse() ):
icone = self.iconeAjoute
elif( self.historique.comparerHistorique( fichier ) ):
icone = self.iconeTelecharge
else:
icone = self.iconeFichier
# On met en place l'icone
self.tableWidgetFichier.item( ligneFichier, 0 ).setIcon( icone )
######################################################
# Methodes pour remplir la liste des telechargements #
######################################################
## Methode qui gere la liste des telechargements
# @param ligne Numero de la ligne (dans la liste des fichiers) de l'element a ajouter
# @param colonne Numero de colonne (inutile, juste pour le slot)
def gererTelechargement( self, ligne, colonne = 0 ):
fichier = self.tableWidgetFichier.getClasse( ligne )
# Si le fichier est deja dans la liste des telechargements
if( fichier in self.tableWidgetTelechargement.getListeClasse() ):
ligneTelechargement = self.tableWidgetTelechargement.getListeClasse().index( fichier )
self.supprimerTelechargement( ligneTelechargement )
else: # S'il n'y est pas, on l'ajoute
numLigne = self.tableWidgetTelechargement.rowCount()
# On insere une nouvelle ligne dans la liste des telechargements
self.tableWidgetTelechargement.insertRow( numLigne )
# On y insere les elements qui vont biens
self.tableWidgetTelechargement.setLigne( numLigne,
[
[ self.tableWidgetTelechargement.creerItem( getattr( fichier, "date" ) ),
self.tableWidgetTelechargement.creerItem( getattr( fichier, "nom" ) ),
self.tableWidgetTelechargement.creerItem( u"En attente de téléchargement" )
],
fichier
]
)
# On adapte la taille des colonnes
self.tableWidgetTelechargement.adapterColonnes()
# On modifie l'icone dans la liste des fichiers
self.gererIconeListeFichier( fichier )
## Methode qui ajoute tous les fichiers a la liste des telechargements
def ajouterTousLesFichiers( self ):
for i in range( self.tableWidgetFichier.rowCount() ):
self.gererTelechargement( i )
## Methode qui supprime un fichier de la liste des telechargements
# @param ligne Numero de la ligne a supprimer
# @param colonne Numero de colonne (inutile, juste pour le slot)
def supprimerTelechargement( self, ligne, colonne = 0 ):
fichier = self.tableWidgetTelechargement.getClasse( ligne )
# On supprime l'element du tableWidgetTelechargement
self.tableWidgetTelechargement.supprimerLigne( ligne )
# On modifie l'icone dans la liste des fichiers
self.gererIconeListeFichier( fichier )
## Methode qui supprime tous les telechargement de la liste des telechargements
def supprimerTousLesTelechargements( self ):
for i in range( self.tableWidgetTelechargement.rowCount() -1, -1, -1 ):
self.supprimerTelechargement( i )
## Methode qui lance le telechargement des fichiers
def lancerTelechargement( self ):
def threadTelechargement( self, listeFichiers ):
for fichier in listeFichiers:
# On debute un telechargement
self.emit( QtCore.SIGNAL( "debutTelechargement(PyQt_PyObject)" ), fichier )
# On le lance
retour = self.downloader.telecharger( fichier )
# On a fini le telechargement
self.emit( QtCore.SIGNAL( "finTelechargement(PyQt_PyObject,bool)" ), fichier, retour )
# On a fini les telechargements
self.emit( QtCore.SIGNAL( "finDesTelechargements()" ) )
# On liste les fichiers a telecharger
listeFichiers = []
for i in range( self.tableWidgetTelechargement.rowCount() ): # Pour chaque ligne
listeFichiers.append( self.tableWidgetTelechargement.getClasse( i ) )
nbATelecharger = len( listeFichiers )
# Si on a des elements a charger
if( nbATelecharger > 0 ):
# On met en place la valeur du progressBar
self.progressBarTelechargement.setMaximum( nbATelecharger )
self.progressBarTelechargement.setValue( 0 )
# On active/desactive ce qui va bien sur l'interface
self.activerDesactiverInterface( True )
# On lance le telechargement
threading.Thread( target = threadTelechargement, args = ( self, listeFichiers ) ).start()
## Methode qui stoppe le telechargement
def stopperTelechargement( self ):
# On stoppe le telechargement
self.downloader.stopperTelechargement()
############################################
# Methodes pour ouvrir les autres fenetres #
############################################
#
# Fenetre About
#
## Methode pour afficher la fenetre About
def ouvrirFenetreAPropos( self ):
if( self.aProposDialog == None ):
self.aProposDialog = AProposDialog()
self.aProposDialog.show()
#
# Fenetre de preference du logiciel
#
## Methode pour ouvrir les preferences du logiciel
def ouvrirPreferencesLogiciel( self ):
if( self.preferencesDialog == None ):
# On cree l'instance
self.preferencesDialog = PreferencesDialog( self )
# On connecte le signal qui va bien
QtCore.QObject.connect( self.preferencesDialog, QtCore.SIGNAL( "actualiserListesDeroulantes()" ) , self.actualiserListesDeroulantes )
self.preferencesDialog.afficher()
#
# Fenetre de mise a jour des plugins
#
## Methode pour ouvrir la fenetre de mise a jour des plugins
def ouvrirFenetreMiseAJour( self ):
if( self.updateManagerDialog == None ):
self.updateManagerDialog = UpdateManagerDialog( self )
self.updateManagerDialog.afficher()
#
# Fenetre de preference des plugins
#
## Methode pour ouvrir les preferences du plugin courant
def ouvrirPreferencesPlugin( self ):
listeOptions = self.api.getPluginListeOptions( self.nomPluginCourant )
self.preferencesPluginDialog.ouvrirDialogPreferences( self.nomPluginCourant, listeOptions )
#########
# Slots #
#########
## Methode qui ouvre le repertoire de telechargement
def ouvrirRepertoireTelechargement( self ):
QtGui.QDesktopServices.openUrl( QtCore.QUrl.fromLocalFile( stringToQstring( self.preferences.getPreference( "repertoireTelechargement" ) ) ) )
## Methode qui rafraichit le plugin courant
def rafraichirPlugin( self ):
def threadRafraichirPlugin( self, nomPlugin ):
self.emit( QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ), nomPlugin )
self.api.pluginRafraichir( nomPlugin )
self.emit( QtCore.SIGNAL( "finActualisation()" ) )
threading.Thread( target = threadRafraichirPlugin, args = ( self, self.nomPluginCourant ) ).start()
## Methode qui rafraichit tous les plugins
# A utiliser au lancement du programme
def rafraichirTousLesPlugins( self ):
def threadRafraichirTousLesPlugins( self ):
self.emit( QtCore.SIGNAL( "debutActualisation(PyQt_PyObject)" ), "TVDownloader" )
self.api.pluginRafraichirAuto()
self.emit( QtCore.SIGNAL( "finActualisation()" ) )
self.emit( QtCore.SIGNAL( "actualiserListesDeroulantes()" ) )
threading.Thread( target = threadRafraichirTousLesPlugins, args = ( self, ) ).start()
## Slot qui active/desactive des elements de l'interface pendant un telechargement
# @param telechargementEnCours Indique si on telecharge ou pas
def activerDesactiverInterface( self, telechargementEnCours = False ):
# Les boutons
self.pushButtonLancer.setEnabled( not telechargementEnCours )
self.pushButtonStop.setEnabled( telechargementEnCours )
self.pushButtonToutSupprimer.setEnabled( not telechargementEnCours )
# Le table widget
self.tableWidgetTelechargement.setEnabled( not telechargementEnCours )
## Slot appele lors ce qu'un le debut d'un telechargement commence
# @param fichier Fichier dont le telechargement vient de commencer
def debutTelechargement( self, fichier ):
ligneTelechargement = self.tableWidgetTelechargement.getListeClasse().index( fichier )
self.tableWidgetTelechargement.item( ligneTelechargement, 2 ).setText( stringToQstring( u"Téléchargement en cours..." ) )
self.tableWidgetTelechargement.adapterColonnes()
self.progressBarTelechargementFichier.setValue( 0 )
## Slot appele lorsqu'un telechargement se finit
# @param fichier Fichier du telechargement qui vient de se finir
# @param reussi Indique si le telechargement s'est fini sans problemes
def finTelechargement( self, fichier, reussi = True ):
ligneTelechargement = self.tableWidgetTelechargement.getListeClasse().index( fichier )
# On ajoute le fichier a l'historique
self.historique.ajouterHistorique( fichier )
# On modifie l'icone dans la liste des fichiers
self.gererIconeListeFichier( fichier )
# On modifie l'interface
self.tableWidgetTelechargement.item( ligneTelechargement, 2 ).setText( stringToQstring( u"Fini !" ) )
self.progressBarTelechargement.setValue( self.progressBarTelechargement.value() + 1 )
self.tableWidgetTelechargement.adapterColonnes()
self.progressBarTelechargementFichier.setValue( 100 )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os.path
import pickle
import logging
logger = logging.getLogger( __name__ )
##########
# Classe #
##########
class Option():
def __init__(self, type, nom, description, valeur, choix=None):
self.type = type
self.nom= nom
self.description= description
self.valeur = valeur
if type == Option.TYPE_CHOIX_MULTIPLE and not isinstance(valeur, list):
raise Exception("La valeur doit être une liste pour le type spécifié.")
if choix != None:
if self.type != Option.TYPE_CHOIX_MULTIPLE and self.type != Option.TYPE_CHOIX_UNIQUE:
raise Exception("Liste des choix inutile pour le type d'option spécifié.")
elif not isinstance(choix, list):
raise Exception("La liste des choix doit être une liste.")
self.choix = choix
elif self.type == Option.TYPE_CHOIX_MULTIPLE or self.type == Option.TYPE_CHOIX_UNIQUE:
raise Exception("Liste des choix obligatoire pour le type d'option spécifié.")
#/*******************
# * CONSTANTES *
# *******************/
TYPE_TEXTE = "texte"
TYPE_BOULEEN = "bouleen"
TYPE_CHOIX_MULTIPLE = "choixmult"
TYPE_CHOIX_UNIQUE = "choixuniq"
def setValeur(self, valeur):
if self.type == Option.TYPE_TEXTE and not isinstance(valeur, str):
raise Exception("La valeur d'une option texte doit être une chaîne.")
elif self.type == Option.TYPE_BOULEEN and not isinstance(valeur, bool):
raise Exception("La valeur d'une option bouléen doit être un bouléen.")
elif self.type == Option.TYPE_CHOIX_MULTIPLE and not isinstance(valeur, list):
raise Exception("La valeur d'une option choix multiple doit être une liste.")
elif self.type == Option.TYPE_CHOIX_UNIQUE and not isinstance(valeur, str):
raise Exception("La valeur d'une option choix unique doit être une liste.")
self.valeur = valeur
def setChoix(self, choix):
if self.type == Option.TYPE_TEXTE:
raise Exception("Pas de choix pour les options de type texte.")
elif self.type == Option.TYPE_BOULEEN:
raise Exception("Pas de choix pour les options de type booléen.")
elif not isinstance(choix, list):
raise Exception("La liste des choix doit être une liste.")
self.choix = choix
def getType(self):
return self.type
def getNom(self):
return self.nom
def getDescription(self):
return self.description
def getValeur(self):
return self.valeur
def getChoix(self):
if self.type == Option.TYPE_TEXTE:
raise Exception("Pas de choix pour les options de type texte.")
elif self.type == Option.TYPE_BOULEEN:
raise Exception("Pas de choix pour les options de type booléen.")
return self.choix
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
# N.B. :
# La gestion des plugins s'appuie sur cet article :
# http://lucumr.pocoo.org/2006/7/3/python-plugin-system
###########
# Modules #
###########
from string import find
import os
import sys
from API import API
from Plugin import Plugin
import Constantes
import logging
logger = logging.getLogger( __name__ )
##########
# Classe #
##########
## Classe qui gere les plugins
class PluginManager( object ):
# Instance de la classe (singleton)
instance = None
## Surcharge de la methode de construction standard (pour mettre en place le singleton)
def __new__( self, *args, **kwargs ):
if( self.instance is None ):
self.instance = super( PluginManager, self ).__new__( self )
return self.instance
## Constructeur
def __init__( self ):
self.api = API.getInstance()
self.listePlugins = {} # Clef : nomPlugin ; Valeur : classe du plugin (!= de son instance)
self.listeInstances = {} # Clef : nomPlugin ; Valeur : son instance
# On importe tous les plugins
for rep in Constantes.REPERTOIRES_PLUGINS:
# On verifie que le repertoire des plugins existe bien
if( not os.path.isdir( rep ) ):
logger.warn( "le repertoire %s des plugins n'existe pas..." %( rep ) )
# On l'ajoute au path si necessaire
if not( rep in sys.path ):
sys.path.insert( 0, rep )
# On importe les plugins
self.importPlugins( rep )
# On liste les plugins
self.listerPlugins()
## Methode qui importe les plugins
# @param rep Repertoire dans lequel se trouvent les plugins a importer
def importPlugins( self, rep ):
for fichier in os.listdir( rep ):
# Tous les fichiers py autre que __init__.py sont des plugins a ajouter au programme
if( fichier [ -3 : ] == ".py" and fichier.find( "__init__.py" ) == -1 ):
# On suppose que c'est la derniere version du plugin
derniereVersion = True
# Pour les autres repertoires de plugins
for autreRep in ( set( Constantes.REPERTOIRES_PLUGINS ).difference( set( [ rep ] ) ) ):
# Si le fichier existe dans l'autre repertoire
if( fichier in os.listdir( autreRep ) ):
# Si la version du plugin de l'autre repertoire est plus recente
if( os.stat( "%s/%s" %( autreRep, fichier ) ).st_mtime > os.stat( "%s/%s" %( rep, fichier ) ).st_mtime ):
derniereVersion = False
break # On arrete le parcourt des repertoires
# Si ce n'est pas la derniere version
if( not derniereVersion ):
continue # On passe au suivant
try :
__import__( fichier.replace( ".py", "" ), None, None, [ '' ] )
except ImportError :
logger.error( "impossible d'importer le fichier %s" %( fichier ) )
continue
## Methode qui retourne la liste des sites/plugins
# N.B. : On doit d'abord importer les plugins
# @return La liste des noms des plugins
def getListeSites( self ):
return self.listePlugins.keys()
## Methode qui liste les plugins
def listerPlugins( self ):
for plugin in Plugin.__subclasses__(): # Pour tous les plugins
# On l'instancie
inst = plugin()
# On recupere son nom
nom = getattr( inst, "nom" )
# On ajoute le plugin a la liste des plugins existants
self.listePlugins[ nom ] = plugin
## Methode pour activer un plugin
# @param nomPlugin Nom du plugin a activer
def activerPlugin( self, nomPlugin ):
if( self.listePlugins.has_key( nomPlugin ) ):
instance = self.listePlugins[ nomPlugin ]()
# On l'ajoute a la liste des instances
self.listeInstances[ nomPlugin ] = instance
# On l'ajoute a l'API
self.api.ajouterPlugin( instance )
self.api.activerPlugin( nomPlugin )
else:
logger.warn( "impossible d'activer le plugin %s" %( nomPlugin ) )
## Methode qui desactive un plugin
# @param nomPlugin Nom du plugin a desactiver
def desactiverPlugin( self, nomPlugin ):
# On le desactive dand l'API
self.api.desactiverPlugin( nomPlugin )
# On le supprime de la liste des instances
if( self.listeInstances.has_key( nomPlugin ) ):
self.listeInstances.pop( nomPlugin )
else:
logger.warn( "impossible de desactiver le plugin %s" %( nomPlugin ) )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
###########
# Modules #
###########
import unittest
import sys
if not( "../" in sys.path ):
sys.path.insert( 0, "../" )
from Historique import Historique
from Fichier import Fichier
##########
# Classe #
##########
## Classe qui gere les tests de la classe Historique
class HistoriqueTests( unittest.TestCase ):
## Initialisation
def setUp( self ):
self.historique = Historique()
## Fin
def tearDown( self ):
pass
def testSingleton( self ):
"""Test si le pattern singleton est bien en place"""
self.assertEqual( id( self.historique ), id( Historique() ) )
def testMauvaisType( self ):
"""Test si l'historique renvoit bien faux si on lui demande s'il contient une variable qui n'est pas un fichier"""
variable = "jeSuisUnString"
self.assertEqual( self.historique.comparerHistorique( variable ), False )
def testPresenceElement( self ):
"""Test si l'historique est capable de retrouver un element"""
element = Fichier( "Napoleon", "1804", "Notre Dame", "Sacre Napoleon" )
# On ajoute l'element a l'historique
self.historique.ajouterHistorique( element )
# On verifie si l'element y est present
self.assertEqual( self.historique.comparerHistorique( element ), True )
if __name__ == "__main__" :
unittest.main() | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
###########
# Modules #
###########
import unittest
from PreferencesTests import PreferencesTests
from HistoriqueTests import HistoriqueTests
#########
# Debut #
#########
unittest.main() | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
from API import API
from Navigateur import Navigateur
from time import time, sleep
urlsDifferentHost = ["http://www.google.fr/",
"http://fr.yahoo.com/",
"http://www.bing.com/",
"http://www.ubuntu-fr.org/",
"http://www.canalplus.fr/",
"http://www.m6.fr/",
"http://www.w9.fr/",
"http://www.tf1.fr/",
"http://www.france2.fr/",
"http://www.france3.fr/",
"http://www.france4.fr/",
"http://www.france5.fr/",
"http://www.franceo.fr/"]
urlsSameHost = ["http://www.canalplus.fr/c-divertissement/pid1784-les-guignols-de-l-info.html?",
"http://www.canalplus.fr/c-divertissement/pid1778-pepites-sur-le-net.html?",
"http://www.canalplus.fr/c-divertissement/pid3279-reperages-l-emission.html?",
"http://www.canalplus.fr/c-divertissement/pid2053-stephane-guillon.html?",
"http://www.canalplus.fr/c-divertissement/pid3591-une-minute-avant.html?",
"http://www.canalplus.fr/c-divertissement/pid3403-c-air-guitar-2010.html",
"http://www.canalplus.fr/c-divertissement/pid3299-album-de-la-semaine.html?",
"http://www.canalplus.fr/c-divertissement/pid3301-concert-prive.html?",
"http://www.canalplus.fr/c-divertissement/pid3535-c-la-musicale.html",
"http://www.canalplus.fr/c-divertissement/pid3308-la-radio-de-moustic.html?",
"http://www.canalplus.fr/c-divertissement/pid3298-coming-next.html?",
"http://www.canalplus.fr/c-divertissement/pid3522-u2-en-concert.html?",
"http://www.canalplus.fr/c-divertissement/pid3303-le-live-du-grand-journal.html?"]
navigateur = Navigateur()
api = API.getInstance()
def testeMechanize(urls):
reponses = {}
for url in urls:
reponses[ url ] = navigateur.getPage( url )
def testeGetPage(urls):
reponses = {}
for url in urls:
reponses[ url ] = api.getPage( url )
def testeGetPages(urls):
reponses = api.getPages(urls)
#~ t = time()
print "Url sur différent serveur:"
sleep(1)
t = time()
testeMechanize(urlsDifferentHost)
print "Mechanize:",time()-t,"secondes"
#~
sleep(1)
t = time()
testeGetPage(urlsDifferentHost)
print "getPage:",time()-t,"secondes"
#~
sleep(1)
t = time()
testeGetPages(urlsDifferentHost)
print "getPages:",time()-t,"secondes"
#~ print "\nUrl sur un même serveur:"
#~ sleep(1)
#~ t = time()
#~ testeMechanize(urlsSameHost)
#~ print "Mechanize:",time()-t,"secondes"
#~
#~ sleep(1)
#~ t = time()
#~ testeGetPage(urlsSameHost)
#~ print "getPage:",time()-t,"secondes"
#~
#~ sleep(1)
#~ t = time()
#~ testeGetPages(urlsSameHost)
#~ print "getPages:",time()-t,"secondes"
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
###########
# Modules #
###########
import unittest
import sys
if not( "../" in sys.path ):
sys.path.insert( 0, "../" )
from Preferences import Preferences
##########
# Classe #
##########
## Classe qui gere les tests de la classe Preferences
class PreferencesTests( unittest.TestCase ):
## Initialisation
def setUp( self ):
self.preferences = Preferences()
## Fin
def tearDown( self ):
pass
def testSingleton( self ):
"""Test si le pattern singleton est bien en place"""
self.assertEqual( id( self.preferences ), id( Preferences() ) )
def testSauvegarde( self ):
"""Test si les preferences sont bien sauvegardees"""
listePreferences = getattr( self.preferences, "preferences" )
nomPreference = listePreferences.keys()[ 0 ]
nouvelleValeur = "ValeurDeTest"
# On met en place la preference
self.preferences.setPreference( nomPreference, nouvelleValeur )
# On verifie qu'elle est bien en place
self.assertEqual( nouvelleValeur, self.preferences.getPreference( nomPreference ) )
if __name__ == "__main__" :
unittest.main() | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import sys
import os.path
import atexit
from lib.dialog import Dialog
from API import API
from Downloader import Downloader
from Historique import Historique
from Preferences import Preferences
##########
# Classe #
##########
## Classe qui gere la version CLI de TVDownloader
class CLIDialog():
## Constructeur
def __init__( self ):
# On cree l'instance de la classe dialog
self.dialog = Dialog()
self.dialog.setBackgroundTitle( "TVDownloader" )
# On recupere l'instance de API
self.api = API.getInstance()
# On instancie le gestionnaire de download
self.downloader = Downloader()
# On instancie le gestionnaire d'historique
self.historique = Historique()
# On instancie le gestionnaire de preferences
self.preferences = Preferences()
# Liste des telechargements
self.listeTelechargements = []
# Quand le programme se termine, on execute la fonction actionsAvantQuitter
atexit.register( self.actionsAvantQuitter )
# On commence
self.bouclePrincipale()
## Debut
def bouclePrincipale( self ):
choix = ( 1, "" )
while( choix != ( 0, "Quitter" ) ):
# On affiche le menu principal
choix = self.dialog.menu( text = "Menu Principal" ,
choices = [ [ "Commencer", "Afficher la liste des plugins" ],
[ "Téléchargements", "Gérer les téléchargements" ],
[ "Préférences", "Modifier les préférences" ],
[ "Quitter", "Quitter TVDownloader" ],
]
)
# On lance la methode qui va bien
if( choix == ( 0, "Commencer" ) ):
self.utilisationPlugins()
elif( choix == ( 0, "Téléchargements" ) ):
self.utlisationTelechargements()
elif( choix == ( 0, "Préférences" ) ):
pass
elif( choix == ( 0, "Quitter" ) ):
# Rien a faire, atexit gere cela
pass
## Methode pour selectionner les fichiers a telecharger avec les plugins
def utilisationPlugins( self ):
# Liste des plugins actifs
listePlugins = []
for nomPlugin in self.preferences.getPreference( "pluginsActifs" ):
listePlugins.append( [ nomPlugin, "" ] )
choixPlugin = ( 0, "" )
while( choixPlugin[ 0 ] != 1 ):
# On affiche le menu de selection de plugins
choixPlugin = self.dialog.menu( text = "De quelle plugin voulez-vous voir les chaines ?",
choices = listePlugins
)
if( choixPlugin[ 0 ] != 1 ):
# Liste des chaines du plugin
listeChaines = []
for nomChaine in self.api.getPluginListeChaines( choixPlugin[ 1 ] ):
listeChaines.append( [ nomChaine, "" ] )
choixChaine = ( 0, "" )
while( choixChaine[ 0 ] != 1 ):
# On affiche le menu de selection de la chaine
choixChaine = self.dialog.menu( text = "De quelle chaine voulez-vous voir les emissions ?",
choices = listeChaines
)
if( choixChaine[ 0 ] != 1 ):
# Liste des emissions de la chaine
listeEmissions = []
for nomEmission in self.api.getPluginListeEmissions( choixPlugin[ 1 ], choixChaine[ 1 ] ):
listeEmissions.append( [ nomEmission, "" ] )
choixEmission = ( 0, "" )
while( choixEmission[ 0 ] != 1 ):
# On affiche le menu de selection de l'emission
choixEmission = self.dialog.menu( text = "De quelle emission voulez-vous voir les fichiers ?",
choices = listeEmissions
)
if( choixEmission[ 0 ] != 1 ):
listeFichiersAAfficher = []
listeFichiersCoches = []
listeFichiersPrecedementCoches = []
listeFichiersAPI = self.api.getPluginListeFichiers( choixPlugin[ 1 ], choixEmission[ 1 ] )
i = 0
for fichier in listeFichiersAPI:
texteAAfficher = "(%s) %s" %( getattr( fichier, "date" ), getattr( fichier, "nom" ) )
if( fichier in self.listeTelechargements ):
listeFichiersPrecedementCoches.append( fichier )
cochee = 1
else:
cochee = 0
listeFichiersAAfficher.append( [ str( i ), texteAAfficher, cochee ] )
i+=1
choixFichiers = ( 0, [] )
while( choixFichiers[ 0 ] != 1 ):
choixFichiers = self.dialog.checklist( text = "Quels fichiers voulez-vous ajouter à la liste des téléchargements ?",
choices = listeFichiersAAfficher
)
if( choixFichiers[ 0 ] != 1 ):
for numeroFichier in choixFichiers[ 1 ]:
fichier = listeFichiersAPI[ int( numeroFichier ) ]
listeFichiersCoches.append( fichier )
for fichier in listeFichiersCoches:
if not ( fichier in listeFichiersPrecedementCoches ):
self.listeTelechargements.append( fichier )
for fichier in listeFichiersPrecedementCoches:
if not ( fichier in listeFichiersCoches ):
self.listeTelechargements.remove( fichier )
# On retourne au menu precedent
choixFichiers = ( 1, "" )
## Methode qui gere le gestionnaire de telechargement
def utlisationTelechargements( self ):
choix = ( 0, "" )
while( choix[ 0 ] != 1 ):
# On affiche le menu principal
choix = self.dialog.menu( text = "Gestionnaire de téléchargement" ,
choices = [ [ "Consulter", "Consulter la liste" ],
[ "Lancer", "Lancer les téléchargements" ]
]
)
# On lance la methode qui va bien
if( choix == ( 0, "Consulter" ) ):
if( len( self.listeTelechargements ) > 0 ):
texte = ""
for fichier in self.listeTelechargements:
texte += "(%s) %s\n" %( getattr( fichier, "date" ), getattr( fichier, "nom" ) )
else:
texte = "La liste des téléchargements est vide"
# On affiche la liste des fichiers a telecharger
self.dialog.msgbox( text = texte )
elif( choix == ( 0, "Lancer" ) ):
if( len( self.listeTelechargements ) > 0 ):
liste = []
for fichier in self.listeTelechargements:
lien = getattr( fichier , "lien" )
nomFichierSortie = getattr( fichier , "nomFichierSortie" )
if( nomFichierSortie == "" ): # Si le nom du fichier de sortie n'existe pas, on l'extrait de l'URL
nomFichierSortie = os.path.basename( lien )
liste.append( [ 0, lien, nomFichierSortie ] )
# On lance le telechargement
self.downloader.lancerTelechargement( liste )
self.dialog.msgbox( text = "Fin du téléchargement des fichiers" )
del self.listeTelechargements[ : ]
else:
self.dialog.msgbox( text = "Aucun fichier à télécharger" )
## Methode qui execute les actions necessaires avant de quitter le programme
def actionsAvantQuitter( self ):
print "Fermeture"
# On sauvegarde les options des plugins
self.api.fermeture()
# On sauvegarde l'historique
self.historique.sauverHistorique()
# On sauvegarde les options du logiciel
self.preferences.sauvegarderConfiguration() | Python |
# dialog.py --- A python interface to the Linux "dialog" utility
# Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov
# Copyright (C) 2002, 2003, 2004 Florent Rougon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Python interface to dialog-like programs.
This module provides a Python interface to dialog-like programs such
as `dialog', `Xdialog' and `whiptail'.
It provides a Dialog class that retains some parameters such as the
program name and path as well as the values to pass as DIALOG*
environment variables to the chosen program.
For a quick start, you should look at the demo.py file that comes
with pythondialog. It demonstrates a simple use of each widget
offered by the Dialog class.
See the Dialog class documentation for general usage information,
list of available widgets and ways to pass options to dialog.
Notable exceptions
------------------
Here is the hierarchy of notable exceptions raised by this module:
error
ExecutableNotFound
BadPythonDialogUsage
PythonDialogSystemError
PythonDialogIOError
PythonDialogOSError
PythonDialogErrorBeforeExecInChildProcess
PythonDialogReModuleError
UnexpectedDialogOutput
DialogTerminatedBySignal
DialogError
UnableToCreateTemporaryDirectory
PythonDialogBug
ProbablyPythonBug
As you can see, every exception `exc' among them verifies:
issubclass(exc, error)
so if you don't need fine-grained error handling, simply catch
`error' (which will probably be accessible as dialog.error from your
program) and you should be safe.
"""
from __future__ import nested_scopes
import sys, os, tempfile, random, string, re, types
# Python < 2.3 compatibility
if sys.hexversion < 0x02030000:
# The assignments would work with Python >= 2.3 but then, pydoc
# shows them in the DATA section of the module...
True = 0 == 0
False = 0 == 1
# Exceptions raised by this module
#
# When adding, suppressing, renaming exceptions or changing their
# hierarchy, don't forget to update the module's docstring.
class error(Exception):
"""Base class for exceptions in pythondialog."""
def __init__(self, message=None):
self.message = message
def __str__(self):
return "<%s: %s>" % (self.__class__.__name__, self.message)
def complete_message(self):
if self.message:
return "%s: %s" % (self.ExceptionShortDescription, self.message)
else:
return "%s" % self.ExceptionShortDescription
ExceptionShortDescription = "pythondialog generic exception"
# For backward-compatibility
#
# Note: this exception was not documented (only the specific ones were), so
# the backward-compatibility binding could be removed relatively easily.
PythonDialogException = error
class ExecutableNotFound(error):
"""Exception raised when the dialog executable can't be found."""
ExceptionShortDescription = "Executable not found"
class PythonDialogBug(error):
"""Exception raised when pythondialog finds a bug in his own code."""
ExceptionShortDescription = "Bug in pythondialog"
# Yeah, the "Probably" makes it look a bit ugly, but:
# - this is more accurate
# - this avoids a potential clash with an eventual PythonBug built-in
# exception in the Python interpreter...
class ProbablyPythonBug(error):
"""Exception raised when pythondialog behaves in a way that seems to \
indicate a Python bug."""
ExceptionShortDescription = "Bug in python, probably"
class BadPythonDialogUsage(error):
"""Exception raised when pythondialog is used in an incorrect way."""
ExceptionShortDescription = "Invalid use of pythondialog"
class PythonDialogSystemError(error):
"""Exception raised when pythondialog cannot perform a "system \
operation" (e.g., a system call) that should work in "normal" situations.
This is a convenience exception: PythonDialogIOError, PythonDialogOSError
and PythonDialogErrorBeforeExecInChildProcess all derive from this
exception. As a consequence, watching for PythonDialogSystemError instead
of the aformentioned exceptions is enough if you don't need precise
details about these kinds of errors.
Don't confuse this exception with Python's builtin SystemError
exception.
"""
ExceptionShortDescription = "System error"
class PythonDialogIOError(PythonDialogSystemError):
"""Exception raised when pythondialog catches an IOError exception that \
should be passed to the calling program."""
ExceptionShortDescription = "IO error"
class PythonDialogOSError(PythonDialogSystemError):
"""Exception raised when pythondialog catches an OSError exception that \
should be passed to the calling program."""
ExceptionShortDescription = "OS error"
class PythonDialogErrorBeforeExecInChildProcess(PythonDialogSystemError):
"""Exception raised when an exception is caught in a child process \
before the exec sytem call (included).
This can happen in uncomfortable situations like when the system is out
of memory or when the maximum number of open file descriptors has been
reached. This can also happen if the dialog-like program was removed
(or if it is has been made non-executable) between the time we found it
with _find_in_path and the time the exec system call attempted to
execute it...
"""
ExceptionShortDescription = "Error in a child process before the exec " \
"system call"
class PythonDialogReModuleError(PythonDialogSystemError):
"""Exception raised when pythondialog catches a re.error exception."""
ExceptionShortDescription = "'re' module error"
class UnexpectedDialogOutput(error):
"""Exception raised when the dialog-like program returns something not \
expected by pythondialog."""
ExceptionShortDescription = "Unexpected dialog output"
class DialogTerminatedBySignal(error):
"""Exception raised when the dialog-like program is terminated by a \
signal."""
ExceptionShortDescription = "dialog-like terminated by a signal"
class DialogError(error):
"""Exception raised when the dialog-like program exits with the \
code indicating an error."""
ExceptionShortDescription = "dialog-like terminated due to an error"
class UnableToCreateTemporaryDirectory(error):
"""Exception raised when we cannot create a temporary directory."""
ExceptionShortDescription = "unable to create a temporary directory"
# Values accepted for checklists
try:
_on_rec = re.compile(r"on", re.IGNORECASE)
_off_rec = re.compile(r"off", re.IGNORECASE)
_calendar_date_rec = re.compile(
r"(?P<day>\d\d)/(?P<month>\d\d)/(?P<year>\d\d\d\d)$")
_timebox_time_rec = re.compile(
r"(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)$")
except re.error, v:
raise PythonDialogReModuleError(v)
# This dictionary allows us to write the dialog common options in a Pythonic
# way (e.g. dialog_instance.checklist(args, ..., title="Foo", no_shadow=1)).
#
# Options such as --separate-output should obviously not be set by the user
# since they affect the parsing of dialog's output:
_common_args_syntax = {
"aspect": lambda ratio: ("--aspect", str(ratio)),
"backtitle": lambda backtitle: ("--backtitle", backtitle),
"beep": lambda enable: _simple_option("--beep", enable),
"beep_after": lambda enable: _simple_option("--beep-after", enable),
# Warning: order = y, x!
"begin": lambda coords: ("--begin", str(coords[0]), str(coords[1])),
"cancel": lambda string: ("--cancel-label", string),
"clear": lambda enable: _simple_option("--clear", enable),
"cr_wrap": lambda enable: _simple_option("--cr-wrap", enable),
"create_rc": lambda file: ("--create-rc", file),
"defaultno": lambda enable: _simple_option("--defaultno", enable),
"default_item": lambda string: ("--default-item", string),
"help": lambda enable: _simple_option("--help", enable),
"help_button": lambda enable: _simple_option("--help-button", enable),
"help_label": lambda string: ("--help-label", string),
"ignore": lambda enable: _simple_option("--ignore", enable),
"item_help": lambda enable: _simple_option("--item-help", enable),
"max_input": lambda size: ("--max-input", str(size)),
"no_kill": lambda enable: _simple_option("--no-kill", enable),
"no_cancel": lambda enable: _simple_option("--no-cancel", enable),
"nocancel": lambda enable: _simple_option("--nocancel", enable),
"no_shadow": lambda enable: _simple_option("--no-shadow", enable),
"ok_label": lambda string: ("--ok-label", string),
"print_maxsize": lambda enable: _simple_option("--print-maxsize",
enable),
"print_size": lambda enable: _simple_option("--print-size", enable),
"print_version": lambda enable: _simple_option("--print-version",
enable),
"separate_output": lambda enable: _simple_option("--separate-output",
enable),
"separate_widget": lambda string: ("--separate-widget", string),
"shadow": lambda enable: _simple_option("--shadow", enable),
"size_err": lambda enable: _simple_option("--size-err", enable),
"sleep": lambda secs: ("--sleep", str(secs)),
"stderr": lambda enable: _simple_option("--stderr", enable),
"stdout": lambda enable: _simple_option("--stdout", enable),
"tab_correct": lambda enable: _simple_option("--tab-correct", enable),
"tab_len": lambda n: ("--tab-len", str(n)),
"timeout": lambda secs: ("--timeout", str(secs)),
"title": lambda title: ("--title", title),
"trim": lambda enable: _simple_option("--trim", enable),
"version": lambda enable: _simple_option("--version", enable)}
def _simple_option(option, enable):
"""Turn on or off the simplest dialog Common Options."""
if enable:
return (option,)
else:
# This will not add any argument to the command line
return ()
def _find_in_path(prog_name):
"""Search an executable in the PATH.
If PATH is not defined, the default path ":/bin:/usr/bin" is
used.
Return a path to the file or None if no readable and executable
file is found.
Notable exception: PythonDialogOSError
"""
try:
# Note that the leading empty component in the default value for PATH
# could lead to the returned path not being absolute.
PATH = os.getenv("PATH", ":/bin:/usr/bin") # see the execvp(3) man page
for dir in string.split(PATH, ":"):
file_path = os.path.join(dir, prog_name)
if os.path.isfile(file_path) \
and os.access(file_path, os.R_OK | os.X_OK):
return file_path
return None
except os.error, v:
raise PythonDialogOSError(v.strerror)
def _path_to_executable(f):
"""Find a path to an executable.
Find a path to an executable, using the same rules as the POSIX
exec*p functions (see execvp(3) for instance).
If `f' contains a '/', it is assumed to be a path and is simply
checked for read and write permissions; otherwise, it is looked
for according to the contents of the PATH environment variable,
which defaults to ":/bin:/usr/bin" if unset.
The returned path is not necessarily absolute.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
"""
try:
if '/' in f:
if os.path.isfile(f) and \
os.access(f, os.R_OK | os.X_OK):
res = f
else:
raise ExecutableNotFound("%s cannot be read and executed" % f)
else:
res = _find_in_path(f)
if res is None:
raise ExecutableNotFound(
"can't find the executable for the dialog-like "
"program")
except os.error, v:
raise PythonDialogOSError(v.strerror)
return res
def _to_onoff(val):
"""Convert boolean expressions to "on" or "off"
This function converts every non-zero integer as well as "on",
"ON", "On" and "oN" to "on" and converts 0, "off", "OFF", etc. to
"off".
Notable exceptions:
PythonDialogReModuleError
BadPythonDialogUsage
"""
if type(val) == types.IntType:
if val:
return "on"
else:
return "off"
elif type(val) == types.StringType:
try:
if _on_rec.match(val):
return "on"
elif _off_rec.match(val):
return "off"
except re.error, v:
raise PythonDialogReModuleError(v)
else:
raise BadPythonDialogUsage("invalid boolean value: %s" % val)
def _compute_common_args(dict):
"""Compute the list of arguments for dialog common options.
Compute a list of the command-line arguments to pass to dialog
from a keyword arguments dictionary for options listed as "common
options" in the manual page for dialog. These are the options
that are not tied to a particular widget.
This allows to specify these options in a pythonic way, such as:
d.checklist(<usual arguments for a checklist>,
title="...",
backtitle="...")
instead of having to pass them with strings like "--title foo" or
"--backtitle bar".
Notable exceptions: None
"""
args = []
for key in dict.keys():
args.extend(_common_args_syntax[key](dict[key]))
return args
def _create_temporary_directory():
"""Create a temporary directory (securely).
Return the directory path.
Notable exceptions:
- UnableToCreateTemporaryDirectory
- PythonDialogOSError
- exceptions raised by the tempfile module (which are
unfortunately not mentioned in its documentation, at
least in Python 2.3.3...)
"""
find_temporary_nb_attempts = 5
for i in range(find_temporary_nb_attempts):
try:
# Using something >= 2**31 causes an error in Python 2.2...
tmp_dir = os.path.join(tempfile.gettempdir(),
"%s-%u" \
% ("pythondialog",
random.randint(0, 2**30-1)))
except os.error, v:
raise PythonDialogOSError(v.strerror)
try:
os.mkdir(tmp_dir, 0700)
except os.error:
continue
else:
break
else:
raise UnableToCreateTemporaryDirectory(
"somebody may be trying to attack us")
return tmp_dir
# DIALOG_OK, DIALOG_CANCEL, etc. are environment variables controlling
# dialog's exit status in the corresponding situation.
#
# Note:
# - 127 must not be used for any of the DIALOG_* values. It is used
# when a failure occurs in the child process before it exec()s
# dialog (where "before" includes a potential exec() failure).
# - 126 is also used (although in presumably rare situations).
_dialog_exit_status_vars = { "OK": 0,
"CANCEL": 1,
"ESC": 2,
"ERROR": 3,
"EXTRA": 4,
"HELP": 5 }
# Main class of the module
class Dialog:
"""Class providing bindings for dialog-compatible programs.
This class allows you to invoke dialog or a compatible program in
a pythonic way to build quicky and easily simple but nice text
interfaces.
An application typically creates one instance of the Dialog class
and uses it for all its widgets, but it is possible to use
concurrently several instances of this class with different
parameters (such as the background title) if you have the need
for this.
The exit code (exit status) returned by dialog is to be
compared with the DIALOG_OK, DIALOG_CANCEL, DIALOG_ESC,
DIALOG_ERROR, DIALOG_EXTRA and DIALOG_HELP attributes of the
Dialog instance (they are integers).
Note: although this class does all it can to allow the caller to
differentiate between the various reasons that caused a
dialog box to be closed, its backend, dialog 0.9a-20020309a
for my tests, doesn't always return DIALOG_ESC when the
user presses the ESC key, but often returns DIALOG_ERROR
instead. The exit codes returned by the corresponding
Dialog methods are of course just as wrong in these cases.
You've been warned.
Public methods of the Dialog class (mainly widgets)
---------------------------------------------------
The Dialog class has the following methods:
add_persistent_args
calendar
checklist
fselect
gauge_start
gauge_update
gauge_stop
infobox
inputbox
menu
msgbox
passwordbox
radiolist
scrollbox
tailbox
textbox
timebox
yesno
clear (obsolete)
setBackgroundTitle (obsolete)
Passing dialog "Common Options"
-------------------------------
Every widget method has a **kwargs argument allowing you to pass
dialog so-called Common Options (see the dialog(1) manual page)
to dialog for this widget call. For instance, if `d' is a Dialog
instance, you can write:
d.checklist(args, ..., title="A Great Title", no_shadow=1)
The no_shadow option is worth looking at:
1. It is an option that takes no argument as far as dialog is
concerned (unlike the "--title" option, for instance). When
you list it as a keyword argument, the option is really
passed to dialog only if the value you gave it evaluates to
true, e.g. "no_shadow=1" will cause "--no-shadow" to be
passed to dialog whereas "no_shadow=0" will cause this
option not to be passed to dialog at all.
2. It is an option that has a hyphen (-) in its name, which you
must change into an underscore (_) to pass it as a Python
keyword argument. Therefore, "--no-shadow" is passed by
giving a "no_shadow=1" keyword argument to a Dialog method
(the leading two dashes are also consistently removed).
Exceptions
----------
Please refer to the specific methods' docstrings or simply to the
module's docstring for a list of all exceptions that might be
raised by this class' methods.
"""
def __init__(self, dialog="dialog", DIALOGRC=None, compat="dialog",
use_stdout=None):
"""Constructor for Dialog instances.
dialog -- name of (or path to) the dialog-like program to
use; if it contains a '/', it is assumed to be a
path and is used as is; otherwise, it is looked
for according to the contents of the PATH
environment variable, which defaults to
":/bin:/usr/bin" if unset.
DIALOGRC -- string to pass to the dialog-like program as the
DIALOGRC environment variable, or None if no
modification to the environment regarding this
variable should be done in the call to the
dialog-like program
compat -- compatibility mode (see below)
The officially supported dialog-like program in pythondialog
is the well-known dialog program written in C, based on the
ncurses library. It is also known as cdialog and its home
page is currently (2004-03-15) located at:
http://dickey.his.com/dialog/dialog.html
If you want to use a different program such as Xdialog, you
should indicate the executable file name with the `dialog'
argument *and* the compatibility type that you think it
conforms to with the `compat' argument. Currently, `compat'
can be either "dialog" (for dialog; this is the default) or
"Xdialog" (for, well, Xdialog).
The `compat' argument allows me to cope with minor
differences in behaviour between the various programs
implementing the dialog interface (not the text or graphical
interface, I mean the "API"). However, having to support
various APIs simultaneously is a bit ugly and I would really
prefer you to report bugs to the relevant maintainers when
you find incompatibilities with dialog. This is for the
benefit of pretty much everyone that relies on the dialog
interface.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
"""
# DIALOGRC differs from the other DIALOG* variables in that:
# 1. It should be a string if not None
# 2. We may very well want it to be unset
if DIALOGRC is not None:
self.DIALOGRC = DIALOGRC
# After reflexion, I think DIALOG_OK, DIALOG_CANCEL, etc.
# should never have been instance attributes (I cannot see a
# reason why the user would want to change their values or
# even read them), but it is a bit late, now. So, we set them
# based on the (global) _dialog_exit_status_vars.keys.
for var in _dialog_exit_status_vars.keys():
varname = "DIALOG_" + var
setattr(self, varname, _dialog_exit_status_vars[var])
self._dialog_prg = _path_to_executable(dialog)
self.compat = compat
self.dialog_persistent_arglist = []
# Use stderr or stdout?
if self.compat == "Xdialog":
# Default to stdout if Xdialog
self.use_stdout = True
else:
self.use_stdout = False
if use_stdout != None:
# Allow explicit setting
self.use_stdout = use_stdout
if self.use_stdout:
self.add_persistent_args(["--stdout"])
def add_persistent_args(self, arglist):
self.dialog_persistent_arglist.extend(arglist)
# For compatibility with the old dialog...
def setBackgroundTitle(self, text):
"""Set the background title for dialog.
This method is obsolete. Please remove calls to it from your
programs.
"""
self.add_persistent_args(("--backtitle", text))
def _call_program(self, redirect_child_stdin, cmdargs, **kwargs):
"""Do the actual work of invoking the dialog-like program.
Communication with the dialog-like program is performed
through one or two pipes, depending on
`redirect_child_stdin'. There is always one pipe that is
created to allow the parent process to read what dialog
writes on its standard error stream.
If `redirect_child_stdin' is True, an additional pipe is
created whose reading end is connected to dialog's standard
input. This is used by the gauge widget to feed data to
dialog.
Beware when interpreting the return value: the length of the
returned tuple depends on `redirect_child_stdin'.
Notable exception: PythonDialogOSError (if pipe() or close()
system calls fail...)
"""
# We want to define DIALOG_OK, DIALOG_CANCEL, etc. in the
# environment of the child process so that we know (and
# even control) the possible dialog exit statuses.
new_environ = {}
new_environ.update(os.environ)
for var in _dialog_exit_status_vars:
varname = "DIALOG_" + var
new_environ[varname] = str(getattr(self, varname))
if hasattr(self, "DIALOGRC"):
new_environ["DIALOGRC"] = self.DIALOGRC
# Create:
# - a pipe so that the parent process can read dialog's output on
# stdout/stderr
# - a pipe so that the parent process can feed data to dialog's
# stdin (this is needed for the gauge widget) if
# redirect_child_stdin is True
try:
# rfd = File Descriptor for Reading
# wfd = File Descriptor for Writing
(child_rfd, child_wfd) = os.pipe()
if redirect_child_stdin:
(child_stdin_rfd, child_stdin_wfd) = os.pipe()
except os.error, v:
raise PythonDialogOSError(v.strerror)
child_pid = os.fork()
if child_pid == 0:
# We are in the child process. We MUST NOT raise any exception.
try:
# The child process doesn't need these file descriptors
os.close(child_rfd)
if redirect_child_stdin:
os.close(child_stdin_wfd)
# We want:
# - dialog's output on stderr/stdout to go to child_wfd
# - data written to child_stdin_wfd to go to dialog's stdin
# if redirect_child_stdin is True
if self.use_stdout:
os.dup2(child_wfd, 1)
else:
os.dup2(child_wfd, 2)
if redirect_child_stdin:
os.dup2(child_stdin_rfd, 0)
arglist = [self._dialog_prg] + \
self.dialog_persistent_arglist + \
_compute_common_args(kwargs) + \
cmdargs
# Insert here the contents of the DEBUGGING file if you want
# to obtain a handy string of the complete command line with
# arguments quoted for the shell and environment variables
# set.
os.execve(self._dialog_prg, arglist, new_environ)
except:
os._exit(127)
# Should not happen unless there is a bug in Python
os._exit(126)
# We are in the father process.
#
# It is essential to close child_wfd, otherwise we will never
# see EOF while reading on child_rfd and the parent process
# will block forever on the read() call.
# [ after the fork(), the "reference count" of child_wfd from
# the operating system's point of view is 2; after the child exits,
# it is 1 until the father closes it itself; then it is 0 and a read
# on child_rfd encounters EOF once all the remaining data in
# the pipe has been read. ]
try:
os.close(child_wfd)
if redirect_child_stdin:
os.close(child_stdin_rfd)
return (child_pid, child_rfd, child_stdin_wfd)
else:
return (child_pid, child_rfd)
except os.error, v:
raise PythonDialogOSError(v.strerror)
def _wait_for_program_termination(self, child_pid, child_rfd):
"""Wait for a dialog-like process to terminate.
This function waits for the specified process to terminate,
raises the appropriate exceptions in case of abnormal
termination and returns the exit status and standard error
output of the process as a tuple: (exit_code, stderr_string).
`child_rfd' must be the file descriptor for the
reading end of the pipe created by self._call_program()
whose writing end was connected by self._call_program() to
the child process's standard error.
This function reads the process's output on standard error
from `child_rfd' and closes this file descriptor once
this is done.
Notable exceptions:
DialogTerminatedBySignal
DialogError
PythonDialogErrorBeforeExecInChildProcess
PythonDialogIOError
PythonDialogBug
ProbablyPythonBug
"""
exit_info = os.waitpid(child_pid, 0)[1]
if os.WIFEXITED(exit_info):
exit_code = os.WEXITSTATUS(exit_info)
# As we wait()ed for the child process to terminate, there is no
# need to call os.WIFSTOPPED()
elif os.WIFSIGNALED(exit_info):
raise DialogTerminatedBySignal("the dialog-like program was "
"terminated by signal %u" %
os.WTERMSIG(exit_info))
else:
raise PythonDialogBug("please report this bug to the "
"pythondialog maintainers")
if exit_code == self.DIALOG_ERROR:
raise DialogError("the dialog-like program exited with "
"code %d (was passed to it as the DIALOG_ERROR "
"environment variable)" % exit_code)
elif exit_code == 127:
raise PythonDialogErrorBeforeExecInChildProcess(
"perhaps the dialog-like program could not be executed; "
"perhaps the system is out of memory; perhaps the maximum "
"number of open file descriptors has been reached")
elif exit_code == 126:
raise ProbablyPythonBug(
"a child process returned with exit status 126; this might "
"be the exit status of the dialog-like program, for some "
"unknown reason (-> probably a bug in the dialog-like "
"program); otherwise, we have probably found a python bug")
# We might want to check here whether exit_code is really one of
# DIALOG_OK, DIALOG_CANCEL, etc. However, I prefer not doing it
# because it would break pythondialog for no strong reason when new
# exit codes are added to the dialog-like program.
#
# As it is now, if such a thing happens, the program using
# pythondialog may receive an exit_code it doesn't know about. OK, the
# programmer just has to tell the pythondialog maintainer about it and
# can temporarily set the appropriate DIALOG_* environment variable if
# he wants and assign the corresponding value to the Dialog instance's
# DIALOG_FOO attribute from his program. He doesn't even need to use a
# patched pythondialog before he upgrades to a version that knows
# about the new exit codes.
#
# The bad thing that might happen is a new DIALOG_FOO exit code being
# the same by default as one of those we chose for the other exit
# codes already known by pythondialog. But in this situation, the
# check that is being discussed wouldn't help at all.
# Read dialog's output on its stderr
try:
child_output = os.fdopen(child_rfd, "rb").read()
# Now, since the file object has no reference anymore, the
# standard IO stream behind it will be closed, causing the
# end of the the pipe we used to read dialog's output on its
# stderr to be closed (this is important, otherwise invoking
# dialog enough times will eventually exhaust the maximum number
# of open file descriptors).
except IOError, v:
raise PythonDialogIOError(v)
return (exit_code, child_output)
def _perform(self, cmdargs, **kwargs):
"""Perform a complete dialog-like program invocation.
This function invokes the dialog-like program, waits for its
termination and returns its exit status and whatever it wrote
on its standard error stream.
Notable exceptions:
any exception raised by self._call_program() or
self._wait_for_program_termination()
"""
(child_pid, child_rfd) = \
self._call_program(False, *(cmdargs,), **kwargs)
(exit_code, output) = \
self._wait_for_program_termination(child_pid,
child_rfd)
return (exit_code, output)
def _strip_xdialog_newline(self, output):
"""Remove trailing newline (if any), if using Xdialog"""
if self.compat == "Xdialog" and output.endswith("\n"):
output = output[:-1]
return output
# This is for compatibility with the old dialog.py
def _perform_no_options(self, cmd):
"""Call dialog without passing any more options."""
return os.system(self._dialog_prg + ' ' + cmd)
# For compatibility with the old dialog.py
def clear(self):
"""Clear the screen. Equivalent to the dialog --clear option.
This method is obsolete. Please remove calls to it from your
programs.
"""
self._perform_no_options('--clear')
def calendar(self, text, height=6, width=0, day=0, month=0, year=0,
**kwargs):
"""Display a calendar dialog box.
text -- text to display in the box
height -- height of the box (minus the calendar height)
width -- width of the box
day -- inititial day highlighted
month -- inititial month displayed
year -- inititial year selected (0 causes the current date
to be used as the initial date)
A calendar box displays month, day and year in separately
adjustable windows. If the values for day, month or year are
missing or negative, the current date's corresponding values
are used. You can increment or decrement any of those using
the left, up, right and down arrows. Use tab or backtab to
move between windows. If the year is given as zero, the
current date is used as an initial value.
Return a tuple of the form (code, date) where `code' is the
exit status (an integer) of the dialog-like program and
`date' is a list of the form [day, month, year] (where `day',
`month' and `year' are integers corresponding to the date
chosen by the user) if the box was closed with OK, or None if
it was closed with the Cancel button.
Notable exceptions:
- any exception raised by self._perform()
- UnexpectedDialogOutput
- PythonDialogReModuleError
"""
(code, output) = self._perform(
*(["--calendar", text, str(height), str(width), str(day),
str(month), str(year)],),
**kwargs)
if code == self.DIALOG_OK:
try:
mo = _calendar_date_rec.match(output)
except re.error, v:
raise PythonDialogReModuleError(v)
if mo is None:
raise UnexpectedDialogOutput(
"the dialog-like program returned the following "
"unexpected date with the calendar box: %s" % output)
date = map(int, mo.group("day", "month", "year"))
else:
date = None
return (code, date)
def checklist(self, text, height=15, width=54, list_height=7,
choices=[], **kwargs):
"""Display a checklist box.
text -- text to display in the box
height -- height of the box
width -- width of the box
list_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a list of tuples (tag, item, status) where
`status' specifies the initial on/off state of
each entry; can be 0 or 1 (integers, 1 meaning
checked, i.e. "on"), or "on", "off" or any
uppercase variant of these two strings.
Return a tuple of the form (code, [tag, ...]) with the tags
for the entries that were selected by the user. `code' is the
exit status of the dialog-like program.
If the user exits with ESC or CANCEL, the returned tag list
is empty.
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
cmd = ["--checklist", text, str(height), str(width), str(list_height)]
for t in choices:
cmd.extend(((t[0], t[1], _to_onoff(t[2]))))
# The dialog output cannot be parsed reliably (at least in dialog
# 0.9b-20040301) without --separate-output (because double quotes in
# tags are escaped with backslashes, but backslashes are not
# themselves escaped and you have a problem when a tag ends with a
# backslash--the output makes you think you've encountered an embedded
# double-quote).
kwargs["separate_output"] = True
(code, output) = self._perform(*(cmd,), **kwargs)
# Since we used --separate-output, the tags are separated by a newline
# in the output. There is also a final newline after the last tag.
if output:
return (code, string.split(output, '\n')[:-1])
else: # empty selection
return (code, [])
def fselect(self, filepath, height, width, **kwargs):
"""Display a file selection dialog box.
filepath -- initial file path
height -- height of the box
width -- width of the box
The file-selection dialog displays a text-entry window in
which you can type a filename (or directory), and above that
two windows with directory names and filenames.
Here, filepath can be a file path in which case the file and
directory windows will display the contents of the path and
the text-entry window will contain the preselected filename.
Use tab or arrow keys to move between the windows. Within the
directory or filename windows, use the up/down arrow keys to
scroll the current selection. Use the space-bar to copy the
current selection into the text-entry window.
Typing any printable character switches focus to the
text-entry window, entering that character as well as
scrolling the directory and filename windows to the closest
match.
Use a carriage return or the "OK" button to accept the
current value in the text-entry window, or the "Cancel"
button to cancel.
Return a tuple of the form (code, path) where `code' is the
exit status (an integer) of the dialog-like program and
`path' is the path chosen by the user (whose last element may
be a directory or a file).
Notable exceptions:
any exception raised by self._perform()
"""
(code, output) = self._perform(
*(["--fselect", filepath, str(height), str(width)],),
**kwargs)
output = self._strip_xdialog_newline(output)
return (code, output)
def gauge_start(self, text="", height=8, width=54, percent=0, **kwargs):
"""Display gauge box.
text -- text to display in the box
height -- height of the box
width -- width of the box
percent -- initial percentage shown in the meter
A gauge box displays a meter along the bottom of the box. The
meter indicates a percentage.
This function starts the dialog-like program telling it to
display a gauge box with a text in it and an initial
percentage in the meter.
Return value: undefined.
Gauge typical usage
-------------------
Gauge typical usage (assuming that `d' is an instance of the
Dialog class) looks like this:
d.gauge_start()
# do something
d.gauge_update(10) # 10% of the whole task is done
# ...
d.gauge_update(100, "any text here") # work is done
exit_code = d.gauge_stop() # cleanup actions
Notable exceptions:
- any exception raised by self._call_program()
- PythonDialogOSError
"""
(child_pid, child_rfd, child_stdin_wfd) = self._call_program(
True,
*(["--gauge", text, str(height), str(width), str(percent)],),
**kwargs)
try:
self._gauge_process = {
"pid": child_pid,
"stdin": os.fdopen(child_stdin_wfd, "wb"),
"child_rfd": child_rfd
}
except os.error, v:
raise PythonDialogOSError(v.strerror)
def gauge_update(self, percent, text="", update_text=0):
"""Update a running gauge box.
percent -- new percentage to show in the gauge meter
text -- new text to optionally display in the box
update-text -- boolean indicating whether to update the
text in the box
This function updates the percentage shown by the meter of a
running gauge box (meaning `gauge_start' must have been
called previously). If update_text is true (for instance, 1),
the text displayed in the box is also updated.
See the `gauge_start' function's documentation for
information about how to use a gauge.
Return value: undefined.
Notable exception: PythonDialogIOError can be raised if there
is an I/O error while writing to the pipe
used to talk to the dialog-like program.
"""
if update_text:
gauge_data = "%d\nXXX\n%s\nXXX\n" % (percent, text)
else:
gauge_data = "%d\n" % percent
try:
self._gauge_process["stdin"].write(gauge_data)
self._gauge_process["stdin"].flush()
except IOError, v:
raise PythonDialogIOError(v)
# For "compatibility" with the old dialog.py...
gauge_iterate = gauge_update
def gauge_stop(self):
"""Terminate a running gauge.
This function performs the appropriate cleanup actions to
terminate a running gauge (started with `gauge_start').
See the `gauge_start' function's documentation for
information about how to use a gauge.
Return value: undefined.
Notable exceptions:
- any exception raised by
self._wait_for_program_termination()
- PythonDialogIOError can be raised if closing the pipe
used to talk to the dialog-like program fails.
"""
p = self._gauge_process
# Close the pipe that we are using to feed dialog's stdin
try:
p["stdin"].close()
except IOError, v:
raise PythonDialogIOError(v)
exit_code = \
self._wait_for_program_termination(p["pid"],
p["child_rfd"])[0]
return exit_code
def infobox(self, text, height=10, width=30, **kwargs):
"""Display an information dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
An info box is basically a message box. However, in this
case, dialog will exit immediately after displaying the
message to the user. The screen is not cleared when dialog
exits, so that the message will remain on the screen until
the calling shell script clears it later. This is useful
when you want to inform the user that some operations are
carrying on that may require some time to finish.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--infobox", text, str(height), str(width)],),
**kwargs)[0]
def inputbox(self, text, height=10, width=30, init='', **kwargs):
"""Display an input dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
init -- default input string
An input box is useful when you want to ask questions that
require the user to input a string as the answer. If init is
supplied it is used to initialize the input string. When
entering the string, the BACKSPACE key can be used to
correct typing errors. If the input string is longer than
can fit in the dialog box, the input field will be scrolled.
Return a tuple of the form (code, string) where `code' is the
exit status of the dialog-like program and `string' is the
string entered by the user.
Notable exceptions:
any exception raised by self._perform()
"""
(code, tag) = self._perform(
*(["--inputbox", text, str(height), str(width), init],),
**kwargs)
tag = self._strip_xdialog_newline(tag)
return (code, tag)
def menu(self, text, height=15, width=54, menu_height=7, choices=[],
**kwargs):
"""Display a menu dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
menu_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a sequence of (tag, item) or (tag, item, help)
tuples (the meaning of each `tag', `item' and
`help' is explained below)
Overview
--------
As its name suggests, a menu box is a dialog box that can be
used to present a list of choices in the form of a menu for
the user to choose. Choices are displayed in the order given.
Each menu entry consists of a `tag' string and an `item'
string. The tag gives the entry a name to distinguish it from
the other entries in the menu. The item is a short
description of the option that the entry represents.
The user can move between the menu entries by pressing the
UP/DOWN keys, the first letter of the tag as a hot-key, or
the number keys 1-9. There are menu-height entries displayed
in the menu at one time, but the menu will be scrolled if
there are more entries than that.
Providing on-line help facilities
---------------------------------
If this function is called with item_help=1 (keyword
argument), the option --item-help is passed to dialog and the
tuples contained in `choices' must contain 3 elements each :
(tag, item, help). The help string for the highlighted item
is displayed in the bottom line of the screen and updated as
the user highlights other items.
If item_help=0 or if this keyword argument is not passed to
this function, the tuples contained in `choices' must contain
2 elements each : (tag, item).
If this function is called with help_button=1, it must also
be called with item_help=1 (this is a limitation of dialog),
therefore the tuples contained in `choices' must contain 3
elements each as explained in the previous paragraphs. This
will cause a Help button to be added to the right of the
Cancel button (by passing --help-button to dialog).
Return value
------------
Return a tuple of the form (exit_info, string).
`exit_info' is either:
- an integer, being the the exit status of the dialog-like
program
- or the string "help", meaning that help_button=1 was
passed and that the user chose the Help button instead of
OK or Cancel.
The meaning of `string' depends on the value of exit_info:
- if `exit_info' is 0, `string' is the tag chosen by the
user
- if `exit_info' is "help", `string' is the `help' string
from the `choices' argument corresponding to the item
that was highlighted when the user chose the Help button
- otherwise (the user chose Cancel or pressed Esc, or there
was a dialog error), the value of `string' is undefined.
Notable exceptions:
any exception raised by self._perform()
"""
cmd = ["--menu", text, str(height), str(width), str(menu_height)]
for t in choices:
cmd.extend(t)
(code, output) = self._perform(*(cmd,), **kwargs)
output = self._strip_xdialog_newline(output)
if "help_button" in kwargs.keys() and output.startswith("HELP "):
return ("help", output[5:])
else:
return (code, output)
def msgbox(self, text, height=10, width=30, **kwargs):
"""Display a message dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
A message box is very similar to a yes/no box. The only
difference between a message box and a yes/no box is that a
message box has only a single OK button. You can use this
dialog box to display any message you like. After reading
the message, the user can press the ENTER key so that dialog
will exit and the calling program can continue its
operation.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--msgbox", text, str(height), str(width)],),
**kwargs)[0]
def passwordbox(self, text, height=10, width=60, init='', **kwargs):
"""Display an password input dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
init -- default input password
A password box is similar to an input box, except that the
text the user enters is not displayed. This is useful when
prompting for passwords or other sensitive information. Be
aware that if anything is passed in "init", it will be
visible in the system's process table to casual snoopers.
Also, it is very confusing to the user to provide them with a
default password they cannot see. For these reasons, using
"init" is highly discouraged.
Return a tuple of the form (code, password) where `code' is
the exit status of the dialog-like program and `password' is
the password entered by the user.
Notable exceptions:
any exception raised by self._perform()
"""
(code, password) = self._perform(
*(["--passwordbox", text, str(height), str(width), init],),
**kwargs)
password = self._strip_xdialog_newline(password)
return (code, password)
def radiolist(self, text, height=15, width=54, list_height=7,
choices=[], **kwargs):
"""Display a radiolist box.
text -- text to display in the box
height -- height of the box
width -- width of the box
list_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a list of tuples (tag, item, status) where
`status' specifies the initial on/off state
each entry; can be 0 or 1 (integers, 1 meaning
checked, i.e. "on"), or "on", "off" or any
uppercase variant of these two strings.
No more than one entry should be set to on.
A radiolist box is similar to a menu box. The main difference
is that you can indicate which entry is initially selected,
by setting its status to on.
Return a tuple of the form (code, tag) with the tag for the
entry that was chosen by the user. `code' is the exit status
of the dialog-like program.
If the user exits with ESC or CANCEL, or if all entries were
initially set to off and not altered before the user chose
OK, the returned tag is the empty string.
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
cmd = ["--radiolist", text, str(height), str(width), str(list_height)]
for t in choices:
cmd.extend(((t[0], t[1], _to_onoff(t[2]))))
(code, tag) = self._perform(*(cmd,), **kwargs)
tag = self._strip_xdialog_newline(tag)
return (code, tag)
def scrollbox(self, text, height=20, width=78, **kwargs):
"""Display a string in a scrollable box.
text -- text to display in the box
height -- height of the box
width -- width of the box
This method is a layer on top of textbox. The textbox option
in dialog allows to display file contents only. This method
allows you to display any text in a scrollable box. This is
simply done by creating a temporary file, calling textbox and
deleting the temporary file afterwards.
Return the dialog-like program's exit status.
Notable exceptions:
- UnableToCreateTemporaryDirectory
- PythonDialogIOError
- PythonDialogOSError
- exceptions raised by the tempfile module (which are
unfortunately not mentioned in its documentation, at
least in Python 2.3.3...)
"""
# In Python < 2.3, the standard library does not have
# tempfile.mkstemp(), and unfortunately, tempfile.mktemp() is
# insecure. So, I create a non-world-writable temporary directory and
# store the temporary file in this directory.
try:
# We want to ensure that f is already bound in the local
# scope when the finally clause (see below) is executed
f = 0
tmp_dir = _create_temporary_directory()
# If we are here, tmp_dir *is* created (no exception was raised),
# so chances are great that os.rmdir(tmp_dir) will succeed (as
# long as tmp_dir is empty).
#
# Don't move the _create_temporary_directory() call inside the
# following try statement, otherwise the user will always see a
# PythonDialogOSError instead of an
# UnableToCreateTemporaryDirectory because whenever
# UnableToCreateTemporaryDirectory is raised, the subsequent
# os.rmdir(tmp_dir) is bound to fail.
try:
fName = os.path.join(tmp_dir, "text")
# No race condition as with the deprecated tempfile.mktemp()
# since tmp_dir is not world-writable.
f = open(fName, "wb")
f.write(text)
f.close()
# Ask for an empty title unless otherwise specified
if not "title" in kwargs.keys():
kwargs["title"] = ""
return self._perform(
*(["--textbox", fName, str(height), str(width)],),
**kwargs)[0]
finally:
if type(f) == types.FileType:
f.close() # Safe, even several times
os.unlink(fName)
os.rmdir(tmp_dir)
except os.error, v:
raise PythonDialogOSError(v.strerror)
except IOError, v:
raise PythonDialogIOError(v)
def tailbox(self, filename, height=20, width=60, **kwargs):
"""Display the contents of a file in a dialog box, as in "tail -f".
filename -- name of the file whose contents is to be
displayed in the box
height -- height of the box
width -- width of the box
Display the contents of the specified file, updating the
dialog box whenever the file grows, as with the "tail -f"
command.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--tailbox", filename, str(height), str(width)],),
**kwargs)[0]
# No tailboxbg widget, at least for now.
def textbox(self, filename, height=20, width=60, **kwargs):
"""Display the contents of a file in a dialog box.
filename -- name of the file whose contents is to be
displayed in the box
height -- height of the box
width -- width of the box
A text box lets you display the contents of a text file in a
dialog box. It is like a simple text file viewer. The user
can move through the file by using the UP/DOWN, PGUP/PGDN
and HOME/END keys available on most keyboards. If the lines
are too long to be displayed in the box, the LEFT/RIGHT keys
can be used to scroll the text region horizontally. For more
convenience, forward and backward searching functions are
also provided.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
# This is for backward compatibility... not that it is
# stupid, but I prefer explicit programming.
if not "title" in kwargs.keys():
kwargs["title"] = filename
return self._perform(
*(["--textbox", filename, str(height), str(width)],),
**kwargs)[0]
def timebox(self, text, height=3, width=30, hour=-1, minute=-1,
second=-1, **kwargs):
"""Display a time dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
hour -- inititial hour selected
minute -- inititial minute selected
second -- inititial second selected
A dialog is displayed which allows you to select hour, minute
and second. If the values for hour, minute or second are
negative (or not explicitely provided, as they default to
-1), the current time's corresponding values are used. You
can increment or decrement any of those using the left-, up-,
right- and down-arrows. Use tab or backtab to move between
windows.
Return a tuple of the form (code, time) where `code' is the
exit status (an integer) of the dialog-like program and
`time' is a list of the form [hour, minute, second] (where
`hour', `minute' and `second' are integers corresponding to
the time chosen by the user) if the box was closed with OK,
or None if it was closed with the Cancel button.
Notable exceptions:
- any exception raised by self._perform()
- PythonDialogReModuleError
- UnexpectedDialogOutput
"""
(code, output) = self._perform(
*(["--timebox", text, str(height), str(width),
str(hour), str(minute), str(second)],),
**kwargs)
if code == self.DIALOG_OK:
try:
mo = _timebox_time_rec.match(output)
if mo is None:
raise UnexpectedDialogOutput(
"the dialog-like program returned the following "
"unexpected time with the --timebox option: %s" % output)
time = map(int, mo.group("hour", "minute", "second"))
except re.error, v:
raise PythonDialogReModuleError(v)
else:
time = None
return (code, time)
def yesno(self, text, height=10, width=30, **kwargs):
"""Display a yes/no dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
A yes/no dialog box of size `height' rows by `width' columns
will be displayed. The string specified by `text' is
displayed inside the dialog box. If this string is too long
to fit in one line, it will be automatically divided into
multiple lines at appropriate places. The text string can
also contain the sub-string "\\n" or newline characters to
control line breaking explicitly. This dialog box is useful
for asking questions that require the user to answer either
yes or no. The dialog box has a Yes button and a No button,
in which the user can switch between by pressing the TAB
key.
Return the exit status (an integer) of the dialog-like
program.
Notable exceptions:
any exception raised by self._perform()
"""
return self._perform(
*(["--yesno", text, str(height), str(width)],),
**kwargs)[0]
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
import xml.sax
from Podcasts import PodcastsHandler
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class Europe1( Plugin ):
listeEmissionsRegEx = re.compile( "<td class=\"programme\">.+?<a href=\".+?>(.+?)</a>.+?podcasts/(.+?)\.xml", re.DOTALL )
listeFichiersRegEx = re.compile( 'media_url=([^"]*)".+?<!\[CDATA\[(.+?)\]\]>', re.DOTALL )
def __init__( self):
Plugin.__init__( self, "Europe1", "http://www.europe1.fr", 1 )
# On instancie la classe qui permet de charger les pages web
self.listeEmissions = {} # Clef = nom emission ; Valeur = lien fichier XML qui contient la liste des emissions
if os.path.exists( self.fichierCache ):
self.listeEmissions = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions..." )
# On remet a zero la liste des emissions
self.listeEmissions.clear()
# On recupere la page qui contient les emissions
for page in [ "http://www.europe1.fr/Radio/Podcasts/Semaine/", "http://www.europe1.fr/Radio/Podcasts/Samedi/", "http://www.europe1.fr/Radio/Podcasts/Dimanche/" ]:
pageEmissions = self.API.getPage( page )
# On extrait le nom des emissions et les liens des fichiers XML correspondants
resultats = re.findall( self.listeEmissionsRegEx, pageEmissions )
for res in resultats:
nom = res[ 0 ]
lien = "http://www.europe1.fr/podcasts/" + res[ 1 ] + ".xml"
self.listeEmissions[ nom ] = lien
self.sauvegarderCache( self.listeEmissions )
self.afficher( str( len( self.listeEmissions ) ) + " émissions concervées." )
def listerChaines( self ):
self.ajouterChaine(self.nom)
def listerEmissions( self, chaine ):
# On renvoit le resulat
liste = self.listeEmissions.keys()
liste.sort()
for emission in liste:
self.ajouterEmission(chaine, emission)
def listerFichiers( self, emission ):
if( emission != "" ):
if( emission in self.listeEmissions ):
# On recupere le lien de la page de l'emission
lienPage = self.listeEmissions[ emission ]
# On recupere la page de l'emission
page = self.API.getPage( lienPage )
# On extrait les fichiers
listeFichiers = []
handler = PodcastsHandler( listeFichiers )
try:
xml.sax.parseString( page, handler )
except:
return
# On ajoute les fichiers
for fichier in listeFichiers:
self.ajouterFichier( emission, fichier )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
# Coucou les amis
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import xml.sax
from xml.sax.handler import ContentHandler
import urllib
import unicodedata
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class Podcasts( Plugin ):
listePodcasts = { "Allo Cine" : { "Bandes Annonces" : "http://rss.allocine.fr/bandesannonces/ipod" },
"Casse Croute" : { "Recettes" : "http://www.casse-croute.fr/media/cassecroute.xml" },
"Game One" : { u"E-NEWS JEUX VIDEO" : "http://podcast13.streamakaci.com/xml/GAMEONE2.xml",
u"NEWS DU JT" : "http://podcast13.streamakaci.com/xml/GAMEONE6.xml",
u"LE TEST" : "http://podcast13.streamakaci.com/xml/GAMEONE3.xml",
u"PLAY HIT" : "http://podcast13.streamakaci.com/xml/GAMEONE9.xml",
u"RETRO GAME ONE" : "http://podcast13.streamakaci.com/xml/GAMEONE11.xml",
u"Funky Web" : "http://podcast13.streamakaci.com/xml/GAMEONE26.xml"
},
"No Watch" : { u"CINEFUZZ" : "http://feeds.feedburner.com/CineFuzz?format=xml",
u"GEEK Inc (SD)" : "http://feeds.feedburner.com/GeekInc?format=xml",
u"GEEk Inc (HD)" : "http://feeds.feedburner.com/GeekIncHD?format=xml",
u"S.C.U.D.S tv (SD)" : "http://feeds2.feedburner.com/scudstv?format=xml",
u"S.C.U.D.S tv (HD)" : "http://feeds2.feedburner.com/scudshd?format=xml",
u"Tonight On Mars (SD)" : "http://feeds2.feedburner.com/tonightonmars?format=xml",
u"Zapcast tv (SD)" : "http://feeds.feedburner.com/Zapcasttv?format=xml",
u"Zapcast tv (HD)" : "http://feeds.feedburner.com/Zapcasthd?format=xml"},
"i>TELE" : { "Le Journal" : "http://podcast12.streamakaci.com/iTELE/iTELElejournal.xml" },
"RMC" : { u"Bourdin & CO" : "http://podcast.rmc.fr/channel30/RMCInfochannel30.xml",
u"Coach Courbis" : "http://podcast.rmc.fr/channel33/RMCInfochannel33.xml",
u"De quoi je me mail" : "http://podcast.rmc.fr/channel35/RMCInfochannel35.xml",
u"Intégrale Foot Made in Di Meco" : "http://podcast.rmc.fr/channel192/RMCInfochannel192.xml",
u"JO Live du jour" : "http://podcast.rmc.fr/channel196/RMCInfochannel196.xml",
u"L'Afterfoot" : "http://podcast.rmc.fr/channel59/RMCInfochannel59.xml",
u"Lahaie, l'amour et vous" : "http://podcast.rmc.fr/channel51/RMCInfochannel51.xml",
u"La politique " : "http://podcast.rmc.fr/channel179/RMCInfochannel179.xml",
u"La quotidienne courses hippiques" : "http://podcast.rmc.fr/channel197/RMCInfochannel197.xml",
u"Larqué Foot" : "http://podcast.rmc.fr/channel53/RMCInfochannel53.xml",
u"Le Billet de Guimard" : "http://podcast.rmc.fr/channel210/RMCInfochannel210.xml",
u"L'économie" : "http://podcast.rmc.fr/channel178/RMCInfochannel178.xml",
u"Le Débat du jour" : "http://podcast.rmc.fr/channel211/RMCInfochannel211.xml",
u"Le Journal du jour" : "http://podcast.rmc.fr/channel39/RMCInfochannel39.xml",
u"Le Mercato Show" : "http://podcast.rmc.fr/channel213/RMCInfochannel213.xml",
u"Le Monde Hi-Tech" : "http://podcast.rmc.fr/channel31/RMCInfochannel31.xml",
u"Les courses RMC" : "http://podcast.rmc.fr/channel193/RMCInfochannel193.xml",
u"Les Experts F1" : "http://podcast.rmc.fr/channel191/RMCInfochannel191.xml",
u"Les GG et vous" : "http://podcast.rmc.fr/channel181/RMCInfochannel181.xml",
u"Les Grandes Gueules" : "http://podcast.rmc.fr/channel36/RMCInfochannel36.xml",
u"Les Paris RMC du samedi" : "http://podcast.rmc.fr/channel160/RMCInfochannel160.xml",
u"Le Top de l'After Foot" : "http://podcast.rmc.fr/channel174/RMCInfochannel174.xml",
u"Le top de Sportisimon" : "http://podcast.rmc.fr/channel188/RMCInfochannel188.xml",
u"Le Top rugby " : "http://podcast.rmc.fr/channel176/RMCInfochannel176.xml",
u"Le Tour du jour" : "http://podcast.rmc.fr/channel209/RMCInfochannel209.xml",
u"L'invité de Bourdin & Co" : "http://podcast.rmc.fr/channel38/RMCInfochannel38.xml",
u"L'invité de Captain Larqué" : "http://podcast.rmc.fr/channel175/RMCInfochannel175.xml",
u"L'invité de Luis" : "http://podcast.rmc.fr/channel170/RMCInfochannel170.xml",
u"Love conseil " : "http://podcast.rmc.fr/channel183/RMCInfochannel183.xml",
u"Luis Attaque" : "http://podcast.rmc.fr/channel40/RMCInfochannel40.xml",
u"Moscato Show" : "http://podcast.rmc.fr/channel131/RMCInfochannel131.xml",
u"Moscato Show " : "http://podcast.rmc.fr/channel190/RMCInfochannel190.xml",
u"Motors" : "http://podcast.rmc.fr/channel42/RMCInfochannel42.xml",
u"RMC première Le 5/7" : "http://podcast.rmc.fr/channel32/RMCInfochannel32.xml",
u"RMC Sport matin" : "http://podcast.rmc.fr/channel77/RMCInfochannel77.xml",
u"Sportisimon" : "http://podcast.rmc.fr/channel186/RMCInfochannel186.xml",
u"Vos Animaux" : "http://podcast.rmc.fr/channel48/RMCInfochannel48.xml",
u"Votre Auto" : "http://podcast.rmc.fr/channel50/RMCInfochannel50.xml",
u"Votre Jardin" : "http://podcast.rmc.fr/channel52/RMCInfochannel52.xml",
u"Votre Maison" : "http://podcast.rmc.fr/channel54/RMCInfochannel54.xml"
},
"RTL" : { u"Grosse Tetes" : "http://www.rtl.fr/podcast/les-grosses-tetes.xml",
u"Laurent Gerra" :
"http://www.rtl.fr/podcast/laurent-gerra.xml",
u"A la bonne heure" :
"http://www.rtl.fr/podcast/a-la-bonne-heure.xml",
u"l heure du crime" :
"http://www.rtl.fr/podcast/l-heure-du-crime.xml",
u"l invite de rtl" :
"http://www.rtl.fr/podcast/linvite-de-rtl.xml",
u"z comme zemmour" :
"http://www.rtl.fr/podcast/z-comme-zemmour.xml",
u"Ca peut vous arriver" :
"http://www.rtl.fr/podcast/ca-peut-vous-arriver.xml",
u"le club liza.xml" :
"http://www.rtl.fr/podcast/le-club-liza.xml",
u"face a face aphatie duhamel en video" :
"http://www.rtl.fr/podcast/face-a-face-aphatie-duhamel-en-video.xml.xml",
u"La marque du mailhot" :
"http://www.rtl.fr/podcast/la-marque-du-mailhot.xml",
u"Le choix de yves calvi" :
"http://www.rtl.fr/podcast/le-choix-de-yves-calvi.xml",
u"Le choix de yves calvi en video" :
"http://www.rtl.fr/podcast/le-choix-de-yves-calvi-en-video.xml",
u"le grand jury" :
"http://www.rtl.fr/podcast/le-grand-jury.xml",
u"le journal inattendu" :
"http://www.rtl.fr/podcast/le-journal-inattendu.xml",
u"le fait politique" :
"http://www.rtl.fr/podcast/le-fait-politique.xml",
u"on est fait pour s entendre" :
"http://www.rtl.fr/podcast/on-est-fait-pour-s-entendre.xml",
u"a-la-bonne-heure didier porte" :
"http://www.rtl.fr/podcast/a-la-bonne-heure-didier-porte.xml",
u"on refait le match - Christophe Pacaud" :
"http://www.rtl.fr/podcast/on-refait-le-match-avec-christophe-pacaud.xml",
u"on refait le match - Eugene Saccomano" :
"http://www.rtl.fr/podcast/on-refait-le-match-avec-eugene-saccomano.xml",
u"a-la-bonne-heure Eric Naulleau" :
"http://www.rtl.fr/podcast/a-la-bonne-heure-eric-naulleau.xml",
u"a-la-bonne-heure Eric Naulleau en video" :
"http://www.rtl.fr/podcast/a-la-bonne-heure-eric-naulleau-en-video.xml",
}
}
derniereChaine = ""
listeFichiers = []
def __init__( self):
Plugin.__init__( self, "Podcasts", "", 30 )
def rafraichir( self ):
pass # Rien a rafraichir ici...
def listerChaines( self ):
listeChaines = self.listePodcasts.keys()
listeChaines.sort()
for chaine in listeChaines:
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listePodcasts.has_key( chaine ) ):
self.derniereChaine = chaine
listeEmissions = self.listePodcasts[ chaine ].keys()
listeEmissions.sort()
for emission in listeEmissions:
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listePodcasts.has_key( self.derniereChaine ) ):
listeEmission = self.listePodcasts[ self.derniereChaine ]
if( listeEmission.has_key( emission ) ):
# On remet a 0 la liste des fichiers
del self.listeFichiers[ : ]
# On recupere la page de l'emission
page = urllib.urlopen( listeEmission[ emission ] )
page = page.read()
#~ page = self.API.getPage( listeEmission[ emission ] )
# Handler
handler = PodcastsHandler( self.listeFichiers )
# On parse le fichier xml
xml.sax.parseString( page, handler )
# On ajoute les fichiers
for fichier in self.listeFichiers:
self.ajouterFichier( emission, fichier )
#
# Parser XML pour les podcasts
#
## Classe qui permet de lire les fichiers XML de podcasts
class PodcastsHandler( ContentHandler ):
# Constructeur
# @param listeFichiers Liste des fichiers que le parser va remplir
def __init__( self, listeFichiers ):
# Liste des fichiers
self.listeFichiers = listeFichiers
# Url de l'image globale
self.urlImageGlobale = ""
# Initialisation des variables a Faux
self.isItem = False
self.isTitle = False
self.isDescription = False
self.isPubDate = False
self.isGuid = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "item" ):
self.isItem = True
self.titre = ""
self.date = ""
self.urlFichier = ""
self.urlImage = ""
self.description = ""
elif( name == "title" and self.isItem ):
self.isTitle = True
elif( name == "description" and self.isItem ):
self.isDescription = True
elif( name == "pubDate" and self.isItem ):
self.isPubDate = True
elif( name == "media:thumbnail" and self.isItem ):
self.urlImage = attrs.get( "url", "" )
elif( name == "media:content" and self.isItem ):
self.urlFichier = attrs.get( "url", "" )
elif( name == "guid" and self.isItem ):
self.isGuid = True
elif( name == "itunes:image" and not self.isItem ):
self.urlImageGlobale = attrs.get( "href", "" )
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
if( self.isTitle ):
self.titre += data
#~ self.isTitle = False
elif( self.isDescription ):
if( data.find( "<" ) == -1 ):
self.description += data
else:
self.isDescription = False
elif( self.isPubDate ):
self.date = data
self.isPubDate = False
elif( self.isGuid ):
self.urlFichier = data
self.isGuid = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "item" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( self.urlFichier )
# Si le fichier n'a pas d'image, on prend l'image globale
if( self.urlImage == "" ):
self.urlImage = self.urlImageGlobale
# On ajoute le fichier
self.listeFichiers.append( Fichier ( self.titre, self.date, self.urlFichier, self.titre + extension, self.urlImage, self.description ) )
self.isTitle = False
elif( name == "description" ):
self.isDescription = False
elif( name == "title" ):
self.isTitle = False
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
from Plugin import Plugin
from Fichier import Fichier
from urllib import quote
import re,unicodedata,datetime
##########
# Classe #
##########
class Pluzz( Plugin ):
"""Classe abstraite Plugin dont doit heriter chacun des plugins"""
listeChainesEmissionsUrl = "http://www.pluzz.fr/appftv/webservices/video/catchup/getListeAutocompletion.php?support=1"
listeChainesEmissionsPattern = re.compile("chaine_principale=\"(.*?)\".*?.\[CDATA\[(.*?)\]\]")
lienEmissionBaseUrl = "http://www.pluzz.fr/"
videoInfosBaseUrl = "http://www.pluzz.fr/appftv/webservices/video/getInfosVideo.php?src=cappuccino&video-type=simple&template=ftvi&template-format=complet&id-externe="
videoTitrePattern = re.compile("titre.public><.\[CDATA\[(.*?)]]>", re.DOTALL)
videoNomPattern = re.compile("nom><.\[CDATA\[(.*?)]]>", re.DOTALL)
videoCheminPattern = re.compile("chemin><!\[CDATA\[(.*?)]]>", re.DOTALL)
videoDatePattern = re.compile("date><!\[CDATA\[(.*?)]]>", re.DOTALL)
def __init__( self):
Plugin.__init__( self, "Pluzz", "http://www.pluzz.fr/")
cache = self.chargerCache()
if cache:
self.listeChaines = cache
else:
self.listeChaines = {}
def listerOptions(self):
self.optionBouleen("france2", "Afficher France 2", True)
t = []
if self.listeChaines.has_key("france2"):
t = self.listeChaines["france2"]
t.sort()
self.optionChoixMultiple("emissionsfrance2", "Liste des émissions à afficher pour France 2", t, t)
self.optionBouleen("france3", "Afficher France 3", True)
t = []
if self.listeChaines.has_key("france3"):
t = self.listeChaines["france3"]
t.sort()
self.optionChoixMultiple("emissionsfrance3", "Liste des émissions à afficher pour France 3", t, t)
self.optionBouleen("france4", "Afficher France 4", True)
t = []
if self.listeChaines.has_key("france4"):
t = self.listeChaines["france4"]
t.sort()
self.optionChoixMultiple("emissionsfrance4", "Liste des émissions à afficher pour France 4", t, t)
self.optionBouleen("france5", "Afficher France 5", True)
t = []
if self.listeChaines.has_key("france5"):
t = self.listeChaines["france5"]
t.sort()
self.optionChoixMultiple("emissionsfrance2", "Liste des émissions à afficher pour France 5", t, t)
self.optionBouleen("franceo", "Afficher France O", True)
t = []
if self.listeChaines.has_key("franceo"):
t = self.listeChaines["franceo"]
t.sort()
self.optionChoixMultiple("emissionsfranceo", "Liste des émissions à afficher pour France O", t, t)
def rafraichir( self ):
self.listeChaines = {}
self.afficher("Récupération de la liste des émissions...")
for item in re.findall(self.listeChainesEmissionsPattern, self.API.getPage(self.listeChainesEmissionsUrl)):
if not(self.listeChaines.has_key(item[0])):
self.listeChaines[item[0]] = []
self.listeChaines[item[0]].append(item[1])
self.sauvegarderCache(self.listeChaines)
def getLienEmission(self, emission):
s = re.sub("[,: !/'\.]+", "-", emission).replace( ',', '' ).lower()
s = unicode( s, "utf8", "replace" )
s = unicodedata.normalize( 'NFD',s )
#~ return self.lienEmissionBaseUrl+unicodedata.normalize( 'NFD', s).encode( 'ascii','ignore' )+".html"
return self.lienEmissionBaseUrl+quote(s.encode( 'ascii','ignore' ))+".html"
def listerChaines( self ):
t = self.listeChaines.keys()
t.sort()
for chaine in t:
if self.getOption(chaine) == True:
self.ajouterChaine(chaine)
def listerEmissions( self, chaine ):
#~ t = []
#~ if self.listeChaines.has_key(chaine):
#~ t = self.listeChaines[chaine]
#~ t.sort()
t = self.getOption("emissions"+chaine)
if not(t):
t = []
if self.listeChaines.has_key(chaine):
t = self.listeChaines[chaine]
t.sort()
for emission in t:
self.ajouterEmission(chaine, emission)
def listerFichiers( self, emission ):
lien = self.getLienEmission(emission)
base = lien.replace(".html", "")
self.afficher("Récupération de la liste des fichiers pour \""+emission+"\"...")
dejaVue = []
nombre = 0
videos = re.findall("("+base+".+?.html)", self.API.getPage(lien));
if videos == None:
return
videos.append(lien)
for fichier in videos:
fichierInfosUrl_match = re.search(re.compile("info.francetelevisions.fr/\?id-video=(.+?)\"", re.DOTALL), self.API.getPage(fichier))
if fichierInfosUrl_match == None:
continue
fichierInfos = self.API.getPage(self.videoInfosBaseUrl+fichierInfosUrl_match.group(1))
titre = re.search(self.videoTitrePattern, fichierInfos)
if titre != None:
titre = titre.group(1)
else:
continue
nom = re.search(self.videoNomPattern, fichierInfos)
if nom != None:
nom = nom.group(1)
else:
continue
chemin = re.search(self.videoCheminPattern, fichierInfos)
if chemin != None:
chemin = chemin.group(1)
else:
continue
date = re.search(self.videoDatePattern, fichierInfos)
if date != None:
date = datetime.date.fromtimestamp(int(date.group(1))).strftime("%d/%m/%Y")
else:
continue
if titre in dejaVue:
continue
else:
dejaVue.append(titre)
lien = None
if( chemin.find( 'http' ) != -1 ):
lien = chemin + titre
elif( nom.find( 'wmv' ) != -1 ):
lien = "mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication" + chemin + nom
elif( nom.find( 'mp4' ) != -1 ):
lien = "rtmp://videozones-rtmp.francetv.fr/ondemand/mp4:cappuccino/publication" + chemin + nom
if not(lien):
continue
self.ajouterFichier(emission, Fichier( titre, date, lien ) )
nombre = nombre+1
self.afficher(str(nombre)+" fichiers trouvés.")
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
from Fichier import Fichier
from Plugin import Plugin
##########
# Classe #
##########
class RadioFrance( Plugin ):
listeFichiersRegEx = re.compile( '<description>([^<]+?)</description>.+?podcast09/([^"]*\.mp3)"', re.DOTALL )
listeEmissionsFranceInter = { u"Allo la planète" : "http://radiofrance-podcast.net/podcast09/rss_10121.xml",
u"Au detour du monde" : "http://radiofrance-podcast.net/podcast09/rss_10039.xml",
u"Bons baisers de Manault" : "http://radiofrance-podcast.net/podcast09/rss_11160.xml",
u"Carnet de campagne" : "http://radiofrance-podcast.net/podcast09/rss_10205.xml",
u"carrefour de l'Eco" : "http://radiofrance-podcast.net/podcast09/rss_11292.xml",
u"C'est demain la veille" : "http://radiofrance-podcast.net/podcast09/rss_11264.xml",
u"CO2 mon Amour" : "http://radiofrance-podcast.net/podcast09/rss_10006.xml",
u"Comme on nous parle" : "http://radiofrance-podcast.net/podcast09/rss_11242.xml",
u"Daniel Morin" : "http://radiofrance-podcast.net/podcast09/rss_10906.xml",
u"Didier Porte" : "http://radiofrance-podcast.net/podcast09/rss_10907.xml",
u"ECLECTIK (dimanche)" : "http://radiofrance-podcast.net/podcast09/rss_10946.xml",
u"Eclectik (samedi)" : "http://radiofrance-podcast.net/podcast09/rss_17621.xml",
u"Esprit critique" : "http://radiofrance-podcast.net/podcast09/rss_10240.xml",
u"Et pourtant elle tourne" : "http://radiofrance-podcast.net/podcast09/rss_10269.xml",
u"Histoire de..." : "http://radiofrance-podcast.net/podcast09/rss_10919.xml",
u"LA BAS, SI J'Y SUIS" : "http://radiofrance-podcast.net/podcast09/rss_14288.xml",
u"La cellule de dégrisement" : "http://radiofrance-podcast.net/podcast09/rss_11259.xml",
u"la chronique anglaise de David LOWE" : "http://radiofrance-podcast.net/podcast09/rss_11345.xml",
u"La chronique de régis Mailhot" : "http://radiofrance-podcast.net/podcast09/rss_11335.xml",
u"La chronique de Vincent Roca" : "http://radiofrance-podcast.net/podcast09/rss_11336.xml",
u"La librairie francophone" : "http://radiofrance-podcast.net/podcast09/rss_18647.xml",
u"La nuit comme si" : "http://radiofrance-podcast.net/podcast09/rss_11254.xml",
u"La presse étrangère" : "http://radiofrance-podcast.net/podcast09/rss_11331.xml",
u"Le Cinq Six Trente" : "http://radiofrance-podcast.net/podcast09/rss_10915.xml",
u"L'économie autrement" : "http://radiofrance-podcast.net/podcast09/rss_11081.xml",
u"Le débat économique" : "http://radiofrance-podcast.net/podcast09/rss_18783.xml",
u"Le jeu des mille euros" : "http://radiofrance-podcast.net/podcast09/rss_10206.xml",
u"Le journal de l'économie" : "http://radiofrance-podcast.net/podcast09/rss_10980.xml",
u"le sept neuf du dimanche" : "http://radiofrance-podcast.net/podcast09/rss_10982.xml",
u"le sept neuf du samedi" : "http://radiofrance-podcast.net/podcast09/rss_10981.xml",
u"Les grandes nuits et les petits ..." : "http://radiofrance-podcast.net/podcast09/rss_11257.xml",
u"Les savanturiers" : "http://radiofrance-podcast.net/podcast09/rss_10908.xml",
u"Le Zapping de France Inter" : "http://radiofrance-podcast.net/podcast09/rss_10309.xml",
u"L'humeur de Didier Porte" : "http://radiofrance-podcast.net/podcast09/rss_11078.xml",
u"L'humeur de François Morel" : "http://radiofrance-podcast.net/podcast09/rss_11079.xml",
u"L'humeur de Stéphane Guillon" : "http://radiofrance-podcast.net/podcast09/rss_10692.xml",
u"L'humeur vagabonde" : "http://radiofrance-podcast.net/podcast09/rss_10054.xml",
u"Noctiluque" : "http://radiofrance-podcast.net/podcast09/rss_10208.xml",
u"Nocturne" : "http://radiofrance-podcast.net/podcast09/rss_10268.xml",
u"Nonobstant" : "http://radiofrance-podcast.net/podcast09/rss_10615.xml",
u"Nous autres" : "http://radiofrance-podcast.net/podcast09/rss_18633.xml",
u"Panique au Mangin palace" : "http://radiofrance-podcast.net/podcast09/rss_10128.xml",
u"panique au ministère psychique" : "http://radiofrance-podcast.net/podcast09/rss_10905.xml",
u"Parking de nuit" : "http://radiofrance-podcast.net/podcast09/rss_10136.xml",
u"Périphéries" : "http://radiofrance-podcast.net/podcast09/rss_10040.xml",
u"Service public" : "http://radiofrance-podcast.net/podcast09/rss_10207.xml",
u"Sous les étoiles exactement" : "http://radiofrance-podcast.net/podcast09/rss_10218.xml",
u"Studio théatre" : "http://radiofrance-podcast.net/podcast09/rss_10629.xml",
u"Système disque" : "http://radiofrance-podcast.net/podcast09/rss_10093.xml",
u"Un jour sur la toile" : "http://radiofrance-podcast.net/podcast09/rss_10274.xml",
u"Un livre sous le bras" : "http://radiofrance-podcast.net/podcast09/rss_10664.xml" }
listeEmissionsFranceInfo = { u"Il était une mauvaise foi" : "http://radiofrance-podcast.net/podcast09/rss_10951.xml",
u"La vie et vous, Le chemin de l'école" : "http://radiofrance-podcast.net/podcast09/rss_11077.xml",
u"Le bruit du net" : "http://radiofrance-podcast.net/podcast09/rss_11064.xml",
u"Le droit d'info" : "http://radiofrance-podcast.net/podcast09/rss_10986.xml",
u"Le sens de l'info" : "http://radiofrance-podcast.net/podcast09/rss_10586.xml",
u"Question d'argent" : "http://radiofrance-podcast.net/podcast09/rss_10556.xml",
u"Tout comprendre" : "http://radiofrance-podcast.net/podcast09/rss_11313.xml",
u"Tout et son contraire" : "http://radiofrance-podcast.net/podcast09/rss_11171.xml" }
listeEmissionsFranceBleu = { u"1999" : "http://radiofrance-podcast.net/podcast09/rss_11325.xml",
u"C'est bon à savoir" : "http://radiofrance-podcast.net/podcast09/rss_10337.xml",
u"Chanson d'Aqui" : "http://radiofrance-podcast.net/podcast09/rss_11298.xml",
u"Club Foot Marseille" : "http://radiofrance-podcast.net/podcast09/rss_11201.xml",
u"Côté Mer" : "http://radiofrance-podcast.net/podcast09/rss_10890.xml",
u"France Bleu Midi " : "http://radiofrance-podcast.net/podcast09/rss_11204.xml",
u"Histoire en Bretagne" : "http://radiofrance-podcast.net/podcast09/rss_10638.xml",
u"La science en question" : "http://radiofrance-podcast.net/podcast09/rss_10336.xml",
u"Les défis du Professeur Gersal" : "http://radiofrance-podcast.net/podcast09/rss_11263.xml",
u"Les Français parlent aux Français" : "http://radiofrance-podcast.net/podcast09/rss_11351.xml",
u"Les nouvelles archives de l étrange" : "http://radiofrance-podcast.net/podcast09/rss_11265.xml",
u"L'horoscope" : "http://radiofrance-podcast.net/podcast09/rss_10020.xml",
u"L'humeur de Fred Ballard" : "http://radiofrance-podcast.net/podcast09/rss_11317.xml",
u"Ligne d'expert" : "http://radiofrance-podcast.net/podcast09/rss_11023.xml",
u"On repeint la musique" : "http://radiofrance-podcast.net/podcast09/rss_11268.xml",
u"Planète Bleu" : "http://radiofrance-podcast.net/podcast09/rss_11031.xml",
u"Sul gouel ha bembez..." : "http://radiofrance-podcast.net/podcast09/rss_10312.xml",
u"Tour de France 2010" : "http://radiofrance-podcast.net/podcast09/rss_11355.xml" }
listeEmissionsFranceCulture = { u"Affinités électives" : "http://radiofrance-podcast.net/podcast09/rss_10346.xml",
u"A plus d'un titre" : "http://radiofrance-podcast.net/podcast09/rss_10466.xml",
u"avec ou sans rdv" : "http://radiofrance-podcast.net/podcast09/rss_10180.xml",
u"A voix nue" : "http://radiofrance-podcast.net/podcast09/rss_10351.xml",
u"Ca rime à quoi" : "http://radiofrance-podcast.net/podcast09/rss_10897.xml",
u"Carnet Nomade" : "http://radiofrance-podcast.net/podcast09/rss_10237.xml",
u"Caroline FOUREST" : "http://radiofrance-podcast.net/podcast09/rss_10725.xml",
u"Chanson boum" : "http://radiofrance-podcast.net/podcast09/rss_10975.xml",
u"Chronique de Caroline Eliacheff" : "http://radiofrance-podcast.net/podcast09/rss_10477.xml",
u"Chronique de Cécile Ladjali" : "http://radiofrance-podcast.net/podcast09/rss_11270.xml",
u"Chronique de Clémentine Autain" : "http://radiofrance-podcast.net/podcast09/rss_10714.xml",
u"CONCORDANCE DES TEMPS" : "http://radiofrance-podcast.net/podcast09/rss_16278.xml",
u"Conférences de Michel Onfray" : "http://radiofrance-podcast.net/podcast09/rss_11141.xml",
u"Continent sciences" : "http://radiofrance-podcast.net/podcast09/rss_16256.xml",
u"Controverses du progrès (les)" : "http://radiofrance-podcast.net/podcast09/rss_11055.xml",
u"Cultures D'Islam" : "http://radiofrance-podcast.net/podcast09/rss_10073.xml",
u"Des histoires à ma façon" : "http://radiofrance-podcast.net/podcast09/rss_11181.xml",
u"Des papous dans la tête" : "http://radiofrance-podcast.net/podcast09/rss_13364.xml",
u"Divers aspects de la pensée (...)" : "http://radiofrance-podcast.net/podcast09/rss_10344.xml",
u"Du grain à moudre" : "http://radiofrance-podcast.net/podcast09/rss_10175.xml",
u"Du jour au Lendemain" : "http://radiofrance-podcast.net/podcast09/rss_10080.xml",
u"En toute franchise" : "http://radiofrance-podcast.net/podcast09/rss_10898.xml",
u"'EPOPEE DE LA FRANCE LIBRE" : "http://radiofrance-podcast.net/podcast09/rss_11365.xml",
u"Foi et tradition" : "http://radiofrance-podcast.net/podcast09/rss_10492.xml",
u"For interieur" : "http://radiofrance-podcast.net/podcast09/rss_10266.xml",
u"HORS" : "http://radiofrance-podcast.net/podcast09/rss_11189.xml",
u"Jeux d'épreuves" : "http://radiofrance-podcast.net/podcast09/rss_10083.xml",
u"La chronique d'Alexandre Adler" : "http://radiofrance-podcast.net/podcast09/rss_18810.xml",
u"La chronique de d'Alain" : "http://radiofrance-podcast.net/podcast09/rss_18809.xml",
u"La chronique d'Olivier Duhamel" : "http://radiofrance-podcast.net/podcast09/rss_18811.xml",
u"LA FABRIQUE DE L'HUMAIN" : "http://radiofrance-podcast.net/podcast09/rss_11188.xml",
u"LA MARCHE DES SCIENCES" : "http://radiofrance-podcast.net/podcast09/rss_11193.xml",
u"La messe" : "http://radiofrance-podcast.net/podcast09/rss_10272.xml",
u"La nelle fabrique de l'histoire" : "http://radiofrance-podcast.net/podcast09/rss_10076.xml",
u"La rumeur du monde" : "http://radiofrance-podcast.net/podcast09/rss_10234.xml",
u"LA SUITE DANS LES IDEES" : "http://radiofrance-podcast.net/podcast09/rss_16260.xml",
u"L'ATELIER LITTERAIRE" : "http://radiofrance-podcast.net/podcast09/rss_11185.xml",
u"LA VIGNETTE" : "http://radiofrance-podcast.net/podcast09/rss_11199.xml",
u"Le bien commun" : "http://radiofrance-podcast.net/podcast09/rss_16279.xml",
u"L'économie en question o" : "http://radiofrance-podcast.net/podcast09/rss_10081.xml",
u"Le journal de 12h30" : "http://radiofrance-podcast.net/podcast09/rss_10059.xml",
u"Le journal de 18h" : "http://radiofrance-podcast.net/podcast09/rss_10060.xml",
u"Le journal de 22h" : "http://radiofrance-podcast.net/podcast09/rss_10061.xml",
u"Le journal de 7h" : "http://radiofrance-podcast.net/podcast09/rss_10055.xml",
u"Le journal de 8h" : "http://radiofrance-podcast.net/podcast09/rss_10057.xml",
u"Le magazine de la rédaction" : "http://radiofrance-podcast.net/podcast09/rss_10084.xml",
u"LE MARDI DES AUTEURS" : "http://radiofrance-podcast.net/podcast09/rss_11194.xml",
u"Le portrait du jour par Marc Krav" : "http://radiofrance-podcast.net/podcast09/rss_18812.xml",
u"Le regard d'Albert Jacquard" : "http://radiofrance-podcast.net/podcast09/rss_16496.xml",
u"Le rendez" : "http://radiofrance-podcast.net/podcast09/rss_10082.xml",
u"Le salon noir" : "http://radiofrance-podcast.net/podcast09/rss_10267.xml",
u"Les ateliers de création radio." : "http://radiofrance-podcast.net/podcast09/rss_10185.xml",
u"Les enjeux internationaux" : "http://radiofrance-podcast.net/podcast09/rss_13305.xml",
u"LES JEUDIS DE L'EXPO" : "http://radiofrance-podcast.net/podcast09/rss_11196.xml",
u"Les lundis de l'histoire" : "http://radiofrance-podcast.net/podcast09/rss_10193.xml",
u"Les matins de France Culture" : "http://radiofrance-podcast.net/podcast09/rss_10075.xml",
u"LES MERCREDIS DU THEATRE" : "http://radiofrance-podcast.net/podcast09/rss_11195.xml",
u"Les nv chemins de la connaissance" : "http://radiofrance-podcast.net/podcast09/rss_10467.xml",
u"LES PASSAGERS DE LA NUIT" : "http://radiofrance-podcast.net/podcast09/rss_11190.xml",
u"Les Pieds sur Terre" : "http://radiofrance-podcast.net/podcast09/rss_10078.xml",
u"L'esprit public" : "http://radiofrance-podcast.net/podcast09/rss_16119.xml",
u"LES RACINES DU CIEL" : "http://radiofrance-podcast.net/podcast09/rss_11200.xml",
u"LES RETOURS DU DIMANCHE" : "http://radiofrance-podcast.net/podcast09/rss_11186.xml",
u"LES VENDREDIS DE LA MUSIQUE" : "http://radiofrance-podcast.net/podcast09/rss_11197.xml",
u"L'oeil du larynx" : "http://radiofrance-podcast.net/podcast09/rss_10311.xml",
u"MACADAM PHILO" : "http://radiofrance-podcast.net/podcast09/rss_11198.xml",
u"Maison d'études" : "http://radiofrance-podcast.net/podcast09/rss_10182.xml",
u"Masse critique" : "http://radiofrance-podcast.net/podcast09/rss_10183.xml",
u"Mauvais Genres" : "http://radiofrance-podcast.net/podcast09/rss_10070.xml",
u"MEGAHERTZ" : "http://radiofrance-podcast.net/podcast09/rss_11182.xml",
u"METROPOLITAINS" : "http://radiofrance-podcast.net/podcast09/rss_16255.xml",
u"Orthodoxie" : "http://radiofrance-podcast.net/podcast09/rss_10491.xml",
u"Place de la toile" : "http://radiofrance-podcast.net/podcast09/rss_10465.xml",
u"PLACE DES PEUPLES" : "http://radiofrance-podcast.net/podcast09/rss_11207.xml",
u"Planète terre" : "http://radiofrance-podcast.net/podcast09/rss_10233.xml",
u"POST FRONTIERE" : "http://radiofrance-podcast.net/podcast09/rss_11191.xml",
u"Projection privée" : "http://radiofrance-podcast.net/podcast09/rss_10198.xml",
u"Question d'éthique" : "http://radiofrance-podcast.net/podcast09/rss_10201.xml",
u"RADIO LIBRE" : "http://radiofrance-podcast.net/podcast09/rss_11183.xml",
u"Répliques" : "http://radiofrance-podcast.net/podcast09/rss_13397.xml",
u"Revue de presse internationale" : "http://radiofrance-podcast.net/podcast09/rss_10901.xml",
u"RUE DES ECOLES" : "http://radiofrance-podcast.net/podcast09/rss_11192.xml",
u"Science publique" : "http://radiofrance-podcast.net/podcast09/rss_10192.xml",
u"Service protestant" : "http://radiofrance-podcast.net/podcast09/rss_10297.xml",
u"Sur les docks" : "http://radiofrance-podcast.net/podcast09/rss_10177.xml",
u"Terre à terre" : "http://radiofrance-podcast.net/podcast09/rss_10867.xml",
u"TIRE TA LANGUE" : "http://radiofrance-podcast.net/podcast09/rss_11184.xml",
u"Tout arrive" : "http://radiofrance-podcast.net/podcast09/rss_10077.xml",
u"Tout un monde" : "http://radiofrance-podcast.net/podcast09/rss_10191.xml",
u"Vivre sa ville" : "http://radiofrance-podcast.net/podcast09/rss_10878.xml" }
listeEmissionsFranceMusique = { u"Histoire de..." : "http://radiofrance-podcast.net/podcast09/rss_10977.xml",
u"Le mot musical du jour" : "http://radiofrance-podcast.net/podcast09/rss_10976.xml",
u"Miniatures" : "http://radiofrance-podcast.net/podcast09/rss_10978.xml",
u"Sonnez les matines" : "http://radiofrance-podcast.net/podcast09/rss_10979.xml" }
listeEmissionsLeMouv = { u"Buzz de la semaine" : "http://radiofrance-podcast.net/podcast09/rss_10924.xml",
u"Cette année là" : "http://radiofrance-podcast.net/podcast09/rss_11280.xml",
u"Chez Francis" : "http://radiofrance-podcast.net/podcast09/rss_11285.xml",
u"Compression de Cartier" : "http://radiofrance-podcast.net/podcast09/rss_11279.xml",
u"Fausse Pub" : "http://radiofrance-podcast.net/podcast09/rss_11309.xml",
u"La BD de Philippe Audoin" : "http://radiofrance-podcast.net/podcast09/rss_11278.xml",
u"La minute culturelle de Cug et Westrou" : "http://radiofrance-podcast.net/podcast09/rss_10914.xml",
u"La minute numérique" : "http://radiofrance-podcast.net/podcast09/rss_11277.xml",
u"La mode de Samyjoe" : "http://radiofrance-podcast.net/podcast09/rss_11048.xml",
u"La Revue de Presse" : "http://radiofrance-podcast.net/podcast09/rss_11281.xml",
u"Le cinema de Jean Z" : "http://radiofrance-podcast.net/podcast09/rss_11045.xml",
u"Le Comedy Club Live" : "http://radiofrance-podcast.net/podcast09/rss_11314.xml",
u"Le meilleur du Mouv'" : "http://radiofrance-podcast.net/podcast09/rss_11274.xml",
u"L'Environnement" : "http://radiofrance-podcast.net/podcast09/rss_11041.xml",
u"Le pire de la semaine" : "http://radiofrance-podcast.net/podcast09/rss_11276.xml",
u"Le Reportage de la Redaction" : "http://radiofrance-podcast.net/podcast09/rss_11311.xml",
u"Les bons plans" : "http://radiofrance-podcast.net/podcast09/rss_11273.xml",
u"Les lectures de Clementine" : "http://radiofrance-podcast.net/podcast09/rss_11051.xml",
u"Les séries TV de Pierre Langlais" : "http://radiofrance-podcast.net/podcast09/rss_11288.xml",
u"Le Top 3 d'Emilie" : "http://radiofrance-podcast.net/podcast09/rss_11287.xml",
u"Le tour du Web" : "http://radiofrance-podcast.net/podcast09/rss_10926.xml",
u"L'invité du Mouv'" : "http://radiofrance-podcast.net/podcast09/rss_11330.xml",
u"L'invité matinal" : "http://radiofrance-podcast.net/podcast09/rss_11286.xml",
u"Revue de Web" : "http://radiofrance-podcast.net/podcast09/rss_11310.xml",
u"Un grand verre d'Orangeade" : "http://radiofrance-podcast.net/podcast09/rss_11282.xml",
u"Un tir dans la lucarne" : "http://radiofrance-podcast.net/podcast09/rss_11289.xml",
u"Zebra" : "http://radiofrance-podcast.net/podcast09/rss_11308.xml" }
listeEmissions = { "France Inter" : listeEmissionsFranceInter,
"France Info" : listeEmissionsFranceInfo,
"France Bleu" : listeEmissionsFranceBleu,
"France Culture" : listeEmissionsFranceCulture,
"France Musique" : listeEmissionsFranceMusique,
"Le Mouv'" : listeEmissionsLeMouv }
def __init__( self):
Plugin.__init__( self, "Radio France", "http://www.radiofrance.fr/", 30 )
def rafraichir( self ):
pass # Rien a rafraichir ici...
def listerChaines( self ):
liste = self.listeEmissions.keys()
liste.sort()
for chaine in liste:
self.ajouterChaine(chaine)
def listerEmissions( self, chaine ):
self.derniereChaine = chaine
liste = []
if( chaine != "" ):
liste = self.listeEmissions[ chaine ].keys()
liste.sort()
for emission in liste:
self.ajouterEmission(chaine, emission)
def listerFichiers( self, emission ):
if( emission != "" ):
if( emission in self.listeEmissions[ self.derniereChaine ] ):
# On recupere le lien de la page de l'emission
lienPage = self.listeEmissions[ self.derniereChaine ][ emission ]
# On recupere la page de l'emission
page = self.API.getPage( lienPage )
# On recupere le lien de l'image de l'emission
try :
urlImage = re.findall( '<itunes:image href="([^"]+?)"', page )[ 0 ]
except :
urlImage = ""
# On extrait les emissions
resultats = re.findall( self.listeFichiersRegEx, page )
for ( descriptif, fichier ) in resultats:
lien = "http://media.radiofrance-podcast.net/podcast09/" + fichier
listeDates = re.findall( "\d{2}\.\d{2}\.\d{2}", fichier )
if( listeDates == [] ): # Si on n'a pas pu extraire une date
date = "Inconnue"
else: # Si on a extrait une date
date = listeDates[ 0 ]
self.ajouterFichier(emission, Fichier( emission + " (" + date + ")", date, lien, urlImage = urlImage, descriptif = descriptif ) )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
from Plugin import Plugin
from Fichier import Fichier
from urllib import quote,unquote
import re,unicodedata
import time,rfc822 # for RFC822 datetime format (rss feed)
from datetime import datetime
from htmlentitydefs import name2codepoint
##########
# Classe #
##########
class Arte(Plugin):
##
## Arte Live Web
##
configArteLiveWeb = {
'nom' : "Arte Live Web",
'qualite' : ['SD', 'HD', 'Live'],
'regexEmissions' : {
'url' : "http://liveweb.arte.tv/",
# Attention à bien nommer les zones de recherche "lien" et "nom"
'pattern' : re.compile("<li><a href=\"http://liveweb.arte.tv/fr/cat/(?P<lien>.*?)\" class=\"accueil\">(?P<nom>.*?)</a></li>", re.DOTALL)
},
'regexListeFichiers' : {
0 : {
# %emission% représente l'émission à lister
'url' : "http://liveweb.arte.tv/fr/cat/%emission%",
'pattern' : re.compile("<a href=\"(http://download.liveweb.arte.tv/o21/liveweb/rss/home.*?\.rss)\"", re.DOTALL)
},
1 : {
# %pattern% représente le résultat de l'expression régulière précédente
'url' : "%pattern%",
# Expression régulière pour extraire les blocs descriptifs de chaque fichier
'pattern' : re.compile("(<item>.*?</item>)", re.DOTALL)
},
},
'regexInfosFichiers' : {
0 : {
# Premère regex, ne se base pas sur une URL mais sur les données extraites par regexListeFichiers
# Liste des informations à récupérer
'patterns' : {
'titre' : re.compile("<title>(.*?)</title>", re.DOTALL),
'lien' : re.compile("<link>(http://liveweb.arte.tv/fr/video/.*?)</link>", re.DOTALL),
'date' : re.compile("<pubDate>(.*?)</pubDate>", re.DOTALL),
'description' : re.compile("<description>(.*?)</description>", re.DOTALL),
#'eventid' : re.compile("<enclosure.*?/event/(.*?)/.*?/>", re.DOTALL),
'eventid' : re.compile("<enclosure.*?/event/.*?/(.*?)-.*?/>", re.DOTALL)
}
},
1 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "%lien%",
# optional = 1, cette étape n'est pas exécutée en mode TURBO
'optional' : 1,
# Liste des informations à récupérer
'patterns' : {
'eventid_html': re.compile("new LwEvent\('(.*?)', ''\);", re.DOTALL)
},
},
2 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "http://arte.vo.llnwd.net/o21/liveweb/events/event-%eventid%.xml",
# Liste des informations à récupérer
'patterns' : {
'titre' : re.compile("<nameFr>(.*?)</nameFr>", re.DOTALL),
'lien.HD': re.compile("<urlHd>(.*?)</urlHd>", re.DOTALL),
'lien.SD': re.compile("<urlSd>(.*?)</urlSd>", re.DOTALL),
'lien.Live': re.compile("<liveUrl>(.*?)</liveUrl>", re.DOTALL)
},
},
},
'infosFichier' : {
'nom' : "[%qualite%] %titre%",
'date' : "%date%",
'lien' : "%lien%",
#'nomFichierSortieStd' : "%lien%",
#'nomFichierSortieRen' : "%titre%",
#~ 'urlImage' : "http://download.liveweb.arte.tv/o21/liveweb/media/event/%eventid%/%eventid%-visual-cropcropcrop-small.jpg",
'urlImage' : "http://download.liveweb.arte.tv/o21/liveweb/media/event/%eventid%/%eventid%-visual.jpg",
'descriptif' : "%description%"
}
}
##
## Arte+7
##
# En cas de souci, on pourrait utiliser la page RSS de chaque chaine
# Pour récupérer la liste des chaines (càd la liste des flux RSS)
# http://videos.arte.tv/fr/videos/meta/index-3188674-3223978.html
# Pour récupérer la liste des émissions d'une chaine
# http://videos.arte.tv/fr/do_delegate/videos/programmes/360_geo/index-3188704,view,rss.xml
configArtePlusSept = {
'nom' : "Arte+7",
'qualite' : ['SD', 'HD'],
'regexEmissions' : {
'url' : "http://videos.arte.tv/fr/videos",
# Attention à bien nommer les zones de recherche "lien" et "nom"
'pattern' : re.compile("<input type=\"checkbox\" value=\"(?P<lien>.*?)\"/>.*?<a href=\"#\">(?P<nom>.*?)</a>", re.DOTALL)
},
'regexListeFichiers' : {
0 : {
# %emission% représente l'émission à lister
'url' : "http://videos.arte.tv/fr/do_delegate/videos/index-%emission%-3188698,view,asList.html?hash=fr/list/date//1/250/",
# Expression régulière pour extraire les blocs descriptifs de chaque vidéo
'pattern' : re.compile("(<tr.*?>.*?</tr>)", re.DOTALL)
},
},
'regexInfosFichiers' : {
0 : {
# Premère regex, ne se base pas sur une URL mais sur les données extraites par regexListeFichiers
# Liste des informations à récupérer
# Les expressions de type texte %xxx% sont remplacées par les options du plugin (choix arbitraire pour l'instant)
'patterns' : {
'titre' : re.compile("title=\"(.*?)\|\|", re.DOTALL),
'lien' : re.compile("<a href=\"/(fr/videos/.*?\.html)\">", re.DOTALL),
'date' : re.compile("<em>(.*?)</em>", re.DOTALL),
'description' : re.compile("\|\|(.*?)\">", re.DOTALL),
'guid' : re.compile("{ajaxUrl:'.*-(.*?).html", re.DOTALL),
'player_swf' : "%default_playerSWF%",
}
},
1 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "http://videos.arte.tv/%lien%",
# optional = 1, cette étape n'est pas exécutée en mode TURBO
'optional' : 1,
# Liste des informations à récupérer
'patterns' : {
'player_swf' : re.compile("<param name=\"movie\" value=\"(.*?\.swf)", re.DOTALL),
'titre' : re.compile("<div class=\"recentTracksMast\">.*?<h3>(.*?)</h3>.*?</div>", re.DOTALL),
'image' : re.compile("<link rel=\"image_src\" href=\"(.*?)\"/>", re.DOTALL),
'description' : re.compile("<div class=\"recentTracksCont\">.*?<div>(.*?)</div>", re.DOTALL),
'guid': re.compile("addToPlaylistOpen {ajaxUrl:'/fr/do_addToPlaylist/videos/.*?-(.*?)\.html'}", re.DOTALL)
},
},
2 : {
# Les variables %xxx% sont remplacées par les éléments déjà trouvés via les expressions précédentes
'url' : "http://videos.arte.tv/fr/do_delegate/videos/-%guid%,view,asPlayerXml.xml",
# Liste des informations à récupérer
'patterns' : {
'titre' : re.compile("<name>(.*?)</name>", re.DOTALL),
'date' : re.compile("<dateVideo>(.*?)</dateVideo>", re.DOTALL),
'image' : re.compile("<firstThumbnailUrl>(.*?)</firstThumbnailUrl>", re.DOTALL),
'lien.HD': re.compile("<url quality=\"hd\">(.*?)</url>", re.DOTALL),
'lien.SD': re.compile("<url quality=\"sd\">(.*?)</url>", re.DOTALL),
},
},
},
'infosFichier' : {
'nom' : "[%qualite%] %titre%",
'date' : "%date%",
'lien' : "%lien% -W %player_swf%",
#'nomFichierSortieStd' : "%lien%.mp4",
#'nomFichierSortieRen' : "%titre%",
'urlImage' : "%image%",
'descriptif' : "%description%"
}
}
##
## Options du plugin
##
listeOptions = {
0: {
# Qualité à rechercher SD ou HD ?
'type' : "ChoixUnique",
'nom' : "qualite",
'description' : "Qualité des vidéos",
'defaut' : "HD",
'valeurs' : ["HD", "SD","HD & SD"],
},
1: {
# Nombre maximum de fichiers à rechercher (0 = aucune limite)
'type' : "Texte",
'nom' : "max_files",
'description' : "Nombre d'enregistrements à analyser\n(0=pas de limite)",
'defaut' : "20",
},
2: {
# Renommer les fichiers à partir du titre de l'émission
'type' : "Bouleen",
'nom' : "rename_files",
'description' : "Renommer les fichiers à partir du titre de l'émission\nATTENTION : plusieurs enregistrements peuvent avoir le même nom",
'defaut' : False,
},
3: {
# Mode turbo : charge moins de pages, donc plus rapide, mais moins de détails
'type' : "Bouleen",
'nom' : "turbo_mode",
'description' : "Mode TURBO\nChargement plus rapide mais informations moins détaillées",
'defaut' : False,
},
4: {
# PlayerSWF par default pour Arte+7
'type' : "Texte",
'nom' : "default_playerSWF",
'description' : "Player Arte+7 à utiliser par défaut (en mode TURBO)\nATTENTION : Réservé aux utilisateurs avancés",
'defaut' : "http://videos.arte.tv/blob/web/i18n/view/player_11-3188338-data-4785094.swf",
}
}
nom = "Arte"
url = "http://www.arte.tv/"
listeChaines = {} # Clef = Nom Chaine, Valeur = { Nom emission : Lien }
# Supprime les caractères spéciaux HTML du tyle &#nn;
# http://www.w3.org/QA/2008/04/unescape-html-entities-python.html
# http://bytes.com/topic/python/answers/21074-unescaping-xml-escape-codes
def htmlent2chr(self, s):
def ent2chr(m):
code = m.group(1)
if code.isdigit(): code = int(code)
else: code = int(code[1:], 16)
if code<256: return chr(code)
else: return '?' #XXX unichr(code).encode('utf-16le') ??
return re.sub(r'\&\#(x?[0-9a-fA-F]+);', ent2chr, s)
# Supprime les caractères spéciaux HTML
# http://wiki.python.org/moin/EscapingHtml
def htmlentitydecode(self, s):
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
# Supprime les caractères spéciaux pour obtenir un nom de fichier correct
def cleanup_filename (self, s):
nouvNom = s
nouvNom = nouvNom.replace(" ","_")
nouvNom = nouvNom.replace(":","_")
nouvNom = nouvNom.replace("/","_")
nouvNom = nouvNom.replace("\\","_")
nouvNom = nouvNom.replace("?","_")
return nouvNom
# Fonction parse_date recopiée de l'application arte+7recorder
# Permet de convertir une date issue d'Arte+7 (hier, aujourd'hui...) en vrai date
def parse_date(self, date_str):
time_re = re.compile("^\d\d[h:]\d\d$")
fr_monthesL = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]
fr_monthesC = ["janv.", "fevr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."]
de_monthes = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]
date_array = date_str.split(",")
if time_re.search(date_array[-1].strip()) is None:
return ""
time_ = date_array[-1].strip()
if date_array[0].strip() in ("Aujourd'hui", "Heute"):
date_ = time.strftime("%Y/%m/%d")
elif date_array[0].strip() in ("Hier", "Gestern"):
date_ = time.strftime("%Y/%m/%d", time.localtime(time.time() - (24*60*60)))
else:
array = date_array[1].split()
day = array[0].strip(".")
month = array[1]
for arr in (fr_monthesL, fr_monthesC, de_monthes):
if array[1] in arr:
month = "%02d" % (arr.index(array[1])+1)
year = array[2]
date_ = "%s/%s/%s" % (year, month, day)
return date_ + ", " + time_
def __init__(self):
Plugin.__init__(self, self.nom, self.url, 7) #7 = fréquence de rafraichissement
if os.path.exists(self.fichierCache):
self.listeChaines = self.chargerCache()
def debug_savefile (self, buffer):
path = os.path.expanduser( "~" )
fichierDebug = path+"/.tvdownloader/"+self.nom.replace( " ", "_" )+".log"
file = open(fichierDebug, "w")
file.write (buffer)
file.close()
def debug_print (self, variable):
#~ print str(variable).replace("},", "},\n\n").replace("',", "',\n").replace("\",", "\",\n")
print str(variable).replace("{", "\n\n{").replace(", ", ",\n")
def listerOptions(self):
for option in self.listeOptions.values():
if option['type']=="ChoixUnique":
self.optionChoixUnique(option['nom'], option['description'], option['defaut'], option['valeurs'])
elif option['type']=="ChoixMultiple":
self.optionChoixMultiple(option['nom'], option['description'], option['defaut'], option['valeurs'])
elif option['type']=="Texte":
self.optionTexte(option['nom'], option['description'], option['defaut'])
elif option['type']=="Bouleen":
self.optionBouleen(option['nom'], option['description'], option['defaut'])
def rafraichir(self):
self.afficher("Global : Création de la liste des chaines...")
# On remet a 0 la liste des chaines
self.listeChaines.clear()
# On boucle sur chaque "chaine" à analyser
for chaineActuelle in [self.configArteLiveWeb, self.configArtePlusSept]:
self.afficher (chaineActuelle['nom']+" Récupération de la liste des catégories "+chaineActuelle['nom']+"...")
listeEmissions = {}
# On recherche toutes les catégories
for item in re.finditer(chaineActuelle['regexEmissions']['pattern'], self.API.getPage(chaineActuelle['regexEmissions']['url'])):
self.afficher (chaineActuelle['nom']+" ... Catégorie "+item.group('nom')+" : "+item.group('lien')+".")
listeEmissions[item.group('nom')]=item.group('lien')
self.listeChaines[chaineActuelle['nom']] = listeEmissions
# On sauvegarde les chaines trouvées
self.listerOptions()
self.sauvegarderCache(self.listeChaines)
self.afficher("Global : Emissions conservées.")
def listerChaines(self):
liste = self.listeChaines.keys()
liste.sort()
for chaine in liste:
self.ajouterChaine(chaine)
def listerEmissions(self, chaine):
if(self.listeChaines.has_key(chaine)):
self.derniereChaine = chaine
liste = self.listeChaines[chaine].keys()
liste.sort()
for emission in liste:
self.ajouterEmission(chaine, emission)
def getLienEmission(self, emission):
# Cherche dans quelle chaine se trouve l'émission
if(self.listeChaines.has_key(self.derniereChaine)):
listeEmissions = self.listeChaines[ self.derniereChaine ]
if(listeEmissions.has_key(emission)):
return listeEmissions[ emission ]
def chargeListeEnregistrements(self, emission, chaineActuelle):
emissionID = self.getLienEmission(emission)
if emissionID == None:
self.afficher (chaineActuelle['nom']+" Erreur de recherche du lien pour \""+emission+"\"")
return None
else:
self.afficher (chaineActuelle['nom']+" Liste des enregistrements pour \""+emission+"\"...")
pattern = ""
for unItem in chaineActuelle['regexListeFichiers'].values():
#~ print str(chaineActuelle['regexListeFichiers'])
# Construction du lien contenant toutes les émissions de cette catégorie
lienPage = unItem['url'].replace("%emission%", emissionID).replace("%pattern%", pattern)
self.afficher (chaineActuelle['nom']+" ... lecture de la page "+lienPage)
laPage = self.API.getPage(lienPage)
if len(laPage)>0:
foundItems = re.findall(unItem['pattern'], laPage)
pattern = foundItems[0]
self.afficher (chaineActuelle['nom']+" On a listé " + str(len(foundItems)) + " enregistrements.")
else:
self.afficher (chaineActuelle['nom']+" Impossible de charger la page. Aucun enregistrement trouvé !")
foundItems = None
return foundItems
def ajouteFichiers (self, emission, listeEnregistrement, chaineActuelle):
self.afficher (chaineActuelle['nom']+" On ajoute les enregitrements trouvés.")
opt_renameFiles = self.getOption("rename_files")
opt_qual = self.getOption("qualite")
nbLiens = 0
for keyEnregistrement in listeEnregistrement.keys():
# on supprime l'enregistrement avec son index actuel
unEnregistrement = listeEnregistrement.copy()[keyEnregistrement]
for infosQualite in chaineActuelle['qualite']:
infosFichier = {}
if opt_qual.find(infosQualite)>=0:
# Lien dans la qualité voulue
unEnregistrement['lien'] = unEnregistrement.get('lien.'+infosQualite, None)
if unEnregistrement['lien'] == None:
self.afficher (chaineActuelle['nom']+" ... Pas de lien "+infosQualite+" trouvé.")
continue
# Date, mise en forme
rfc_date = rfc822.parsedate(unEnregistrement['date'])
# Format année/mois/jour hh:mm, mieux pour effectuer un tri
unEnregistrement['date'] = time.strftime("%Y/%m/%d %H:%M", rfc_date)
lesInfos = {}
for keyInfo in chaineActuelle['infosFichier'].keys():
uneInfo = chaineActuelle['infosFichier'][keyInfo]
# On effectue les remplacements selon les informations collectées
for unTag in unEnregistrement.keys():
if unEnregistrement[unTag] != None:
uneInfo = uneInfo.replace("%"+unTag+"%", unEnregistrement[unTag])
else:
uneInfo = uneInfo.replace("%"+unTag+"%", "")
# Qualité de la video
uneInfo = uneInfo.replace("%qualite%", infosQualite)
lesInfos[keyInfo] = uneInfo
# Nom fichier
if opt_renameFiles:
nomFichierSortie = self.cleanup_filename(unEnregistrement['titre'])
else:
nomFichierSortie = unEnregistrement['lien'].split('/')[-1]
if nomFichierSortie.find('?')>0:
nomFichierSortie = nomFichierSortie.split('?')[0]
if not re.match(".*\.mp4", nomFichierSortie):
nomFichierSortie = nomFichierSortie+".mp4"
# Ajout du fichier
nbLiens += 1
self.afficher (chaineActuelle['nom']+" Ajoute dans la liste...")
self.afficher (chaineActuelle['nom']+" ... Date : "+ lesInfos['date'])
self.afficher (chaineActuelle['nom']+" ... Nom : "+ lesInfos['nom'])
self.afficher (chaineActuelle['nom']+" ... Lien : " + lesInfos['lien'])
self.afficher (chaineActuelle['nom']+" ... Image : " + lesInfos['urlImage'])
self.afficher (chaineActuelle['nom']+" ... Nom fichier : " + nomFichierSortie)
leFichier = Fichier(
lesInfos['nom'],
lesInfos['date'],
lesInfos['lien'],
nomFichierSortie,
lesInfos['urlImage'],
lesInfos['descriptif']
)
self.ajouterFichier(emission, leFichier)
return nbLiens
def listerEnregistrements(self, emission, chaineActuelle):
opt_maxFiles = int(self.getOption("max_files"))
opt_turbo = self.getOption("turbo_mode")
nbLiens = 0
# Charge la page contenant la liste des émissions
videosList = self.chargeListeEnregistrements(emission, chaineActuelle)
# A-t-on une liste d'enregistrements ?
if videosList != None:
listeEnregistrement = {}
# Boucle sur chaque traitement de recherche
for unItem in chaineActuelle['regexInfosFichiers'].values():
optional = unItem.get('optional',0)
if not (opt_turbo and optional):
if unItem.get('url', None) == None:
# On n'a pas d'url, on travaille sur videoList
# C'est la première passe
nbFichiers = 0
lesPages = {}
for infosVideo in videosList:
lesPages[nbFichiers] = infosVideo
# On crée, et on indexe listeEnregistrement en phase avec videosList
listeEnregistrement[nbFichiers] = {}
nbFichiers += 1
if (opt_maxFiles>0 and nbFichiers>=opt_maxFiles):
break
else:
# Chargement des pages HTML sur lesquelles on va devoir travailler
self.afficher (chaineActuelle['nom']+" Chargement des pages nécessaires...")
listeURL = []
# On boucle sur chaque enregistrement à travailler
for keyEnregistrement in listeEnregistrement.keys():
# on supprime l'enregistrement avec son index actuel
unEnregistrement = listeEnregistrement.pop (keyEnregistrement)
lienHTML = unItem['url']
# On effectue les remplacements des paramètres dans l'url
for unTag in unEnregistrement.keys():
if unEnregistrement[unTag] != None:
lienHTML = lienHTML.replace("%"+unTag+"%", unEnregistrement[unTag])
else:
lienHTML = lienHTML.replace("%"+unTag+"%", "")
listeURL.append(lienHTML)
# on recrée l'enregistrement avec son nouvel index
listeEnregistrement[lienHTML] = unEnregistrement
# On charge les pages désirées
lesPages = self.API.getPages(listeURL)
# On boucle et exécute les expressions régulières
for pageNum in lesPages.keys():
unePage = lesPages[pageNum]
if len(unePage)==0:
self.afficher (chaineActuelle['nom']+" ERREUR : La page "+pageNum+" n'a pas été chargée !")
#~ print "Page : "+repr(unePage)
unEnregistrement = listeEnregistrement[pageNum]
for unTag in unItem['patterns'].keys():
if type(unItem['patterns'][unTag]).__name__==type(re.compile("foo")).__name__:
reFound = re.search(unItem['patterns'][unTag], unePage)
if reFound != None:
unEnregistrement[unTag] = reFound.group(1)
else:
unEnregistrement[unTag] = None
else:
texte = unItem['patterns'][unTag]
for option in self.listeOptions.values():
texte = texte.replace("%"+option['nom']+"%", str(self.getOption(option['nom'])))
unEnregistrement[unTag] = texte
# On ajoute enfin la liste des fichiers à télécharger
nbLiens = self.ajouteFichiers(emission, listeEnregistrement, chaineActuelle)
def listerFichiers(self, emission):
for chaineActuelle in [self.configArteLiveWeb, self.configArtePlusSept]:
if (self.derniereChaine == chaineActuelle['nom']):
self.listerEnregistrements (emission, chaineActuelle) | Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
import pickle
import base64
from Crypto.Cipher import DES
import xml.sax
from xml.sax.handler import ContentHandler
import unicodedata
from Fichier import Fichier
from Plugin import Plugin
###########
# Classes #
###########
class M6Replay( Plugin ):
def __init__( self ):
Plugin.__init__( self, "M6Replay", "www.m6replay.fr/", 1 )
self.listeFichiers = {} # Clefs = nomChaine, Valeurs = { nomEmission, [ [ Episode 1, Date1, URL1 ], ... ] }
if os.path.exists( self.fichierCache ):
self.listeFichiers = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions..." )
# On remet a 0 la liste des fichiers
self.listeFichiers.clear()
# On recupere la page qui contient les donnees chiffrees
pageEmissionsChiffree = self.API.getPage( "http://www.m6replay.fr/catalogue/catalogueWeb3.xml" )
#
# N.B. : La page http://www.m6replay.fr/catalogue/catalogueWeb4.xml semble contenir
# des videos non presentent sur le site...
# Il faudrait voir ce qu'il en retourne (pourquoi ne sont-elles pas sur le site ? les liens fonctionnent-ils ?)
#
# Classe pour dechiffrer la page
decryptor = DES.new( "ElFsg.Ot", DES.MODE_ECB )
# Page des emissions dechiffree
pageEmissions = decryptor.decrypt( base64.decodestring( pageEmissionsChiffree ) )
# On cherche la fin du fichier XML
finXML = pageEmissions.find( "</template_exchange_WEB>" ) + len( "</template_exchange_WEB>" )
# On enleve ce qui est apres la fin du fichier XML
pageEmissions = pageEmissions[ : finXML ]
# Handler
handler = M6ReplayHandler( self.listeFichiers )
# On parse le fichier xml
xml.sax.parseString( pageEmissions, handler )
self.sauvegarderCache( self.listeFichiers )
self.afficher( "Fichier sauvegarde" )
def listerChaines( self ):
for chaine in self.listeFichiers.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeFichiers.has_key( chaine ) ):
self.listeEmissionsCourantes = self.listeFichiers[ chaine ]
for emission in self.listeFichiers[ chaine ].keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeEmissionsCourantes.has_key( emission ) ):
listeFichiers = self.listeEmissionsCourantes[ emission ]
for ( nom, date, lien, urlImage, descriptif ) in listeFichiers:
lienValide = "rtmpe://m6dev.fcod.llnwd.net:443/a3100/d1/mp4:production/regienum/" + lien
urlImage = "http://images.m6replay.fr" + urlImage
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lien )
self.ajouterFichier( emission, Fichier( nom, date, lienValide, nom + extension, urlImage, descriptif ) )
#
# Parser XML pour M6Replay
#
## Classe qui permet de lire les fichiers XML de M6Replay
class M6ReplayHandler( ContentHandler ):
# Constructeur
# @param listeFichiers Liste des fichiers que le parser va remplir
def __init__( self, listeFichiers ):
# Liste des fichiers
self.listeFichiers = listeFichiers
# Liste des emissions (temporaire, ajoute au fur et a mesure dans listeFichiers)
self.listeEmissions = {}
# Liste des videos (temporaire, ajoute au fur et a mesure dans listeEmissions)
self.listeVideos = []
# Initialisation des variables a Faux
self.nomChaineConnu = False
self.nomEmissionConnu = False
self.nomEpisodeConnu = False
self.nomVideoConnu = False
self.isNomChaine = False
self.isNomEmission = False
self.isNomEpisode = False
self.isNomVideo = False
self.isResume = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "categorie" ):
if( self.nomChaineConnu ):
# On commence une nouvelle emission
pass
else:
# On commence une nouvelle chaine
pass
elif( name == "nom" ):
# Si on a nom, cela peut etre (toujours dans cet ordre) :
# - Le nom de la chaine
# - Le nom de l'emission
# - Le nom d'un episode de cette emission
# - Le nom de la vidéo de cet episode
# De plus, si on ne connait pas la nom de la chaine, alors le 1er nom rencontre est le nom de la chaine
if( self.nomChaineConnu ):
if( self.nomEmissionConnu ):
if( self.nomEpisodeConnu ): # Alors on a le nom de la video
self.isNomVideo = True
else: # Alors on a le nom de l'episode
self.isNomEpisode = True
else: # Alors on a le nom de l'emission
self.isNomEmission = True
else: # Alors on a le nom de la chaine
self.isNomChaine = True
elif( name == "diffusion" ):
self.dateEpisode = attrs.get( "date", "" )
elif( name == "resume" ):
self.isResume = True
elif( name == "produit" ):
self.image = attrs.get( "sml_img_url", "" )
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
data = unicodedata.normalize( 'NFKD', data ).encode( 'ascii','ignore' )
if( self.isNomChaine ):
self.nomChaine = data
self.nomChaineConnu = True
self.isNomChaine = False
elif( self.isNomEmission ):
self.nomEmission = data
self.nomEmissionConnu = True
self.isNomEmission = False
elif( self.isNomEpisode ):
self.nomEpisode = data
self.nomEpisodeConnu = True
self.isNomEpisode = False
elif( self.isNomVideo ):
self.nomVideo = data
self.nomVideoConnu = True
self.isNomVideo = False
elif( self.isResume ):
self.resume = data
self.isResume = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "categorie" ):
if( self.nomEmissionConnu ): # On a fini de traiter une emission
self.listeEmissions[ self.nomEmission.title() ] = self.listeVideos
self.listeVideos = []
self.nomEmissionConnu = False
else: # On a fini de traiter une chaine
self.listeFichiers[ self.nomChaine.title() ] = self.listeEmissions
self.listeEmissions = {}
self.nomChaineConnu = False
elif( name == "nom" ):
pass
elif( name == "diffusion" ):
self.listeVideos.append( [ self.nomEpisode.title(), self.dateEpisode, self.nomVideo, self.image, self.resume ] )
self.nomEpisodeConnu = False
self.nomVideoConnu = False
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
import pickle
import xml.sax
from xml.sax.handler import ContentHandler
import urllib
import unicodedata
from Fichier import Fichier
from Plugin import Plugin
###########
# Classes #
###########
class W9Replay( Plugin ):
urlFichierXML = "http://www.w9replay.fr/catalogue/3637.xml"
listeFichiers = {} # Clefs = nomChaine, Valeurs = { nomEmission, [ [ Episode 1, Date1, URL1 ], ... ] }
def __init__( self ):
Plugin.__init__( self, "W9Replay", "http://www.w9replay.fr/", 1 )
self.listeEmissionsCourantes = {}
if os.path.exists( self.fichierCache ):
self.listeFichiers = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions et des fichiers..." )
# On remet a 0 la liste des fichiers
self.listeFichiers.clear()
# On recupere la page qui contient les infos
page = urllib.urlopen( self.urlFichierXML )
pageXML = page.read()
#~ pageXML = self.API.getPage( self.urlFichierXML )
# Handler
handler = W9ReplayHandler( self.listeFichiers )
# On parse le fichier xml
xml.sax.parseString( pageXML, handler )
self.sauvegarderCache( self.listeFichiers )
self.afficher( u"Liste sauvegardée" )
def listerChaines( self ):
for chaine in self.listeFichiers.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeFichiers.has_key( chaine ) ):
self.listeEmissionsCourantes = self.listeFichiers[ chaine ]
for emission in self.listeEmissionsCourantes.keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeEmissionsCourantes.has_key( emission ) ):
listeFichiers = self.listeEmissionsCourantes[ emission ]
for ( nom, date, lien, urlImage, descriptif ) in listeFichiers:
lienValide = "rtmpe://m6dev.fcod.llnwd.net:443/a3100/d1/mp4:production/w9replay/" + lien
urlImage = "http://images.w9replay.fr" + urlImage
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lien )
self.ajouterFichier( emission, Fichier( nom, date, lienValide, nom + extension, urlImage, descriptif ) )
#
# Parser XML pour W9Replay
#
## Classe qui permet de lire les fichiers XML de W9Replay
class W9ReplayHandler( ContentHandler ):
# Constructeur
# @param listeFichiers Liste des fichiers que le parser va remplir
def __init__( self, listeFichiers ):
# Liste des fichiers
self.listeFichiers = listeFichiers
# Liste des emissions (temporaire, ajoute au fur et a mesure dans listeFichiers)
self.listeEmissions = {}
# Liste des videos (temporaire, ajoute au fur et a mesure dans listeEmissions)
self.listeVideos = []
# Initialisation des variables a Faux
self.nomChaineConnu = False
self.nomEmissionConnu = False
self.nomEpisodeConnu = False
self.nomVideoConnu = False
self.isNomChaine = False
self.isNomEmission = False
self.isNomEpisode = False
self.isNomVideo = False
self.isResume = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "categorie" ):
if( self.nomChaineConnu ):
# On commence une nouvelle emission
pass
else:
# On commence une nouvelle chaine
pass
elif( name == "nom" ):
# Si on a nom, cela peut etre (toujours dans cet ordre) :
# - Le nom de l'emission
# - Le nom d'un episode de cette emission
# - Le nom de la vidéo de cet episode
# De plus, si on ne connait pas la nom de la chaine, alors le 1er nom rencontre est le nom de la chaine
if( self.nomChaineConnu ):
if( self.nomEmissionConnu ):
if( self.nomEpisodeConnu ): # Alors on a le nom de la video
self.isNomVideo = True
else: # Alors on a le nom de l'episode
self.isNomEpisode = True
else: # Alors on a le nom de l'emission
self.isNomEmission = True
else: # Alors on a le nom de la chaine
self.isNomChaine = True
elif( name == "diffusion" ):
self.dateEpisode = attrs.get( "date", "" )
elif( name == "resume" ):
self.isResume = True
elif( name == "produit" ):
self.image = attrs.get( "sml_img_url", "" )
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
data = unicodedata.normalize( 'NFKD', data ).encode( 'ascii','ignore' )
if( self.isNomChaine ):
self.nomChaine = data
self.nomChaineConnu = True
self.isNomChaine = False
elif( self.isNomEmission ):
self.nomEmission = data
self.nomEmissionConnu = True
self.isNomEmission = False
elif( self.isNomEpisode ):
self.nomEpisode = data
self.nomEpisodeConnu = True
self.isNomEpisode = False
elif( self.isNomVideo ):
self.nomVideo = data
self.nomVideoConnu = True
self.isNomVideo = False
elif( self.isResume ):
self.resume = data
self.isResume = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "categorie" ):
if( self.nomEmissionConnu ): # On a fini de traiter une emission
self.listeEmissions[ self.nomEmission.title() ] = self.listeVideos
self.listeVideos = []
self.nomEmissionConnu = False
else: # On a fini de traiter une chaine
self.listeFichiers[ self.nomChaine.title() ] = self.listeEmissions
self.listeEmissions = {}
self.nomChaineConnu = False
elif( name == "nom" ):
pass
elif( name == "diffusion" ):
self.listeVideos.append( [ self.nomEpisode.title(), self.dateEpisode, self.nomVideo, self.image, self.resume ] )
self.nomEpisodeConnu = False
self.nomVideoConnu = False
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import re
import os
import os.path
#~ import pickle
import xml.sax
from Podcasts import PodcastsHandler
from Fichier import Fichier
from Plugin import Plugin
###########
# Classes #
###########
class FranceInter( Plugin ):
ulrListeEmission = "http://www.franceinter.fr/podcasts/liste-des-emissions"
listeEmissions = {} # { Nom emission, URL fichier XML }
pageRegEx = re.compile( 'class="visuel" title="([^"]*?)".+?href="(http://radiofrance-podcast.net/podcast09/.+?.xml)', re.DOTALL )
def __init__( self ):
Plugin.__init__( self, "France Inter", "http://www.franceinter.fr/podcasts", 30 )
if os.path.exists( self.fichierCache ):
self.listeEmissions = self.chargerCache()
def rafraichir( self ):
self.afficher( u"Récupération de la liste des émissions..." )
# On remet a 0 la liste des emissions
self.listeEmissions.clear()
# On recupere la page web
page = self.API.getPage( self.ulrListeEmission )
# Extraction des emissions
self.listeEmissions = dict( re.findall( self.pageRegEx, page ) )
self.sauvegarderCache( self.listeEmissions )
self.afficher( u"Liste des émissions sauvegardées" )
def listerChaines( self ):
self.ajouterChaine( self.nom )
def listerEmissions( self, chaine ):
for emission in self.listeEmissions.keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeEmissions.has_key( emission ) ):
# On recupere la page web qui liste les fichiers
pageXML = self.API.getPage( self.listeEmissions[ emission ] )
# On extrait les fichiers
listeFichiers = []
handler = PodcastsHandler( listeFichiers )
try:
xml.sax.parseString( pageXML, handler )
except:
return
# On ajoute les fichiers
for fichier in listeFichiers:
self.ajouterFichier( emission, fichier )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier COPYING #
#########################################
# Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
# Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
# Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
# Modules Python
import datetime
import os.path
import re
import xml.sax
from xml.sax.handler import ContentHandler
# Modules de TVD
from Fichier import Fichier
from Plugin import Plugin
# Logger de TVD
import logging
logger = logging.getLogger( __name__ )
###########
# Classes #
###########
class CanalPlus( Plugin ):
urlFichierXMLListeProgrammes = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/initPlayer"
urlFichierXMLEmissions = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getMEAs/"
urlFichierXMLFichiers = "http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/getVideos/"
def __init__( self ):
Plugin.__init__( self, "Canal+", "http://www.canalplus.fr/", 7 )
self.listeProgrammes = {} # { Nom chaine : { Nom emission : ID emission } }
self.derniereChaine = ""
if os.path.exists( self.fichierCache ):
self.listeProgrammes = self.chargerCache()
def rafraichir( self ):
logger.info( "récupération de la liste des chaines et des émissions" )
# On remet a 0 la liste des programmes
self.listeProgrammes.clear()
# On recupere la page qui contient les infos
pageXML = self.API.getPage( self.urlFichierXMLListeProgrammes )
# Handler
handler = CanalPlusListeProgrammesHandler( self.listeProgrammes )
# On parse le fichier xml
try:
xml.sax.parseString( pageXML, handler )
except:
logger.error( "impossible de parser le fichier XML de la liste des programmes" )
return
# On sauvegarde la liste dans le cache
self.sauvegarderCache( self.listeProgrammes )
logger.info( "liste des programmes sauvegardée" )
def listerChaines( self ):
for chaine in self.listeProgrammes.keys():
self.ajouterChaine( chaine )
def listerEmissions( self, chaine ):
if( self.listeProgrammes.has_key( chaine ) ):
self.derniereChaine = chaine
for emission in self.listeProgrammes[ chaine ].keys():
self.ajouterEmission( chaine, emission )
def listerFichiers( self, emission ):
if( self.listeProgrammes.has_key( self.derniereChaine ) ):
listeEmissions = self.listeProgrammes[ self.derniereChaine ]
if( listeEmissions.has_key( emission ) ):
IDEmission = listeEmissions[ emission ]
# On recupere la page qui contient les ids des fichiers
pageXML = self.API.getPage( self.urlFichierXMLEmissions + IDEmission )
# On extrait les ids
listeIDs = re.findall( "<ID>(.+?)</ID>", pageXML )
# On construit la liste des liens a recuperer
listeURL = []
for IDFichier in listeIDs:
listeURL.append( self.urlFichierXMLFichiers + IDFichier )
# On recupere les pages correspondantes
pagesXML = self.API.getPages( listeURL )
# On parse chacune de ces pages
for URL in listeURL:
pageXMLFichier = pagesXML[ URL ]
# Handler
infosFichier = []
handler = CanalPlusListeFichierHandler( infosFichier )
# On parse le fichier xml
try:
xml.sax.parseString( pageXMLFichier, handler )
except:
logger.error( "impossible de parser le fichier XML de la liste des fichiers" )
continue
# On ajoute le fichier
nom, date, lienLD, lienMD, lienHD, urlImage, descriptif = infosFichier
# On transforme la date en type datetime.date
try:
dateDecoupee = map( int, date.split( "/" ) )
dateBonFormat = datetime.date( dateDecoupee[ 2 ], dateDecoupee[ 1 ], dateDecoupee[ 0 ] )
except:
dateBonFormat = date
if( lienHD != "" and lienHD[ : 4 ] == "rtmp" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lienHD )
self.ajouterFichier( emission, Fichier( "[HD]" + nom, dateBonFormat, lienHD, nom + extension, urlImage, descriptif ) )
elif( lienMD != "" and lienMD[ : 4 ] == "rtmp" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lienMD )
self.ajouterFichier( emission, Fichier( "[MD]" + nom, dateBonFormat, lienMD, nom + extension, urlImage, descriptif ) )
elif( lienLD != "" and lienLD[ : 4 ] == "rtmp" ):
# On extrait l'extension du fichier
basename, extension = os.path.splitext( lienLD )
self.ajouterFichier( emission, Fichier( "[LD]" + nom, dateBonFormat, lienLD, nom + extension, urlImage, descriptif ) )
#
# Parsers XML pour Canal+
#
## Classe qui permet de lire le fichier XML de Canal qui liste les emissions
class CanalPlusListeProgrammesHandler( ContentHandler ):
# Constructeur
# @param listeProgrammes Liste des programmes que le parser va remplir
def __init__( self, listeProgrammes ):
# Liste des programmes
self.listeProgrammes = listeProgrammes
# Liste des emissions d'un programme (temporaire)
# Clef : nom emission, Valeur : ID
self.listeEmissions = {}
# Initialisation des variables a Faux
self.nomChaineConnu = False
self.isNomChaine = False
self.isIDEmission = False
self.nomEmissionConnu = False
self.isNomEmission = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "THEMATIQUE" ):
pass
elif( name == "NOM" and self.nomChaineConnu == False ):
self.isNomChaine = True
elif( name == "ID" and self.nomChaineConnu == True ):
self.isIDEmission = True
elif( name == "NOM" and self.nomChaineConnu == True ):
self.isNomEmission = True
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
if( self.isNomChaine ):
self.nomChaine = data
self.nomChaineConnu = True
self.isNomChaine = False
elif( self.isIDEmission ):
self.IDEmission = data
self.isIDEmission = False
elif( self.isNomEmission ):
self.nomEmission = data
self.nomEmissionConnu = True
self.isNomEmission = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "THEMATIQUE" ):
self.listeProgrammes[ self.nomChaine.title() ] = self.listeEmissions
self.listeEmissions = {}
self.nomChaineConnu = False
elif( name == "NOM" and self.nomEmissionConnu ):
self.listeEmissions[ self.nomEmission.title() ] = self.IDEmission
self.nomEmissionConnu = False
## Classe qui permet de lire le fichier XML d'un fichier de Canal
class CanalPlusListeFichierHandler( ContentHandler ):
# Constructeur
# @param infosFichier Infos du fichier que le parser va remplir
def __init__( self, infosFichier ):
# Liste des programmes
self.infosFichier = infosFichier
# On n'a pas forcement les 3 liens
self.lienLD = ""
self.lienMD = ""
self.lienHD = ""
# Initialisation des variables a Faux
self.isTitre = False
self.isDate = False
self.isLienLD = False
self.isLienMD = False
self.isLienHD = False
self.isLienImage = False
self.isDescriptif = False
## Methode appelee lors de l'ouverture d'une balise
# @param name Nom de la balise
# @param attrs Attributs de cette balise
def startElement( self, name, attrs ):
if( name == "DESCRIPTION" ):
self.descriptif = ""
self.isDescriptif = True
elif( name == "DATE" ):
self.isDate = True
elif( name == "TITRAGE" ):
self.titre = ""
elif( name == "TITRE" or name == "SOUS_TITRE" ):
self.isTitre = True
elif( name == "PETIT" ):
self.isLienImage = True
elif( name == "BAS_DEBIT" ):
self.isLienLD = True
elif( name == "HAUT_DEBIT" ):
self.isLienMD = True
elif( name == "HD" ):
self.isLienHD = True
## Methode qui renvoie les donnees d'une balise
# @param data Donnees d'une balise
def characters( self, data ):
if( self.isDescriptif ):
self.descriptif += data
elif( self.isDate ):
self.date = data
self.isDate = False
elif( self.isTitre ):
self.titre += " %s" %( data )
self.isTitre = False
elif( self.isLienImage ):
self.urlImage = data
self.isLienImage = False
elif( self.isLienLD ):
self.lienLD = data
self.isLienLD = False
elif( self.isLienHD ):
self.lienHD = data
self.isLienHD = False
## Methode appelee lors de la fermeture d'une balise
# @param name Nom de la balise
def endElement( self, name ):
if( name == "DESCRIPTION" ):
self.isDescriptif = False
elif( name == "VIDEO" ):
self.infosFichier[:] = self.titre, self.date, self.lienLD, self.lienMD, self.lienHD, self.urlImage, self.descriptif
| Python |
# -*- mode: python -*-
a = Analysis(['C:\\pluzzdl\\mainGui.py'],
pathex=['C:\\pyinstaller-2.0'],
hiddenimports=[],
hookspath=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas + [ ('pluzzdl.cfg', 'C:\pluzzdl\pluzzdl.cfg', 'DATA') ],
name=os.path.join('dist', 'pluzzdl.exe'),
debug=False,
strip=None,
upx=True,
console=False , icon='C:\\pluzzdl\\tvdownloader.ico')
app = BUNDLE(exe,
name=os.path.join('dist', 'pluzzdl.exe.app'))
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#
# Lancer : python setup.py py2exe
#
#
# Modules
#
import os
from distutils.core import setup
import py2exe
#
# Code
#
# Icones
listeIcones = []
for fichier in os.listdir( "ico" ):
if( fichier[ -4 : ] == ".png" or fichier[ -4 : ] == ".ico" ):
listeIcones.append( "ico/" + fichier )
setup( name = "pluzzdl",
version = "0.9.2",
author = "Chaoswizard",
url = "http://code.google.com/p/tvdownloader/",
license = "GNU General Public License 2(GPL 2)",
options = { "py2exe" : { "includes" : [ "sip" ] } },
data_files = [ ( "", [ "COPYING", "pluzzdl_default.cfg" ] ),
( "ico", listeIcones )
],
scripts = [ "mainGui.py" ],
windows = [ { "script" : "mainGui.py", "icon_resources" : [ ( 1, "ico/tvdownloader.ico" ) ] } ] )
| Python |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#
# Lancer : python setup.py py2exe
#
###########
# Modules #
###########
import os
from distutils.core import setup
import py2exe
########
# Code #
########
#
# Liste des fichiers à inclure au programme
#
# Icones
listeIcones = []
for fichier in os.listdir( "ico" ):
if( fichier[ -4 : ] == ".png" ):
listeIcones.append( "ico/" + fichier )
# Images
listeImages = []
for fichier in os.listdir( "img" ):
if( fichier[ -4 : ] == ".png" ):
listeImages.append( "img/" + fichier )
# Plugins
listePlugins = []
for fichier in os.listdir( "plugins" ):
if( fichier[ -3 : ] == ".py" ):
listePlugins.append( "plugins/" + fichier )
setup( name = "TVDownloader",
version = "0.7",
author = "Chaoswizard",
url = "http://code.google.com/p/tvdownloader/",
license = "GNU General Public License 2(GPL 2)",
options = { "py2exe" : { "includes" : [ "mechanize", "sip" ] } },
data_files = [ ( "", [ "COPYING" ] ),
( "ico", listeIcones ),
( "img", listeImages ),
( "plugins", listePlugins )
],
scripts = [ "main.py" ],
windows = [ { "script" : 'main.py' } ] )
| Python |
#!/bin/env python
import xml.dom.minidom as dom
import sys
import struct
WEAP_NUM = 780
struct_fmt = "<H BBHBBBB 8B8B8b8b8b8b8H bbBBBB"
def pack_weapon(dict):
l = []
l.append(dict['drain'])
l.append(dict['shotRepeat'])
l.append(dict['multi'])
l.append(dict['weapAni'])
l.append(dict['max'])
l.append(dict['tx'])
l.append(dict['ty'])
l.append(dict['aim'])
tmp = dict['patterns']
for j in xrange(8):
l.append(tmp[j]['attack'])
for j in xrange(8):
l.append(tmp[j]['del'])
for j in xrange(8):
l.append(tmp[j]['sx'])
for j in xrange(8):
l.append(tmp[j]['sy'])
for j in xrange(8):
l.append(tmp[j]['bx'])
for j in xrange(8):
l.append(tmp[j]['by'])
for j in xrange(8):
l.append(tmp[j]['sg'])
l.append(dict['acceleration'])
l.append(dict['accelerationx'])
l.append(dict['circleSize'])
l.append(dict['sound'])
l.append(dict['trail'])
l.append(dict['shipBlastFilter'])
return struct.pack(struct_fmt, *l)
def unpack_weapon(str):
tup = struct.unpack(struct_fmt, str)
dict = {}
dict['drain'] = tup[0]
dict['shotRepeat'] = tup[1]
dict['multi'] = tup[2]
dict['weapAni'] = tup[3]
dict['max'] = tup[4]
dict['tx'] = tup[5]
dict['ty'] = tup[6]
dict['aim'] = tup[7]
i = 8
tmp = [{} for j in xrange(8)]
for j in xrange(8):
tmp[j]['attack'] = tup[i]
i += 1
for j in xrange(8):
tmp[j]['del'] = tup[i]
i += 1
for j in xrange(8):
tmp[j]['sx'] = tup[i]
i += 1
for j in xrange(8):
tmp[j]['sy'] = tup[i]
i += 1
for j in xrange(8):
tmp[j]['bx'] = tup[i]
i += 1
for j in xrange(8):
tmp[j]['by'] = tup[i]
i += 1
for j in xrange(8):
tmp[j]['sg'] = tup[i]
i += 1
dict['patterns'] = tmp
dict['acceleration'] = tup[i]
dict['accelerationx'] = tup[i+1]
dict['circleSize'] = tup[i+2]
dict['sound'] = tup[i+3]
dict['trail'] = tup[i+4]
dict['shipBlastFilter'] = tup[i+5]
return dict
def DOMToDict(doc, weap_node):
dict = {}
for i in weap_node.childNodes:
if i.nodeType != i.ELEMENT_NODE:
continue
if i.hasAttribute("value"):
dict[i.tagName] = int(i.getAttribute("value"))
elif i.tagName == "patterns":
dict['patterns'] = [{} for el in xrange(8)]
index = 0
for j in i.childNodes:
if j.nodeType != i.ELEMENT_NODE:
continue
attrs = [j.attributes.item(i) for i in xrange(j.attributes.length)]
for i in attrs:
dict['patterns'][index][i.name] = int(i.nodeValue)
index += 1
return dict
def dictToDOM(doc, root, dict, index=None):
entry = doc.createElement("weapon")
if index != None:
entry.setAttribute("index", "%04X" % (index,))
keys = dict.keys()
keys.sort()
for i in keys:
node = doc.createElement(i)
if isinstance(dict[i], list):
for j in dict[i]:
keys = j.keys()
keys.sort()
n = doc.createElement("entry")
for i in keys:
n.setAttribute(i, str(j[i]))
node.appendChild(n)
else:
node.setAttribute("value", str(dict[i]))
entry.appendChild(node)
root.appendChild(entry)
def toXML(hdt, output):
doc = dom.getDOMImplementation().createDocument(None, "TyrianHDT", None)
try:
f = file(hdt, "rb")
except IOError:
print "%s couldn't be opened for reading." % (hdt,)
sys.exit(1)
try:
outf = file(output, "w")
except IOError:
print "%s couldn't be opened for writing." % (outf,)
sys.exit(1)
f.seek(struct.unpack("<i", f.read(4))[0])
f.read(7*2)
sys.stdout.write("Converting weapons")
index = 0
for i in xrange(WEAP_NUM+1):
tmp = f.read(struct.calcsize(struct_fmt))
shot = unpack_weapon(tmp)
dictToDOM(doc, doc.documentElement, shot, index)
index += 1
sys.stdout.write(".")
sys.stdout.flush()
sys.stdout.write("Done!\n")
sys.stdout.write("Writing XML...")
sys.stdout.flush()
doc.writexml(outf, addindent="\t", newl="\n")
sys.stdout.write("Done!\n")
def toHDT(input, hdt):
try:
f = file(input, "r")
except IOError:
print "%s couldn't be opened for reading." % (input,)
sys.exit(1)
try:
outf = file(hdt, "r+b")
except IOError:
print "%s couldn't be opened for writing." % (hdt,)
sys.exit(1)
outf.seek(struct.unpack("<i", outf.read(4))[0])
outf.read(7*2)
sys.stdout.write("Reading XML...")
sys.stdout.flush()
doc = dom.parse(f)
sys.stdout.write("Done!\n")
sys.stdout.write("Writing weapons")
for i in doc.documentElement.childNodes:
if i.nodeType != i.ELEMENT_NODE:
continue
shot = DOMToDict(doc, i)
str = pack_weapon(shot)
outf.write(str)
sys.stdout.write(".")
sys.stdout.flush()
sys.stdout.write("Done!\n")
def printHelp():
print "Usage: weapons.py toxml path/to/tyrian.hdt output.xml"
print " weapons.py tohdt input.xml path/to/tyrian.hdt"
sys.exit(1)
##############################
if __name__ == "__main__":
if len(sys.argv) != 4:
printHelp()
if sys.argv[1] == "toxml":
toXML(sys.argv[2], sys.argv[3])
elif sys.argv[1] == "tohdt":
toHDT(sys.argv[2], sys.argv[3])
else:
printHelp()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
from collections import deque
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC''',
'\n@ATTRIBUTE open_class {' ,
'}',
'\n@ATTRIBUTE app_class {',
'}',
'\n@ATTRIBUTE cata_class {',
'}',
'''
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
normal_prog=re.compile("[_0-9a-zA-Z]")
def FuckString(s):
ss = s.split(".")[0]
rs = ""
for i in ss:
if not re.match(normal_prog,i):
i = ''
rs += i
#print (rs)
return rs
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
parser.add_option("-s", "--set_queue_type", dest = "set_queue_type",
help = "set queue type: all, opendpi, app, cata, none\n\
all : maxmiun instances number\n\
none : not limited\n\
default/or not specified is opendpi queue.")
parser.add_option("-p","--pure_duplicatedflows",dest = "pureflow",
action="store_true",default=False,
help = "ignore duplicated flows")
parser.add_option("-n","--max_queue_len",dest = "max_queue_len",
help = "set maxmium queue length, default is 5000")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
elif os.path.isfile(options.from_path):
items.add(os.path.abspath(options.from_path ))
else:
print "not set input file/path"
exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
opendpi_class_list=[]
app_class_list=[]
cata_class_list=[]
opendpi_prog = re.compile("^@ATTRIBUTE\ open.*$")
app_prog = re.compile("^@ATTRIBUTE app.*$")
cata_prog = re.compile("^@ATTRIBUTE cata.*$")
content_prog = re.compile("{.*}")
data_prog = re.compile("^@DATA")
#magic_colum_couter=-1
is_opendpi_class = False
is_app_class = False
is_cata_class = False
fivetuples=[]
writelines_data=[]
for input_arff_filename in items:
is_opendpi_class = False
is_app_class = False
is_cata_class = False
magic_col_couter = 0
opendpi_col = -1
app_col = -1
cata_col = -1
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
opendpi_re = opendpi_prog.search(line)
if opendpi_re:
is_opendpi_class = True
magic_col_couter += -1
o = content_prog.search(opendpi_re.group(0) )
w = o.group(0)[1:-1]
#print (w)
v = w.split(",")
#print (v)
for vv in v:
if vv not in opendpi_class_list and vv !="":
opendpi_class_list.append(vv)
app_re = app_prog.match(line)
if app_re:
is_app_class = True
magic_col_couter += -1
o = content_prog.search ( app_re.group(0) )
w = o.group(0)[1:-1]
v = w.split(",")
for vv in v:
if vv not in app_class_list and vv !="":
app_class_list.append(vv)
#print (vv)
cata_re = cata_prog.match(line)
if cata_re:
is_cata_class = True
magic_col_couter += -1
o = content_prog.search ( cata_re.group(0) )
w = o.group(0)[1:-1]
v = w.split(",")
for vv in v:
if vv not in cata_class_list and vv !="":
cata_class_list.append(vv)
#print (vv)
#print (magic_col_couter)
opendpi_col = magic_col_couter
app_col = magic_col_couter +1
cata_col = magic_col_couter +2
m = data_prog.match(line)
if m:
foundData = True
continue
if ( foundData == True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#appname = input_arff_filename.split('@')[0].split(os.path.sep)[-1]
#print (appname)
writline=line.split(',')
if is_opendpi_class:
opendpi_class = writline[ opendpi_col ].strip()
if opendpi_class not in opendpi_class_list:
opendpi_class_list.append(opendpi_class)
if is_app_class:
app_class = writline[ app_col ].strip()
if app_class not in app_class_list:
app_class_list.append(app_class)
if is_cata_class:
cata_class = writline[ cata_col ].strip()
if cata_class not in cata_class_list:
cata_class_list.append(cata_class)
if (options.pureflow == True) :
s = writline[:5]
#s = ""
#for i in writline[:5]:
# s += i
if ( s not in fivetuples ):
if options.verbose == True:
print (i)
fivetuples.append(s)
writelines_data.append( line )
else:
if options.verbose == True:
print ("ignoring duplicated flows!")
pass
else:
writelines_data.append( line )
print (magic_col_couter)
p.close()
##print lists
if options.verbose == True:
print ("---opendpi_class_list{")
for i in opendpi_class_list:
print (i)
print ("}opendpi_class_list-----")
print ("---app_class_list{")
for i in app_class_list:
print (i)
print ("}app_class_list-----")
print ("---cata_class_list{")
for i in cata_class_list:
print (i)
print ("}cata_class_list-----")
print ("------------------------------")
QueueDict={}
QueueName_prefix = ""
if options.set_queue_type:
if options.max_queue_len:
max_length = int ( options.max_queue_len )
if options.set_queue_type == "all":
QueueName_prefix = 'mydeque_byall_'
elif options.set_queue_type == "cata":
if ( is_cata_class == True ):
QueueName_prefix = 'mydeque_bycata_'
for s in cata_class_list:
createqueue_cmd = ( "%s%s = deque(maxlen = max_length )\nQueueDict[\'%s\'] = %s%s " % (QueueName_prefix,s,s,QueueName_prefix,s ) )
createqueue_code = compile(createqueue_cmd,'','exec')
exec(createqueue_code)
#print (QueueDict)
for i in writelines_data:
#print (i)
cata_type = i.strip().split(",")[cata_col]
#print ( cata_type )
appendqueue_cmd = "QueueDict[\'%s\'].append(i)" % (cata_type)
appendqueue_code = compile(appendqueue_cmd,'','exec')
exec(appendqueue_code)
if options.verbose == True:
for s in cata_class_list:
printqueue_cmd = ( "print QueueDict['%s']" % s )
printqueue_code = compile(printqueue_cmd,'','exec')
exec(printqueue_code)
writelines_data=[]
for w in cata_class_list:
QueueName_s=QueueName_prefix+w
writequeue_cmd = ( "while True:\n\ttry:\n\t\tss = %s.pop()\n\t\t#print ss\n\t\twritelines_data.append(ss)\n\texcept IndexError:\n\t\tbreak " % (QueueName_s) )
writequeue_code = compile(writequeue_cmd,'','exec')
exec(writequeue_code)
if options.verbose == True:
for t in writelines_data:
print (t.split(",")[-1])
else:
print ("no cata_class in input arff")
exit()
elif options.set_queue_type == "app":
if ( is_app_class == True ):
QueueName_prefix='mydeque_byapp_'
for ss in app_class_list:
#print (ss)
#s = ss.split(".")[0]
s = FuckString(ss)
createqueue_cmd = ( "%s%s = deque(maxlen = max_length )\nQueueDict[\'%s\'] = %s%s " % (QueueName_prefix,s,s,QueueName_prefix,s ) )
createqueue_code = compile(createqueue_cmd,'','exec')
exec(createqueue_code)
#print (QueueDict)
for i in writelines_data:
#print (i)
a = i.strip().split(",")[app_col]
app_type = FuckString(a)
#print ( cata_type )
appendqueue_cmd = "QueueDict[\'%s\'].append(i)" % (app_type)
appendqueue_code = compile(appendqueue_cmd,'','exec')
exec(appendqueue_code)
if options.verbose == True:
for s in app_class_list:
printqueue_cmd = ( "print QueueDict['%s']" % s )
printqueue_code = compile(printqueue_cmd,'','exec')
exec(printqueue_code)
writelines_data=[]
for w in app_class_list:
rw = FuckString(w)
QueueName_s=QueueName_prefix+rw
writequeue_cmd = ( "while True:\n\ttry:\n\t\tss = %s.pop()\n\t\t#print ss\n\t\twritelines_data.append(ss)\n\texcept IndexError:\n\t\tbreak " % (QueueName_s) )
writequeue_code = compile(writequeue_cmd,'','exec')
exec(writequeue_code)
if options.verbose == True:
for t in writelines_data:
print (t.split(",")[-1])
else:
print ("no app_class in input arff")
exit()
elif options.set_queue_type == "opendpi":
if (is_opendpi_class == True) :
QueueName_prefix='mydeque_by_opendpi_'
for ss in opendpi_class_list:
#print (ss)
#s = ss.split(".")[0]
s = FuckString(ss)
createqueue_cmd = ( "%s%s = deque(maxlen = max_length )\nQueueDict[\'%s\'] = %s%s " % (QueueName_prefix,s,s,QueueName_prefix,s ) )
createqueue_code = compile(createqueue_cmd,'','exec')
exec(createqueue_code)
#print (QueueDict)
for i in writelines_data:
#print (i)
a = i.strip().split(",")[opendpi_col]
app_type = FuckString(a)
#print ( cata_type )
appendqueue_cmd = "QueueDict[\'%s\'].append(i)" % (app_type)
appendqueue_code = compile(appendqueue_cmd,'','exec')
exec(appendqueue_code)
if options.verbose == True:
for s in opendpi_class_list:
printqueue_cmd = ( "print QueueDict['%s']" % s )
printqueue_code = compile(printqueue_cmd,'','exec')
exec(printqueue_code)
writelines_data=[]
for w in opendpi_class_list:
rw = FuckString(w)
QueueName_s=QueueName_prefix+rw
writequeue_cmd = ( "while True:\n\ttry:\n\t\tss = %s.pop()\n\t\t#print ss\n\t\twritelines_data.append(ss)\n\texcept IndexError:\n\t\tbreak " % (QueueName_s) )
writequeue_code = compile(writequeue_cmd,'','exec')
exec(writequeue_code)
if options.verbose == True:
for t in writelines_data:
print (t.split(",")[-1])
else:
print ("no opendpi_class in input arff")
exit()
else:
max_length = 5000
else:
print ("not specified max queue length, not limited!")
output_file.write(arff_head_s[0])
# write opendpi_class_list
if is_opendpi_class:
output_file.write(arff_head_s[1])
for i in opendpi_class_list:
output_file.write( "%s," % i )
output_file.write(arff_head_s[2])
# write app_class_list
if is_app_class:
output_file.write(arff_head_s[3])
for i in app_class_list:
output_file.write( "%s," % i )
output_file.write(arff_head_s[4])
# write cata_class_list
if is_cata_class:
output_file.write(arff_head_s[5])
for i in cata_class_list:
output_file.write( "%s," % i )
output_file.write(arff_head_s[6])
# write @DATA
output_file.write(arff_head_s[7])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
from collections import deque
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC''',
'\n@ATTRIBUTE open_class {' ,
'}',
'\n@ATTRIBUTE app_class {',
'}',
'\n@ATTRIBUTE cata_class {',
'}',
'''
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
normal_prog=re.compile("[_0-9a-zA-Z]")
def FuckString(s):
ss = s.split(".")[0]
rs = ""
for i in ss:
if not re.match(normal_prog,i):
i = ''
rs += i
#print (rs)
return rs
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
parser.add_option("-s", "--set_queue_type", dest = "set_queue_type",
help = "set queue type: all, opendpi, app, cata, none\n\
all : maxmiun instances number\n\
none : not limited\n\
default/or not specified is opendpi queue.")
parser.add_option("-p","--pure_duplicatedflows",dest = "pureflow",
action="store_true",default=False,
help = "ignore duplicated flows")
parser.add_option("-n","--max_queue_len",dest = "max_queue_len",
help = "set maxmium queue length, default is 5000")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
elif os.path.isfile(options.from_path):
items.add(os.path.abspath(options.from_path ))
else:
print "not set input file/path"
exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
opendpi_class_list=[]
app_class_list=[]
cata_class_list=[]
opendpi_prog = re.compile("^@ATTRIBUTE\ open.*$")
app_prog = re.compile("^@ATTRIBUTE app.*$")
cata_prog = re.compile("^@ATTRIBUTE cata.*$")
content_prog = re.compile("{.*}")
data_prog = re.compile("^@DATA")
#magic_colum_couter=-1
is_opendpi_class = False
is_app_class = False
is_cata_class = False
fivetuples=[]
writelines_data=[]
for input_arff_filename in items:
is_opendpi_class = False
is_app_class = False
is_cata_class = False
magic_col_couter = 0
opendpi_col = -1
app_col = -1
cata_col = -1
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
opendpi_re = opendpi_prog.search(line)
if opendpi_re:
is_opendpi_class = True
magic_col_couter += -1
o = content_prog.search(opendpi_re.group(0) )
w = o.group(0)[1:-1]
#print (w)
v = w.split(",")
#print (v)
for vv in v:
if vv not in opendpi_class_list and vv !="":
opendpi_class_list.append(vv)
app_re = app_prog.match(line)
if app_re:
is_app_class = True
magic_col_couter += -1
o = content_prog.search ( app_re.group(0) )
w = o.group(0)[1:-1]
v = w.split(",")
for vv in v:
if vv not in app_class_list and vv !="":
app_class_list.append(vv)
#print (vv)
cata_re = cata_prog.match(line)
if cata_re:
is_cata_class = True
magic_col_couter += -1
o = content_prog.search ( cata_re.group(0) )
w = o.group(0)[1:-1]
v = w.split(",")
for vv in v:
if vv not in cata_class_list and vv !="":
cata_class_list.append(vv)
#print (vv)
#print (magic_col_couter)
opendpi_col = magic_col_couter
app_col = magic_col_couter +1
cata_col = magic_col_couter +2
m = data_prog.match(line)
if m:
foundData = True
continue
if ( foundData == True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#appname = input_arff_filename.split('@')[0].split(os.path.sep)[-1]
#print (appname)
writline=line.split(',')
if is_opendpi_class:
opendpi_class = writline[ opendpi_col ].strip()
if opendpi_class not in opendpi_class_list:
opendpi_class_list.append(opendpi_class)
if is_app_class:
app_class = writline[ app_col ].strip()
if app_class not in app_class_list:
app_class_list.append(app_class)
if is_cata_class:
cata_class = writline[ cata_col ].strip()
if cata_class not in cata_class_list:
cata_class_list.append(cata_class)
if (options.pureflow == True) :
s = writline[:5]
#s = ""
#for i in writline[:5]:
# s += i
if ( s not in fivetuples ):
if options.verbose == True:
print (i)
fivetuples.append(s)
writelines_data.append( line )
else:
if options.verbose == True:
print ("ignoring duplicated flows!")
pass
else:
writelines_data.append( line )
print (magic_col_couter)
p.close()
##print lists
if options.verbose == True:
print ("---opendpi_class_list{")
for i in opendpi_class_list:
print (i)
print ("}opendpi_class_list-----")
print ("---app_class_list{")
for i in app_class_list:
print (i)
print ("}app_class_list-----")
print ("---cata_class_list{")
for i in cata_class_list:
print (i)
print ("}cata_class_list-----")
print ("------------------------------")
QueueDict={}
QueueName_prefix = ""
if options.set_queue_type:
if options.max_queue_len:
max_length = int ( options.max_queue_len )
if options.set_queue_type == "all":
QueueName_prefix = 'mydeque_byall_'
elif options.set_queue_type == "cata":
if ( is_cata_class == True ):
QueueName_prefix = 'mydeque_bycata_'
for s in cata_class_list:
createqueue_cmd = ( "%s%s = deque(maxlen = max_length )\nQueueDict[\'%s\'] = %s%s " % (QueueName_prefix,s,s,QueueName_prefix,s ) )
createqueue_code = compile(createqueue_cmd,'','exec')
exec(createqueue_code)
#print (QueueDict)
for i in writelines_data:
#print (i)
cata_type = i.strip().split(",")[cata_col]
#print ( cata_type )
appendqueue_cmd = "QueueDict[\'%s\'].append(i)" % (cata_type)
appendqueue_code = compile(appendqueue_cmd,'','exec')
exec(appendqueue_code)
if options.verbose == True:
for s in cata_class_list:
printqueue_cmd = ( "print QueueDict['%s']" % s )
printqueue_code = compile(printqueue_cmd,'','exec')
exec(printqueue_code)
writelines_data=[]
for w in cata_class_list:
QueueName_s=QueueName_prefix+w
writequeue_cmd = ( "while True:\n\ttry:\n\t\tss = %s.pop()\n\t\t#print ss\n\t\twritelines_data.append(ss)\n\texcept IndexError:\n\t\tbreak " % (QueueName_s) )
writequeue_code = compile(writequeue_cmd,'','exec')
exec(writequeue_code)
if options.verbose == True:
for t in writelines_data:
print (t.split(",")[-1])
else:
print ("no cata_class in input arff")
exit()
elif options.set_queue_type == "app":
if ( is_app_class == True ):
QueueName_prefix='mydeque_byapp_'
for ss in app_class_list:
#print (ss)
#s = ss.split(".")[0]
s = FuckString(ss)
createqueue_cmd = ( "%s%s = deque(maxlen = max_length )\nQueueDict[\'%s\'] = %s%s " % (QueueName_prefix,s,s,QueueName_prefix,s ) )
createqueue_code = compile(createqueue_cmd,'','exec')
exec(createqueue_code)
#print (QueueDict)
for i in writelines_data:
#print (i)
a = i.strip().split(",")[app_col]
app_type = FuckString(a)
#print ( cata_type )
appendqueue_cmd = "QueueDict[\'%s\'].append(i)" % (app_type)
appendqueue_code = compile(appendqueue_cmd,'','exec')
exec(appendqueue_code)
if options.verbose == True:
for s in app_class_list:
printqueue_cmd = ( "print QueueDict['%s']" % s )
printqueue_code = compile(printqueue_cmd,'','exec')
exec(printqueue_code)
writelines_data=[]
for w in app_class_list:
rw = FuckString(w)
QueueName_s=QueueName_prefix+rw
writequeue_cmd = ( "while True:\n\ttry:\n\t\tss = %s.pop()\n\t\t#print ss\n\t\twritelines_data.append(ss)\n\texcept IndexError:\n\t\tbreak " % (QueueName_s) )
writequeue_code = compile(writequeue_cmd,'','exec')
exec(writequeue_code)
if options.verbose == True:
for t in writelines_data:
print (t.split(",")[-1])
else:
print ("no app_class in input arff")
exit()
elif options.set_queue_type == "opendpi":
if (is_opendpi_class == True) :
QueueName_prefix='mydeque_by_opendpi_'
for ss in opendpi_class_list:
#print (ss)
#s = ss.split(".")[0]
s = FuckString(ss)
createqueue_cmd = ( "%s%s = deque(maxlen = max_length )\nQueueDict[\'%s\'] = %s%s " % (QueueName_prefix,s,s,QueueName_prefix,s ) )
createqueue_code = compile(createqueue_cmd,'','exec')
exec(createqueue_code)
#print (QueueDict)
for i in writelines_data:
#print (i)
a = i.strip().split(",")[opendpi_col]
app_type = FuckString(a)
#print ( cata_type )
appendqueue_cmd = "QueueDict[\'%s\'].append(i)" % (app_type)
appendqueue_code = compile(appendqueue_cmd,'','exec')
exec(appendqueue_code)
if options.verbose == True:
for s in opendpi_class_list:
printqueue_cmd = ( "print QueueDict['%s']" % s )
printqueue_code = compile(printqueue_cmd,'','exec')
exec(printqueue_code)
writelines_data=[]
for w in opendpi_class_list:
rw = FuckString(w)
QueueName_s=QueueName_prefix+rw
writequeue_cmd = ( "while True:\n\ttry:\n\t\tss = %s.pop()\n\t\t#print ss\n\t\twritelines_data.append(ss)\n\texcept IndexError:\n\t\tbreak " % (QueueName_s) )
writequeue_code = compile(writequeue_cmd,'','exec')
exec(writequeue_code)
if options.verbose == True:
for t in writelines_data:
print (t.split(",")[-1])
else:
print ("no opendpi_class in input arff")
exit()
else:
max_length = 5000
else:
print ("not specified max queue length, not limited!")
output_file.write(arff_head_s[0])
# write opendpi_class_list
if is_opendpi_class:
output_file.write(arff_head_s[1])
for i in opendpi_class_list:
output_file.write( "%s," % i )
output_file.write(arff_head_s[2])
# write app_class_list
if is_app_class:
output_file.write(arff_head_s[3])
for i in app_class_list:
output_file.write( "%s," % i )
output_file.write(arff_head_s[4])
# write cata_class_list
if is_cata_class:
output_file.write(arff_head_s[5])
for i in cata_class_list:
output_file.write( "%s," % i )
output_file.write(arff_head_s[6])
# write @DATA
output_file.write(arff_head_s[7])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' , '''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
appname = input_arff_filename.split('@')[0].split('/')[-1]
print appname
writline=line
opendpi_class = writline.split(',')[-1].strip()
if opendpi_class not in applist:
applist.append(opendpi_class)
writelines_data.append( writline )
p.close()
#write output arff file
output_file.write(arff_head_s[0])
for i in applist:
output_file.write( "%s," % i )
output_file.write(arff_head_s[1])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' , '''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.merged.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
appname = input_arff_filename.split('@')[0].split('/')[-1]
print appname
writline=line.strip()+appname+"\n"
opendpi_class = writline.split(',')[-1].strip()
if opendpi_class not in applist:
applist.append(opendpi_class)
writelines_data.append( writline )
p.close()
#write output arff file
output_file.write(arff_head_s[0])
for i in applist:
output_file.write( "%s," % i )
output_file.write(arff_head_s[1])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
import appconfig as APPCONFIG
sys.stderr=sys.stdout
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_path_name",
metavar="OUTPUT_PATH", help="write output OUTPUT_PATH")
parser.add_option('-w',"--script",dest="outputScript",
default="runall.sh",
help="generate run.sh, default is ./runall.sh")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
arguments_list=[]
items = set()
if options.output_arff_path_name:
if os.path.isdir(options.output_arff_path_name):
output_real_path_file_name= os.path.abspath(options.output_arff_path_name)
elif os.path.isfile(options.output_arff_path_name):
print ("error, file exists, plz specify a director")
exit()
else:
APPCONFIG.mkdir_p(options.output_arff_path_name)
output_real_path_file_name=options.output_arff_path_name
patern=re.compile('[a-zA-Z]')
if options.from_path:
if os.path.isdir(options.from_path):
#for f in glob.glob(os.path.join(options.from_path, '*.pcap')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
for (thisDir, subsHere, filesHere) in os.walk(options.from_path):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
if( os.path.isfile(pcapfullname) and (extension==".pcap" or extension == ".PCAP" ) ):
m = shortname.split('.')[-1]
#print (m)
if patern.search(m): # in shortname.split('.')[-1]:
items.add(pcapfullname)
#print (shortname)
gg_path = os.path.join(thisDir,'*.xml')
gg = glob.glob(gg_path)
xmlfilename= shortname+'.xml'
realxml=''
r=os.path.join(thisDir,xmlfilename)
if os.path.isfile(r ):
print ("found xml: %s " % (r))
realxml=r
elif gg :
i = 0
for f in gg:
i+=1
print ("cannot found an exact xml file, use %d: %s instead" %(i,f))
realxml=f
else:
print("no xml found in %s" %(thisDir))
continue
outputpath=''
if options.output_arff_path_name:
outputpath=output_real_path_file_name
else:
outputpath=os.path.join(thisDir,( shortname+'.pcap.demux' ) )
a = (pcapfullname,realxml,outputpath)
arguments_list.append(a)
else:
continue
elif os.path.isfile(options.from_path):
items.add(options.from_path)
else:
print "not set input file/path"
exit()
for arg in args:
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
realpath=os.path.realpath(options.outputScript)
runfile=open(options.outputScript,'w')
writelines=[]
writeline=''
mergedarff_list=[]
for i in arguments_list:
print (i)
#for ii in i:
# runfile.write(ii)
writeline=( "flowsing.py -f %s -x %s -o %s -n\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
writeline=( "flowsing.py -f %s -x %s -o %s -c\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
writeline=( "flowsing.py -f %s -x %s -o %s -m\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
writeline=( "flowsing.py -f %s -x %s -o %s -g\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
mergearff=i[0]+".merged.arff"
mergedarff_list.append(mergearff)
writeline=( "arffmerge.py -f %s -o %s \n\n"%( i[2], mergearff ) )
writelines.append(writeline)
computed_arff_list=[]
yamlconf="catalogue.details.yaml"
for m in mergedarff_list:
outputarff = m+".ARFF"
computed_arff_list.append(outputarff)
#yamlconf="catalogue.details.yaml"
writeline= ( "catalogue.py -d -c %s -o %s -f %s\n\n\n" % (yamlconf,outputarff,m) )
writelines.append(writeline)
computed_arff_s=''
for n in computed_arff_list:
#print (n)
computed_arff_s+=n+" "
final_arff='ALLinONE.arff'
writeline= ( "topmerger2.py -q -p -n 3000 -s opendpi -o %s -f %s\n\n" % ( final_arff, computed_arff_s ) )
writelines.append(writeline)
writelines_s=''
for w in writelines:
writelines_s+=w
runfile.write(writelines_s)
runfile.close()
os.system("chmod +x %s" %(realpath) )
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' , '''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
appname = input_arff_filename.split('@')[0].split('/')[-1]
print appname
writline=line
opendpi_class = writline.split(',')[-1].strip()
if opendpi_class not in applist:
applist.append(opendpi_class)
writelines_data.append( writline )
p.close()
#write output arff file
output_file.write(arff_head_s[0])
for i in applist:
output_file.write( "%s," % i )
output_file.write(arff_head_s[1])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' , '''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.merged.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
appname = input_arff_filename.split('@')[0].split('/')[-1]
print appname
writline=line.strip()+appname+"\n"
opendpi_class = writline.split(',')[-1].strip()
if opendpi_class not in applist:
applist.append(opendpi_class)
writelines_data.append( writline )
p.close()
#write output arff file
output_file.write(arff_head_s[0])
for i in applist:
output_file.write( "%s," % i )
output_file.write(arff_head_s[1])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
import appconfig as APPCONFIG
sys.stderr=sys.stdout
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_path_name",
metavar="OUTPUT_PATH", help="write output OUTPUT_PATH")
parser.add_option('-w',"--script",dest="outputScript",
default="runall.sh",
help="generate run.sh, default is ./runall.sh")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
arguments_list=[]
items = set()
if options.output_arff_path_name:
if os.path.isdir(options.output_arff_path_name):
output_real_path_file_name= os.path.abspath(options.output_arff_path_name)
elif os.path.isfile(options.output_arff_path_name):
print ("error, file exists, plz specify a director")
exit()
else:
APPCONFIG.mkdir_p(options.output_arff_path_name)
output_real_path_file_name=options.output_arff_path_name
patern=re.compile('[a-zA-Z]')
if options.from_path:
if os.path.isdir(options.from_path):
#for f in glob.glob(os.path.join(options.from_path, '*.pcap')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
for (thisDir, subsHere, filesHere) in os.walk(options.from_path):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
if( os.path.isfile(pcapfullname) and (extension==".pcap" or extension == ".PCAP" ) ):
m = shortname.split('.')[-1]
#print (m)
if patern.search(m): # in shortname.split('.')[-1]:
items.add(pcapfullname)
#print (shortname)
gg_path = os.path.join(thisDir,'*.xml')
gg = glob.glob(gg_path)
xmlfilename= shortname+'.xml'
realxml=''
r=os.path.join(thisDir,xmlfilename)
if os.path.isfile(r ):
print ("found xml: %s " % (r))
realxml=r
elif gg :
i = 0
for f in gg:
i+=1
print ("cannot found an exact xml file, use %d: %s instead" %(i,f))
realxml=f
else:
print("no xml found in %s" %(thisDir))
continue
outputpath=''
if options.output_arff_path_name:
outputpath=output_real_path_file_name
else:
outputpath=os.path.join(thisDir,( shortname+'.pcap.demux' ) )
a = (pcapfullname,realxml,outputpath)
arguments_list.append(a)
else:
continue
elif os.path.isfile(options.from_path):
items.add(options.from_path)
else:
print "not set input file/path"
exit()
for arg in args:
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
realpath=os.path.realpath(options.outputScript)
runfile=open(options.outputScript,'w')
writelines=[]
writeline=''
mergedarff_list=[]
for i in arguments_list:
print (i)
#for ii in i:
# runfile.write(ii)
writeline=( "flowsing.py -f %s -x %s -o %s -n\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
writeline=( "flowsing.py -f %s -x %s -o %s -c\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
writeline=( "flowsing.py -f %s -x %s -o %s -m\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
writeline=( "flowsing.py -f %s -x %s -o %s -g\n" % (i[0], i[1], i[2]) )
writelines.append(writeline)
mergearff=i[0]+".merged.arff"
mergedarff_list.append(mergearff)
writeline=( "arffmerge.py -f %s -o %s \n\n"%( i[2], mergearff ) )
writelines.append(writeline)
computed_arff_list=[]
yamlconf="catalogue.details.yaml"
for m in mergedarff_list:
outputarff = m+".ARFF"
computed_arff_list.append(outputarff)
#yamlconf="catalogue.details.yaml"
writeline= ( "catalogue.py -d -c %s -o %s -f %s\n\n\n" % (yamlconf,outputarff,m) )
writelines.append(writeline)
computed_arff_s=''
for n in computed_arff_list:
#print (n)
computed_arff_s+=n+" "
final_arff='ALLinONE.arff'
writeline= ( "topmerger2.py -q -p -n 3000 -s opendpi -o %s -f %s\n\n" % ( final_arff, computed_arff_s ) )
writelines.append(writeline)
writelines_s=''
for w in writelines:
writelines_s+=w
runfile.write(writelines_s)
runfile.close()
os.system("chmod +x %s" %(realpath) )
exit()
| Python |
#!/usr/bin/env python
import os,sys,logging
import string
from exceptions import Exception
from optparse import OptionParser
import re
import glob
import yaml
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' ,
'}',
'\n@ATTRIBUTE app_class {',
'}',
'\n@ATTRIBUTE cata_class {',
'}',
'''
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
def LoadStream(FileName_s='default.yaml'):
f = file(FileName_s,'r')
stream=yaml.load(f)
return stream
def SaveStream(stream,FileName_s='default.yaml'):
f = file(FileName_s,'w')
yaml.dump(stream,f)
f.close()
def FindCataFromYAML(realapp_name,fromyaml):
#print ("looking for %s in %s"%(realapp_name,yamlfile))
#f=LoadStream(yamlfile)
for i in fromyaml:
for j in i['Applications']:
for k in i['Applications'][j]:
#print (k)
if k.lower() == realapp_name.lower():
return i['CatalogueName']
return "Others"
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",default=True,
help="be very quiet")
parser.add_option("-f", "--from_arff",dest="from_arff",
metavar="INPUT_ARFF", help="read from INPUT_ARFF")
parser.add_option("-o", "--output_arff",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
parser.add_option("-c","--catalogue",dest="cataloguefile",
metavar="catalogue", help="read from catalogue.yaml",)
parser.add_option("-d","--details",dest="isdetails",default=True,
action="store_true",
help="parser ")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'catalogue.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./catalogue.arff"
if options.cataloguefile:
catalogue_yaml_file=options.cataloguefile
else:
catalogue_yaml_file="catalogue.yaml"
if options.from_arff:
if os.path.isdir(options.from_arff):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
if os.path.isfile(options.from_arff):
items.add(options.from_arff)
elif '*' in options.from_arff:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
#output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
opendpi_class_list=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#appname = input_arff_filename.split('@')[0].split('/')[-1]
#print appname
writline=line
opendpi_class=''
pp_line = writline.split(',')[-1].strip()
p_line=pp_line.split('_')[-3:]
if not p_line[0] == 'notfound' :
#print p_line[-1]
opendpi_class=p_line[-1]
else:
#print ("ignore notfound apps")
continue
#a=re.compile('^[ \t]*\r?\n?$')
a=re.compile('^[ \t]*\r?\n?$')
if not a.match(opendpi_class):
if opendpi_class not in applist:
applist.append(opendpi_class)
if pp_line not in opendpi_class_list:
opendpi_class_list.append(pp_line)
#print (opendpi_class)
#for i in writline.split(',')[:-1]:
# writelines_data.append( i+"," )
writelines_data.append(writline.strip()+","+opendpi_class+"\n")
else:
print ("ignore blank apps:"),
print (opendpi_class)
continue
p.close()
#write output arff file
f_yaml=LoadStream(catalogue_yaml_file)
realapp_list=[]
cata_list=[]
final_data_to_write=[]
for write_item in writelines_data:
splited=write_item.strip().split(',')
realapp=splited[-1]
if options.isdetails:
cata=FindCataFromYAML(splited[-2],f_yaml)
else:
cata=FindCataFromYAML(splited[-1],f_yaml)
if cata not in cata_list:
cata_list.append(cata)
if realapp not in realapp_list:
realapp_list.append(realapp)
final_data_to_write.append(write_item.strip()+","+cata+"\n")
output_file = open(output_real_arff_file_name,'a')
#opendpi_class_list=[]
output_file.write(arff_head_s[0])
print("opendpi_class:")
for i in opendpi_class_list:
output_file.write( "%s," % i )
print("\t%s"%i)
output_file.write(arff_head_s[1])
output_file.write(arff_head_s[2])
print ("realapp_class:")
for i in realapp_list:
output_file.write( "%s,"% i )
print ("\t%s"%i)
output_file.write(arff_head_s[3])
output_file.write(arff_head_s[4])
print ("catalogue_class:")
for i in cata_list:
output_file.write("%s,"%i)
print ("\t%s"%i)
output_file.write(arff_head_s[5])
output_file.write(arff_head_s[6])
for ii in final_data_to_write:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/python
# Copyright (c)
#
# pcapy: open_offline, pcapdumper.
# ImpactDecoder.
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
import pcapy
from pcapy import open_offline
import impacket
from impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder
import appconfig as APPCONFIG
import ipdef as IPDEF
sys.stderr=sys.stdout
try:
from lxml import etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree")
except ImportError:
logging.info("Failed to import ElementTree from any known place")
this_dir = os.path.dirname(__file__)
if this_dir not in sys.path:
sys.path.insert(0, this_dir) # needed for Py3
#from common_imports import etree, StringIO, BytesIO, HelperTestCase, fileInTestDir
#from common_imports import SillyFileLike, LargeFileLikeUnicode, doctest, make_doctest
#from common_imports import canonicalize, sorted, _str, _bytes
try:
_unicode = unicode
except NameError:
# Python 3
_unicode = str
ETHERNET_MAX_FRAME_SIZE = 1518
PROMISC_MODE = 0
class Connection:
"""This class can be used as a key in a dictionary to select a connection
given a pair of peers. Two connections are considered the same if both
peers are equal, despite the order in which they were passed to the
class constructor.
"""
def __init__(self, p1, p2, p3):
"""This constructor takes two tuples, one for each peer. The first
element in each tuple is the IP address as a string, and the
second is the port as an integer.
"""
self.p1 = p1
self.p2 = p2
#self.p3 = p3
self.proto_id=int(p3)
self.protocol = "unknown"
self.curpath= "."
def getFilename(self):
"""Utility function that returns a filename composed by the IP
addresses and ports of both peers.
"""
try:
if self.proto_id:
if self.proto_id == socket.IPPROTO_TCP:
self.protocol = "TCP"
elif self.proto_id == socket.IPPROTO_UDP:
self.protocol = "UDP"
else:
self.protocol = IPDEF.ip_protocols[self.proto_id]
except Exception, e:
logging.error("failed setting protocol. Error: %s" % str(e))
#APPCONFIG.GlobalConfig["appname"] = self.FindNameFromXML(self.p1, self.p2, self.protocol)
appname_s= self.FindNameFromXML(self.p1, self.p2, self.protocol)
#global this_dir
self.curpath=APPCONFIG.GlobalConfig["outputpathname"]+os.path.sep+appname_s+os.path.sep
#self.curpath=os.path.join(APPCONFIG.GlobalConfig["outputpathname"],APPCONFIG.GlobalConfig["appname"])
APPCONFIG.mkdir_p(self.curpath)
#print (self.curpath, self.p1[0],self.p1[1],self.protocol, self.p2[0],self.p2[1])
m ='%s%s-%s-%s-%s-%s.pcap' % (self.curpath, self.p1[0], str(self.p1[1] ),self.protocol, str(self.p2[0] ),self.p2[1])
return m
def FindNameFromXML(self, src, dst, protocol):
for line in APPCONFIG.xmlbuffer:
if (line[2][1] == src[0] and line[3][1] ==str(src[1]) and line[4][1] == dst[0] and line[5][1] == str(dst[1]) and line[6][1] == protocol ):
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ( "found!: application %s, PID %s"% (line[0][1] , line[1][1] ))
app_str= line[0][1] +"@"+line[1][1]
app_str_limited=''
p = re.compile('[a-zA-Z0-9,.@]')
for i in app_str:
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='-'
return app_str_limited
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ("missed!....")
return "notfound_in_XML@0"
def getNetdudeFileName(self):
netdude_output_path=APPCONFIG.GlobalConfig['tmp_netdude_path']
proto_number = self.proto_id
s_ip=self.p1[0]
s_port=self.p1[1]
d_ip=self.p2[0]
d_port=self.p2[1]
fullpath1 = "%s%s%d%s%s%s%s"%(netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
s_ip,
os.path.sep,
d_ip)
fullpath2 = "%s%s%d%s%s%s%s"% (netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
d_ip,
os.path.sep,
s_ip)
fullpath=[fullpath1,fullpath2]
ports1="*-%s-%s.trace" % (s_port,d_port)
ports2="*-%s-%s.trace" % (d_port,s_port)
port_pair = [ports1,ports2]
tracename_list=[]
#print ports2
for i_path in fullpath:
#print (i_path),
if os.path.isdir(i_path):
for i_port in port_pair:
#print (i_port)
fullfilename=i_path+os.path.sep+i_port
#print (fullfilename)
for f in glob.glob(fullfilename):
#print (f)
if os.path.isfile(f):
tracename_list.append(f)
return tracename_list
def __cmp__(self, other):
if ((self.p1 == other.p1 and self.p2 == other.p2)
or (self.p1 == other.p2 and self.p2 == other.p1)):
return 0
else:
return -1
def __hash__(self):
return (hash(self.p1[0]) ^ hash(self.p1[1])^ hash(self.proto_id)
^ hash(self.p2[0]) ^ hash(self.p2[1]))
class Decoder:
def __init__(self, pcapObj):
# Query the type of the link and instantiate a decoder accordingly.
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def start(self):
# Sniff ad infinitum.
# PacketHandler shall be invoked by pcap for every packet.
self.pcap.loop(0, self.packetHandler)
def packetHandler(self, hdr, data):
"""Handles an incoming pcap packet. This method only knows how
to recognize TCP/IP connections.
Be sure that only TCP packets are passed onto this handler (or
fix the code to ignore the others).
Setting r"ip proto \tcp" as part of the pcap filter expression
suffices, and there shouldn't be any problem combining that with
other expressions.
"""
# Use the ImpactDecoder to turn the rawpacket into a hierarchy
# of ImpactPacket instances.
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
#ip = p.child()
#tcp = ip.child()
# Build a distinctive key for this pair of peers.
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#os.remove(tmpPCAPFileName)
#open(tmpPCAPFileName, 'w').close()
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#if not self.connections.has_key(con):
if con not in self.connections:
logging.info("found flow for the first time: saving to %s" % outputPCAPFileName)
#self.connections[con]=1
self.connections.append(con)
try:
open(outputPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
else:
logging.info( "found duplicated flows, creating a tempfile: %s to append to %s" % (tmpPCAPFileName,outputPCAPFileName) )
try:
open(tmpPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(tmpPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error("Can't write packet to:\n---%s ", tmpPCAPFileName,str(e) )
##Write the packet to the corresponding file.
del dumper
tmpPCAPFileName2 = "/tmp/append2.pcap"
if os.path.isfile(outputPCAPFileName):
#os.rename( outputPCAPFileName , tmpPCAPFileName2 )
os.system("mv %s %s"%( outputPCAPFileName, tmpPCAPFileName2 ))
appendpcap_cmd_1 = "mergecap -w %s %s %s " % (outputPCAPFileName,tmpPCAPFileName2,tmpPCAPFileName)
#appendpcap_cmd_1="pcapnav-concat %s %s"%(outputPCAPFileName, tmpPCAPFileName)
os.system(appendpcap_cmd_1)
#self.connections[con] += 1
os.remove(tmpPCAPFileName2)
#os.rename(tmpPCAPFileName2,outputPCAPFileName)
#logging.info ( self.connections[con] )
else:
logging.error( "did nothing" )
logging.error("%s is in %s\ntry again!!!" % (outputPCAPFileName, str(con in self.connections) ))
try:
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
logging.error("succeded =%s" % str(os.path.isfile(outputPCAPFileName)))
class NetdudeDecoder(Decoder):
"""
"""
def __init__(self,pcapObj ):
"""
"""
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def packetHandler(self, hdr, data):
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
merge_cmd1="mergecap -w %s" % (outputPCAPFileName)
merge_cmd_readtrace_filename=' '
readPCAPFileNameFromNetdude=con.getNetdudeFileName()
for rr in readPCAPFileNameFromNetdude:
merge_cmd_readtrace_filename += ( "%s " % (rr) )
merge_cmd = ("%s%s" % (merge_cmd1, merge_cmd_readtrace_filename) )
print (merge_cmd)
os.system(merge_cmd)
print ("------")
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
import shutil
def SplitPcapByNetdude():
shutil.rmtree(APPCONFIG.GlobalConfig["tmp_netdude_path"],ignore_errors=True)
netdude_cmd1=( "lndtool -r Demux -o %s %s" % (APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["pcapfilename"]) )
os.system(netdude_cmd1)
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#print filename
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
print "Reading from %s: linktype=%d" % (filename, p.datalink())
# Start decoding process.
NetdudeDecoder(p).start()
os.system('ls %s' % (APPCONFIG.GlobalConfig["tmp_netdude_path"] ))
os.system("rm -rf %s"% (APPCONFIG.GlobalConfig["tmp_netdude_path"] ) )
def getFiveTupleListFromDemuxedPath(demuxedpath):
#print ("in getFiveTupleFromDemuxedPath")
fivetuplelist=[]
for (thisDir, subsHere, filesHere) in os.walk(demuxedpath):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
if( os.path.isfile(pcapfullname) and (extension==".trace" or extension == ".TRACE" ) ):
ipprotocol_pair=thisDir.split(os.path.sep)[-3:]
pro_num=ipprotocol_pair[0]
ip_pair=ipprotocol_pair[-2:]
if ipprotocol_pair[0] in ['6','17']:
port_pair=shortname.split('-')[-2:]
a = ((ip_pair[0],port_pair[0]),(ip_pair[1],port_pair[1]),pro_num)
fivetuplelist.append(a)
else:
logging.info ("no ip protocol %s "%(ipprotocol_pair[0]))
return fivetuplelist
def SplitPcapByTraverseNetdudeDir():
shutil.rmtree(APPCONFIG.GlobalConfig["tmp_netdude_path"],ignore_errors=True)
netdude_cmd1=( "lndtool -r Demux -o %s %s" % (APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["pcapfilename"]) )
os.system(netdude_cmd1)
# Start decoding process.
#print ("%s\n%s\n%s"% (APPCONFIG.GlobalConfig["xmlfilename"], APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["outputpathname"]) )
xmlFilename =APPCONFIG.GlobalConfig['xmlfilename']
tmpNetdudeDir = APPCONFIG.GlobalConfig['tmp_netdude_path']
outputDir = APPCONFIG.GlobalConfig['outputpathname']
fivetupleList=getFiveTupleListFromDemuxedPath(tmpNetdudeDir)
connections = []
merge_cmd=''
for i in fivetupleList:
#print (i)
con = Connection(i[0],i[1],i[2])
if con not in connections:
connections.append(con)
outputPCAPFileName=con.getFilename()
inputPCAPFileNameList=con.getNetdudeFileName()
#print (outputPCAPFileName)
#print (inputPCAPFileNameList)
merge_cmd1="mergecap -w %s" % (outputPCAPFileName)
merge_cmd_readtrace_filename=' '
for rr in inputPCAPFileNameList:
merge_cmd_readtrace_filename += ( "%s " % (rr) )
merge_cmd = ("%s%s" % (merge_cmd1, merge_cmd_readtrace_filename) )
print (merge_cmd)
os.system(merge_cmd)
else:
print ("duplicated! in SplitPcapByTraverseNetdudeDir")
print i
os.system('ls %s' % (APPCONFIG.GlobalConfig["tmp_netdude_path"] ))
#os.system("rm -rf %s"% (APPCONFIG.GlobalConfig["tmp_netdude_path"] ) )
#os.system(merge_cmd)
def main():
#mkdir output_path
APPCONFIG.mkdir_p(APPCONFIG.GlobalConfig["outputpathname"])
xmlfile=open(APPCONFIG.GlobalConfig["xmlfilename"], 'r')
root = etree.parse(xmlfile)
for element in root.iter("session"):
line=element.attrib.items()
APPCONFIG.xmlbuffer.append(line)
if APPCONFIG.GlobalConfig["isNetdude"] == True:
logging.info("splitting pcap trace into flows by netdude")
#SplitPcapByNetdude()
SplitPcapByTraverseNetdudeDir()
if APPCONFIG.GlobalConfig["isSplit"]==True:
logging.info("splitting pcap trace into flows")
SplitPcap()
if APPCONFIG.GlobalConfig["isMerge"]==True:
logging.info("Merging flows into applications")
MergepcapInDir(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig["isFeature"]==True:
logging.info("computing flow features")
FeatureCompute(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig['ismergearff']==True:
logging.info ("merging arff filenames")
MergeARFF(APPCONFIG.GlobalConfig["outputpathname"])
logging.info("---done---")
def SplitPcap():
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#logging.info (filename )
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
logging.info ("Reading from %s: linktype=%d" % (filename, p.datalink()) )
# Start decoding process.
Decoder(p).start()
#p.close() #flk3y: avoid p.close() error, after GC?
def FeatureCompute(currentdirname):
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
#featurefilename =
if( os.path.isfile(pcapfullname) and (extension==".pcap" or extension == ".PCAP" ) ):
#fullfeaturefilename=pcapfullname+".arff"
#cmd1_s= "rm %s" % (APPCONFIG.GlobalConfig['tmp_arff_filename'])
if os.path.isfile(APPCONFIG.GlobalConfig['tmp_arff_filename']):
os.remove(APPCONFIG.GlobalConfig['tmp_arff_filename'])
cmd1_s='OpenDPI_demo -f %s' % pcapfullname
p = Popen(cmd1_s, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,close_fds=True)
output = p.stdout.read()
prog=re.compile("###.*###")
m = prog.search(output)
p = re.compile('[a-zA-Z0-9,.@#_]')
app_str_limited=''
for i in m.group(0):
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='='
appfilename=pcapfullname+"."+app_str_limited+".arff"
logging.info ("computing feature to: %s" % appfilename)
cmd2_s= "netmate -f %s" % (pcapfullname )
cmd3_s= "mv %s %s"%(APPCONFIG.GlobalConfig['tmp_arff_filename'],appfilename)
#os.system(cmd1_s)
#os.system(cmd2_s)
#os.system(cmd3_s)
allcmd_s=("%s && %s"%(cmd2_s,cmd3_s))
os.system(allcmd_s)
else:
logging.info ("%s is not a directory" % pcapfullname )
pass
def MergepcapInDir(currentdirname):#TODO: add mergecap files into a list, then pop up when merging
all_cmd_s=[]
BATCH_NUM=50
tmp_pcap="/tmp/tmp_pcap"
os.system(("rm -f %s%s*.pcap ")%(currentdirname,os.sep))
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in subsHere:
#print ("==%s" % filename)
fullname = os.path.join(thisDir,filename)
if(os.path.isdir(fullname) ):
pcapname=fullname+".pcap"
print ("==%s" % filename)
os.system(("rm -f %s ")%(tmp_pcap))
pcap_list=[]
#if os.path.isfile(pcapname):
# os.remove(pcapname)
for (f_dir,f_subs,f_files) in os.walk(fullname):
pcap_f=[]
for f in f_files:
if (f[-5:] == '.pcap'):
pcap_f.append(f_dir+os.sep+f)
#print (pcap_f)
while (len(pcap_f) != 0):
tmp_s=""
pcap_f_length=len(pcap_f)
if (pcap_f_length >=BATCH_NUM):
for i in range(BATCH_NUM) :
tmp_s =tmp_s+" "+pcap_f.pop()+" "
pcap_list.append(tmp_s)
else:
for i in range(pcap_f_length):
tmp_s=tmp_s+" "+pcap_f.pop()+" "
#print (tmp_s)
pcap_list.append(tmp_s)
print ("remaining pcap %d files to read" % pcap_f_length)
#print (pcap_list)
#for i in pcap_list:
# #cmd_s='mergecap -w %s %s' % (pcapname,i)
# all_cmd_s.append(i)
#print (cmd_s)
#print (all_cmd_s)
print ("----- %s ------\ntmp_pcap output_pcap" % pcapname)
logging.info ("%s is a directory, merging all pcap files in it" % fullname )
for i in pcap_list:
if ( os.path.isfile(tmp_pcap) and os.path.isfile(pcapname) ):
print (" Y Y :You'd better not be here, but it OK")
os.remove(tmp_pcap)
#os.rename(pcapname,tmp_pcap)
os.system( "mv %s %s"% ( pcapname , tmp_pcap) )
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
elif ( os.path.isfile(tmp_pcap) and (not os.path.isfile(pcapname)) ):
print (" Y N :You should not be here! there may errors happened ")
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
elif ((not os.path.isfile(tmp_pcap)) and (os.path.isfile(pcapname)) ) :
print (" N Y")
#os.rename(pcapname,tmp_pcap)
os.system( "mv %s %s" % ( pcapname,tmp_pcap ) )
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
else:
print ("creating...\n N N")
cmd="mergecap -w %s %s" % (pcapname,i)
#print (cmd)
os.system(cmd)
else:
logging.info ("%s is not a directory" % fullname )
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpiclass {''',
'''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
def MergeARFF(currentdirname):
global arff_head_s
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for dirname in subsHere:
fullsubdirname = os.path.join(thisDir,dirname)
if(os.path.isdir(fullsubdirname) ):
#appendable=False
arff_big_name=fullsubdirname+".merged.arff"
opendpiclass_list=[]
writelines_data=[]
if (os.path.isfile(arff_big_name)) :
os.remove(arff_big_name)
appendable = True
#q_arff_big = open(arff_big_name,'a')
#q_arff_big.write(arff_head_s[0])
#q_arff_big.write("test")
#q_arff_big.write(arff_head_s[1])
logging.info ("%s is a directory, merging all arff files in it" % fullsubdirname )
for (sub_thisdir,sub_subshere,sub_filesHere ) in os.walk(fullsubdirname):
for filename in sub_filesHere:
(shortname, extension) = os.path.splitext(filename)
foundData=False
#appendable=False
#logging.info ("merging %s" % filename)
if( (extension==".arff" or extension == ".ARFF" ) and (shortname[-3:]=='###' ) ):
logging.info ("merging %s" % filename)
opendpi_apptype=shortname.split('.')[-1][3:-3] # for example: blah.blah.blah.###type1_type2_###
logging.error (opendpi_apptype)
if opendpi_apptype not in opendpiclass_list:
opendpiclass_list.append(opendpi_apptype)
full_arff_name = os.path.join(sub_thisdir,filename)
if appendable == True:
p = open(full_arff_name,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData=True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#q_arff_big.write
writelines_data.append( (line.strip()+","+opendpi_apptype+"\n") )
q_arff_big = open(arff_big_name,'a')
q_arff_big.write(arff_head_s[0])
for i in opendpiclass_list:
q_arff_big.write( "%s," % i )
q_arff_big.write(arff_head_s[1])
for ii in writelines_data:
q_arff_big.write(ii)
q_arff_big.close()
else:
logging.info ("%s is not a directory" % fullname )
pass
def ParseCMD():
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-x","--xmlfilename",dest="xmlfilename",
metavar="XML", help= "read XML, which was generated by network bandwith monitor")
parser.add_option("-f", "--pcapfilename",dest="pcapfilename",
metavar="FILE", help="write output to FILE")
parser.add_option("-o", "--output_path",dest="output_path",
metavar="OUTPUT_PATH", help="write output OUTPUT_PATH/FILE.demux")
#parser.add_option('-M', '--MODE',
# type='choice',
# action='store',
# dest='modechoice',
# choices=['all','split_only', 'merge_only', 'feature_only',],
# default='all',
# help='mode to run on: all, split_only, merge_only, feature_only',)
parser.add_option("-a", "--all",
default=False,
dest='isall',
action='store_true',
help="enable all: split->merge->calculate features ",)
parser.add_option("-s","--split",
default=False,
dest='issplit',
action='store_true',
help="split pcap trace into flows",)
parser.add_option("-m","--merge",
default=False,
dest='ismerge',
action='store_true',
help="merge flows from the same application into one pcap trace",)
parser.add_option("-g","--mergearff",
default=False,
dest='ismergearff',
action='store_true',
help="merge .arff files from the same application into one",)
parser.add_option("-c","--computefeatures",
default=False,
dest='isfeature',
action='store_true',
help="compute features for every pcap file in OUTPUT_PATH",)
parser.add_option("-n","--netdude",
default=False,
dest='isNetdude',
action='store_true',
help="enable libnetdude's demuxer")
(options, args) = parser.parse_args()
#if len(args) != 1:
# parser.error("incorrect number of arguments")
if options.pcapfilename:
APPCONFIG.GlobalConfig["pcapfilename"] = options.pcapfilename
if options.output_path:
APPCONFIG.GlobalConfig["outputpathname"] = options.output_path
else:
APPCONFIG.GlobalConfig["outputpathname"] = options.pcapfilename+".demux"
if options.xmlfilename:
APPCONFIG.GlobalConfig["xmlfilename"]= options.xmlfilename
if options.isall:
APPCONFIG.GlobalConfig['isAll']=True
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.isNetdude:
options.isNetdude=True
options.issplit=False
APPCONFIG.GlobalConfig['isSplit']=False
APPCONFIG.GlobalConfig['isNetdude']=True
if options.issplit:
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
if options.ismerge:
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
if options.ismergearff:
options.ismergearff=True
APPCONFIG.GlobalConfig['ismergearff']=True
if options.isfeature:
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.verbose:
APPCONFIG.GlobalConfig['isVerbose']=True
logging.info ("------running info.---------")
logging.info ("Reading xmlfile %s..." % options.xmlfilename)
logging.info ("Reading pcapfile %s..." % options.pcapfilename)
if options.output_path:
logging.info ("demux to path: %s"%options.output_path)
else:
logging.info ("have not assigned, output to %s.demux by default"%options.pcapfilename)
logging.info ( "Split pcap trace: %s" % str(APPCONFIG.GlobalConfig['isSplit']) )
logging.info ( "Merge flows into applications: %s"% str(APPCONFIG.GlobalConfig['isMerge']) )
logging.info ( "compute features: %s"% str(APPCONFIG.GlobalConfig['isFeature']) )
logging.info ("------------end info.------------")
# Process command-line arguments.
if __name__ == '__main__':
ParseCMD()
main()
exit()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A pure Python GlobalConfig implementation. Copyright (c) 2010, flk3y """
__version__ = '0.1'
import os
import sys
GlobalConfig = {'xmlfilename':"test.xml",
'pcapfilename':"test.pcap",
'outputpathname':"outputdir",
'appname':"default_app",
'tmp_arff_filename':"/tmp/testdata.log",
'tmp_netdude_path':"/tmp/netdude_demux",
'isALL':False,
'isSplit':False,
'isMerge':False,
'isFeature':False,
'isVerbose':False,
'ismergearff':False,
'isNetdude':False,
}
xmlbuffer=[]
def mkdir_p(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
"""
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
head, tail = os.path.split(newdir)
if head and not os.path.isdir(head):
os.mkdir(head)
#print "_mkdir %s" % repr(newdir)
if tail:
os.mkdir(newdir)
| Python |
# Type of service (ip_tos), RFC 1349 ("obsoleted by RFC 2474")
IP_TOS_DEFAULT = 0x00 # default
IP_TOS_LOWDELAY = 0x10 # low delay
IP_TOS_THROUGHPUT = 0x08 # high throughput
IP_TOS_RELIABILITY = 0x04 # high reliability
IP_TOS_LOWCOST = 0x02 # low monetary cost - XXX
IP_TOS_ECT = 0x02 # ECN-capable transport
IP_TOS_CE = 0x01 # congestion experienced
# IP precedence (high 3 bits of ip_tos), hopefully unused
IP_TOS_PREC_ROUTINE = 0x00
IP_TOS_PREC_PRIORITY = 0x20
IP_TOS_PREC_IMMEDIATE = 0x40
IP_TOS_PREC_FLASH = 0x60
IP_TOS_PREC_FLASHOVERRIDE = 0x80
IP_TOS_PREC_CRITIC_ECP = 0xa0
IP_TOS_PREC_INTERNETCONTROL = 0xc0
IP_TOS_PREC_NETCONTROL = 0xe0
# Fragmentation flags (ip_off)
IP_RF = 0x8000 # reserved
IP_DF = 0x4000 # don't fragment
IP_MF = 0x2000 # more fragments (not last frag)
IP_OFFMASK = 0x1fff # mask for fragment offset
# Time-to-live (ip_ttl), seconds
IP_TTL_DEFAULT = 64 # default ttl, RFC 1122, RFC 1340
IP_TTL_MAX = 255 # maximum ttl
# Type of service (ip_tos), RFC 1349 ("obsoleted by RFC 2474")
IP_TOS_DEFAULT = 0x00 # default
IP_TOS_LOWDELAY = 0x10 # low delay
IP_TOS_THROUGHPUT = 0x08 # high throughput
IP_TOS_RELIABILITY = 0x04 # high reliability
IP_TOS_LOWCOST = 0x02 # low monetary cost - XXX
IP_TOS_ECT = 0x02 # ECN-capable transport
IP_TOS_CE = 0x01 # congestion experienced
# IP precedence (high 3 bits of ip_tos), hopefully unused
IP_TOS_PREC_ROUTINE = 0x00
IP_TOS_PREC_PRIORITY = 0x20
IP_TOS_PREC_IMMEDIATE = 0x40
IP_TOS_PREC_FLASH = 0x60
IP_TOS_PREC_FLASHOVERRIDE = 0x80
IP_TOS_PREC_CRITIC_ECP = 0xa0
IP_TOS_PREC_INTERNETCONTROL = 0xc0
IP_TOS_PREC_NETCONTROL = 0xe0
# Fragmentation flags (ip_off)
IP_RF = 0x8000 # reserved
IP_DF = 0x4000 # don't fragment
IP_MF = 0x2000 # more fragments (not last frag)
IP_OFFMASK = 0x1fff # mask for fragment offset
# Time-to-live (ip_ttl), seconds
IP_TTL_DEFAULT = 64 # default ttl, RFC 1122, RFC 1340
IP_TTL_MAX = 255 # maximum ttl
# Protocol (ip_p) - http://www.iana.org/assignments/protocol-numbers
IP_PROTO_IP = 0 # dummy for IP
IP_PROTO_HOPOPTS = IP_PROTO_IP # IPv6 hop-by-hop options
IP_PROTO_ICMP = 1 # ICMP
IP_PROTO_IGMP = 2 # IGMP
IP_PROTO_GGP = 3 # gateway-gateway protocol
IP_PROTO_IPIP = 4 # IP in IP
IP_PROTO_ST = 5 # ST datagram mode
IP_PROTO_TCP = 6 # TCP
IP_PROTO_CBT = 7 # CBT
IP_PROTO_EGP = 8 # exterior gateway protocol
IP_PROTO_IGP = 9 # interior gateway protocol
IP_PROTO_BBNRCC = 10 # BBN RCC monitoring
IP_PROTO_NVP = 11 # Network Voice Protocol
IP_PROTO_PUP = 12 # PARC universal packet
IP_PROTO_ARGUS = 13 # ARGUS
IP_PROTO_EMCON = 14 # EMCON
IP_PROTO_XNET = 15 # Cross Net Debugger
IP_PROTO_CHAOS = 16 # Chaos
IP_PROTO_UDP = 17 # UDP
IP_PROTO_MUX = 18 # multiplexing
IP_PROTO_DCNMEAS = 19 # DCN measurement
IP_PROTO_HMP = 20 # Host Monitoring Protocol
IP_PROTO_PRM = 21 # Packet Radio Measurement
IP_PROTO_IDP = 22 # Xerox NS IDP
IP_PROTO_TRUNK1 = 23 # Trunk-1
IP_PROTO_TRUNK2 = 24 # Trunk-2
IP_PROTO_LEAF1 = 25 # Leaf-1
IP_PROTO_LEAF2 = 26 # Leaf-2
IP_PROTO_RDP = 27 # "Reliable Datagram" proto
IP_PROTO_IRTP = 28 # Inet Reliable Transaction
IP_PROTO_TP = 29 # ISO TP class 4
IP_PROTO_NETBLT = 30 # Bulk Data Transfer
IP_PROTO_MFPNSP = 31 # MFE Network Services
IP_PROTO_MERITINP = 32 # Merit Internodal Protocol
IP_PROTO_SEP = 33 # Sequential Exchange proto
IP_PROTO_3PC = 34 # Third Party Connect proto
IP_PROTO_IDPR = 35 # Interdomain Policy Route
IP_PROTO_XTP = 36 # Xpress Transfer Protocol
IP_PROTO_DDP = 37 # Datagram Delivery Proto
IP_PROTO_CMTP = 38 # IDPR Ctrl Message Trans
IP_PROTO_TPPP = 39 # TP++ Transport Protocol
IP_PROTO_IL = 40 # IL Transport Protocol
IP_PROTO_IP6 = 41 # IPv6
IP_PROTO_SDRP = 42 # Source Demand Routing
IP_PROTO_ROUTING = 43 # IPv6 routing header
IP_PROTO_FRAGMENT = 44 # IPv6 fragmentation header
IP_PROTO_IDRP = 45 # Inter-Domain Routing Protocol [Hares]
IP_PROTO_RSVP = 46 # Reservation protocol
IP_PROTO_GRE = 47 # General Routing Encap
IP_PROTO_MHRP = 48 # Mobile Host Routing
IP_PROTO_ENA = 49 # ENA
IP_PROTO_ESP = 50 # Encap Security Payload
IP_PROTO_AH = 51 # Authentication Header
IP_PROTO_INLSP = 52 # Integated Net Layer Sec
IP_PROTO_SWIPE = 53 # SWIPE
IP_PROTO_NARP = 54 # NBMA Address Resolution
IP_PROTO_MOBILE = 55 # Mobile IP, RFC 2004
IP_PROTO_TLSP = 56 # Transport Layer Security
IP_PROTO_SKIP = 57 # SKIP
IP_PROTO_ICMP6 = 58 # ICMP for IPv6
IP_PROTO_NONE = 59 # IPv6 no next header
IP_PROTO_DSTOPTS = 60 # IPv6 destination options
IP_PROTO_ANYHOST = 61 # any host internal proto
IP_PROTO_CFTP = 62 # CFTP
IP_PROTO_ANYNET = 63 # any local network
IP_PROTO_EXPAK = 64 # SATNET and Backroom EXPAK
IP_PROTO_KRYPTOLAN = 65 # Kryptolan
IP_PROTO_RVD = 66 # MIT Remote Virtual Disk
IP_PROTO_IPPC = 67 # Inet Pluribus Packet Core
IP_PROTO_DISTFS = 68 # any distributed fs
IP_PROTO_SATMON = 69 # SATNET Monitoring
IP_PROTO_VISA = 70 # VISA Protocol
IP_PROTO_IPCV = 71 # Inet Packet Core Utility
IP_PROTO_CPNX = 72 # Comp Proto Net Executive
IP_PROTO_CPHB = 73 # Comp Protocol Heart Beat
IP_PROTO_WSN = 74 # Wang Span Network
IP_PROTO_PVP = 75 # Packet Video Protocol
IP_PROTO_BRSATMON = 76 # Backroom SATNET Monitor
IP_PROTO_SUNND = 77 # SUN ND Protocol
IP_PROTO_WBMON = 78 # WIDEBAND Monitoring
IP_PROTO_WBEXPAK = 79 # WIDEBAND EXPAK
IP_PROTO_EON = 80 # ISO CNLP
IP_PROTO_VMTP = 81 # Versatile Msg Transport
IP_PROTO_SVMTP = 82 # Secure VMTP
IP_PROTO_VINES = 83 # VINES
IP_PROTO_TTP = 84 # TTP
IP_PROTO_NSFIGP = 85 # NSFNET-IGP
IP_PROTO_DGP = 86 # Dissimilar Gateway Proto
IP_PROTO_TCF = 87 # TCF
IP_PROTO_EIGRP = 88 # EIGRP
IP_PROTO_OSPF = 89 # Open Shortest Path First
IP_PROTO_SPRITERPC = 90 # Sprite RPC Protocol
IP_PROTO_LARP = 91 # Locus Address Resolution
IP_PROTO_MTP = 92 # Multicast Transport Proto
IP_PROTO_AX25 = 93 # AX.25 Frames
IP_PROTO_IPIPENCAP = 94 # yet-another IP encap
IP_PROTO_MICP = 95 # Mobile Internet Ctrl
IP_PROTO_SCCSP = 96 # Semaphore Comm Sec Proto
IP_PROTO_ETHERIP = 97 # Ethernet in IPv4
IP_PROTO_ENCAP = 98 # encapsulation header
IP_PROTO_ANYENC = 99 # private encryption scheme
IP_PROTO_GMTP = 100 # GMTP
IP_PROTO_IFMP = 101 # Ipsilon Flow Mgmt Proto
IP_PROTO_PNNI = 102 # PNNI over IP
IP_PROTO_PIM = 103 # Protocol Indep Multicast
IP_PROTO_ARIS = 104 # ARIS
IP_PROTO_SCPS = 105 # SCPS
IP_PROTO_QNX = 106 # QNX
IP_PROTO_AN = 107 # Active Networks
IP_PROTO_IPCOMP = 108 # IP Payload Compression
IP_PROTO_SNP = 109 # Sitara Networks Protocol
IP_PROTO_COMPAQPEER = 110 # Compaq Peer Protocol
IP_PROTO_IPXIP = 111 # IPX in IP
IP_PROTO_VRRP = 112 # Virtual Router Redundancy
IP_PROTO_PGM = 113 # PGM Reliable Transport
IP_PROTO_ANY0HOP = 114 # 0-hop protocol
IP_PROTO_L2TP = 115 # Layer 2 Tunneling Proto
IP_PROTO_DDX = 116 # D-II Data Exchange (DDX)
IP_PROTO_IATP = 117 # Interactive Agent Xfer
IP_PROTO_STP = 118 # Schedule Transfer Proto
IP_PROTO_SRP = 119 # SpectraLink Radio Proto
IP_PROTO_UTI = 120 # UTI
IP_PROTO_SMP = 121 # Simple Message Protocol
IP_PROTO_SM = 122 # SM
IP_PROTO_PTP = 123 # Performance Transparency
IP_PROTO_ISIS = 124 # ISIS over IPv4
IP_PROTO_FIRE = 125 # FIRE
IP_PROTO_CRTP = 126 # Combat Radio Transport
IP_PROTO_CRUDP = 127 # Combat Radio UDP
IP_PROTO_SSCOPMCE = 128 # SSCOPMCE
IP_PROTO_IPLT = 129 # IPLT
IP_PROTO_SPS = 130 # Secure Packet Shield
IP_PROTO_PIPE = 131 # Private IP Encap in IP
IP_PROTO_SCTP = 132 # Stream Ctrl Transmission
IP_PROTO_FC = 133 # Fibre Channel
IP_PROTO_RSVPIGN = 134 # RSVP-E2E-IGNORE
IP_PROTO_Mobility_Header = 135 #Mobility Header
IP_PROTO_UDPLite =136 #UDPLite
IP_PROTO_MPLS_in_IP =137 #MPLS-in-IP
IP_PROTO_MANET =138 #MANET
IP_PROTO_HIP =139 #HIP
IP_PROTO_Shim6 =140 #Shim6
IP_PROTO_WESP =141 #WESP
IP_PROTO_ROHC =142 #ROHC
IP_PROTO_RAW = 255 # Raw IP packets
IP_PROTO_RESERVED = IP_PROTO_RAW # Reserved
IP_PROTO_MAX = 255
ip_protocols = {
IP_PROTO_IP : 'HOPOPT', #dummy for IP
IP_PROTO_HOPOPTS : 'HOPOPT', #IPv6 hop-by-hop options
IP_PROTO_ICMP : 'ICMP', #IPv6 hop-by-hop options
IP_PROTO_IGMP : 'IGMP', #ICMP
IP_PROTO_GGP : 'GGP', #IGMP
IP_PROTO_IPIP : 'IPv4', #IP in IP
IP_PROTO_ST : 'ST', #ST datagram mode
IP_PROTO_TCP : 'TCP', #TCP
IP_PROTO_CBT : 'CBT', #CBT
IP_PROTO_EGP : 'EGP', #exterior gateway protocol
IP_PROTO_IGP : 'IGP', #interior gateway protocol
IP_PROTO_BBNRCC : 'BBN-RCC-MON', #BBN RCC monitoring
IP_PROTO_NVP : 'NVP-II', #Network Voice Protocol
IP_PROTO_PUP : 'PUP', #PARC universal packet
IP_PROTO_ARGUS : 'ARGUS', #ARGUS
IP_PROTO_EMCON : 'EMCON', #EMCON
IP_PROTO_XNET : 'XNET', #Cross Net Debugger
IP_PROTO_CHAOS : 'CHAOS', #Chaos
IP_PROTO_UDP : 'UDP', #UDP
IP_PROTO_MUX : 'MUX', #multiplexing
IP_PROTO_DCNMEAS : 'DCN-MEAS', #DCN measurement
IP_PROTO_HMP : 'HMP', #Host Monitoring Protocol
IP_PROTO_PRM : 'PRM', #Packet Radio Measurement
IP_PROTO_IDP : 'XNS-IDP', #Xerox NS IDP
IP_PROTO_TRUNK1 : 'TRUNK-1', #Trunk-1
IP_PROTO_TRUNK2 : 'TRUNK-2', #Trunk-2
IP_PROTO_LEAF1 : 'LEAF-1', #Leaf-1
IP_PROTO_LEAF2 : 'LEAF-2', #Leaf-2
IP_PROTO_RDP : 'RDP', #Reliable Datagram proto
IP_PROTO_IRTP : 'IRTP', #Inet Reliable Transaction
IP_PROTO_TP : 'ISO-TP4', #ISO TP class 4
IP_PROTO_NETBLT : 'NETBLT', #Bulk Data Transfer
IP_PROTO_MFPNSP : 'MFE-NSP', #MFE Network Services
IP_PROTO_MERITINP : 'MERIT-INP', #Merit Internodal Protocol
IP_PROTO_SEP : 'DCCP', #Sequential Exchange proto
IP_PROTO_3PC : '3PC', #Third Party Connect proto
IP_PROTO_IDPR : 'IDPR', #Interdomain Policy Route
IP_PROTO_XTP : 'XTP', #Xpress Transfer Protocol
IP_PROTO_DDP : 'DDP', #Datagram Delivery Proto
IP_PROTO_CMTP : 'IDPR-CMTP', #IDPR Ctrl Message Trans
IP_PROTO_TPPP : 'TP++', #TP++ Transport Protocol
IP_PROTO_IL : 'IL', #IL Transport Protocol
IP_PROTO_IP6 : 'IPv6', #IPv6
IP_PROTO_SDRP : 'SDRP', #Source Demand Routing
IP_PROTO_ROUTING : 'IPv6-Route', #IPv6 routing header
IP_PROTO_FRAGMENT : 'IPv6-Frag', #IPv6 fragmentation header
IP_PROTO_IDRP : 'IDRP', #Inter-Domain Routing Protocol [Hares]
IP_PROTO_RSVP : 'RSVP', #Reservation protocol
IP_PROTO_GRE : 'GRE', #General Routing Encap
IP_PROTO_MHRP : 'DSR', #Mobile Host Routing
IP_PROTO_ENA : 'BNA', #ENA
IP_PROTO_ESP : 'ESP', #Encap Security Payload
IP_PROTO_AH : 'AH', #Authentication Header
IP_PROTO_INLSP : 'I-NLSP', #Integated Net Layer Sec
IP_PROTO_SWIPE : 'SWIPE', #SWIPE
IP_PROTO_NARP : 'NARP', #NBMA Address Resolution
IP_PROTO_MOBILE : 'MOBILE', #Mobile IP, RFC 2004
IP_PROTO_TLSP : 'TLSP', #Transport Layer Security
IP_PROTO_SKIP : 'SKIP', #SKIP
IP_PROTO_ICMP6 : 'IPv6-ICMP', #IPv6 ICMP
IP_PROTO_NONE : 'IPv6-NoNxt', #IPv6 no next header
IP_PROTO_DSTOPTS : 'IPv6-Opts', #IPv6 destination options
IP_PROTO_ANYHOST : 'ANYHOST', #any host internal proto
IP_PROTO_CFTP : 'CFTP', #CFTP
IP_PROTO_ANYNET : 'ANYNET', #any local network
IP_PROTO_EXPAK : 'SAT-EXPAK', #SATNET and Backroom EXPAK
IP_PROTO_KRYPTOLAN : 'KRYPTOLAN', #Kryptolan
IP_PROTO_RVD : 'RVD', #MIT Remote Virtual Disk
IP_PROTO_IPPC : 'IPPC', #Inet Pluribus Packet Core
IP_PROTO_DISTFS : 'DISTFS', #any distributed fs
IP_PROTO_SATMON : 'SAT-MON', #SATNET Monitoring
IP_PROTO_VISA : 'VISA', #VISA Protocol
IP_PROTO_IPCV : 'IPCV', #Inet Packet Core Utility
IP_PROTO_CPNX : 'CPNX', #Comp Proto Net Executive
IP_PROTO_CPHB : 'CPHB', #Comp Protocol Heart Beat
IP_PROTO_WSN : 'WSN', #Wang Span Network
IP_PROTO_PVP : 'PVP', #Packet Video Protocol
IP_PROTO_BRSATMON : 'BR-SAT-MON', #Backroom SATNET Monitor
IP_PROTO_SUNND : 'SUN-ND', #SUN ND Protocol
IP_PROTO_WBMON : 'WB-MON', #WIDEBAND Monitoring
IP_PROTO_WBEXPAK : 'WB-EXPAK', #WIDEBAND EXPAK
IP_PROTO_EON : 'ISO-IP', #ISO CNLP
IP_PROTO_VMTP : 'VMTP', #Versatile Msg Transport
IP_PROTO_SVMTP : 'SECURE-VMTP', #Secure VMTP
IP_PROTO_VINES : 'VINES', #VINES
IP_PROTO_TTP : 'TTP', #TTP
IP_PROTO_NSFIGP : 'NSFNET-IGP', #NSFNET-IGP
IP_PROTO_DGP : 'DGP', #Dissimilar Gateway Proto
IP_PROTO_TCF : 'TCF', #TCF
IP_PROTO_EIGRP : 'EIGRP', #EIGRP
IP_PROTO_OSPF : 'OSPFIGP', #Open Shortest Path First
IP_PROTO_SPRITERPC : 'Sprite-RPC', #Sprite RPC Protocol
IP_PROTO_LARP : 'LARP', #Locus Address Resolution
IP_PROTO_MTP : 'MTP', #Multicast Transport Proto
IP_PROTO_AX25 : 'AX.25', #AX.25 Frames
IP_PROTO_IPIPENCAP : 'IPIP', #yet-another IP encap
IP_PROTO_MICP : 'MICP', #Mobile Internet Ctrl
IP_PROTO_SCCSP : 'SCC-SP', #Semaphore Comm Sec Proto
IP_PROTO_ETHERIP : 'ETHERIP', #Ethernet in IPv4
IP_PROTO_ENCAP : 'ENCAP', #encapsulation header
IP_PROTO_ANYENC : 'ANYENC', #Ipsilon #private encryption scheme
IP_PROTO_GMTP : 'GMTP', #GMTP
IP_PROTO_IFMP : 'IFMP', #Flow Mgmt Proto
IP_PROTO_PNNI : 'PNNI', #PNNI over IP
IP_PROTO_PIM : 'PIM', #Protocol Indep Multicast
IP_PROTO_ARIS : 'ARIS', #ARIS
IP_PROTO_SCPS : 'SCPS', #SCPS
IP_PROTO_QNX : 'QNX', #QNX
IP_PROTO_AN : 'A_N', #Active Networks
IP_PROTO_IPCOMP : 'IPComp', #IP Payload Compression
IP_PROTO_SNP : 'SNP', #Sitara Networks Protocol
IP_PROTO_COMPAQPEER : 'Compaq-Peer', #Compaq Peer Protocol
IP_PROTO_IPXIP : 'IPX-in-IP', #IPX in IP
IP_PROTO_VRRP : 'VRRP', #Virtual Router Redundancy
IP_PROTO_PGM : 'PGM', #PGM Reliable Transport
IP_PROTO_ANY0HOP : 'ANY0HOP', #0-hop protocol
IP_PROTO_L2TP : 'L2TP', #Layer 2 Tunneling Proto
IP_PROTO_DDX : 'DDX', #Data Exchange (DDX)
IP_PROTO_IATP : 'IATP', #Interactive Agent Xfer
IP_PROTO_STP : 'STP', #Schedule Transfer Proto
IP_PROTO_SRP : 'SRP', #SpectraLink Radio Proto
IP_PROTO_UTI : 'UTI', #UTI
IP_PROTO_SMP : 'SMP', #Simple Message Protocol
IP_PROTO_SM : 'SM', #SM
IP_PROTO_PTP : 'PTP', #Performance Transparency
IP_PROTO_ISIS : 'ISIS', #ISIS over IPv4
IP_PROTO_FIRE : 'FIRE', #FIRE
IP_PROTO_CRTP : 'CRTP', #over IPv4 #Combat Radio Transport
IP_PROTO_CRUDP : 'CRUDP', #Combat Radio UDP
IP_PROTO_SSCOPMCE : 'SSCOPMCE', #SSCOPMCE
IP_PROTO_IPLT : 'IPLT', #IPLT
IP_PROTO_SPS : 'SPS', #Secure Packet Shield
IP_PROTO_PIPE : 'PIPE', #Private IP Encap in IP
IP_PROTO_SCTP : 'SCTP', #Stream Ctrl Transmission
IP_PROTO_FC : 'FC', #Fibre Channel
IP_PROTO_RSVPIGN : 'RSVP-E2E-IGNORE', #RSVP-E2E-IGNORE
IP_PROTO_Mobility_Header : 'Mobility_Header', #Mobility Header
IP_PROTO_UDPLite : 'UDPLite', #UDPLite
IP_PROTO_MPLS_in_IP : 'MPLS-in-IP', #MPLS-in-IP
IP_PROTO_MANET : 'MANET', #MANET
IP_PROTO_HIP : 'HIP', #HIP
IP_PROTO_Shim6 : 'Shime6', #Shim6
IP_PROTO_WESP : 'WESP', #WESP
IP_PROTO_ROHC : 'ROHC', #ROHC
IP_PROTO_RAW : 'RAW', #raw
IP_PROTO_RESERVED : 'RESERVED', #Reserved
IP_PROTO_MAX : 'MAX', #Reserved
}
ip_protocols_rev = {
'HOPOPT' : IP_PROTO_IP , #dummy for IP
'HOPOPT' : IP_PROTO_HOPOPTS, #IPv6 hop-by-hop options
'ICMP' : IP_PROTO_ICMP , #IPv6 hop-by-hop options
'IGMP' : IP_PROTO_IGMP , #ICMP
'GGP' : IP_PROTO_GGP , #IGMP
'IPv4' : IP_PROTO_IPIP , #IP in IP
'ST' : IP_PROTO_ST , #ST datagram mode
'TCP' : IP_PROTO_TCP , #TCP
'CBT' : IP_PROTO_CBT , #CBT
'EGP' : IP_PROTO_EGP , #exterior gateway protocol
'IGP' : IP_PROTO_IGP , #interior gateway protocol
'BBN-RCC-MON' : IP_PROTO_BBNRCC , #BBN RCC monitoring
'NVP-II' : IP_PROTO_NVP , #Network Voice Protocol
'PUP' : IP_PROTO_PUP , #PARC universal packet
'ARGUS' : IP_PROTO_ARGUS , #ARGUS
'EMCON' : IP_PROTO_EMCON , #EMCON
'XNET' : IP_PROTO_XNET , #Cross Net Debugger
'CHAOS' : IP_PROTO_CHAOS , #Chaos
'UDP' : IP_PROTO_UDP , #UDP
'MUX' : IP_PROTO_MUX , #multiplexing
'DCN-MEAS' : IP_PROTO_DCNMEAS , #DCN measurement
'HMP' : IP_PROTO_HMP , #Host Monitoring Protocol
'PRM' : IP_PROTO_PRM , #Packet Radio Measurement
'XNS-IDP' : IP_PROTO_IDP , #Xerox NS IDP
'TRUNK-1' : IP_PROTO_TRUNK1 , #Trunk-1
'TRUNK-2' : IP_PROTO_TRUNK2 , #Trunk-2
'LEAF-1' : IP_PROTO_LEAF1 , #Leaf-1
'LEAF-2' : IP_PROTO_LEAF2 , #Leaf-2
'RDP' : IP_PROTO_RDP , #Reliable Datagram proto
'IRTP' : IP_PROTO_IRTP , #Inet Reliable Transaction
'ISO-TP4' : IP_PROTO_TP , #ISO TP class 4
'NETBLT' : IP_PROTO_NETBLT , #Bulk Data Transfer
'MFE-NSP' : IP_PROTO_MFPNSP , #MFE Network Services
'MERIT-INP' : IP_PROTO_MERITINP , #Merit Internodal Protocol
'DCCP' : IP_PROTO_SEP , #Sequential Exchange proto
'3PC' : IP_PROTO_3PC , #Third Party Connect proto
'IDPR' : IP_PROTO_IDPR , #Interdomain Policy Route
'XTP' : IP_PROTO_XTP , #Xpress Transfer Protocol
'DDP' : IP_PROTO_DDP , #Datagram Delivery Proto
'IDPR-CMTP' : IP_PROTO_CMTP , #IDPR Ctrl Message Trans
'TP++' : IP_PROTO_TPPP , #TP++ Transport Protocol
'IL' : IP_PROTO_IL , #IL Transport Protocol
'IPv6' : IP_PROTO_IP6 , #IPv6
'SDRP' : IP_PROTO_SDRP , #Source Demand Routing
'IPv6-Route' : IP_PROTO_ROUTING , #IPv6 routing header
'IPv6-Frag' : IP_PROTO_FRAGMENT , #IPv6 fragmentation header
'IDRP' : IP_PROTO_IDRP , #Inter-Domain Routing Protocol [Hares]
'RSVP' : IP_PROTO_RSVP , #Reservation protocol
'GRE' : IP_PROTO_GRE , #General Routing Encap
'DSR' : IP_PROTO_MHRP, #Mobile Host Routing
'BNA' : IP_PROTO_ENA , #ENA
'ESP' : IP_PROTO_ESP , #Encap Security Payload
'AH' : IP_PROTO_AH , #Authentication Header
'I-NLSP' : IP_PROTO_INLSP , #Integated Net Layer Sec
'SWIPE' : IP_PROTO_SWIPE , #SWIPE
'NARP' : IP_PROTO_NARP , #NBMA Address Resolution
'MOBILE' : IP_PROTO_MOBILE , #Mobile IP , RFC 2004
'TLSP' : IP_PROTO_TLSP , #Transport Layer Security
'SKIP' : IP_PROTO_SKIP , #SKIP
'IPv6-ICMP' : IP_PROTO_ICMP6 , #IPv6 ICMP
'IPv6-NoNxt' : IP_PROTO_NONE , #IPv6 no next header
'IPv6-Opts' : IP_PROTO_DSTOPTS , #IPv6 destination options
'ANYHOST' : IP_PROTO_ANYHOST , #any host internal proto
'CFTP' : IP_PROTO_CFTP , #CFTP
'ANYNET' : IP_PROTO_ANYNET , #any local network
'SAT-EXPAK' : IP_PROTO_EXPAK , #SATNET and Backroom EXPAK
'KRYPTOLAN' : IP_PROTO_KRYPTOLAN , #Kryptolan
'RVD' : IP_PROTO_RVD , #MIT Remote Virtual Disk
'IPPC' : IP_PROTO_IPPC , #Inet Pluribus Packet Core
'DISTFS' : IP_PROTO_DISTFS , #any distributed fs
'SAT-MON' : IP_PROTO_SATMON , #SATNET Monitoring
'VISA' : IP_PROTO_VISA , #VISA Protocol
'IPCV' : IP_PROTO_IPCV , #Inet Packet Core Utility
'CPNX' : IP_PROTO_CPNX , #Comp Proto Net Executive
'CPHB' : IP_PROTO_CPHB , #Comp Protocol Heart Beat
'WSN' : IP_PROTO_WSN , #Wang Span Network
'PVP' : IP_PROTO_PVP , #Packet Video Protocol
'BR-SAT-MON' : IP_PROTO_BRSATMON , #Backroom SATNET Monitor
'SUN-ND' : IP_PROTO_SUNND , #SUN ND Protocol
'WB-MON' : IP_PROTO_WBMON , #WIDEBAND Monitoring
'WB-EXPAK' : IP_PROTO_WBEXPAK , #WIDEBAND EXPAK
'ISO-IP' : IP_PROTO_EON , #ISO CNLP
'VMTP' : IP_PROTO_VMTP , #Versatile Msg Transport
'SECURE-VMTP' : IP_PROTO_SVMTP , #Secure VMTP
'VINES' : IP_PROTO_VINES , #VINES
'TTP' : IP_PROTO_TTP , #TTP
'NSFNET-IGP' : IP_PROTO_NSFIGP , #NSFNET-IGP
'DGP' : IP_PROTO_DGP , #Dissimilar Gateway Proto
'TCF' : IP_PROTO_TCF , #TCF
'EIGRP' : IP_PROTO_EIGRP , #EIGRP
'OSPFIGP' : IP_PROTO_OSPF , #Open Shortest Path First
'Sprite-RPC' : IP_PROTO_SPRITERPC , #Sprite RPC Protocol
'LARP' : IP_PROTO_LARP , #Locus Address Resolution
'MTP' : IP_PROTO_MTP , #Multicast Transport Proto
'AX.25' : IP_PROTO_AX25 , #AX.25 Frames
'IPIP' : IP_PROTO_IPIPENCAP, #yet-another IP encap
'MICP' : IP_PROTO_MICP , #Mobile Internet Ctrl
'SCC-SP' : IP_PROTO_SCCSP , #Semaphore Comm Sec Proto
'ETHERIP' : IP_PROTO_ETHERIP , #Ethernet in IPv4
'ENCAP' : IP_PROTO_ENCAP , #encapsulation header
'ANYENC' : IP_PROTO_ANYENC , #Ipsilon #private encryption scheme
'GMTP' : IP_PROTO_GMTP , #GMTP
'IFMP' : IP_PROTO_IFMP , #Flow Mgmt Proto
'PNNI' : IP_PROTO_PNNI , #PNNI over IP
'PIM' : IP_PROTO_PIM , #Protocol Indep Multicast
'ARIS' : IP_PROTO_ARIS , #ARIS
'SCPS' : IP_PROTO_SCPS , #SCPS
'QNX' : IP_PROTO_QNX , #QNX
'A_N' : IP_PROTO_AN , #Active Networks
'IPComp' : IP_PROTO_IPCOMP , #IP Payload Compression
'SNP' : IP_PROTO_SNP , #Sitara Networks Protocol
'Compaq-Peer' : IP_PROTO_COMPAQPEER , #Compaq Peer Protocol
'IPX-in-IP' : IP_PROTO_IPXIP , #IPX in IP
'VRRP' : IP_PROTO_VRRP , #Virtual Router Redundancy
'PGM' : IP_PROTO_PGM , #PGM Reliable Transport
'ANY0HOP' : IP_PROTO_ANY0HOP, #0-hop protocol
'L2TP' : IP_PROTO_L2TP , #Layer 2 Tunneling Proto
'DDX' : IP_PROTO_DDX , #Data Exchange (DDX)
'IATP' : IP_PROTO_IATP , #Interactive Agent Xfer
'STP' : IP_PROTO_STP , #Schedule Transfer Proto
'SRP' : IP_PROTO_SRP , #SpectraLink Radio Proto
'UTI' : IP_PROTO_UTI , #UTI
'SMP' : IP_PROTO_SMP , #Simple Message Protocol
'SM' : IP_PROTO_SM , #SM
'PTP' : IP_PROTO_PTP , #Performance Transparency
'ISIS' : IP_PROTO_ISIS , #ISIS over IPv4
'FIRE' : IP_PROTO_FIRE , #FIRE
'CRTP' : IP_PROTO_CRTP , #over IPv4 #Combat Radio Transport
'CRUDP' : IP_PROTO_CRUDP , #Combat Radio UDP
'SSCOPMCE' : IP_PROTO_SSCOPMCE , #SSCOPMCE
'IPLT' : IP_PROTO_IPLT , #IPLT
'SPS' : IP_PROTO_SPS , #Secure Packet Shield
'PIPE' : IP_PROTO_PIPE , #Private IP Encap in IP
'SCTP' : IP_PROTO_SCTP , #Stream Ctrl Transmission
'FC' : IP_PROTO_FC , #Fibre Channel
'RSVP-E2E-IGNORE' : IP_PROTO_RSVPIGN , #RSVP-E2E-IGNORE
'Mobility_Header' : IP_PROTO_Mobility_Header , #Mobility Header
'UDPLite' : IP_PROTO_UDPLite , #UDPLite
'MPLS-in-IP' : IP_PROTO_MPLS_in_IP , #MPLS-in-IP
'MANET' : IP_PROTO_MANET , #MANET
'HIP' : IP_PROTO_HIP , #HIP
'Shime6' : IP_PROTO_Shim6 , #Shim6
'WESP' : IP_PROTO_WESP , #WESP
'ROHC' : IP_PROTO_ROHC , #ROHC
'RAW' : IP_PROTO_RAW , #raw
'RESERVED' : IP_PROTO_RESERVED , #Reserved
'MAX' : IP_PROTO_MAX , #Reserved
}
import unittest
class IPTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testIP_protocols(self):
for i in range(143):
print ("protocol no. %d is %s"%(i, ip_protocols[i]) )
#print ("6 is %s"%( ip_protocols[6]))
assert 'TCP' == ip_protocols[6]
def testIP_protocols_rev(self):
for i in range(143):
print ("protocol %s is no. %d "%(ip_protocols[i], ip_protocols_rev[ip_protocols[i]]) )
#print ("TCP is %s"%( ip_protocols_rev['TCP']))
assert 6 == ip_protocols_rev['TCP']
def testIP_IPrev(self):
for i in range(143):
assert ( i==ip_protocols_rev[ip_protocols[i]] )
def test_suite():
suite = unittest.TestSuite()
suite.addTests([unittest.makeSuite(IPTestCase)])
return suite
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
import os,sys,logging
import string
from exceptions import Exception
from optparse import OptionParser
import re
import glob
import yaml
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' ,
'}',
'\n@ATTRIBUTE app_class {',
'}',
'\n@ATTRIBUTE cata_class {',
'}',
'''
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
def LoadStream(FileName_s='default.yaml'):
f = file(FileName_s,'r')
stream=yaml.load(f)
return stream
def SaveStream(stream,FileName_s='default.yaml'):
f = file(FileName_s,'w')
yaml.dump(stream,f)
f.close()
def FindCataFromYAML(realapp_name,fromyaml):
#print ("looking for %s in %s"%(realapp_name,yamlfile))
#f=LoadStream(yamlfile)
for i in fromyaml:
for j in i['Applications']:
for k in i['Applications'][j]:
#print (k)
if k.lower() == realapp_name.lower():
return i['CatalogueName']
return "Others"
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",default=True,
help="be very quiet")
parser.add_option("-f", "--from_arff",dest="from_arff",
metavar="INPUT_ARFF", help="read from INPUT_ARFF")
parser.add_option("-o", "--output_arff",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
parser.add_option("-c","--catalogue",dest="cataloguefile",
metavar="catalogue", help="read from catalogue.yaml",)
parser.add_option("-d","--details",dest="isdetails",default=True,
action="store_true",
help="parser ")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'catalogue.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./catalogue.arff"
if options.cataloguefile:
catalogue_yaml_file=options.cataloguefile
else:
catalogue_yaml_file="catalogue.yaml"
if options.from_arff:
if os.path.isdir(options.from_arff):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
if os.path.isfile(options.from_arff):
items.add(options.from_arff)
elif '*' in options.from_arff:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
#output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
opendpi_class_list=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#appname = input_arff_filename.split('@')[0].split('/')[-1]
#print appname
writline=line
opendpi_class=''
pp_line = writline.split(',')[-1].strip()
p_line=pp_line.split('_')[-3:]
if not p_line[0] == 'notfound' :
#print p_line[-1]
opendpi_class=p_line[-1]
else:
#print ("ignore notfound apps")
continue
#a=re.compile('^[ \t]*\r?\n?$')
a=re.compile('^[ \t]*\r?\n?$')
if not a.match(opendpi_class):
if opendpi_class not in applist:
applist.append(opendpi_class)
if pp_line not in opendpi_class_list:
opendpi_class_list.append(pp_line)
#print (opendpi_class)
#for i in writline.split(',')[:-1]:
# writelines_data.append( i+"," )
writelines_data.append(writline.strip()+","+opendpi_class+"\n")
else:
print ("ignore blank apps:"),
print (opendpi_class)
continue
p.close()
#write output arff file
f_yaml=LoadStream(catalogue_yaml_file)
realapp_list=[]
cata_list=[]
final_data_to_write=[]
for write_item in writelines_data:
splited=write_item.strip().split(',')
realapp=splited[-1]
if options.isdetails:
cata=FindCataFromYAML(splited[-2],f_yaml)
else:
cata=FindCataFromYAML(splited[-1],f_yaml)
if cata not in cata_list:
cata_list.append(cata)
if realapp not in realapp_list:
realapp_list.append(realapp)
final_data_to_write.append(write_item.strip()+","+cata+"\n")
output_file = open(output_real_arff_file_name,'a')
#opendpi_class_list=[]
output_file.write(arff_head_s[0])
print("opendpi_class:")
for i in opendpi_class_list:
output_file.write( "%s," % i )
print("\t%s"%i)
output_file.write(arff_head_s[1])
output_file.write(arff_head_s[2])
print ("realapp_class:")
for i in realapp_list:
output_file.write( "%s,"% i )
print ("\t%s"%i)
output_file.write(arff_head_s[3])
output_file.write(arff_head_s[4])
print ("catalogue_class:")
for i in cata_list:
output_file.write("%s,"%i)
print ("\t%s"%i)
output_file.write(arff_head_s[5])
output_file.write(arff_head_s[6])
for ii in final_data_to_write:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/python
# Copyright (c)
#
# pcapy: open_offline, pcapdumper.
# ImpactDecoder.
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
import pcapy
from pcapy import open_offline
import impacket
from impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder
import appconfig as APPCONFIG
import ipdef as IPDEF
sys.stderr=sys.stdout
try:
from lxml import etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree")
except ImportError:
logging.info("Failed to import ElementTree from any known place")
this_dir = os.path.dirname(__file__)
if this_dir not in sys.path:
sys.path.insert(0, this_dir) # needed for Py3
#from common_imports import etree, StringIO, BytesIO, HelperTestCase, fileInTestDir
#from common_imports import SillyFileLike, LargeFileLikeUnicode, doctest, make_doctest
#from common_imports import canonicalize, sorted, _str, _bytes
try:
_unicode = unicode
except NameError:
# Python 3
_unicode = str
ETHERNET_MAX_FRAME_SIZE = 1518
PROMISC_MODE = 0
class Connection:
"""This class can be used as a key in a dictionary to select a connection
given a pair of peers. Two connections are considered the same if both
peers are equal, despite the order in which they were passed to the
class constructor.
"""
def __init__(self, p1, p2, p3):
"""This constructor takes two tuples, one for each peer. The first
element in each tuple is the IP address as a string, and the
second is the port as an integer.
"""
self.p1 = p1
self.p2 = p2
#self.p3 = p3
self.proto_id=int(p3)
self.protocol = "unknown"
self.curpath= "."
def getFilename(self):
"""Utility function that returns a filename composed by the IP
addresses and ports of both peers.
"""
try:
if self.proto_id:
if self.proto_id == socket.IPPROTO_TCP:
self.protocol = "TCP"
elif self.proto_id == socket.IPPROTO_UDP:
self.protocol = "UDP"
else:
self.protocol = IPDEF.ip_protocols[self.proto_id]
except Exception, e:
logging.error("failed setting protocol. Error: %s" % str(e))
#APPCONFIG.GlobalConfig["appname"] = self.FindNameFromXML(self.p1, self.p2, self.protocol)
appname_s= self.FindNameFromXML(self.p1, self.p2, self.protocol)
#global this_dir
self.curpath=APPCONFIG.GlobalConfig["outputpathname"]+os.path.sep+appname_s+os.path.sep
#self.curpath=os.path.join(APPCONFIG.GlobalConfig["outputpathname"],APPCONFIG.GlobalConfig["appname"])
APPCONFIG.mkdir_p(self.curpath)
#print (self.curpath, self.p1[0],self.p1[1],self.protocol, self.p2[0],self.p2[1])
m ='%s%s-%s-%s-%s-%s.pcap' % (self.curpath, self.p1[0], str(self.p1[1] ),self.protocol, str(self.p2[0] ),self.p2[1])
return m
def FindNameFromXML(self, src, dst, protocol):
for line in APPCONFIG.xmlbuffer:
if (line[2][1] == src[0] and line[3][1] ==str(src[1]) and line[4][1] == dst[0] and line[5][1] == str(dst[1]) and line[6][1] == protocol ):
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ( "found!: application %s, PID %s"% (line[0][1] , line[1][1] ))
app_str= line[0][1] +"@"+line[1][1]
app_str_limited=''
p = re.compile('[a-zA-Z0-9,.@]')
for i in app_str:
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='-'
return app_str_limited
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ("missed!....")
return "notfound_in_XML@0"
def getNetdudeFileName(self):
netdude_output_path=APPCONFIG.GlobalConfig['tmp_netdude_path']
proto_number = self.proto_id
s_ip=self.p1[0]
s_port=self.p1[1]
d_ip=self.p2[0]
d_port=self.p2[1]
fullpath1 = "%s%s%d%s%s%s%s"%(netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
s_ip,
os.path.sep,
d_ip)
fullpath2 = "%s%s%d%s%s%s%s"% (netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
d_ip,
os.path.sep,
s_ip)
fullpath=[fullpath1,fullpath2]
ports1="*-%s-%s.trace" % (s_port,d_port)
ports2="*-%s-%s.trace" % (d_port,s_port)
port_pair = [ports1,ports2]
tracename_list=[]
#print ports2
for i_path in fullpath:
#print (i_path),
if os.path.isdir(i_path):
for i_port in port_pair:
#print (i_port)
fullfilename=i_path+os.path.sep+i_port
#print (fullfilename)
for f in glob.glob(fullfilename):
#print (f)
if os.path.isfile(f):
tracename_list.append(f)
return tracename_list
def __cmp__(self, other):
if ((self.p1 == other.p1 and self.p2 == other.p2)
or (self.p1 == other.p2 and self.p2 == other.p1)):
return 0
else:
return -1
def __hash__(self):
return (hash(self.p1[0]) ^ hash(self.p1[1])^ hash(self.proto_id)
^ hash(self.p2[0]) ^ hash(self.p2[1]))
class Decoder:
def __init__(self, pcapObj):
# Query the type of the link and instantiate a decoder accordingly.
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def start(self):
# Sniff ad infinitum.
# PacketHandler shall be invoked by pcap for every packet.
self.pcap.loop(0, self.packetHandler)
def packetHandler(self, hdr, data):
"""Handles an incoming pcap packet. This method only knows how
to recognize TCP/IP connections.
Be sure that only TCP packets are passed onto this handler (or
fix the code to ignore the others).
Setting r"ip proto \tcp" as part of the pcap filter expression
suffices, and there shouldn't be any problem combining that with
other expressions.
"""
# Use the ImpactDecoder to turn the rawpacket into a hierarchy
# of ImpactPacket instances.
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
#ip = p.child()
#tcp = ip.child()
# Build a distinctive key for this pair of peers.
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#os.remove(tmpPCAPFileName)
#open(tmpPCAPFileName, 'w').close()
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#if not self.connections.has_key(con):
if con not in self.connections:
logging.info("found flow for the first time: saving to %s" % outputPCAPFileName)
#self.connections[con]=1
self.connections.append(con)
try:
open(outputPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
else:
logging.info( "found duplicated flows, creating a tempfile: %s to append to %s" % (tmpPCAPFileName,outputPCAPFileName) )
try:
open(tmpPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(tmpPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error("Can't write packet to:\n---%s ", tmpPCAPFileName,str(e) )
##Write the packet to the corresponding file.
del dumper
tmpPCAPFileName2 = "/tmp/append2.pcap"
if os.path.isfile(outputPCAPFileName):
#os.rename( outputPCAPFileName , tmpPCAPFileName2 )
os.system("mv %s %s"%( outputPCAPFileName, tmpPCAPFileName2 ))
appendpcap_cmd_1 = "mergecap -w %s %s %s " % (outputPCAPFileName,tmpPCAPFileName2,tmpPCAPFileName)
#appendpcap_cmd_1="pcapnav-concat %s %s"%(outputPCAPFileName, tmpPCAPFileName)
os.system(appendpcap_cmd_1)
#self.connections[con] += 1
os.remove(tmpPCAPFileName2)
#os.rename(tmpPCAPFileName2,outputPCAPFileName)
#logging.info ( self.connections[con] )
else:
logging.error( "did nothing" )
logging.error("%s is in %s\ntry again!!!" % (outputPCAPFileName, str(con in self.connections) ))
try:
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
logging.error("succeded =%s" % str(os.path.isfile(outputPCAPFileName)))
class NetdudeDecoder(Decoder):
"""
"""
def __init__(self,pcapObj ):
"""
"""
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def packetHandler(self, hdr, data):
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
merge_cmd1="mergecap -w %s" % (outputPCAPFileName)
merge_cmd_readtrace_filename=' '
readPCAPFileNameFromNetdude=con.getNetdudeFileName()
for rr in readPCAPFileNameFromNetdude:
merge_cmd_readtrace_filename += ( "%s " % (rr) )
merge_cmd = ("%s%s" % (merge_cmd1, merge_cmd_readtrace_filename) )
print (merge_cmd)
os.system(merge_cmd)
print ("------")
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
import shutil
def SplitPcapByNetdude():
shutil.rmtree(APPCONFIG.GlobalConfig["tmp_netdude_path"],ignore_errors=True)
netdude_cmd1=( "lndtool -r Demux -o %s %s" % (APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["pcapfilename"]) )
os.system(netdude_cmd1)
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#print filename
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
print "Reading from %s: linktype=%d" % (filename, p.datalink())
# Start decoding process.
NetdudeDecoder(p).start()
os.system('ls %s' % (APPCONFIG.GlobalConfig["tmp_netdude_path"] ))
os.system("rm -rf %s"% (APPCONFIG.GlobalConfig["tmp_netdude_path"] ) )
def getFiveTupleListFromDemuxedPath(demuxedpath):
#print ("in getFiveTupleFromDemuxedPath")
fivetuplelist=[]
for (thisDir, subsHere, filesHere) in os.walk(demuxedpath):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
if( os.path.isfile(pcapfullname) and (extension==".trace" or extension == ".TRACE" ) ):
ipprotocol_pair=thisDir.split(os.path.sep)[-3:]
pro_num=ipprotocol_pair[0]
ip_pair=ipprotocol_pair[-2:]
if ipprotocol_pair[0] in ['6','17']:
port_pair=shortname.split('-')[-2:]
a = ((ip_pair[0],port_pair[0]),(ip_pair[1],port_pair[1]),pro_num)
fivetuplelist.append(a)
else:
logging.info ("no ip protocol %s "%(ipprotocol_pair[0]))
return fivetuplelist
def SplitPcapByTraverseNetdudeDir():
shutil.rmtree(APPCONFIG.GlobalConfig["tmp_netdude_path"],ignore_errors=True)
netdude_cmd1=( "lndtool -r Demux -o %s %s" % (APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["pcapfilename"]) )
os.system(netdude_cmd1)
# Start decoding process.
#print ("%s\n%s\n%s"% (APPCONFIG.GlobalConfig["xmlfilename"], APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["outputpathname"]) )
xmlFilename =APPCONFIG.GlobalConfig['xmlfilename']
tmpNetdudeDir = APPCONFIG.GlobalConfig['tmp_netdude_path']
outputDir = APPCONFIG.GlobalConfig['outputpathname']
fivetupleList=getFiveTupleListFromDemuxedPath(tmpNetdudeDir)
connections = []
merge_cmd=''
for i in fivetupleList:
#print (i)
con = Connection(i[0],i[1],i[2])
if con not in connections:
connections.append(con)
outputPCAPFileName=con.getFilename()
inputPCAPFileNameList=con.getNetdudeFileName()
#print (outputPCAPFileName)
#print (inputPCAPFileNameList)
merge_cmd1="mergecap -w %s" % (outputPCAPFileName)
merge_cmd_readtrace_filename=' '
for rr in inputPCAPFileNameList:
merge_cmd_readtrace_filename += ( "%s " % (rr) )
merge_cmd = ("%s%s" % (merge_cmd1, merge_cmd_readtrace_filename) )
print (merge_cmd)
os.system(merge_cmd)
else:
print ("duplicated! in SplitPcapByTraverseNetdudeDir")
print i
os.system('ls %s' % (APPCONFIG.GlobalConfig["tmp_netdude_path"] ))
#os.system("rm -rf %s"% (APPCONFIG.GlobalConfig["tmp_netdude_path"] ) )
#os.system(merge_cmd)
def main():
#mkdir output_path
APPCONFIG.mkdir_p(APPCONFIG.GlobalConfig["outputpathname"])
xmlfile=open(APPCONFIG.GlobalConfig["xmlfilename"], 'r')
root = etree.parse(xmlfile)
for element in root.iter("session"):
line=element.attrib.items()
APPCONFIG.xmlbuffer.append(line)
if APPCONFIG.GlobalConfig["isNetdude"] == True:
logging.info("splitting pcap trace into flows by netdude")
#SplitPcapByNetdude()
SplitPcapByTraverseNetdudeDir()
if APPCONFIG.GlobalConfig["isSplit"]==True:
logging.info("splitting pcap trace into flows")
SplitPcap()
if APPCONFIG.GlobalConfig["isMerge"]==True:
logging.info("Merging flows into applications")
MergepcapInDir(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig["isFeature"]==True:
logging.info("computing flow features")
FeatureCompute(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig['ismergearff']==True:
logging.info ("merging arff filenames")
MergeARFF(APPCONFIG.GlobalConfig["outputpathname"])
logging.info("---done---")
def SplitPcap():
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#logging.info (filename )
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
logging.info ("Reading from %s: linktype=%d" % (filename, p.datalink()) )
# Start decoding process.
Decoder(p).start()
#p.close() #flk3y: avoid p.close() error, after GC?
def FeatureCompute(currentdirname):
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
#featurefilename =
if( os.path.isfile(pcapfullname) and (extension==".pcap" or extension == ".PCAP" ) ):
#fullfeaturefilename=pcapfullname+".arff"
#cmd1_s= "rm %s" % (APPCONFIG.GlobalConfig['tmp_arff_filename'])
if os.path.isfile(APPCONFIG.GlobalConfig['tmp_arff_filename']):
os.remove(APPCONFIG.GlobalConfig['tmp_arff_filename'])
cmd1_s='OpenDPI_demo -f %s' % pcapfullname
p = Popen(cmd1_s, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,close_fds=True)
output = p.stdout.read()
prog=re.compile("###.*###")
m = prog.search(output)
p = re.compile('[a-zA-Z0-9,.@#_]')
app_str_limited=''
for i in m.group(0):
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='='
appfilename=pcapfullname+"."+app_str_limited+".arff"
logging.info ("computing feature to: %s" % appfilename)
cmd2_s= "netmate -f %s" % (pcapfullname )
cmd3_s= "mv %s %s"%(APPCONFIG.GlobalConfig['tmp_arff_filename'],appfilename)
#os.system(cmd1_s)
#os.system(cmd2_s)
#os.system(cmd3_s)
allcmd_s=("%s && %s"%(cmd2_s,cmd3_s))
os.system(allcmd_s)
else:
logging.info ("%s is not a directory" % pcapfullname )
pass
def MergepcapInDir(currentdirname):#TODO: add mergecap files into a list, then pop up when merging
all_cmd_s=[]
BATCH_NUM=50
tmp_pcap="/tmp/tmp_pcap"
os.system(("rm -f %s%s*.pcap ")%(currentdirname,os.sep))
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in subsHere:
#print ("==%s" % filename)
fullname = os.path.join(thisDir,filename)
if(os.path.isdir(fullname) ):
pcapname=fullname+".pcap"
print ("==%s" % filename)
os.system(("rm -f %s ")%(tmp_pcap))
pcap_list=[]
#if os.path.isfile(pcapname):
# os.remove(pcapname)
for (f_dir,f_subs,f_files) in os.walk(fullname):
pcap_f=[]
for f in f_files:
if (f[-5:] == '.pcap'):
pcap_f.append(f_dir+os.sep+f)
#print (pcap_f)
while (len(pcap_f) != 0):
tmp_s=""
pcap_f_length=len(pcap_f)
if (pcap_f_length >=BATCH_NUM):
for i in range(BATCH_NUM) :
tmp_s =tmp_s+" "+pcap_f.pop()+" "
pcap_list.append(tmp_s)
else:
for i in range(pcap_f_length):
tmp_s=tmp_s+" "+pcap_f.pop()+" "
#print (tmp_s)
pcap_list.append(tmp_s)
print ("remaining pcap %d files to read" % pcap_f_length)
#print (pcap_list)
#for i in pcap_list:
# #cmd_s='mergecap -w %s %s' % (pcapname,i)
# all_cmd_s.append(i)
#print (cmd_s)
#print (all_cmd_s)
print ("----- %s ------\ntmp_pcap output_pcap" % pcapname)
logging.info ("%s is a directory, merging all pcap files in it" % fullname )
for i in pcap_list:
if ( os.path.isfile(tmp_pcap) and os.path.isfile(pcapname) ):
print (" Y Y :You'd better not be here, but it OK")
os.remove(tmp_pcap)
#os.rename(pcapname,tmp_pcap)
os.system( "mv %s %s"% ( pcapname , tmp_pcap) )
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
elif ( os.path.isfile(tmp_pcap) and (not os.path.isfile(pcapname)) ):
print (" Y N :You should not be here! there may errors happened ")
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
elif ((not os.path.isfile(tmp_pcap)) and (os.path.isfile(pcapname)) ) :
print (" N Y")
#os.rename(pcapname,tmp_pcap)
os.system( "mv %s %s" % ( pcapname,tmp_pcap ) )
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
else:
print ("creating...\n N N")
cmd="mergecap -w %s %s" % (pcapname,i)
#print (cmd)
os.system(cmd)
else:
logging.info ("%s is not a directory" % fullname )
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpiclass {''',
'''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
def MergeARFF(currentdirname):
global arff_head_s
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for dirname in subsHere:
fullsubdirname = os.path.join(thisDir,dirname)
if(os.path.isdir(fullsubdirname) ):
#appendable=False
arff_big_name=fullsubdirname+".merged.arff"
opendpiclass_list=[]
writelines_data=[]
if (os.path.isfile(arff_big_name)) :
os.remove(arff_big_name)
appendable = True
#q_arff_big = open(arff_big_name,'a')
#q_arff_big.write(arff_head_s[0])
#q_arff_big.write("test")
#q_arff_big.write(arff_head_s[1])
logging.info ("%s is a directory, merging all arff files in it" % fullsubdirname )
for (sub_thisdir,sub_subshere,sub_filesHere ) in os.walk(fullsubdirname):
for filename in sub_filesHere:
(shortname, extension) = os.path.splitext(filename)
foundData=False
#appendable=False
#logging.info ("merging %s" % filename)
if( (extension==".arff" or extension == ".ARFF" ) and (shortname[-3:]=='###' ) ):
logging.info ("merging %s" % filename)
opendpi_apptype=shortname.split('.')[-1][3:-3] # for example: blah.blah.blah.###type1_type2_###
logging.error (opendpi_apptype)
if opendpi_apptype not in opendpiclass_list:
opendpiclass_list.append(opendpi_apptype)
full_arff_name = os.path.join(sub_thisdir,filename)
if appendable == True:
p = open(full_arff_name,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData=True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#q_arff_big.write
writelines_data.append( (line.strip()+","+opendpi_apptype+"\n") )
q_arff_big = open(arff_big_name,'a')
q_arff_big.write(arff_head_s[0])
for i in opendpiclass_list:
q_arff_big.write( "%s," % i )
q_arff_big.write(arff_head_s[1])
for ii in writelines_data:
q_arff_big.write(ii)
q_arff_big.close()
else:
logging.info ("%s is not a directory" % fullname )
pass
def ParseCMD():
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-x","--xmlfilename",dest="xmlfilename",
metavar="XML", help= "read XML, which was generated by network bandwith monitor")
parser.add_option("-f", "--pcapfilename",dest="pcapfilename",
metavar="FILE", help="write output to FILE")
parser.add_option("-o", "--output_path",dest="output_path",
metavar="OUTPUT_PATH", help="write output OUTPUT_PATH/FILE.demux")
#parser.add_option('-M', '--MODE',
# type='choice',
# action='store',
# dest='modechoice',
# choices=['all','split_only', 'merge_only', 'feature_only',],
# default='all',
# help='mode to run on: all, split_only, merge_only, feature_only',)
parser.add_option("-a", "--all",
default=False,
dest='isall',
action='store_true',
help="enable all: split->merge->calculate features ",)
parser.add_option("-s","--split",
default=False,
dest='issplit',
action='store_true',
help="split pcap trace into flows",)
parser.add_option("-m","--merge",
default=False,
dest='ismerge',
action='store_true',
help="merge flows from the same application into one pcap trace",)
parser.add_option("-g","--mergearff",
default=False,
dest='ismergearff',
action='store_true',
help="merge .arff files from the same application into one",)
parser.add_option("-c","--computefeatures",
default=False,
dest='isfeature',
action='store_true',
help="compute features for every pcap file in OUTPUT_PATH",)
parser.add_option("-n","--netdude",
default=False,
dest='isNetdude',
action='store_true',
help="enable libnetdude's demuxer")
(options, args) = parser.parse_args()
#if len(args) != 1:
# parser.error("incorrect number of arguments")
if options.pcapfilename:
APPCONFIG.GlobalConfig["pcapfilename"] = options.pcapfilename
if options.output_path:
APPCONFIG.GlobalConfig["outputpathname"] = options.output_path
else:
APPCONFIG.GlobalConfig["outputpathname"] = options.pcapfilename+".demux"
if options.xmlfilename:
APPCONFIG.GlobalConfig["xmlfilename"]= options.xmlfilename
if options.isall:
APPCONFIG.GlobalConfig['isAll']=True
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.isNetdude:
options.isNetdude=True
options.issplit=False
APPCONFIG.GlobalConfig['isSplit']=False
APPCONFIG.GlobalConfig['isNetdude']=True
if options.issplit:
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
if options.ismerge:
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
if options.ismergearff:
options.ismergearff=True
APPCONFIG.GlobalConfig['ismergearff']=True
if options.isfeature:
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.verbose:
APPCONFIG.GlobalConfig['isVerbose']=True
logging.info ("------running info.---------")
logging.info ("Reading xmlfile %s..." % options.xmlfilename)
logging.info ("Reading pcapfile %s..." % options.pcapfilename)
if options.output_path:
logging.info ("demux to path: %s"%options.output_path)
else:
logging.info ("have not assigned, output to %s.demux by default"%options.pcapfilename)
logging.info ( "Split pcap trace: %s" % str(APPCONFIG.GlobalConfig['isSplit']) )
logging.info ( "Merge flows into applications: %s"% str(APPCONFIG.GlobalConfig['isMerge']) )
logging.info ( "compute features: %s"% str(APPCONFIG.GlobalConfig['isFeature']) )
logging.info ("------------end info.------------")
# Process command-line arguments.
if __name__ == '__main__':
ParseCMD()
main()
exit()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A pure Python GlobalConfig implementation. Copyright (c) 2010, flk3y """
__version__ = '0.1'
import os
import sys
GlobalConfig = {'xmlfilename':"test.xml",
'pcapfilename':"test.pcap",
'outputpathname':"outputdir",
'appname':"default_app",
'tmp_arff_filename':"/tmp/testdata.log",
'tmp_netdude_path':"/tmp/netdude_demux",
'isALL':False,
'isSplit':False,
'isMerge':False,
'isFeature':False,
'isVerbose':False,
'ismergearff':False,
'isNetdude':False,
}
xmlbuffer=[]
def mkdir_p(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
"""
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
head, tail = os.path.split(newdir)
if head and not os.path.isdir(head):
os.mkdir(head)
#print "_mkdir %s" % repr(newdir)
if tail:
os.mkdir(newdir)
| Python |
#!/usr/bin/env python
import os,sys,logging
import string
from exceptions import Exception
from optparse import OptionParser
import re
import glob
import yaml
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE open_class {''' ,
'}',
'\n@ATTRIBUTE app_class {',
'}',
'\n@ATTRIBUTE cata_class {',
'}',
'''
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
def LoadStream(FileName_s='default.yaml'):
f = file(FileName_s,'r')
stream=yaml.load(f)
return stream
def SaveStream(stream,FileName_s='default.yaml'):
f = file(FileName_s,'w')
yaml.dump(stream,f)
f.close()
def FindCataFromYAML(realapp_name,fromyaml):
#print ("looking for %s in %s"%(realapp_name,yamlfile))
#f=LoadStream(yamlfile)
for i in fromyaml:
for j in i['Applications']:
for k in i['Applications'][j]:
#print (k)
if k.lower() == realapp_name.lower():
return i['CatalogueName']
return "Others"
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",default=True,
help="be very quiet")
parser.add_option("-f", "--from_arff",dest="from_arff",
metavar="INPUT_ARFF", help="read from INPUT_ARFF")
parser.add_option("-o", "--output_arff",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
parser.add_option("-c","--catalogue",dest="cataloguefile",
metavar="catalogue", help="read from catalogue.yaml",)
parser.add_option("-d","--details",dest="isdetails",default=True,
action="store_true",
help="parser ")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'catalogue.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./catalogue.arff"
if options.cataloguefile:
catalogue_yaml_file=options.cataloguefile
else:
catalogue_yaml_file="catalogue.yaml"
if options.from_arff:
if os.path.isdir(options.from_arff):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
if os.path.isfile(options.from_arff):
items.add(options.from_arff)
elif '*' in options.from_arff:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
#output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
opendpi_class_list=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#appname = input_arff_filename.split('@')[0].split('/')[-1]
#print appname
writline=line
opendpi_class=''
pp_line = writline.split(',')[-1].strip()
p_line=pp_line.split('_')[-3:]
if not p_line[0] == 'notfound' :
#print p_line[-1]
opendpi_class=p_line[-1]
else:
#print ("ignore notfound apps")
continue
#a=re.compile('^[ \t]*\r?\n?$')
a=re.compile('^[ \t]*\r?\n?$')
if not a.match(opendpi_class):
if opendpi_class not in applist:
applist.append(opendpi_class)
if pp_line not in opendpi_class_list:
opendpi_class_list.append(pp_line)
#print (opendpi_class)
#for i in writline.split(',')[:-1]:
# writelines_data.append( i+"," )
writelines_data.append(writline.strip()+","+opendpi_class+"\n")
else:
print ("ignore blank apps:"),
print (opendpi_class)
continue
p.close()
#write output arff file
f_yaml=LoadStream(catalogue_yaml_file)
realapp_list=[]
cata_list=[]
final_data_to_write=[]
for write_item in writelines_data:
splited=write_item.strip().split(',')
realapp=splited[-1]
if options.isdetails:
cata=FindCataFromYAML(splited[-2],f_yaml)
else:
cata=FindCataFromYAML(splited[-1],f_yaml)
if cata not in cata_list:
cata_list.append(cata)
if realapp not in realapp_list:
realapp_list.append(realapp)
final_data_to_write.append(write_item.strip()+","+cata+"\n")
output_file = open(output_real_arff_file_name,'a')
#opendpi_class_list=[]
output_file.write(arff_head_s[0])
print("opendpi_class:")
for i in opendpi_class_list:
output_file.write( "%s," % i )
print("\t%s"%i)
output_file.write(arff_head_s[1])
output_file.write(arff_head_s[2])
print ("realapp_class:")
for i in realapp_list:
output_file.write( "%s,"% i )
print ("\t%s"%i)
output_file.write(arff_head_s[3])
output_file.write(arff_head_s[4])
print ("catalogue_class:")
for i in cata_list:
output_file.write("%s,"%i)
print ("\t%s"%i)
output_file.write(arff_head_s[5])
output_file.write(arff_head_s[6])
for ii in final_data_to_write:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A pure Python GlobalConfig implementation. Copyright (c) 2010, flk3y """
__version__ = '0.1'
import os
import sys
GlobalConfig = {'xmlfilename':"test.xml",
'pcapfilename':"test.pcap",
'outputpathname':"outputdir",
'appname':"default_app",
'tmp_arff_filename':"/tmp/testdata.log",
'tmp_netdude_path':"/tmp/netdude_demux",
'isALL':False,
'isSplit':False,
'isMerge':False,
'isFeature':False,
'isVerbose':False,
'ismergearff':False,
'isNetdude':False,
}
xmlbuffer=[]
def mkdir_p(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
"""
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
head, tail = os.path.split(newdir)
if head and not os.path.isdir(head):
os.mkdir(head)
#print "_mkdir %s" % repr(newdir)
if tail:
os.mkdir(newdir)
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' , '''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
appname = input_arff_filename.split('@')[0].split('/')[-1]
print appname
writline=line
opendpi_class = writline.split(',')[-1].strip()
if opendpi_class not in applist:
applist.append(opendpi_class)
writelines_data.append( writline )
p.close()
#write output arff file
output_file.write(arff_head_s[0])
for i in applist:
output_file.write( "%s," % i )
output_file.write(arff_head_s[1])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' , '''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.merged.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
appname = input_arff_filename.split('@')[0].split('/')[-1]
print appname
writline=line.strip()+appname+"\n"
opendpi_class = writline.split(',')[-1].strip()
if opendpi_class not in applist:
applist.append(opendpi_class)
writelines_data.append( writline )
p.close()
#write output arff file
output_file.write(arff_head_s[0])
for i in applist:
output_file.write( "%s," % i )
output_file.write(arff_head_s[1])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
#!/usr/bin/python
# Copyright (c)
#
# pcapy: open_offline, pcapdumper.
# ImpactDecoder.
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
import pcapy
from pcapy import open_offline
import impacket
from impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder
import appconfig as APPCONFIG
import ipdef as IPDEF
sys.stderr=sys.stdout
try:
from lxml import etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree")
except ImportError:
logging.info("Failed to import ElementTree from any known place")
this_dir = os.path.dirname(__file__)
if this_dir not in sys.path:
sys.path.insert(0, this_dir) # needed for Py3
#from common_imports import etree, StringIO, BytesIO, HelperTestCase, fileInTestDir
#from common_imports import SillyFileLike, LargeFileLikeUnicode, doctest, make_doctest
#from common_imports import canonicalize, sorted, _str, _bytes
try:
_unicode = unicode
except NameError:
# Python 3
_unicode = str
ETHERNET_MAX_FRAME_SIZE = 1518
PROMISC_MODE = 0
class Connection:
"""This class can be used as a key in a dictionary to select a connection
given a pair of peers. Two connections are considered the same if both
peers are equal, despite the order in which they were passed to the
class constructor.
"""
def __init__(self, p1, p2, p3):
"""This constructor takes two tuples, one for each peer. The first
element in each tuple is the IP address as a string, and the
second is the port as an integer.
"""
self.p1 = p1
self.p2 = p2
#self.p3 = p3
self.proto_id=p3
self.protocol = "unknown"
self.curpath= "."
def getFilename(self):
"""Utility function that returns a filename composed by the IP
addresses and ports of both peers.
"""
try:
if self.proto_id:
if self.proto_id == socket.IPPROTO_TCP:
self.protocol = "TCP"
elif self.proto_id == socket.IPPROTO_UDP:
self.protocol = "UDP"
else:
self.protocol = IPDEF.ip_protocols[self.proto_id]
except Exception, e:
logging.error("failed setting protocol. Error: %s" % str(e))
#APPCONFIG.GlobalConfig["appname"] = self.FindNameFromXML(self.p1, self.p2, self.protocol)
appname_s= self.FindNameFromXML(self.p1, self.p2, self.protocol)
#global this_dir
self.curpath=APPCONFIG.GlobalConfig["outputpathname"]+os.path.sep+appname_s+os.path.sep
#self.curpath=os.path.join(APPCONFIG.GlobalConfig["outputpathname"],APPCONFIG.GlobalConfig["appname"])
APPCONFIG.mkdir_p(self.curpath)
return '%s%s-%d-%s-%s-%d.pcap'%(self.curpath, self.p1[0],self.p1[1],self.protocol, self.p2[0],self.p2[1])
def FindNameFromXML(self, src, dst, protocol):
for line in APPCONFIG.xmlbuffer:
if (line[2][1] == src[0] and line[3][1] ==str(src[1]) and line[4][1] == dst[0] and line[5][1] == str(dst[1]) and line[6][1] == protocol ):
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ( "found!: application %s, PID %s"% (line[0][1] , line[1][1] ))
app_str= line[0][1] +"@"+line[1][1]
app_str_limited=''
p = re.compile('[a-zA-Z0-9,.@]')
for i in app_str:
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='-'
return app_str_limited
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ("missed!....")
return "notfound_in_XML@0"
def getNetdudeFileName(self):
netdude_output_path=APPCONFIG.GlobalConfig['tmp_netdude_path']
proto_number = self.proto_id
s_ip=self.p1[0]
s_port=self.p1[1]
d_ip=self.p2[0]
d_port=self.p2[1]
fullpath1 = "%s%s%d%s%s%s%s"%(netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
s_ip,
os.path.sep,
d_ip)
fullpath2 = "%s%s%d%s%s%s%s"% (netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
d_ip,
os.path.sep,
s_ip)
fullpath=[fullpath1,fullpath2]
ports1="*-%s-%s.trace" % (s_port,d_port)
ports2="*-%s-%s.trace" % (d_port,s_port)
port_pair = [ports1,ports2]
tracename_list=[]
#print ports2
for i_path in fullpath:
#print (i_path),
if os.path.isdir(i_path):
for i_port in port_pair:
#print (i_port)
fullfilename=i_path+os.path.sep+i_port
#print (fullfilename)
for f in glob.glob(fullfilename):
#print (f)
if os.path.isfile(f):
tracename_list.append(f)
return tracename_list
def __cmp__(self, other):
if ((self.p1 == other.p1 and self.p2 == other.p2)
or (self.p1 == other.p2 and self.p2 == other.p1)):
return 0
else:
return -1
def __hash__(self):
return (hash(self.p1[0]) ^ hash(self.p1[1])^ hash(self.proto_id)
^ hash(self.p2[0]) ^ hash(self.p2[1]))
class Decoder:
def __init__(self, pcapObj):
# Query the type of the link and instantiate a decoder accordingly.
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def start(self):
# Sniff ad infinitum.
# PacketHandler shall be invoked by pcap for every packet.
self.pcap.loop(0, self.packetHandler)
def packetHandler(self, hdr, data):
"""Handles an incoming pcap packet. This method only knows how
to recognize TCP/IP connections.
Be sure that only TCP packets are passed onto this handler (or
fix the code to ignore the others).
Setting r"ip proto \tcp" as part of the pcap filter expression
suffices, and there shouldn't be any problem combining that with
other expressions.
"""
# Use the ImpactDecoder to turn the rawpacket into a hierarchy
# of ImpactPacket instances.
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
#ip = p.child()
#tcp = ip.child()
# Build a distinctive key for this pair of peers.
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#os.remove(tmpPCAPFileName)
#open(tmpPCAPFileName, 'w').close()
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#if not self.connections.has_key(con):
if con not in self.connections:
logging.info("found flow for the first time: saving to %s" % outputPCAPFileName)
#self.connections[con]=1
self.connections.append(con)
try:
open(outputPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
else:
logging.info( "found duplicated flows, creating a tempfile: %s to append to %s" % (tmpPCAPFileName,outputPCAPFileName) )
try:
open(tmpPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(tmpPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error("Can't write packet to:\n---%s ", tmpPCAPFileName,str(e) )
##Write the packet to the corresponding file.
del dumper
tmpPCAPFileName2 = "/tmp/append2.pcap"
if os.path.isfile(outputPCAPFileName):
#os.rename( outputPCAPFileName , tmpPCAPFileName2 )
os.system("mv %s %s"%( outputPCAPFileName, tmpPCAPFileName2 ))
appendpcap_cmd_1 = "mergecap -w %s %s %s " % (outputPCAPFileName,tmpPCAPFileName2,tmpPCAPFileName)
#appendpcap_cmd_1="pcapnav-concat %s %s"%(outputPCAPFileName, tmpPCAPFileName)
os.system(appendpcap_cmd_1)
#self.connections[con] += 1
os.remove(tmpPCAPFileName2)
#os.rename(tmpPCAPFileName2,outputPCAPFileName)
#logging.info ( self.connections[con] )
else:
logging.error( "did nothing" )
logging.error("%s is in %s\ntry again!!!" % (outputPCAPFileName, str(con in self.connections) ))
try:
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
logging.error("succeded =%s" % str(os.path.isfile(outputPCAPFileName)))
class NetdudeDecoder(Decoder):
"""
"""
def __init__(self,pcapObj ):
"""
"""
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def packetHandler(self, hdr, data):
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
merge_cmd1="mergecap -w %s" % (outputPCAPFileName)
merge_cmd_readtrace_filename=' '
readPCAPFileNameFromNetdude=con.getNetdudeFileName()
for rr in readPCAPFileNameFromNetdude:
merge_cmd_readtrace_filename += ( "%s " % (rr) )
merge_cmd = ("%s%s" % (merge_cmd1, merge_cmd_readtrace_filename) )
print (merge_cmd)
os.system(merge_cmd)
print ("------")
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
import shutil
def SplitPcapByNetdude():
shutil.rmtree(APPCONFIG.GlobalConfig["tmp_netdude_path"],ignore_errors=True)
netdude_cmd1=( "lndtool -r Demux -o %s %s" % (APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["pcapfilename"]) )
os.system(netdude_cmd1)
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#print filename
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
print "Reading from %s: linktype=%d" % (filename, p.datalink())
# Start decoding process.
NetdudeDecoder(p).start()
os.system('ls %s' % (APPCONFIG.GlobalConfig["tmp_netdude_path"] ))
os.system("rm -rf %s"% (APPCONFIG.GlobalConfig["tmp_netdude_path"] ) )
def main():
#mkdir output_path
APPCONFIG.mkdir_p(APPCONFIG.GlobalConfig["outputpathname"])
xmlfile=open(APPCONFIG.GlobalConfig["xmlfilename"], 'r')
root = etree.parse(xmlfile)
for element in root.iter("session"):
line=element.attrib.items()
APPCONFIG.xmlbuffer.append(line)
if APPCONFIG.GlobalConfig["isNetdude"] == True:
logging.info("splitting pcap trace into flows by netdude")
SplitPcapByNetdude()
if APPCONFIG.GlobalConfig["isSplit"]==True:
logging.info("splitting pcap trace into flows")
SplitPcap()
if APPCONFIG.GlobalConfig["isMerge"]==True:
logging.info("Merging flows into applications")
MergepcapInDir(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig["isFeature"]==True:
logging.info("computing flow features")
FeatureCompute(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig['ismergearff']==True:
logging.info ("merging arff filenames")
MergeARFF(APPCONFIG.GlobalConfig["outputpathname"])
logging.info("---done---")
def SplitPcap():
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#logging.info (filename )
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
logging.info ("Reading from %s: linktype=%d" % (filename, p.datalink()) )
# Start decoding process.
Decoder(p).start()
#p.close() #flk3y: avoid p.close() error, after GC?
def FeatureCompute(currentdirname):
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
#featurefilename =
if( os.path.isfile(pcapfullname) and (extension==".pcap" or extension == ".PCAP" ) ):
#fullfeaturefilename=pcapfullname+".arff"
#cmd1_s= "rm %s" % (APPCONFIG.GlobalConfig['tmp_arff_filename'])
if os.path.isfile(APPCONFIG.GlobalConfig['tmp_arff_filename']):
os.remove(APPCONFIG.GlobalConfig['tmp_arff_filename'])
cmd1_s='OpenDPI_demo -f %s' % pcapfullname
p = Popen(cmd1_s, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,close_fds=True)
output = p.stdout.read()
prog=re.compile("###.*###")
m = prog.search(output)
p = re.compile('[a-zA-Z0-9,.@#_]')
app_str_limited=''
for i in m.group(0):
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='='
appfilename=pcapfullname+"."+app_str_limited+".arff"
logging.info ("computing feature to: %s" % appfilename)
cmd2_s= "netmate -f %s" % (pcapfullname )
cmd3_s= "mv %s %s"%(APPCONFIG.GlobalConfig['tmp_arff_filename'],appfilename)
#os.system(cmd1_s)
#os.system(cmd2_s)
#os.system(cmd3_s)
allcmd_s=("%s && %s"%(cmd2_s,cmd3_s))
os.system(allcmd_s)
else:
logging.info ("%s is not a directory" % pcapfullname )
pass
def MergepcapInDir(currentdirname):#TODO: add mergecap files into a list, then pop up when merging
all_cmd_s=[]
BATCH_NUM=50
tmp_pcap="/tmp/tmp_pcap"
os.system(("rm -f %s%s*.pcap ")%(currentdirname,os.sep))
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in subsHere:
#print ("==%s" % filename)
fullname = os.path.join(thisDir,filename)
if(os.path.isdir(fullname) ):
pcapname=fullname+".pcap"
print ("==%s" % filename)
os.system(("rm -f %s ")%(tmp_pcap))
pcap_list=[]
#if os.path.isfile(pcapname):
# os.remove(pcapname)
for (f_dir,f_subs,f_files) in os.walk(fullname):
pcap_f=[]
for f in f_files:
if (f[-5:] == '.pcap'):
pcap_f.append(f_dir+os.sep+f)
#print (pcap_f)
while (len(pcap_f) != 0):
tmp_s=""
pcap_f_length=len(pcap_f)
if (pcap_f_length >=BATCH_NUM):
for i in range(BATCH_NUM) :
tmp_s =tmp_s+" "+pcap_f.pop()+" "
pcap_list.append(tmp_s)
else:
for i in range(pcap_f_length):
tmp_s=tmp_s+" "+pcap_f.pop()+" "
#print (tmp_s)
pcap_list.append(tmp_s)
print ("remaining pcap %d files to read" % pcap_f_length)
#print (pcap_list)
#for i in pcap_list:
# #cmd_s='mergecap -w %s %s' % (pcapname,i)
# all_cmd_s.append(i)
#print (cmd_s)
#print (all_cmd_s)
print ("----- %s ------\ntmp_pcap output_pcap" % pcapname)
logging.info ("%s is a directory, merging all pcap files in it" % fullname )
for i in pcap_list:
if ( os.path.isfile(tmp_pcap) and os.path.isfile(pcapname) ):
print (" Y Y :You'd better not be here, but it OK")
os.remove(tmp_pcap)
os.rename(pcapname,tmp_pcap)
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
elif ( os.path.isfile(tmp_pcap) and (not os.path.isfile(pcapname)) ):
print (" Y N :You should not be here! there may errors happened ")
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
elif ((not os.path.isfile(tmp_pcap)) and (os.path.isfile(pcapname)) ) :
print (" N Y")
os.rename(pcapname,tmp_pcap)
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
else:
print ("creating...\n N N")
cmd="mergecap -w %s %s" % (pcapname,i)
#print (cmd)
os.system(cmd)
else:
logging.info ("%s is not a directory" % fullname )
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpiclass {''',
'''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
def MergeARFF(currentdirname):
global arff_head_s
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for dirname in subsHere:
fullsubdirname = os.path.join(thisDir,dirname)
if(os.path.isdir(fullsubdirname) ):
#appendable=False
arff_big_name=fullsubdirname+".merged.arff"
opendpiclass_list=[]
writelines_data=[]
if (os.path.isfile(arff_big_name)) :
os.remove(arff_big_name)
appendable = True
#q_arff_big = open(arff_big_name,'a')
#q_arff_big.write(arff_head_s[0])
#q_arff_big.write("test")
#q_arff_big.write(arff_head_s[1])
logging.info ("%s is a directory, merging all arff files in it" % fullsubdirname )
for (sub_thisdir,sub_subshere,sub_filesHere ) in os.walk(fullsubdirname):
for filename in sub_filesHere:
(shortname, extension) = os.path.splitext(filename)
foundData=False
#appendable=False
#logging.info ("merging %s" % filename)
if( (extension==".arff" or extension == ".ARFF" ) and (shortname[-3:]=='###' ) ):
logging.info ("merging %s" % filename)
opendpi_apptype=shortname.split('.')[-1][3:-3] # for example: blah.blah.blah.###type1_type2_###
logging.error (opendpi_apptype)
if opendpi_apptype not in opendpiclass_list:
opendpiclass_list.append(opendpi_apptype)
full_arff_name = os.path.join(sub_thisdir,filename)
if appendable == True:
p = open(full_arff_name,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData=True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#q_arff_big.write
writelines_data.append( (line.strip()+","+opendpi_apptype+"\n") )
q_arff_big = open(arff_big_name,'a')
q_arff_big.write(arff_head_s[0])
for i in opendpiclass_list:
q_arff_big.write( "%s," % i )
q_arff_big.write(arff_head_s[1])
for ii in writelines_data:
q_arff_big.write(ii)
q_arff_big.close()
else:
logging.info ("%s is not a directory" % fullname )
pass
def ParseCMD():
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-x","--xmlfilename",dest="xmlfilename",
metavar="XML", help= "read XML, which was generated by network bandwith monitor")
parser.add_option("-f", "--pcapfilename",dest="pcapfilename",
metavar="FILE", help="write output to FILE")
parser.add_option("-o", "--output_path",dest="output_path",
metavar="OUTPUT_PATH", help="write output OUTPUT_PATH/FILE.demux")
#parser.add_option('-M', '--MODE',
# type='choice',
# action='store',
# dest='modechoice',
# choices=['all','split_only', 'merge_only', 'feature_only',],
# default='all',
# help='mode to run on: all, split_only, merge_only, feature_only',)
parser.add_option("-a", "--all",
default=False,
dest='isall',
action='store_true',
help="enable all: split->merge->calculate features ",)
parser.add_option("-s","--split",
default=False,
dest='issplit',
action='store_true',
help="split pcap trace into flows",)
parser.add_option("-m","--merge",
default=False,
dest='ismerge',
action='store_true',
help="merge flows from the same application into one pcap trace",)
parser.add_option("-g","--mergearff",
default=False,
dest='ismergearff',
action='store_true',
help="merge .arff files from the same application into one",)
parser.add_option("-c","--computefeatures",
default=False,
dest='isfeature',
action='store_true',
help="compute features for every pcap file in OUTPUT_PATH",)
parser.add_option("-n","--netdude",
default=False,
dest='isNetdude',
action='store_true',
help="enable libnetdude's demuxer")
(options, args) = parser.parse_args()
#if len(args) != 1:
# parser.error("incorrect number of arguments")
if options.pcapfilename:
APPCONFIG.GlobalConfig["pcapfilename"] = options.pcapfilename
if options.output_path:
APPCONFIG.GlobalConfig["outputpathname"] = options.output_path
else:
APPCONFIG.GlobalConfig["outputpathname"] = options.pcapfilename+".demux"
if options.xmlfilename:
APPCONFIG.GlobalConfig["xmlfilename"]= options.xmlfilename
if options.isall:
APPCONFIG.GlobalConfig['isAll']=True
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.isNetdude:
options.isNetdude=True
options.issplit=False
APPCONFIG.GlobalConfig['isSplit']=False
APPCONFIG.GlobalConfig['isNetdude']=True
if options.issplit:
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
if options.ismerge:
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
if options.ismergearff:
options.ismergearff=True
APPCONFIG.GlobalConfig['ismergearff']=True
if options.isfeature:
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.verbose:
APPCONFIG.GlobalConfig['isVerbose']=True
logging.info ("------running info.---------")
logging.info ("Reading xmlfile %s..." % options.xmlfilename)
logging.info ("Reading pcapfile %s..." % options.pcapfilename)
if options.output_path:
logging.info ("demux to path: %s"%options.output_path)
else:
logging.info ("have not assigned, output to %s.demux by default"%options.pcapfilename)
logging.info ( "Split pcap trace: %s" % str(APPCONFIG.GlobalConfig['isSplit']) )
logging.info ( "Merge flows into applications: %s"% str(APPCONFIG.GlobalConfig['isMerge']) )
logging.info ( "compute features: %s"% str(APPCONFIG.GlobalConfig['isFeature']) )
logging.info ("------------end info.------------")
# Process command-line arguments.
if __name__ == '__main__':
ParseCMD()
main()
exit()
| Python |
# Type of service (ip_tos), RFC 1349 ("obsoleted by RFC 2474")
IP_TOS_DEFAULT = 0x00 # default
IP_TOS_LOWDELAY = 0x10 # low delay
IP_TOS_THROUGHPUT = 0x08 # high throughput
IP_TOS_RELIABILITY = 0x04 # high reliability
IP_TOS_LOWCOST = 0x02 # low monetary cost - XXX
IP_TOS_ECT = 0x02 # ECN-capable transport
IP_TOS_CE = 0x01 # congestion experienced
# IP precedence (high 3 bits of ip_tos), hopefully unused
IP_TOS_PREC_ROUTINE = 0x00
IP_TOS_PREC_PRIORITY = 0x20
IP_TOS_PREC_IMMEDIATE = 0x40
IP_TOS_PREC_FLASH = 0x60
IP_TOS_PREC_FLASHOVERRIDE = 0x80
IP_TOS_PREC_CRITIC_ECP = 0xa0
IP_TOS_PREC_INTERNETCONTROL = 0xc0
IP_TOS_PREC_NETCONTROL = 0xe0
# Fragmentation flags (ip_off)
IP_RF = 0x8000 # reserved
IP_DF = 0x4000 # don't fragment
IP_MF = 0x2000 # more fragments (not last frag)
IP_OFFMASK = 0x1fff # mask for fragment offset
# Time-to-live (ip_ttl), seconds
IP_TTL_DEFAULT = 64 # default ttl, RFC 1122, RFC 1340
IP_TTL_MAX = 255 # maximum ttl
# Type of service (ip_tos), RFC 1349 ("obsoleted by RFC 2474")
IP_TOS_DEFAULT = 0x00 # default
IP_TOS_LOWDELAY = 0x10 # low delay
IP_TOS_THROUGHPUT = 0x08 # high throughput
IP_TOS_RELIABILITY = 0x04 # high reliability
IP_TOS_LOWCOST = 0x02 # low monetary cost - XXX
IP_TOS_ECT = 0x02 # ECN-capable transport
IP_TOS_CE = 0x01 # congestion experienced
# IP precedence (high 3 bits of ip_tos), hopefully unused
IP_TOS_PREC_ROUTINE = 0x00
IP_TOS_PREC_PRIORITY = 0x20
IP_TOS_PREC_IMMEDIATE = 0x40
IP_TOS_PREC_FLASH = 0x60
IP_TOS_PREC_FLASHOVERRIDE = 0x80
IP_TOS_PREC_CRITIC_ECP = 0xa0
IP_TOS_PREC_INTERNETCONTROL = 0xc0
IP_TOS_PREC_NETCONTROL = 0xe0
# Fragmentation flags (ip_off)
IP_RF = 0x8000 # reserved
IP_DF = 0x4000 # don't fragment
IP_MF = 0x2000 # more fragments (not last frag)
IP_OFFMASK = 0x1fff # mask for fragment offset
# Time-to-live (ip_ttl), seconds
IP_TTL_DEFAULT = 64 # default ttl, RFC 1122, RFC 1340
IP_TTL_MAX = 255 # maximum ttl
# Protocol (ip_p) - http://www.iana.org/assignments/protocol-numbers
IP_PROTO_IP = 0 # dummy for IP
IP_PROTO_HOPOPTS = IP_PROTO_IP # IPv6 hop-by-hop options
IP_PROTO_ICMP = 1 # ICMP
IP_PROTO_IGMP = 2 # IGMP
IP_PROTO_GGP = 3 # gateway-gateway protocol
IP_PROTO_IPIP = 4 # IP in IP
IP_PROTO_ST = 5 # ST datagram mode
IP_PROTO_TCP = 6 # TCP
IP_PROTO_CBT = 7 # CBT
IP_PROTO_EGP = 8 # exterior gateway protocol
IP_PROTO_IGP = 9 # interior gateway protocol
IP_PROTO_BBNRCC = 10 # BBN RCC monitoring
IP_PROTO_NVP = 11 # Network Voice Protocol
IP_PROTO_PUP = 12 # PARC universal packet
IP_PROTO_ARGUS = 13 # ARGUS
IP_PROTO_EMCON = 14 # EMCON
IP_PROTO_XNET = 15 # Cross Net Debugger
IP_PROTO_CHAOS = 16 # Chaos
IP_PROTO_UDP = 17 # UDP
IP_PROTO_MUX = 18 # multiplexing
IP_PROTO_DCNMEAS = 19 # DCN measurement
IP_PROTO_HMP = 20 # Host Monitoring Protocol
IP_PROTO_PRM = 21 # Packet Radio Measurement
IP_PROTO_IDP = 22 # Xerox NS IDP
IP_PROTO_TRUNK1 = 23 # Trunk-1
IP_PROTO_TRUNK2 = 24 # Trunk-2
IP_PROTO_LEAF1 = 25 # Leaf-1
IP_PROTO_LEAF2 = 26 # Leaf-2
IP_PROTO_RDP = 27 # "Reliable Datagram" proto
IP_PROTO_IRTP = 28 # Inet Reliable Transaction
IP_PROTO_TP = 29 # ISO TP class 4
IP_PROTO_NETBLT = 30 # Bulk Data Transfer
IP_PROTO_MFPNSP = 31 # MFE Network Services
IP_PROTO_MERITINP = 32 # Merit Internodal Protocol
IP_PROTO_SEP = 33 # Sequential Exchange proto
IP_PROTO_3PC = 34 # Third Party Connect proto
IP_PROTO_IDPR = 35 # Interdomain Policy Route
IP_PROTO_XTP = 36 # Xpress Transfer Protocol
IP_PROTO_DDP = 37 # Datagram Delivery Proto
IP_PROTO_CMTP = 38 # IDPR Ctrl Message Trans
IP_PROTO_TPPP = 39 # TP++ Transport Protocol
IP_PROTO_IL = 40 # IL Transport Protocol
IP_PROTO_IP6 = 41 # IPv6
IP_PROTO_SDRP = 42 # Source Demand Routing
IP_PROTO_ROUTING = 43 # IPv6 routing header
IP_PROTO_FRAGMENT = 44 # IPv6 fragmentation header
IP_PROTO_IDRP = 45 # Inter-Domain Routing Protocol [Hares]
IP_PROTO_RSVP = 46 # Reservation protocol
IP_PROTO_GRE = 47 # General Routing Encap
IP_PROTO_MHRP = 48 # Mobile Host Routing
IP_PROTO_ENA = 49 # ENA
IP_PROTO_ESP = 50 # Encap Security Payload
IP_PROTO_AH = 51 # Authentication Header
IP_PROTO_INLSP = 52 # Integated Net Layer Sec
IP_PROTO_SWIPE = 53 # SWIPE
IP_PROTO_NARP = 54 # NBMA Address Resolution
IP_PROTO_MOBILE = 55 # Mobile IP, RFC 2004
IP_PROTO_TLSP = 56 # Transport Layer Security
IP_PROTO_SKIP = 57 # SKIP
IP_PROTO_ICMP6 = 58 # ICMP for IPv6
IP_PROTO_NONE = 59 # IPv6 no next header
IP_PROTO_DSTOPTS = 60 # IPv6 destination options
IP_PROTO_ANYHOST = 61 # any host internal proto
IP_PROTO_CFTP = 62 # CFTP
IP_PROTO_ANYNET = 63 # any local network
IP_PROTO_EXPAK = 64 # SATNET and Backroom EXPAK
IP_PROTO_KRYPTOLAN = 65 # Kryptolan
IP_PROTO_RVD = 66 # MIT Remote Virtual Disk
IP_PROTO_IPPC = 67 # Inet Pluribus Packet Core
IP_PROTO_DISTFS = 68 # any distributed fs
IP_PROTO_SATMON = 69 # SATNET Monitoring
IP_PROTO_VISA = 70 # VISA Protocol
IP_PROTO_IPCV = 71 # Inet Packet Core Utility
IP_PROTO_CPNX = 72 # Comp Proto Net Executive
IP_PROTO_CPHB = 73 # Comp Protocol Heart Beat
IP_PROTO_WSN = 74 # Wang Span Network
IP_PROTO_PVP = 75 # Packet Video Protocol
IP_PROTO_BRSATMON = 76 # Backroom SATNET Monitor
IP_PROTO_SUNND = 77 # SUN ND Protocol
IP_PROTO_WBMON = 78 # WIDEBAND Monitoring
IP_PROTO_WBEXPAK = 79 # WIDEBAND EXPAK
IP_PROTO_EON = 80 # ISO CNLP
IP_PROTO_VMTP = 81 # Versatile Msg Transport
IP_PROTO_SVMTP = 82 # Secure VMTP
IP_PROTO_VINES = 83 # VINES
IP_PROTO_TTP = 84 # TTP
IP_PROTO_NSFIGP = 85 # NSFNET-IGP
IP_PROTO_DGP = 86 # Dissimilar Gateway Proto
IP_PROTO_TCF = 87 # TCF
IP_PROTO_EIGRP = 88 # EIGRP
IP_PROTO_OSPF = 89 # Open Shortest Path First
IP_PROTO_SPRITERPC = 90 # Sprite RPC Protocol
IP_PROTO_LARP = 91 # Locus Address Resolution
IP_PROTO_MTP = 92 # Multicast Transport Proto
IP_PROTO_AX25 = 93 # AX.25 Frames
IP_PROTO_IPIPENCAP = 94 # yet-another IP encap
IP_PROTO_MICP = 95 # Mobile Internet Ctrl
IP_PROTO_SCCSP = 96 # Semaphore Comm Sec Proto
IP_PROTO_ETHERIP = 97 # Ethernet in IPv4
IP_PROTO_ENCAP = 98 # encapsulation header
IP_PROTO_ANYENC = 99 # private encryption scheme
IP_PROTO_GMTP = 100 # GMTP
IP_PROTO_IFMP = 101 # Ipsilon Flow Mgmt Proto
IP_PROTO_PNNI = 102 # PNNI over IP
IP_PROTO_PIM = 103 # Protocol Indep Multicast
IP_PROTO_ARIS = 104 # ARIS
IP_PROTO_SCPS = 105 # SCPS
IP_PROTO_QNX = 106 # QNX
IP_PROTO_AN = 107 # Active Networks
IP_PROTO_IPCOMP = 108 # IP Payload Compression
IP_PROTO_SNP = 109 # Sitara Networks Protocol
IP_PROTO_COMPAQPEER = 110 # Compaq Peer Protocol
IP_PROTO_IPXIP = 111 # IPX in IP
IP_PROTO_VRRP = 112 # Virtual Router Redundancy
IP_PROTO_PGM = 113 # PGM Reliable Transport
IP_PROTO_ANY0HOP = 114 # 0-hop protocol
IP_PROTO_L2TP = 115 # Layer 2 Tunneling Proto
IP_PROTO_DDX = 116 # D-II Data Exchange (DDX)
IP_PROTO_IATP = 117 # Interactive Agent Xfer
IP_PROTO_STP = 118 # Schedule Transfer Proto
IP_PROTO_SRP = 119 # SpectraLink Radio Proto
IP_PROTO_UTI = 120 # UTI
IP_PROTO_SMP = 121 # Simple Message Protocol
IP_PROTO_SM = 122 # SM
IP_PROTO_PTP = 123 # Performance Transparency
IP_PROTO_ISIS = 124 # ISIS over IPv4
IP_PROTO_FIRE = 125 # FIRE
IP_PROTO_CRTP = 126 # Combat Radio Transport
IP_PROTO_CRUDP = 127 # Combat Radio UDP
IP_PROTO_SSCOPMCE = 128 # SSCOPMCE
IP_PROTO_IPLT = 129 # IPLT
IP_PROTO_SPS = 130 # Secure Packet Shield
IP_PROTO_PIPE = 131 # Private IP Encap in IP
IP_PROTO_SCTP = 132 # Stream Ctrl Transmission
IP_PROTO_FC = 133 # Fibre Channel
IP_PROTO_RSVPIGN = 134 # RSVP-E2E-IGNORE
IP_PROTO_Mobility_Header = 135 #Mobility Header
IP_PROTO_UDPLite =136 #UDPLite
IP_PROTO_MPLS_in_IP =137 #MPLS-in-IP
IP_PROTO_MANET =138 #MANET
IP_PROTO_HIP =139 #HIP
IP_PROTO_Shim6 =140 #Shim6
IP_PROTO_WESP =141 #WESP
IP_PROTO_ROHC =142 #ROHC
IP_PROTO_RAW = 255 # Raw IP packets
IP_PROTO_RESERVED = IP_PROTO_RAW # Reserved
IP_PROTO_MAX = 255
ip_protocols = {
IP_PROTO_IP : 'HOPOPT', #dummy for IP
IP_PROTO_HOPOPTS : 'HOPOPT', #IPv6 hop-by-hop options
IP_PROTO_ICMP : 'ICMP', #IPv6 hop-by-hop options
IP_PROTO_IGMP : 'IGMP', #ICMP
IP_PROTO_GGP : 'GGP', #IGMP
IP_PROTO_IPIP : 'IPv4', #IP in IP
IP_PROTO_ST : 'ST', #ST datagram mode
IP_PROTO_TCP : 'TCP', #TCP
IP_PROTO_CBT : 'CBT', #CBT
IP_PROTO_EGP : 'EGP', #exterior gateway protocol
IP_PROTO_IGP : 'IGP', #interior gateway protocol
IP_PROTO_BBNRCC : 'BBN-RCC-MON', #BBN RCC monitoring
IP_PROTO_NVP : 'NVP-II', #Network Voice Protocol
IP_PROTO_PUP : 'PUP', #PARC universal packet
IP_PROTO_ARGUS : 'ARGUS', #ARGUS
IP_PROTO_EMCON : 'EMCON', #EMCON
IP_PROTO_XNET : 'XNET', #Cross Net Debugger
IP_PROTO_CHAOS : 'CHAOS', #Chaos
IP_PROTO_UDP : 'UDP', #UDP
IP_PROTO_MUX : 'MUX', #multiplexing
IP_PROTO_DCNMEAS : 'DCN-MEAS', #DCN measurement
IP_PROTO_HMP : 'HMP', #Host Monitoring Protocol
IP_PROTO_PRM : 'PRM', #Packet Radio Measurement
IP_PROTO_IDP : 'XNS-IDP', #Xerox NS IDP
IP_PROTO_TRUNK1 : 'TRUNK-1', #Trunk-1
IP_PROTO_TRUNK2 : 'TRUNK-2', #Trunk-2
IP_PROTO_LEAF1 : 'LEAF-1', #Leaf-1
IP_PROTO_LEAF2 : 'LEAF-2', #Leaf-2
IP_PROTO_RDP : 'RDP', #Reliable Datagram proto
IP_PROTO_IRTP : 'IRTP', #Inet Reliable Transaction
IP_PROTO_TP : 'ISO-TP4', #ISO TP class 4
IP_PROTO_NETBLT : 'NETBLT', #Bulk Data Transfer
IP_PROTO_MFPNSP : 'MFE-NSP', #MFE Network Services
IP_PROTO_MERITINP : 'MERIT-INP', #Merit Internodal Protocol
IP_PROTO_SEP : 'DCCP', #Sequential Exchange proto
IP_PROTO_3PC : '3PC', #Third Party Connect proto
IP_PROTO_IDPR : 'IDPR', #Interdomain Policy Route
IP_PROTO_XTP : 'XTP', #Xpress Transfer Protocol
IP_PROTO_DDP : 'DDP', #Datagram Delivery Proto
IP_PROTO_CMTP : 'IDPR-CMTP', #IDPR Ctrl Message Trans
IP_PROTO_TPPP : 'TP++', #TP++ Transport Protocol
IP_PROTO_IL : 'IL', #IL Transport Protocol
IP_PROTO_IP6 : 'IPv6', #IPv6
IP_PROTO_SDRP : 'SDRP', #Source Demand Routing
IP_PROTO_ROUTING : 'IPv6-Route', #IPv6 routing header
IP_PROTO_FRAGMENT : 'IPv6-Frag', #IPv6 fragmentation header
IP_PROTO_IDRP : 'IDRP', #Inter-Domain Routing Protocol [Hares]
IP_PROTO_RSVP : 'RSVP', #Reservation protocol
IP_PROTO_GRE : 'GRE', #General Routing Encap
IP_PROTO_MHRP : 'DSR', #Mobile Host Routing
IP_PROTO_ENA : 'BNA', #ENA
IP_PROTO_ESP : 'ESP', #Encap Security Payload
IP_PROTO_AH : 'AH', #Authentication Header
IP_PROTO_INLSP : 'I-NLSP', #Integated Net Layer Sec
IP_PROTO_SWIPE : 'SWIPE', #SWIPE
IP_PROTO_NARP : 'NARP', #NBMA Address Resolution
IP_PROTO_MOBILE : 'MOBILE', #Mobile IP, RFC 2004
IP_PROTO_TLSP : 'TLSP', #Transport Layer Security
IP_PROTO_SKIP : 'SKIP', #SKIP
IP_PROTO_ICMP6 : 'IPv6-ICMP', #IPv6 ICMP
IP_PROTO_NONE : 'IPv6-NoNxt', #IPv6 no next header
IP_PROTO_DSTOPTS : 'IPv6-Opts', #IPv6 destination options
IP_PROTO_ANYHOST : 'ANYHOST', #any host internal proto
IP_PROTO_CFTP : 'CFTP', #CFTP
IP_PROTO_ANYNET : 'ANYNET', #any local network
IP_PROTO_EXPAK : 'SAT-EXPAK', #SATNET and Backroom EXPAK
IP_PROTO_KRYPTOLAN : 'KRYPTOLAN', #Kryptolan
IP_PROTO_RVD : 'RVD', #MIT Remote Virtual Disk
IP_PROTO_IPPC : 'IPPC', #Inet Pluribus Packet Core
IP_PROTO_DISTFS : 'DISTFS', #any distributed fs
IP_PROTO_SATMON : 'SAT-MON', #SATNET Monitoring
IP_PROTO_VISA : 'VISA', #VISA Protocol
IP_PROTO_IPCV : 'IPCV', #Inet Packet Core Utility
IP_PROTO_CPNX : 'CPNX', #Comp Proto Net Executive
IP_PROTO_CPHB : 'CPHB', #Comp Protocol Heart Beat
IP_PROTO_WSN : 'WSN', #Wang Span Network
IP_PROTO_PVP : 'PVP', #Packet Video Protocol
IP_PROTO_BRSATMON : 'BR-SAT-MON', #Backroom SATNET Monitor
IP_PROTO_SUNND : 'SUN-ND', #SUN ND Protocol
IP_PROTO_WBMON : 'WB-MON', #WIDEBAND Monitoring
IP_PROTO_WBEXPAK : 'WB-EXPAK', #WIDEBAND EXPAK
IP_PROTO_EON : 'ISO-IP', #ISO CNLP
IP_PROTO_VMTP : 'VMTP', #Versatile Msg Transport
IP_PROTO_SVMTP : 'SECURE-VMTP', #Secure VMTP
IP_PROTO_VINES : 'VINES', #VINES
IP_PROTO_TTP : 'TTP', #TTP
IP_PROTO_NSFIGP : 'NSFNET-IGP', #NSFNET-IGP
IP_PROTO_DGP : 'DGP', #Dissimilar Gateway Proto
IP_PROTO_TCF : 'TCF', #TCF
IP_PROTO_EIGRP : 'EIGRP', #EIGRP
IP_PROTO_OSPF : 'OSPFIGP', #Open Shortest Path First
IP_PROTO_SPRITERPC : 'Sprite-RPC', #Sprite RPC Protocol
IP_PROTO_LARP : 'LARP', #Locus Address Resolution
IP_PROTO_MTP : 'MTP', #Multicast Transport Proto
IP_PROTO_AX25 : 'AX.25', #AX.25 Frames
IP_PROTO_IPIPENCAP : 'IPIP', #yet-another IP encap
IP_PROTO_MICP : 'MICP', #Mobile Internet Ctrl
IP_PROTO_SCCSP : 'SCC-SP', #Semaphore Comm Sec Proto
IP_PROTO_ETHERIP : 'ETHERIP', #Ethernet in IPv4
IP_PROTO_ENCAP : 'ENCAP', #encapsulation header
IP_PROTO_ANYENC : 'ANYENC', #Ipsilon #private encryption scheme
IP_PROTO_GMTP : 'GMTP', #GMTP
IP_PROTO_IFMP : 'IFMP', #Flow Mgmt Proto
IP_PROTO_PNNI : 'PNNI', #PNNI over IP
IP_PROTO_PIM : 'PIM', #Protocol Indep Multicast
IP_PROTO_ARIS : 'ARIS', #ARIS
IP_PROTO_SCPS : 'SCPS', #SCPS
IP_PROTO_QNX : 'QNX', #QNX
IP_PROTO_AN : 'A_N', #Active Networks
IP_PROTO_IPCOMP : 'IPComp', #IP Payload Compression
IP_PROTO_SNP : 'SNP', #Sitara Networks Protocol
IP_PROTO_COMPAQPEER : 'Compaq-Peer', #Compaq Peer Protocol
IP_PROTO_IPXIP : 'IPX-in-IP', #IPX in IP
IP_PROTO_VRRP : 'VRRP', #Virtual Router Redundancy
IP_PROTO_PGM : 'PGM', #PGM Reliable Transport
IP_PROTO_ANY0HOP : 'ANY0HOP', #0-hop protocol
IP_PROTO_L2TP : 'L2TP', #Layer 2 Tunneling Proto
IP_PROTO_DDX : 'DDX', #Data Exchange (DDX)
IP_PROTO_IATP : 'IATP', #Interactive Agent Xfer
IP_PROTO_STP : 'STP', #Schedule Transfer Proto
IP_PROTO_SRP : 'SRP', #SpectraLink Radio Proto
IP_PROTO_UTI : 'UTI', #UTI
IP_PROTO_SMP : 'SMP', #Simple Message Protocol
IP_PROTO_SM : 'SM', #SM
IP_PROTO_PTP : 'PTP', #Performance Transparency
IP_PROTO_ISIS : 'ISIS', #ISIS over IPv4
IP_PROTO_FIRE : 'FIRE', #FIRE
IP_PROTO_CRTP : 'CRTP', #over IPv4 #Combat Radio Transport
IP_PROTO_CRUDP : 'CRUDP', #Combat Radio UDP
IP_PROTO_SSCOPMCE : 'SSCOPMCE', #SSCOPMCE
IP_PROTO_IPLT : 'IPLT', #IPLT
IP_PROTO_SPS : 'SPS', #Secure Packet Shield
IP_PROTO_PIPE : 'PIPE', #Private IP Encap in IP
IP_PROTO_SCTP : 'SCTP', #Stream Ctrl Transmission
IP_PROTO_FC : 'FC', #Fibre Channel
IP_PROTO_RSVPIGN : 'RSVP-E2E-IGNORE', #RSVP-E2E-IGNORE
IP_PROTO_Mobility_Header : 'Mobility_Header', #Mobility Header
IP_PROTO_UDPLite : 'UDPLite', #UDPLite
IP_PROTO_MPLS_in_IP : 'MPLS-in-IP', #MPLS-in-IP
IP_PROTO_MANET : 'MANET', #MANET
IP_PROTO_HIP : 'HIP', #HIP
IP_PROTO_Shim6 : 'Shime6', #Shim6
IP_PROTO_WESP : 'WESP', #WESP
IP_PROTO_ROHC : 'ROHC', #ROHC
IP_PROTO_RAW : 'RAW', #raw
IP_PROTO_RESERVED : 'RESERVED', #Reserved
IP_PROTO_MAX : 'MAX', #Reserved
}
ip_protocols_rev = {
'HOPOPT' : IP_PROTO_IP , #dummy for IP
'HOPOPT' : IP_PROTO_HOPOPTS, #IPv6 hop-by-hop options
'ICMP' : IP_PROTO_ICMP , #IPv6 hop-by-hop options
'IGMP' : IP_PROTO_IGMP , #ICMP
'GGP' : IP_PROTO_GGP , #IGMP
'IPv4' : IP_PROTO_IPIP , #IP in IP
'ST' : IP_PROTO_ST , #ST datagram mode
'TCP' : IP_PROTO_TCP , #TCP
'CBT' : IP_PROTO_CBT , #CBT
'EGP' : IP_PROTO_EGP , #exterior gateway protocol
'IGP' : IP_PROTO_IGP , #interior gateway protocol
'BBN-RCC-MON' : IP_PROTO_BBNRCC , #BBN RCC monitoring
'NVP-II' : IP_PROTO_NVP , #Network Voice Protocol
'PUP' : IP_PROTO_PUP , #PARC universal packet
'ARGUS' : IP_PROTO_ARGUS , #ARGUS
'EMCON' : IP_PROTO_EMCON , #EMCON
'XNET' : IP_PROTO_XNET , #Cross Net Debugger
'CHAOS' : IP_PROTO_CHAOS , #Chaos
'UDP' : IP_PROTO_UDP , #UDP
'MUX' : IP_PROTO_MUX , #multiplexing
'DCN-MEAS' : IP_PROTO_DCNMEAS , #DCN measurement
'HMP' : IP_PROTO_HMP , #Host Monitoring Protocol
'PRM' : IP_PROTO_PRM , #Packet Radio Measurement
'XNS-IDP' : IP_PROTO_IDP , #Xerox NS IDP
'TRUNK-1' : IP_PROTO_TRUNK1 , #Trunk-1
'TRUNK-2' : IP_PROTO_TRUNK2 , #Trunk-2
'LEAF-1' : IP_PROTO_LEAF1 , #Leaf-1
'LEAF-2' : IP_PROTO_LEAF2 , #Leaf-2
'RDP' : IP_PROTO_RDP , #Reliable Datagram proto
'IRTP' : IP_PROTO_IRTP , #Inet Reliable Transaction
'ISO-TP4' : IP_PROTO_TP , #ISO TP class 4
'NETBLT' : IP_PROTO_NETBLT , #Bulk Data Transfer
'MFE-NSP' : IP_PROTO_MFPNSP , #MFE Network Services
'MERIT-INP' : IP_PROTO_MERITINP , #Merit Internodal Protocol
'DCCP' : IP_PROTO_SEP , #Sequential Exchange proto
'3PC' : IP_PROTO_3PC , #Third Party Connect proto
'IDPR' : IP_PROTO_IDPR , #Interdomain Policy Route
'XTP' : IP_PROTO_XTP , #Xpress Transfer Protocol
'DDP' : IP_PROTO_DDP , #Datagram Delivery Proto
'IDPR-CMTP' : IP_PROTO_CMTP , #IDPR Ctrl Message Trans
'TP++' : IP_PROTO_TPPP , #TP++ Transport Protocol
'IL' : IP_PROTO_IL , #IL Transport Protocol
'IPv6' : IP_PROTO_IP6 , #IPv6
'SDRP' : IP_PROTO_SDRP , #Source Demand Routing
'IPv6-Route' : IP_PROTO_ROUTING , #IPv6 routing header
'IPv6-Frag' : IP_PROTO_FRAGMENT , #IPv6 fragmentation header
'IDRP' : IP_PROTO_IDRP , #Inter-Domain Routing Protocol [Hares]
'RSVP' : IP_PROTO_RSVP , #Reservation protocol
'GRE' : IP_PROTO_GRE , #General Routing Encap
'DSR' : IP_PROTO_MHRP, #Mobile Host Routing
'BNA' : IP_PROTO_ENA , #ENA
'ESP' : IP_PROTO_ESP , #Encap Security Payload
'AH' : IP_PROTO_AH , #Authentication Header
'I-NLSP' : IP_PROTO_INLSP , #Integated Net Layer Sec
'SWIPE' : IP_PROTO_SWIPE , #SWIPE
'NARP' : IP_PROTO_NARP , #NBMA Address Resolution
'MOBILE' : IP_PROTO_MOBILE , #Mobile IP , RFC 2004
'TLSP' : IP_PROTO_TLSP , #Transport Layer Security
'SKIP' : IP_PROTO_SKIP , #SKIP
'IPv6-ICMP' : IP_PROTO_ICMP6 , #IPv6 ICMP
'IPv6-NoNxt' : IP_PROTO_NONE , #IPv6 no next header
'IPv6-Opts' : IP_PROTO_DSTOPTS , #IPv6 destination options
'ANYHOST' : IP_PROTO_ANYHOST , #any host internal proto
'CFTP' : IP_PROTO_CFTP , #CFTP
'ANYNET' : IP_PROTO_ANYNET , #any local network
'SAT-EXPAK' : IP_PROTO_EXPAK , #SATNET and Backroom EXPAK
'KRYPTOLAN' : IP_PROTO_KRYPTOLAN , #Kryptolan
'RVD' : IP_PROTO_RVD , #MIT Remote Virtual Disk
'IPPC' : IP_PROTO_IPPC , #Inet Pluribus Packet Core
'DISTFS' : IP_PROTO_DISTFS , #any distributed fs
'SAT-MON' : IP_PROTO_SATMON , #SATNET Monitoring
'VISA' : IP_PROTO_VISA , #VISA Protocol
'IPCV' : IP_PROTO_IPCV , #Inet Packet Core Utility
'CPNX' : IP_PROTO_CPNX , #Comp Proto Net Executive
'CPHB' : IP_PROTO_CPHB , #Comp Protocol Heart Beat
'WSN' : IP_PROTO_WSN , #Wang Span Network
'PVP' : IP_PROTO_PVP , #Packet Video Protocol
'BR-SAT-MON' : IP_PROTO_BRSATMON , #Backroom SATNET Monitor
'SUN-ND' : IP_PROTO_SUNND , #SUN ND Protocol
'WB-MON' : IP_PROTO_WBMON , #WIDEBAND Monitoring
'WB-EXPAK' : IP_PROTO_WBEXPAK , #WIDEBAND EXPAK
'ISO-IP' : IP_PROTO_EON , #ISO CNLP
'VMTP' : IP_PROTO_VMTP , #Versatile Msg Transport
'SECURE-VMTP' : IP_PROTO_SVMTP , #Secure VMTP
'VINES' : IP_PROTO_VINES , #VINES
'TTP' : IP_PROTO_TTP , #TTP
'NSFNET-IGP' : IP_PROTO_NSFIGP , #NSFNET-IGP
'DGP' : IP_PROTO_DGP , #Dissimilar Gateway Proto
'TCF' : IP_PROTO_TCF , #TCF
'EIGRP' : IP_PROTO_EIGRP , #EIGRP
'OSPFIGP' : IP_PROTO_OSPF , #Open Shortest Path First
'Sprite-RPC' : IP_PROTO_SPRITERPC , #Sprite RPC Protocol
'LARP' : IP_PROTO_LARP , #Locus Address Resolution
'MTP' : IP_PROTO_MTP , #Multicast Transport Proto
'AX.25' : IP_PROTO_AX25 , #AX.25 Frames
'IPIP' : IP_PROTO_IPIPENCAP, #yet-another IP encap
'MICP' : IP_PROTO_MICP , #Mobile Internet Ctrl
'SCC-SP' : IP_PROTO_SCCSP , #Semaphore Comm Sec Proto
'ETHERIP' : IP_PROTO_ETHERIP , #Ethernet in IPv4
'ENCAP' : IP_PROTO_ENCAP , #encapsulation header
'ANYENC' : IP_PROTO_ANYENC , #Ipsilon #private encryption scheme
'GMTP' : IP_PROTO_GMTP , #GMTP
'IFMP' : IP_PROTO_IFMP , #Flow Mgmt Proto
'PNNI' : IP_PROTO_PNNI , #PNNI over IP
'PIM' : IP_PROTO_PIM , #Protocol Indep Multicast
'ARIS' : IP_PROTO_ARIS , #ARIS
'SCPS' : IP_PROTO_SCPS , #SCPS
'QNX' : IP_PROTO_QNX , #QNX
'A_N' : IP_PROTO_AN , #Active Networks
'IPComp' : IP_PROTO_IPCOMP , #IP Payload Compression
'SNP' : IP_PROTO_SNP , #Sitara Networks Protocol
'Compaq-Peer' : IP_PROTO_COMPAQPEER , #Compaq Peer Protocol
'IPX-in-IP' : IP_PROTO_IPXIP , #IPX in IP
'VRRP' : IP_PROTO_VRRP , #Virtual Router Redundancy
'PGM' : IP_PROTO_PGM , #PGM Reliable Transport
'ANY0HOP' : IP_PROTO_ANY0HOP, #0-hop protocol
'L2TP' : IP_PROTO_L2TP , #Layer 2 Tunneling Proto
'DDX' : IP_PROTO_DDX , #Data Exchange (DDX)
'IATP' : IP_PROTO_IATP , #Interactive Agent Xfer
'STP' : IP_PROTO_STP , #Schedule Transfer Proto
'SRP' : IP_PROTO_SRP , #SpectraLink Radio Proto
'UTI' : IP_PROTO_UTI , #UTI
'SMP' : IP_PROTO_SMP , #Simple Message Protocol
'SM' : IP_PROTO_SM , #SM
'PTP' : IP_PROTO_PTP , #Performance Transparency
'ISIS' : IP_PROTO_ISIS , #ISIS over IPv4
'FIRE' : IP_PROTO_FIRE , #FIRE
'CRTP' : IP_PROTO_CRTP , #over IPv4 #Combat Radio Transport
'CRUDP' : IP_PROTO_CRUDP , #Combat Radio UDP
'SSCOPMCE' : IP_PROTO_SSCOPMCE , #SSCOPMCE
'IPLT' : IP_PROTO_IPLT , #IPLT
'SPS' : IP_PROTO_SPS , #Secure Packet Shield
'PIPE' : IP_PROTO_PIPE , #Private IP Encap in IP
'SCTP' : IP_PROTO_SCTP , #Stream Ctrl Transmission
'FC' : IP_PROTO_FC , #Fibre Channel
'RSVP-E2E-IGNORE' : IP_PROTO_RSVPIGN , #RSVP-E2E-IGNORE
'Mobility_Header' : IP_PROTO_Mobility_Header , #Mobility Header
'UDPLite' : IP_PROTO_UDPLite , #UDPLite
'MPLS-in-IP' : IP_PROTO_MPLS_in_IP , #MPLS-in-IP
'MANET' : IP_PROTO_MANET , #MANET
'HIP' : IP_PROTO_HIP , #HIP
'Shime6' : IP_PROTO_Shim6 , #Shim6
'WESP' : IP_PROTO_WESP , #WESP
'ROHC' : IP_PROTO_ROHC , #ROHC
'RAW' : IP_PROTO_RAW , #raw
'RESERVED' : IP_PROTO_RESERVED , #Reserved
'MAX' : IP_PROTO_MAX , #Reserved
}
import unittest
class IPTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testIP_protocols(self):
for i in range(143):
print ("protocol no. %d is %s"%(i, ip_protocols[i]) )
#print ("6 is %s"%( ip_protocols[6]))
assert 'TCP' == ip_protocols[6]
def testIP_protocols_rev(self):
for i in range(143):
print ("protocol %s is no. %d "%(ip_protocols[i], ip_protocols_rev[ip_protocols[i]]) )
#print ("TCP is %s"%( ip_protocols_rev['TCP']))
assert 6 == ip_protocols_rev['TCP']
def testIP_IPrev(self):
for i in range(143):
assert ( i==ip_protocols_rev[ip_protocols[i]] )
def test_suite():
suite = unittest.TestSuite()
suite.addTests([unittest.makeSuite(IPTestCase)])
return suite
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
# Copyright (c)
#
# pcapy: open_offline, pcapdumper.
# ImpactDecoder.
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
import pcapy
from pcapy import open_offline
import impacket
from impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder
import appconfig as APPCONFIG
import ipdef as IPDEF
sys.stderr=sys.stdout
try:
from lxml import etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info("running with ElementTree")
except ImportError:
logging.info("Failed to import ElementTree from any known place")
this_dir = os.path.dirname(__file__)
if this_dir not in sys.path:
sys.path.insert(0, this_dir) # needed for Py3
#from common_imports import etree, StringIO, BytesIO, HelperTestCase, fileInTestDir
#from common_imports import SillyFileLike, LargeFileLikeUnicode, doctest, make_doctest
#from common_imports import canonicalize, sorted, _str, _bytes
try:
_unicode = unicode
except NameError:
# Python 3
_unicode = str
ETHERNET_MAX_FRAME_SIZE = 1518
PROMISC_MODE = 0
class Connection:
"""This class can be used as a key in a dictionary to select a connection
given a pair of peers. Two connections are considered the same if both
peers are equal, despite the order in which they were passed to the
class constructor.
"""
def __init__(self, p1, p2, p3):
"""This constructor takes two tuples, one for each peer. The first
element in each tuple is the IP address as a string, and the
second is the port as an integer.
"""
self.p1 = p1
self.p2 = p2
#self.p3 = p3
self.proto_id=p3
self.protocol = "unknown"
self.curpath= "."
def getFilename(self):
"""Utility function that returns a filename composed by the IP
addresses and ports of both peers.
"""
try:
if self.proto_id:
if self.proto_id == socket.IPPROTO_TCP:
self.protocol = "TCP"
elif self.proto_id == socket.IPPROTO_UDP:
self.protocol = "UDP"
else:
self.protocol = IPDEF.ip_protocols[self.proto_id]
except Exception, e:
logging.error("failed setting protocol. Error: %s" % str(e))
#APPCONFIG.GlobalConfig["appname"] = self.FindNameFromXML(self.p1, self.p2, self.protocol)
appname_s= self.FindNameFromXML(self.p1, self.p2, self.protocol)
#global this_dir
self.curpath=APPCONFIG.GlobalConfig["outputpathname"]+os.path.sep+appname_s+os.path.sep
#self.curpath=os.path.join(APPCONFIG.GlobalConfig["outputpathname"],APPCONFIG.GlobalConfig["appname"])
APPCONFIG.mkdir_p(self.curpath)
return '%s%s-%d-%s-%s-%d.pcap'%(self.curpath, self.p1[0],self.p1[1],self.protocol, self.p2[0],self.p2[1])
def FindNameFromXML(self, src, dst, protocol):
for line in APPCONFIG.xmlbuffer:
if (line[2][1] == src[0] and line[3][1] ==str(src[1]) and line[4][1] == dst[0] and line[5][1] == str(dst[1]) and line[6][1] == protocol ):
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ( "found!: application %s, PID %s"% (line[0][1] , line[1][1] ))
app_str= line[0][1] +"@"+line[1][1]
app_str_limited=''
p = re.compile('[a-zA-Z0-9,.@]')
for i in app_str:
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='-'
return app_str_limited
if APPCONFIG.GlobalConfig['isVerbose']==True:
logging.info ("missed!....")
return "notfound_in_XML@0"
def getNetdudeFileName(self):
netdude_output_path=APPCONFIG.GlobalConfig['tmp_netdude_path']
proto_number = self.proto_id
s_ip=self.p1[0]
s_port=self.p1[1]
d_ip=self.p2[0]
d_port=self.p2[1]
fullpath1 = "%s%s%d%s%s%s%s"%(netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
s_ip,
os.path.sep,
d_ip)
fullpath2 = "%s%s%d%s%s%s%s"% (netdude_output_path,
os.path.sep,
proto_number,
os.path.sep,
d_ip,
os.path.sep,
s_ip)
fullpath=[fullpath1,fullpath2]
ports1="*-%s-%s.trace" % (s_port,d_port)
ports2="*-%s-%s.trace" % (d_port,s_port)
port_pair = [ports1,ports2]
tracename_list=[]
#print ports2
for i_path in fullpath:
#print (i_path),
if os.path.isdir(i_path):
for i_port in port_pair:
#print (i_port)
fullfilename=i_path+os.path.sep+i_port
#print (fullfilename)
for f in glob.glob(fullfilename):
#print (f)
if os.path.isfile(f):
tracename_list.append(f)
return tracename_list
def __cmp__(self, other):
if ((self.p1 == other.p1 and self.p2 == other.p2)
or (self.p1 == other.p2 and self.p2 == other.p1)):
return 0
else:
return -1
def __hash__(self):
return (hash(self.p1[0]) ^ hash(self.p1[1])^ hash(self.proto_id)
^ hash(self.p2[0]) ^ hash(self.p2[1]))
class Decoder:
def __init__(self, pcapObj):
# Query the type of the link and instantiate a decoder accordingly.
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def start(self):
# Sniff ad infinitum.
# PacketHandler shall be invoked by pcap for every packet.
self.pcap.loop(0, self.packetHandler)
def packetHandler(self, hdr, data):
"""Handles an incoming pcap packet. This method only knows how
to recognize TCP/IP connections.
Be sure that only TCP packets are passed onto this handler (or
fix the code to ignore the others).
Setting r"ip proto \tcp" as part of the pcap filter expression
suffices, and there shouldn't be any problem combining that with
other expressions.
"""
# Use the ImpactDecoder to turn the rawpacket into a hierarchy
# of ImpactPacket instances.
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
#ip = p.child()
#tcp = ip.child()
# Build a distinctive key for this pair of peers.
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#os.remove(tmpPCAPFileName)
#open(tmpPCAPFileName, 'w').close()
#dumper = self.pcap.dump_open(tmpPCAPFileName)
#if not self.connections.has_key(con):
if con not in self.connections:
logging.info("found flow for the first time: saving to %s" % outputPCAPFileName)
#self.connections[con]=1
self.connections.append(con)
try:
open(outputPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
else:
logging.info( "found duplicated flows, creating a tempfile: %s to append to %s" % (tmpPCAPFileName,outputPCAPFileName) )
try:
open(tmpPCAPFileName, 'w').close()
dumper = self.pcap.dump_open(tmpPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error("Can't write packet to:\n---%s ", tmpPCAPFileName,str(e) )
##Write the packet to the corresponding file.
del dumper
tmpPCAPFileName2 = "/tmp/append2.pcap"
if os.path.isfile(outputPCAPFileName):
#os.rename( outputPCAPFileName , tmpPCAPFileName2 )
os.system("mv %s %s"%( outputPCAPFileName, tmpPCAPFileName2 ))
appendpcap_cmd_1 = "mergecap -w %s %s %s " % (outputPCAPFileName,tmpPCAPFileName2,tmpPCAPFileName)
#appendpcap_cmd_1="pcapnav-concat %s %s"%(outputPCAPFileName, tmpPCAPFileName)
os.system(appendpcap_cmd_1)
#self.connections[con] += 1
os.remove(tmpPCAPFileName2)
#os.rename(tmpPCAPFileName2,outputPCAPFileName)
#logging.info ( self.connections[con] )
else:
logging.error( "did nothing" )
logging.error("%s is in %s\ntry again!!!" % (outputPCAPFileName, str(con in self.connections) ))
try:
dumper = self.pcap.dump_open(outputPCAPFileName)
dumper.dump(hdr,data)
except pcapy.PcapError, e:
logging.error( "Can't write packet to :%s\n---%s", outputPCAPFileName, str(e) )
del dumper
logging.error("succeded =%s" % str(os.path.isfile(outputPCAPFileName)))
class NetdudeDecoder(Decoder):
"""
"""
def __init__(self,pcapObj ):
"""
"""
self.proto_id = None
self.src_ip = None
self.tgt_ip = None
self.src_port = None
self.tgt_port = None
self.msgs = [] # error msgs
datalink = pcapObj.datalink()
if pcapy.DLT_EN10MB == datalink:
self.decoder = EthDecoder()
elif pcapy.DLT_LINUX_SLL == datalink:
self.decoder = LinuxSLLDecoder()
else:
raise Exception("Datalink type not supported: " % datalink)
self.pcap = pcapObj
self.connections = []
def packetHandler(self, hdr, data):
try:
p = self.decoder.decode(data)
logging.debug("start decoding" )
except Exception, e:
logging.error("p = self.decoder.decode(data) failed for device" )
msgs.append(str(e))
# get the details from the decoded packet data
if p:
try:
self.src_ip = p.child().get_ip_src()
self.tgt_ip = p.child().get_ip_dst()
self.proto_id = p.child().child().protocol
except Exception, e:
logging.error("exception while parsing ip packet: %s" % str(e))
self.msgs.append(str(e))
if self.proto_id:
try:
if self.proto_id == socket.IPPROTO_TCP:
self.tgt_port = p.child().child().get_th_dport()
self.src_port = p.child().child().get_th_sport()
elif self.proto_id == socket.IPPROTO_UDP:
self.tgt_port = p.child().child().get_uh_dport()
self.src_port = p.child().child().get_uh_sport()
except Exception, e:
logging.error("exception while parsing tcp/udp packet: %s" % str(e))
self.msgs.append(str(e))
src = (self.src_ip, self.src_port)
dst = (self.tgt_ip, self.tgt_port )
con = Connection(src,dst, self.proto_id)
outputPCAPFileName=con.getFilename()
merge_cmd1="mergecap -w %s" % (outputPCAPFileName)
merge_cmd_readtrace_filename=' '
readPCAPFileNameFromNetdude=con.getNetdudeFileName()
for rr in readPCAPFileNameFromNetdude:
merge_cmd_readtrace_filename += ( "%s " % (rr) )
merge_cmd = ("%s%s" % (merge_cmd1, merge_cmd_readtrace_filename) )
print (merge_cmd)
os.system(merge_cmd)
print ("------")
tmpPCAPFileName="/tmp/appending.pcap"
appendpcap_cmd_1=''
import shutil
def SplitPcapByNetdude():
shutil.rmtree(APPCONFIG.GlobalConfig["tmp_netdude_path"],ignore_errors=True)
netdude_cmd1=( "lndtool -r Demux -o %s %s" % (APPCONFIG.GlobalConfig["tmp_netdude_path"], APPCONFIG.GlobalConfig["pcapfilename"]) )
os.system(netdude_cmd1)
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#print filename
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
print "Reading from %s: linktype=%d" % (filename, p.datalink())
# Start decoding process.
NetdudeDecoder(p).start()
os.system('ls %s' % (APPCONFIG.GlobalConfig["tmp_netdude_path"] ))
os.system("rm -rf %s"% (APPCONFIG.GlobalConfig["tmp_netdude_path"] ) )
def main():
#mkdir output_path
APPCONFIG.mkdir_p(APPCONFIG.GlobalConfig["outputpathname"])
xmlfile=open(APPCONFIG.GlobalConfig["xmlfilename"], 'r')
root = etree.parse(xmlfile)
for element in root.iter("session"):
line=element.attrib.items()
APPCONFIG.xmlbuffer.append(line)
if APPCONFIG.GlobalConfig["isNetdude"] == True:
logging.info("splitting pcap trace into flows by netdude")
SplitPcapByNetdude()
if APPCONFIG.GlobalConfig["isSplit"]==True:
logging.info("splitting pcap trace into flows")
SplitPcap()
if APPCONFIG.GlobalConfig["isMerge"]==True:
logging.info("Merging flows into applications")
MergepcapInDir(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig["isFeature"]==True:
logging.info("computing flow features")
FeatureCompute(APPCONFIG.GlobalConfig["outputpathname"])
if APPCONFIG.GlobalConfig['ismergearff']==True:
logging.info ("merging arff filenames")
MergeARFF(APPCONFIG.GlobalConfig["outputpathname"])
logging.info("---done---")
def SplitPcap():
# Open file
filename=APPCONFIG.GlobalConfig["pcapfilename"]
#logging.info (filename )
p = open_offline(filename)
# At the moment the callback only accepts TCP/IP packets.
#p.setfilter(r'ip proto \tcp')
p.setfilter(r'ip')
logging.info ("Reading from %s: linktype=%d" % (filename, p.datalink()) )
# Start decoding process.
Decoder(p).start()
#p.close() #flk3y: avoid p.close() error, after GC?
def FeatureCompute(currentdirname):
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in filesHere:
(shortname, extension) = os.path.splitext(filename)
pcapfullname = os.path.join(thisDir,filename)
#featurefilename =
if( os.path.isfile(pcapfullname) and (extension==".pcap" or extension == ".PCAP" ) ):
#fullfeaturefilename=pcapfullname+".arff"
#cmd1_s= "rm %s" % (APPCONFIG.GlobalConfig['tmp_arff_filename'])
if os.path.isfile(APPCONFIG.GlobalConfig['tmp_arff_filename']):
os.remove(APPCONFIG.GlobalConfig['tmp_arff_filename'])
cmd1_s='OpenDPI_demo -f %s' % pcapfullname
p = Popen(cmd1_s, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,close_fds=True)
output = p.stdout.read()
prog=re.compile("###.*###")
m = prog.search(output)
p = re.compile('[a-zA-Z0-9,.@#_]')
app_str_limited=''
for i in m.group(0):
if p.match(i):
app_str_limited+=i
else:
app_str_limited+='='
appfilename=pcapfullname+"."+app_str_limited+".arff"
logging.info ("computing feature to: %s" % appfilename)
cmd2_s= "netmate -f %s" % (pcapfullname )
cmd3_s= "mv %s %s"%(APPCONFIG.GlobalConfig['tmp_arff_filename'],appfilename)
#os.system(cmd1_s)
#os.system(cmd2_s)
#os.system(cmd3_s)
allcmd_s=("%s && %s"%(cmd2_s,cmd3_s))
os.system(allcmd_s)
else:
logging.info ("%s is not a directory" % pcapfullname )
pass
def MergepcapInDir(currentdirname):#TODO: add mergecap files into a list, then pop up when merging
all_cmd_s=[]
BATCH_NUM=50
tmp_pcap="/tmp/tmp_pcap"
os.system(("rm -f %s%s*.pcap ")%(currentdirname,os.sep))
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for filename in subsHere:
#print ("==%s" % filename)
fullname = os.path.join(thisDir,filename)
if(os.path.isdir(fullname) ):
pcapname=fullname+".pcap"
print ("==%s" % filename)
os.system(("rm -f %s ")%(tmp_pcap))
pcap_list=[]
#if os.path.isfile(pcapname):
# os.remove(pcapname)
for (f_dir,f_subs,f_files) in os.walk(fullname):
pcap_f=[]
for f in f_files:
if (f[-5:] == '.pcap'):
pcap_f.append(f_dir+os.sep+f)
#print (pcap_f)
while (len(pcap_f) != 0):
tmp_s=""
pcap_f_length=len(pcap_f)
if (pcap_f_length >=BATCH_NUM):
for i in range(BATCH_NUM) :
tmp_s =tmp_s+" "+pcap_f.pop()+" "
pcap_list.append(tmp_s)
else:
for i in range(pcap_f_length):
tmp_s=tmp_s+" "+pcap_f.pop()+" "
#print (tmp_s)
pcap_list.append(tmp_s)
print ("remaining pcap %d files to read" % pcap_f_length)
#print (pcap_list)
#for i in pcap_list:
# #cmd_s='mergecap -w %s %s' % (pcapname,i)
# all_cmd_s.append(i)
#print (cmd_s)
#print (all_cmd_s)
print ("----- %s ------\ntmp_pcap output_pcap" % pcapname)
logging.info ("%s is a directory, merging all pcap files in it" % fullname )
for i in pcap_list:
if ( os.path.isfile(tmp_pcap) and os.path.isfile(pcapname) ):
print (" Y Y :You'd better not be here, but it OK")
os.remove(tmp_pcap)
os.rename(pcapname,tmp_pcap)
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
elif ( os.path.isfile(tmp_pcap) and (not os.path.isfile(pcapname)) ):
print (" Y N :You should not be here! there may errors happened ")
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
elif ((not os.path.isfile(tmp_pcap)) and (os.path.isfile(pcapname)) ) :
print (" N Y")
os.rename(pcapname,tmp_pcap)
cmd="mergecap -w %s %s %s" % (pcapname,tmp_pcap,i)
os.system(cmd)
os.remove(tmp_pcap)
else:
print ("creating...\n N N")
cmd="mergecap -w %s %s" % (pcapname,i)
#print (cmd)
os.system(cmd)
else:
logging.info ("%s is not a directory" % fullname )
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpiclass {''',
'''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
def MergeARFF(currentdirname):
global arff_head_s
for (thisDir, subsHere, filesHere) in os.walk(currentdirname):
for dirname in subsHere:
fullsubdirname = os.path.join(thisDir,dirname)
if(os.path.isdir(fullsubdirname) ):
#appendable=False
arff_big_name=fullsubdirname+".merged.arff"
opendpiclass_list=[]
writelines_data=[]
if (os.path.isfile(arff_big_name)) :
os.remove(arff_big_name)
appendable = True
#q_arff_big = open(arff_big_name,'a')
#q_arff_big.write(arff_head_s[0])
#q_arff_big.write("test")
#q_arff_big.write(arff_head_s[1])
logging.info ("%s is a directory, merging all arff files in it" % fullsubdirname )
for (sub_thisdir,sub_subshere,sub_filesHere ) in os.walk(fullsubdirname):
for filename in sub_filesHere:
(shortname, extension) = os.path.splitext(filename)
foundData=False
#appendable=False
#logging.info ("merging %s" % filename)
if( (extension==".arff" or extension == ".ARFF" ) and (shortname[-3:]=='###' ) ):
logging.info ("merging %s" % filename)
opendpi_apptype=shortname.split('.')[-1][3:-3] # for example: blah.blah.blah.###type1_type2_###
logging.error (opendpi_apptype)
if opendpi_apptype not in opendpiclass_list:
opendpiclass_list.append(opendpi_apptype)
full_arff_name = os.path.join(sub_thisdir,filename)
if appendable == True:
p = open(full_arff_name,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData=True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
#q_arff_big.write
writelines_data.append( (line.strip()+","+opendpi_apptype+"\n") )
q_arff_big = open(arff_big_name,'a')
q_arff_big.write(arff_head_s[0])
for i in opendpiclass_list:
q_arff_big.write( "%s," % i )
q_arff_big.write(arff_head_s[1])
for ii in writelines_data:
q_arff_big.write(ii)
q_arff_big.close()
else:
logging.info ("%s is not a directory" % fullname )
pass
def ParseCMD():
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-x","--xmlfilename",dest="xmlfilename",
metavar="XML", help= "read XML, which was generated by network bandwith monitor")
parser.add_option("-f", "--pcapfilename",dest="pcapfilename",
metavar="FILE", help="write output to FILE")
parser.add_option("-o", "--output_path",dest="output_path",
metavar="OUTPUT_PATH", help="write output OUTPUT_PATH/FILE.demux")
#parser.add_option('-M', '--MODE',
# type='choice',
# action='store',
# dest='modechoice',
# choices=['all','split_only', 'merge_only', 'feature_only',],
# default='all',
# help='mode to run on: all, split_only, merge_only, feature_only',)
parser.add_option("-a", "--all",
default=False,
dest='isall',
action='store_true',
help="enable all: split->merge->calculate features ",)
parser.add_option("-s","--split",
default=False,
dest='issplit',
action='store_true',
help="split pcap trace into flows",)
parser.add_option("-m","--merge",
default=False,
dest='ismerge',
action='store_true',
help="merge flows from the same application into one pcap trace",)
parser.add_option("-g","--mergearff",
default=False,
dest='ismergearff',
action='store_true',
help="merge .arff files from the same application into one",)
parser.add_option("-c","--computefeatures",
default=False,
dest='isfeature',
action='store_true',
help="compute features for every pcap file in OUTPUT_PATH",)
parser.add_option("-n","--netdude",
default=False,
dest='isNetdude',
action='store_true',
help="enable libnetdude's demuxer")
(options, args) = parser.parse_args()
#if len(args) != 1:
# parser.error("incorrect number of arguments")
if options.pcapfilename:
APPCONFIG.GlobalConfig["pcapfilename"] = options.pcapfilename
if options.output_path:
APPCONFIG.GlobalConfig["outputpathname"] = options.output_path
else:
APPCONFIG.GlobalConfig["outputpathname"] = options.pcapfilename+".demux"
if options.xmlfilename:
APPCONFIG.GlobalConfig["xmlfilename"]= options.xmlfilename
if options.isall:
APPCONFIG.GlobalConfig['isAll']=True
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.isNetdude:
options.isNetdude=True
options.issplit=False
APPCONFIG.GlobalConfig['isSplit']=False
APPCONFIG.GlobalConfig['isNetdude']=True
if options.issplit:
options.issplit=True
APPCONFIG.GlobalConfig['isSplit']=True
if options.ismerge:
options.ismerge=True
APPCONFIG.GlobalConfig['isMerge']=True
if options.ismergearff:
options.ismergearff=True
APPCONFIG.GlobalConfig['ismergearff']=True
if options.isfeature:
options.isfeature=True
APPCONFIG.GlobalConfig['isFeature']=True
if options.verbose:
APPCONFIG.GlobalConfig['isVerbose']=True
logging.info ("------running info.---------")
logging.info ("Reading xmlfile %s..." % options.xmlfilename)
logging.info ("Reading pcapfile %s..." % options.pcapfilename)
if options.output_path:
logging.info ("demux to path: %s"%options.output_path)
else:
logging.info ("have not assigned, output to %s.demux by default"%options.pcapfilename)
logging.info ( "Split pcap trace: %s" % str(APPCONFIG.GlobalConfig['isSplit']) )
logging.info ( "Merge flows into applications: %s"% str(APPCONFIG.GlobalConfig['isMerge']) )
logging.info ( "compute features: %s"% str(APPCONFIG.GlobalConfig['isFeature']) )
logging.info ("------------end info.------------")
# Process command-line arguments.
if __name__ == '__main__':
ParseCMD()
main()
exit()
| Python |
#!/usr/bin/env python
import os,sys, logging, socket
import subprocess
import string
from exceptions import Exception
from threading import Thread
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import re
import glob
sys.stderr=sys.stdout
arff_head_s=('''@RELATION <netmate>
@ATTRIBUTE srcip STRING
@ATTRIBUTE srcport NUMERIC
@ATTRIBUTE dstip STRING
@ATTRIBUTE dstport NUMERIC
@ATTRIBUTE proto NUMERIC
@ATTRIBUTE total_fpackets NUMERIC
@ATTRIBUTE total_fvolume NUMERIC
@ATTRIBUTE total_bpackets NUMERIC
@ATTRIBUTE total_bvolume NUMERIC
@ATTRIBUTE min_fpktl NUMERIC
@ATTRIBUTE mean_fpktl NUMERIC
@ATTRIBUTE max_fpktl NUMERIC
@ATTRIBUTE std_fpktl NUMERIC
@ATTRIBUTE min_bpktl NUMERIC
@ATTRIBUTE mean_bpktl NUMERIC
@ATTRIBUTE max_bpktl NUMERIC
@ATTRIBUTE std_bpktl NUMERIC
@ATTRIBUTE min_fiat NUMERIC
@ATTRIBUTE mean_fiat NUMERIC
@ATTRIBUTE max_fiat NUMERIC
@ATTRIBUTE std_fiat NUMERIC
@ATTRIBUTE min_biat NUMERIC
@ATTRIBUTE mean_biat NUMERIC
@ATTRIBUTE max_biat NUMERIC
@ATTRIBUTE std_biat NUMERIC
@ATTRIBUTE duration NUMERIC
@ATTRIBUTE min_active NUMERIC
@ATTRIBUTE mean_active NUMERIC
@ATTRIBUTE max_active NUMERIC
@ATTRIBUTE std_active NUMERIC
@ATTRIBUTE min_idle NUMERIC
@ATTRIBUTE mean_idle NUMERIC
@ATTRIBUTE max_idle NUMERIC
@ATTRIBUTE std_idle NUMERIC
@ATTRIBUTE sflow_fpackets NUMERIC
@ATTRIBUTE sflow_fbytes NUMERIC
@ATTRIBUTE sflow_bpackets NUMERIC
@ATTRIBUTE sflow_bbytes NUMERIC
@ATTRIBUTE fpsh_cnt NUMERIC
@ATTRIBUTE bpsh_cnt NUMERIC
@ATTRIBUTE furg_cnt NUMERIC
@ATTRIBUTE burg_cnt NUMERIC
@ATTRIBUTE opendpi_class {''' , '''}
% you need to add a nominal class attribute!
% @ATTRIBUTE class {class0,class1}
@DATA
''')
if __name__ == '__main__':
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="make lots of noise")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose",
help="be very quiet")
parser.add_option("-f", "--from_path",dest="from_path",
metavar="INPUT_PATH", help="read from INPUT_PATH")
parser.add_option("-o", "--output",dest="output_arff_file_name",
metavar="OUTPUT_FILES", help="write output OUTPUT_FILES")
(options, args) = parser.parse_args()
output_real_arff_file_name=""
items = set()
if os.path.isdir(options.output_arff_file_name):
output_real_arff_file_name= os.path.join(output_arff_file_name,'default.arff' )
elif options.output_arff_file_name:
output_real_arff_file_name=options.output_arff_file_name
else:
output_real_arff_file_name="./default.arff"
if options.from_path:
if os.path.isdir(options.from_path):
for f in glob.glob(os.path.join(options.from_path, '*.arff')):
if os.path.isfile(f):
items.add(os.path.abspath(f))
elif '*' in options.from_path:
for n in glob.glob(options.from_path):
items.add(os.path.abspath(f))
else:
print "not set input file/path"
#exit()
for arg in args:
# if os.path.isdir(arg):
# for f in glob.glob(os.path.join(arg, '*.merged.arff')):
# if os.path.isfile(f):
# items.add(os.path.abspath(f))
#print arg
if '*' in arg:
for n in glob.glob(arg):
items.add(os.path.abspath(n))
elif os.path.isfile(arg):
items.add(os.path.abspath(arg))
else:
pass
#add arff header into output_real_arff_file_name
if os.path.isfile(output_real_arff_file_name):
os.remove(output_real_arff_file_name)
output_file = open(output_real_arff_file_name,'a')
#output_file.write(arff_head_s[0])
#output_file.write(arff_head_s[1])
#from collections import deque
applist=[]
#writelines_header=[]
writelines_data=[]
for input_arff_filename in items:
foundData = False
p = open(input_arff_filename,'r')
for line in p.readlines():
prog=re.compile("^@DATA")
m = prog.match(line)
if m:
foundData = True
continue
if ( foundData==True and ( not line.isspace() ) and (not re.match('^@',line)) and (not re.match('^%',line)) ):
appname = input_arff_filename.split('@')[0].split('/')[-1]
print appname
writline=line
opendpi_class = writline.split(',')[-1].strip()
if opendpi_class not in applist:
applist.append(opendpi_class)
writelines_data.append( writline )
p.close()
#write output arff file
output_file.write(arff_head_s[0])
for i in applist:
output_file.write( "%s," % i )
output_file.write(arff_head_s[1])
for ii in writelines_data:
output_file.write(ii)
output_file.close()
exit()
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.