gmyth-stream/server/0.3/lib/utils.py
author melunko
Tue Aug 21 16:02:24 2007 +0100 (2007-08-21)
branchtrunk
changeset 814 8a6b143057d7
parent 718 3fbcd3d9b2d1
child 815 7f290a3a34b1
permissions -rw-r--r--
[svn r820] Added gmyth_scheduler_add_exception() function to remove only one schedule when all occurrences options has been used.
     1 #!/usr/bin/env
     2 
     3 __author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
     4 __author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
     5 __license__ = "GPL"
     6 __version__ = "0.3"
     7 
     8 import os
     9 import stat
    10 import sys
    11 import logging
    12 import urllib
    13 import gobject
    14 import imp
    15 
    16 log = logging.getLogger("gms.utils")
    17 
    18 __all__ = ("which", "load_plugins", "PluginSet", "getHTML",
    19            "progress_bar", "create_tid", "list_media_files")
    20 
    21 def which(app):
    22     """Function to implement which(1) unix command"""
    23     pl = os.environ["PATH"].split(os.pathsep)
    24     for p in pl:
    25         path = os.path.join(p, app)
    26         if os.path.isfile(path):
    27             st = os.stat(path)
    28             if st[stat.ST_MODE] & 0111:
    29                 return path
    30     return ""
    31 # which()
    32 
    33 
    34 def _load_module(pathlist, name):
    35     fp, path, desc = imp.find_module(name, pathlist)
    36     try:
    37         module = imp.load_module(name, fp, path, desc)
    38         return module
    39     finally:
    40         if fp:
    41             fp.close()
    42 # _load_module()
    43 
    44 
    45 class PluginSet(object):
    46     def __init__(self, basetype, *items):
    47         self.basetype = basetype
    48         self.map = {}
    49         self.list = []
    50 
    51         for i in items:
    52             self._add(i)
    53         self._sort()
    54     # __init__()
    55 
    56 
    57     def _add(self, item):
    58         self.map[item.name] = item
    59         self.list.append(item)
    60     # _add()
    61 
    62 
    63     def add(self, item):
    64         self._add()
    65         self._sort()
    66     # add()
    67 
    68 
    69     def __getitem__(self, spec):
    70         if isinstance(spec, basestring):
    71             return self.map[spec]
    72         else:
    73             return self.list[spec]
    74     # __getitem__()
    75 
    76 
    77     def get(self, name, default=None):
    78         return self.map.get(name, default)
    79     # get()
    80 
    81 
    82     def __iter__(self):
    83         return self.list.__iter__()
    84     # __iter__()
    85 
    86 
    87     def __len__(self):
    88         return len(self.list)
    89     # __len__()
    90 
    91 
    92     def _sort(self):
    93         self.list.sort(lambda a, b: cmp(a.priority, b.priority))
    94     # _sort()
    95 
    96 
    97     def update(self, pluginset):
    98         self.map.update(pluginset.map)
    99         self.list.extend(pluginset.list)
   100         self._sort()
   101     # update()
   102 
   103 
   104     def load_from_directory(self, directory):
   105         for i in load_plugins(directory, self.basetype):
   106             self._add(i)
   107         self._sort()
   108     # load_from_directory()
   109 
   110 
   111     def __str__(self):
   112         lst = []
   113         for o in self.list:
   114             lst.append('"%s" (%s)' % (o.name, o.__name__))
   115 
   116         return "%s(basetype=%s, items=[%s])" % \
   117                (self.__class__.__name__,
   118                 self.basetype.__name__,
   119                 ", ".join(lst))
   120     # __str__()
   121 # PluginSet
   122 
   123 
   124 def load_plugins(directory, basetype):
   125     """Function to load plugins from a given directory"""
   126     tn = basetype.__name__
   127     log.debug("Loading plugins from %s, type=%s" % (directory, tn))
   128 
   129 
   130     plugins = []
   131     for d in os.listdir(directory):
   132         if not d.endswith(".py"):
   133             continue
   134 
   135         name = d[0: -3]
   136         if name == "__init__":
   137             continue
   138 
   139         directory.replace(os.path.sep, ".")
   140         mod = _load_module([directory], name)
   141         for sym in dir(mod):
   142             cls = getattr(mod, sym)
   143             if isinstance(cls, type) and issubclass(cls, basetype) and \
   144                 cls != basetype:
   145                 plugins.append(cls)
   146                 log.info("Loaded %s (%s) from %s" % \
   147                          (cls.__name__, tn, os.path.join(directory, d)))
   148 
   149     return plugins
   150 # load_plugins()
   151 
   152 def getHTML(html_file, params={}):
   153     """This function parses an html file with the given
   154     parameters and returns a formated web-page"""
   155     try:
   156         filename = os.path.join(sys.path[0], "html", html_file + ".html")
   157         html = open(filename).read() % params
   158         return html
   159     except Exception, e:
   160         return "HTML format error. Wrong keys: %s" % e
   161 
   162 # getHTML
   163 
   164 def _create_html_item(opt):
   165     """Create an <li> item using HTML."""
   166     return "<li>%s</li>\n" % opt
   167 # _create_html_item
   168 
   169 def progress_bar(value, max, barsize):
   170     """Creates and displays a progressbar. By OSantana"""
   171     chars = int(value * barsize / float(max))
   172     percent = int((value / float(max)) * 100)
   173     sys.stdout.write("#" * chars)
   174     sys.stdout.write(" " * (barsize - chars + 2))
   175     if value >= max:
   176         sys.stdout.write("done.\n\n")
   177     else:
   178         sys.stdout.write("[%3i%%]\r" % (percent))
   179         sys.stdout.flush()
   180     return percent
   181 # progress_bar() by osantana
   182 
   183 def create_tid(last_tid):
   184     """Function to generate TIDs (ids for transcoders).
   185     At first it just do +1 on last_tid but can be implemented
   186     to generate more sparse TIDs"""
   187     tid = last_tid + 1
   188     return tid
   189 # create_id()
   190 
   191