functions.py

00001 #!/usr/bin/env python
00002 # -*- coding: utf-8 -*-
00003 
00004 # ----------------------------------------------------------------------------
00005 # pyjama - python jamendo audioplayer
00006 # Copyright (c) 2008 Daniel Nögel
00007 #
00008 # This program is free software: you can redistribute it and/or modify
00009 # it under the terms of the GNU General Public License as published by
00010 # the Free Software Foundation, either version 3 of the License, or
00011 # (at your option) any later version.
00012 #
00013 # This program is distributed in the hope that it will be useful,
00014 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00015 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016 # GNU General Public License for more details.
00017 # You should have received a copy of the GNU General Public License
00018 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
00019 # ----------------------------------------------------------------------------
00020 
00021 ## @package functions
00022 # The function module holds some general
00023 # functions.
00024 
00025 import gettext
00026 import os, sys
00027 import shutil
00028 from time import strftime, gmtime
00029 import re
00030 import gtk
00031 
00032 import constants
00033 
00034 import urllib2, httplib
00035 httplib.HTTPConnection.debuglevel = 1
00036 
00037 ## Returns the directory from which pyjama was started.
00038 # This might be the install directory or the script's
00039 # directory.
00040 # @return A string containing a path
00041 def install_dir():
00042     dirname = os.path.dirname(sys.argv[0])
00043     abspath =  os.path.abspath(dirname)
00044 
00045     if os.name == "nt":
00046         if os.path.exists(os.path.join(abspath, "modules", "clGstreamer010.py")):
00047             #libs here
00048             return abspath
00049         else:
00050             return os.path.join(os.getenv('PROGRAMFILES'), "pyjama")
00051     else:
00052         if os.path.exists(os.path.join(abspath, "modules", "clGstreamer010.py")):
00053             #libs here
00054             return abspath
00055         else:
00056             return constants.INSTALL_DIR_POSIX
00057 
00058 ## Takes a given url, opens it and returns
00059 # the url it redirects to
00060 # @param url The url to resolve
00061 def resolve_redirect(self, url):
00062     request = urllib2.Request(location)
00063     opener = urllib2.build_opener()
00064     ret = opener.open(request)
00065     location = ret.url
00066     return location
00067 
00068 
00069 ## Getting the installed pyjama version
00070 # deprecated: just use "from modules.functions import VERSION" instead
00071 # @return 
00072 # - "0.0.0" if an error occured
00073 # - Another string if succesfull
00074 def get_version():  
00075     pass
00076 #def get_version():
00077 #    try:
00078 #        txt=open(os.path.join(install_dir(), "about.glade"), "r").read()
00079 
00080 #        re1='.*?'  # Non-greedy match on filler
00081 #        re2='()'   # Tag 1
00082 #        re3='(\\d+)'   # Integer Number 1
00083 #        re4='(\\.)'    # Any Single Character 1
00084 #        re5='(\\d+)'   # Integer Number 2
00085 #        re6='(\\.)'    # Any Single Character 2
00086 #        re7='(\\d+)'   # Integer Number 3
00087 #        re8='(<\\/property>)'  # Tag 2
00088 
00089 #        rg = re.compile(re1+re2+re3+re4+re5+re6+re7+re8,re.IGNORECASE|re.DOTALL)
00090 #        m = rg.search(txt)
00091 #        if m:
00092 #            tag1=m.group(1)
00093 #            int1=m.group(2)
00094 #            c1=m.group(3)
00095 #            int2=m.group(4)
00096 #            c2=m.group(5)
00097 #            int3=m.group(6)
00098 #            tag2=m.group(7)
00099 ##            print "%s.%s.%s" % (int1, int2, int3)
00100 #            return "%s.%s.%s" % (int1, int2, int3)
00101 #        else:
00102 #            return "0.0.0"
00103 #    except Exception, inst:
00104 #        return "0.0.0"
00105 
00106 VERSION="0.3.0.10" #!!Version line 
00107 
00108 
00109 ## Getting and making pyjama- dirs
00110 # @param set_privilegs Tries to set 0777 privilegs to the pyjama
00111 # directory in your home folder in order to prevent the root
00112 # from accidentially owning it.
00113 # @return A string containing pyjama's home directory (~/.pyjama)
00114 def preparedirs(set_privilegs = False):
00115     home = os.getenv("HOME")
00116     if home == None: # WINDOWS
00117         home = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
00118     HOME_DIR_NAME = constants.PYJAMA_HOME_DIRECTORY_NAME
00119     home_pyjama = os.path.join(home, HOME_DIR_NAME)
00120     if set_privilegs:
00121         if os.path.exists(os.path.join(home, HOME_DIR_NAME)):
00122             os.system("chmod -R 0777 %s" % os.path.join(home, HOME_DIR_NAME))
00123         if os.path.exists(os.path.join(home, HOME_DIR_NAME, "images")) == False:
00124             os.makedirs(os.path.join(home, HOME_DIR_NAME, "images"))
00125         if os.path.exists(os.path.join(home, HOME_DIR_NAME, "cache")) == False:
00126             os.makedirs(os.path.join(home, HOME_DIR_NAME, "cache"))
00127         if os.path.exists(os.path.join(home, HOME_DIR_NAME, "cache", "long")) == False:
00128             os.makedirs(os.path.join(home, HOME_DIR_NAME, "cache", "long"))
00129         if os.path.exists(os.path.join(home, HOME_DIR_NAME, "cache", "short")) == False:
00130             os.makedirs(os.path.join(home, HOME_DIR_NAME, "cache", "short"))
00131         if os.path.exists(os.path.join(home, HOME_DIR_NAME, "themes")) == False:
00132             os.makedirs(os.path.join(home, HOME_DIR_NAME, "themes"))
00133         if not os.path.isfile(os.path.join(home_pyjama, "pyjama.cfg")):
00134             shutil.copy(os.path.join(install_dir(), "pyjama.cfg"), os.path.join(home_pyjama, "pyjama.cfg"))
00135             if not os.path.isfile(os.path.join(home_pyjama, "pyjama.cfg")):
00136                 print "Error copying config file to user's pyjama directory"
00137                 print "Please try to do so on your own"
00138         os.chmod(home_pyjama, 0777)
00139     return home_pyjama
00140 
00141 
00142 #def get_pyjama_dir():
00143 #    return os.path.join(os.getenv("HOME"), ".pyjama")
00144 
00145 ## List with some theme paths
00146 theme_dirs = [os.path.join(preparedirs(),"themes"), gtk.rc_get_theme_dir(), os.path.join(install_dir(), "themes") ]
00147 
00148 ## Returns a list of available Themes
00149 # @return A list of themes
00150 def sorteddirlist():
00151     theme_list = []
00152     for t in theme_dirs:
00153         if os.path.exists(t):
00154             for theme in os.listdir(os.path.join(t)):
00155                 theme_path = os.path.join(t, theme, "gtk-2.0", "gtkrc")
00156                 if os.path.exists(theme_path) and not theme in theme_list:
00157                     theme_list.append(theme)
00158     return sorted(theme_list)
00159     
00160 
00161 
00162 ## Load a theme
00163 # @param theme A theme name or the number of a theme
00164 # @return 
00165 # - An error message and None as tuple if an error occured
00166 # - tk.rc_parse() and theme name as tuple if succesfull
00167 def showtheme(theme, reparse=False):
00168     home = preparedirs()
00169     if theme.isdigit():
00170         dirs = sorteddirlist()
00171         if int(theme)-1 < len(dirs):
00172            theme = dirs[int(theme)-1]
00173         else:
00174            return _("No theme for entry '%s'") % theme, None
00175     fl = None
00176     for t in theme_dirs:
00177         f = os.path.join(t, theme, "gtk-2.0", "gtkrc")
00178         if  os.path.exists(f):
00179             fl = f
00180     if not fl:
00181         return _("No theme for entry '%s'") % theme, None
00182     else:
00183         return gtk.rc_parse(fl), theme
00184 
00185 
00186 
00187 ## Checks file write permissions for the current user
00188 # @return Bool
00189 def is_writeable(path):
00190     return os.access(path, os.W_OK)
00191 
00192 
00193 
00194 from htmlentitydefs import name2codepoint as n2cp
00195 import re
00196 ## Decoding Display Names
00197 # In the old dbdumps Jamendo had some string
00198 # that did not work well with pango. This
00199 # function should remove those strings
00200 # @return string
00201 def decode_htmlentities(string):
00202     entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")
00203     return entity_re.subn(__substitute_entity, string)[0]
00204 def __substitute_entity(match):
00205     ent = match.group(2)
00206     if match.group(1) == "#":
00207         return unichr(int(ent))
00208     else:
00209         cp = n2cp.get(ent)
00210 
00211         if cp:
00212             return unichr(cp)
00213         else:
00214             return match.group()
00215 
00216 ## Format time
00217 # @parram seconds Time in seconds
00218 # @return time string
00219 # @todo Fix ValueErrors
00220 def sec2time(seconds):
00221     if seconds > (60*60):
00222         try:
00223             time_string = strftime("%H:%M:%S", gmtime(int(seconds)))
00224         except ValueError:
00225             return "00:00:00"
00226     else:
00227         try:
00228             time_string = strftime("%M:%S", gmtime(int(seconds)))
00229         except ValueError:
00230             return "00:00"
00231     return time_string
00232 
00233 
00234 ## Convert numeric genre-id to genre names
00235 # @param id The id3 ID as INT
00236 # @result string
00237 def id2genre(id):
00238     genres = [
00239     "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", 
00240     "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", 
00241     "Pop", "R&amp;B", "Rap", "Reggae", "Rock", "Techno", "Industrial", 
00242     "Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", 
00243     "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", 
00244     "Trance", "Classical", "Instrumental", "Acid", "House", "Game", 
00245     "Sound Clip", "Gospel", "Noise", "Alt. Rock", "Bass", "Soul", 
00246     "Punk", "Space", "Meditative", "Instrum. Pop", "Instrum. Rock", 
00247     "Ethnic", "Gothic", "Darkwave", "Techno-Indust.", "Electronic", 
00248     "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", 
00249     "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", 
00250     "Native American", "Cabaret", "New Wave", "Psychadelic", "Rave", 
00251     "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", 
00252     "Polka", "Retro", "Musical", "Rock &amp; Roll", "Hard Rock", "Folk", 
00253     "Folk/Rock", "National Folk", "Swing", "Fusion", "Bebob", "Latin", 
00254     "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", 
00255     "Progress. Rock", "Psychadel. Rock", "Symphonic Rock", "Slow Rock", 
00256     "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", 
00257     "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", 
00258     "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", 
00259     "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", 
00260     "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", 
00261     "A Capella", "Euro-House", "Dance Hall", "Goa", "Drum &amp; Bass", 
00262     "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", 
00263     "Polsk Punk", "Beat", "Christian Gangsta Rap", "Heavy Metal", 
00264     "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock",
00265     "Merengue", "Salsa", "Thrash Metal", "Anime", "Jpop", "Synthpop" 
00266     ]
00267     if id == None:
00268         return "n/A"
00269     return genres[int(id)]
00270 
00271 ## Gettext for translating _() strings
00272 # For usual you won't have to call this
00273 def translation_gettext():
00274     path = "locale"
00275     if not os.path.exists(path):
00276         path = os.path.join(install_dir(), "locale")
00277     try:
00278         trans = gettext.translation('pyjama', path)
00279     except IOError:
00280         trans = gettext.translation('pyjama', path, ["en_GB"])
00281         print "No language file for you found - using english language file"
00282     trans.install()
00283 
00284 ## Checks if some necessary modules can be found
00285 # @return Number of errors as INT
00286 def check_modules():
00287     err = 0
00288     nf1, nf2 = False, False
00289 
00290     try:
00291         import pygtk
00292     except ImportError:
00293         err += 1
00294         print ("Module '%s' not found") % "pygtk"
00295 
00296     try:
00297         import gtk
00298     except ImportError:
00299         err += 1
00300         print ("Module '%s' not found") % "gtk"
00301 
00302     try:
00303         import gtk.glade
00304     except ImportError:
00305         err += 1
00306         print ("Module '%s' not found") % "gtk.glade"
00307         
00308     try:
00309         import simplejson
00310     except ImportError:
00311         err += 1
00312         print ("Module '%s' not found") % "simplejson"
00313 
00314     try:
00315         import gst
00316     except ImportError:
00317         err += 1
00318         print ("Module '%s' not found") % "gst (gstreamer)"
00319         
00320     try:
00321         import xml.sax
00322     except ImportError:
00323         err += 1
00324         print ("Module '%s' not found") % "xml.sax"
00325 
00326     try:
00327         import sqlite3
00328     except ImportError:
00329         nf1 = True
00330         
00331     try:
00332         import pysqlite2
00333     except ImportError:
00334         nf2 = True
00335         if nf1 and nf2:
00336             err += 1
00337             print ("You need to have sqlite3 or pysqlite2 or libsqlite3-0 installed")
00338 
00339     if err == 0:
00340         print ("All modules found")
00341     else:
00342         print ("%s module(s) missing") % err
00343 
00344     return err
00345 
00346 def license2text(license):
00347     if len(license) <= 10:
00348         l = license.lower()
00349         if l == "gplv3":
00350             name = "GNU GENERAL PUBLIC LICENSE Version 3"
00351             url = ""
00352         elif l == "gplv2":
00353             name = "GNU GENERAL PUBLIC LICENSE Version 2"
00354             url = ""
00355         elif l == "gpl":
00356             name = "GNU GENERAL PUBLIC LICENSE"
00357             url = ""
00358         elif "cc" in l:
00359             name = "Creative Commons"
00360             url = ""
00361         elif l == "lgpl":
00362             name = "GNU LESSER GENERAL PUBLIC LICENSE"
00363             url = ""
00364         elif l == "lgpl2":
00365             name = "GNU LESSER GENERAL PUBLIC LICENSE Version 2"
00366             url = ""
00367         elif l == "lgpl2.1":
00368             name = "GNU LESSER GENERAL PUBLIC LICENSE Version 2.1"
00369             url = ""
00370         elif l == "lgpl3":
00371             name = "GNU LESSER GENERAL PUBLIC LICENSE Version 3"
00372             url = ""
00373         elif l == "gfdl":
00374             name = "GNU Free Documentation License"
00375             url = ""
00376         elif l == "gfdl1.2":
00377             name = "GNU Free Documentation License Version 2"
00378             url = ""
00379         elif l == "apache":
00380             name = "Apache License Version 2"
00381             url = ""
00382         elif l == "artistic":
00383             name = "Artistic License"
00384             url = ""
00385         elif l == "bsd":
00386             name = "BSD License"
00387             url = ""
00388         else:
00389             print ("Don't know the given license '%s'. " % license)
00390             return license
00391         if url != "":
00392             return "This plugin is licensed under '%s'. Please visit %s for more information" % (name, url )
00393         else:
00394             return "This plugin is licensed under '%s'." % name
00395     else:
00396         return license

Generated on Thu Jun 4 19:08:24 2009 for Pyjama by  doxygen 1.5.8