Author: jerome
Date: 2009-03-19 17:21:51 +0100 (Thu, 19 Mar 2009)
New Revision: 4155

Added:
   
software_suite_v2/libraries/python/webRadioDiscover/trunk/webRadioDiscover/webRadioContainer.py
Log:
* Added web radio container (download pickle struct from ftp).

Added: 
software_suite_v2/libraries/python/webRadioDiscover/trunk/webRadioDiscover/webRadioContainer.py
===================================================================
--- 
software_suite_v2/libraries/python/webRadioDiscover/trunk/webRadioDiscover/webRadioContainer.py
                             (rev 0)
+++ 
software_suite_v2/libraries/python/webRadioDiscover/trunk/webRadioDiscover/webRadioContainer.py
     2009-03-19 16:21:51 UTC (rev 4155)
@@ -0,0 +1,394 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+#    Copyright (C) 2009 KYSOH Sa
+#    Jérôme Conan <[email protected]>
+#    Distributed under the terms of the GNU General Public License
+#    http://www.gnu.org/copyleft/gpl.html
+
+import os
+import sys
+import pickle
+from urllib2 import Request, urlopen, URLError, HTTPError
+from threading import Thread
+import socket
+
+
+class WebRadioContainer(object):
+    '''
+    This class create a web radio container.
+    '''
+    
+    #***************** Private vars **************************#
+    __url = 
"http://ftp.kysoh.com/misc/other/web_radios/pickleStruct/webRadiosList.wrl";
+    __webRadios = []
+    __targetDownload = "./"
+    __pickleStruct = {}
+    
+    #*****************  Handlers  ****************************#
+    onNoConnectionFound = None
+    onNoConnectionFoundArgs = []
+    
+    onDownloadError = None
+    onDownloadErrorArgs = []
+    
+    onStructLoadError = None
+    onStructLoadErrorArgs = []
+    
+    onStructLoaded = None
+    onStructLoadedArgs = []
+    
+    onNoWebRadioFound = None
+    onNoWebRadioFoundArgs = []
+    
+    
+    #*********************************************************#
+    #**********         Private functions       **************#
+
+    def __init__(self):
+        '''
+        Object initialization.
+        '''
+        #Getting pickle struct from ftp. 
+        if(self.__URLCheckConnection()):
+            separator = "/"
+            
+            if self.__isWindows():
+                separator = "\\"
+                
+            self.__targetDownload = os.environ["TMP"] + separator 
+"webRadiosList.wrl"
+            self.__getPickleStruct(self.__targetDownload, self.__url)
+            
+            if os.path.isfile(self.__targetDownload):
+                dump = file(self.__targetDownload, "r")
+                try:
+                    self.__pickleStruct = pickle.load(dump)
+                except:
+                    self.__triggerStructLoadError()
+                dump.close()
+                #Deleting downloaded file now pickle struct is loaded.
+                os.remove(self.__targetDownload)
+            else:
+                #Trgiger error here.
+                self.__triggerDownloadError()
+                
+        else:
+            self.__triggerNoConnectionError()
+        
+        if self.getWebRadiosCount() > 0:
+            #Creating WebRadios objects.
+            radios = self.__pickleStruct.keys()
+            for radio in radios:
+                wRadio = WebRadio(radio, self.__pickleStruct[radio])
+                self.__webRadios.append(wRadio)
+            
+            self.__triggerStructLoaded()
+        else:
+            self.__triggerNoWebRadioFound()
+            
+    
+    
+    
+    def __triggerNoConnectionError(self):
+        '''
+        Trigger noConnectionError.
+        '''
+        if self.onNoConnectionFound != None:
+            noConnection = Thread(target=self.onNoConnectionFound, 
args=self.onNoConnectionFoundArgs)
+            noConnection.start()
+    
+    
+    
+    def __triggerDownloadError(self):
+        '''
+        Trigger downloadError event.
+        '''
+        #start onDownloadError function.
+        if self.onDownloadError != None:
+            downloadError = Thread( target=self.onDownloadError, 
args=self.onDownloadErrorArgs)
+            downloadError.start() 
+    
+    
+    def __triggerStructLoadError(self):
+        '''
+        Trigger structLoadError.
+        '''
+        if self.onStructLoadError != None:
+            structError = Thread( target=self.onStructLoadError, 
args=self.onStructLoadErrorArgs)
+            structError.start()
+    
+    
+    def __triggerStructLoaded(self):
+        '''
+        Trigger struct loaded event.
+        '''
+        if self.onStructLoaded != None:
+            structLoaded = Thread( target=self.onStructLoaded, 
args=self.onStructLoadedArgs)
+            structLoaded.start()
+    
+    
+    def __triggerNoWebRadioFound(self):
+        '''
+        Trigger no web radio found event.
+        '''
+        if self.onNoWebRadioFound != None:
+            noRadio = Thread(target=self.onNoWebRadioFound, 
args=self.onNoWebRadioFoundArgs)
+            noRadio.start()
+            
+    
+    
+    def __isWindows(self):
+        return (os.environ["OS"].find("Windows") > -1) or 
(os.environ["OS"].find("windows") > -1)
+    
+    
+    
+    def __URLCheckConnection(self):
+        """
+        Check the internet connection.
+        @return: The internet connection state.
+        @author: Remi Jocaille
+        """
+        # Save the old default connection timeout
+        old_timeout = socket.getdefaulttimeout()
+        # Set the default connection timeout
+        socket.setdefaulttimeout(10.)
+        # Initialize the result dictionary
+        result = True
+        # Attempt to connect to the google web site
+        try:
+            f = urlopen("http://www.google.com";)
+            f.close()
+        except HTTPError, exc:
+            result = False
+        except urllib2.URLError, exc:
+            result = False
+        except:
+            result = False
+        # Restore the old default connection timeout
+        socket.setdefaulttimeout(old_timeout)
+        # Return the result
+        return result
+    
+    
+    
+    
+    def __getPickleStruct(self, file_name, base_url):
+        '''
+        Download and write one url file.
+        '''
+        #create the url and the request
+        url = base_url
+        req = Request(url)
+
+        # Open the url
+        try:
+            f = urlopen(req)
+
+            # Open our local file for writing
+            local_file = open(file_name, "wb")
+            #Write to our local file
+            local_file.write(f.read())
+            local_file.close()
+
+        #handle errors
+        except HTTPError, e:
+            self.__triggerDownloadError()
+        except URLError, e:
+            self.__triggerDownloadError()
+    
+    
+    
+    #*********************************************************#
+    #******************    User functions    *****************#
+    def setOnNoConnectionFound(self, funct, args):
+        '''
+        Add 'no connection found error'.
+        @param funct: pointer to the target function.
+        @param args : list of arguments.
+        '''
+        self.onNoConnectionFound = funct
+        self.onNoConnectionFoundArgs = args
+        
+    
+    def setOnDownloadError(self, funct, args):
+        '''
+        Add a download error pointer.
+        @param funct : pointer to the target function.
+        @param args  : list of arguments.        
+        '''
+        self.onDownloadError = funct
+        self.onDownloadErrorArgs = args   
+
+
+    def setOnStructLoadingError(self, funct, args):
+        '''
+        Add a struct load error.
+        @param funct : pointer to the target function.
+        @args : list of arguments.
+        '''        
+        self.onStructLoadError = funct
+        self.onStructLoadErrorArgs = args
+     
+     
+    def setOnStructLoaded(self, funct, args):
+        '''
+        Add event when the web radio list is completly retreived.
+        @param funct : pointer to the target function.
+        @args : list of arguments.
+        '''
+        self.onStructLoaded = funct
+        self.onStructLoadedArgs = args
+    
+    
+    
+    def setOnNoWebRadioFound(self, funct, args):
+        '''
+        Add event in case of no web radio was found.
+        @param funct : pointer to the target function.
+        @args : list of arguments.
+        '''
+        self.onNoWebRadioFound = funct
+        self.onNoWebRadioFoundArgs = args
+    
+    
+    
+    def getWebRadiosCount(self):
+        '''
+        Return how many web radios was retreived.
+        '''
+        return len(self.__pickleStruct)
+    
+    
+    
+    def getWebRadios(self):
+        '''
+        Return the complete list of WebRadio objects.
+        '''
+        return self.__webRadios
+    
+    
+    
+    def getWebRadiosStartingWith(self, startchars):
+        '''
+        Return all web radio that starts with 'startChars'
+        '''
+        list = []
+        for radio in self.getWebRadios():
+            if radio.getLoweredName().startswith(startchars):
+                list.append(radio)
+        return list
+    
+    
+    
+    def getWebRadiosContaining(self, content):
+        '''
+        Return web radios containing 'content'
+        '''
+        list = []
+        for radio in self.getWebRadios():
+            if radio.getLoweredName().find(content) > -1:
+                list.append(radio)
+        return list
+        
+    
+class WebRadio(object):
+    '''
+    This class create a web radio object.
+    '''
+    
+    __name = None
+    __url = None
+    
+    
+    def __init__(self, name, url):
+        '''
+        Initialize web radio object
+        '''
+        self.__name = name
+        self.__url = url
+    
+    
+    def getName(self):
+        '''
+        Return the web radio name.
+        '''
+        return self.__name
+     
+    
+    
+    def getLoweredName(self):
+        '''
+        Return lower case name (to apply filters)
+        '''
+        return self.__name.lower()
+    
+    
+    
+    def getUrl(self):
+        '''
+        Return the web radio url.
+        '''
+        return self.__url
+    
+    
+    
+    def setName(self, newName):
+        '''
+        Set the web radio name (not stored on ftp ;) ).
+        '''
+        self.__name = newName
+     
+    
+    
+    def setUrl(self, newUrl):
+        '''
+        Set the web radio url.
+        '''
+        self.__url = newUrl
+    
+    
+    
+    def ping(self):
+        '''
+        Make a ping to the web radio url.
+        @return True in case of url response.
+        '''
+        # Save the old default connection timeout
+        old_timeout = socket.getdefaulttimeout()
+        # Set the default connection timeout
+        socket.setdefaulttimeout(10.)
+        # Initialize the result dictionary
+        result = True
+        # Attempt to connect to stringUrl
+        try:
+            f = urllib2.urlopen(self.webRadios[radio])
+            f.close()
+        except urllib2.HTTPError, exc:
+            result = False
+        except urllib2.URLError, exc:
+            result = False
+        except:
+            result = False
+        # Restore the old default connection timeout
+        socket.setdefaulttimeout(old_timeout)
+        # Return the result
+        return result
+    
+    
+ 
+if __name__ == "__main__":
+
+    conteneur = WebRadioContainer()
+    for webradio in conteneur.getWebRadios():
+        print(webradio.getLoweredName())
+        
+    print("\n")
+    
+    list_radios_fm = conteneur.getWebRadiosContaining("fm")
+    for radioFm in list_radios_fm:
+        print("Radio containing 'fm': " + radioFm.getName())
+    
+    
+    list_radios_france = conteneur.getWebRadiosStartingWith("france")
+    for radio_france in list_radios_france:
+        print("Radio commencant par 'france': " + radio_france.getName())
\ No newline at end of file


------------------------------------------------------------------------------
Apps built with the Adobe(R) Flex(R) framework and Flex Builder(TM) are
powering Web 2.0 with engaging, cross-platform capabilities. Quickly and
easily build your RIAs with Flex Builder, the Eclipse(TM)based development
software that enables intelligent coding and step-through debugging.
Download the free 60 day trial. http://p.sf.net/sfu/www-adobe-com
_______________________________________________
Tux-droid-svn mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/tux-droid-svn

Reply via email to