Esempio n. 1
0
def main():
    config = ConfigObject(defaults=dict(here=os.getcwd()))
    config.read(os.path.expanduser('~/.alainrc'))
    conn = IRCConnection('irc.freenode.net',
                         6667,
                         config.bot.nick + '_',
                         verbosity=config.bot.verbosity.as_int(),
                         logfile=config.bot.logfile or None)
    conn.config = config
    conn.channel = config.bot.channel
    conn.services = services
    conn.connect()
    time.sleep(3)
    conn.ghost()
    bot = Alain(conn)
    bot.config = config
    bot.channel = config.bot.channel
    bot.sudoers = sudoers
    bot.messages = []
    conn.join(config.bot.channel)
    time.sleep(2)
    conn.respond('matin', config.bot.channel)
    try:
        conn.enter_event_loop()
    except Exception, e:
        conn.logger.exception(e)
Esempio n. 2
0
class Connection(object):
    node_class = Node
    user_class = User
    group_class = GroupOfNames
    perm_class = None
    def __init__(self, section='ldap', prefix='ldap.', filename=os.path.expanduser('~/.ldap.cfg')):
        self.config = ConfigObject()
        self.config.read([filename])
        self.prefix = prefix
        self.section = self.config[section]
        self._conn = self.connection_factory()
        try:
            self.bind_dn = self.get('bind_dn')
            self.bind_pw = self.get('bind_pwd')
            self.base_dn = self.get('base_dn', self.bind_dn.split(',', 1)[1])
        except Exception, e:
            raise e.__class__('Invalid configuration %s - %s' % (section, self.section))

        for name in ('user', 'group', 'perm', 'node'):
            attr = '%s_class' % name
            klass = self.get('%s_class' % name, None)
            if klass:
                klass = resolve_class(klass)
                if getattr(self, attr) is not klass:
                    setattr(self, attr, klass)
                    self.bind(klass)
                    log.warn('Setting %s to %s', attr, klass)
        if self.group_class.member_nodes.item_class is not self.user_class:
            self.group_class.member_nodes.item_class = self.user_class
Esempio n. 3
0
 def write(self, path_or_fd=None):
     if path_or_fd is None and self._filename:
         path_or_fd = self._filename
     if isinstance(path_or_fd, basestring):
         fd = open(path_or_fd, 'w')
     else:
         fd = path_or_fd
     ConfigObject.write(self, fd)
     if isinstance(path_or_fd, basestring):
         fd.close()
Esempio n. 4
0
 def __init__(self, section='ldap', prefix='ldap.', filename=os.path.expanduser('~/.ldap.cfg')):
     self.config = ConfigObject()
     self.config.read([filename])
     self.prefix = prefix
     self.section = self.config[section]
     self._conn = self.connection_factory()
     try:
         self.bind_dn = self.get('bind_dn')
         self.bind_pw = self.get('bind_pwd')
         self.base_dn = self.get('base_dn', self.bind_dn.split(',', 1)[1])
     except Exception, e:
         raise e.__class__('Invalid configuration %s - %s' % (section, self.section))
Esempio n. 5
0
def ldap2map():
    """store google maps coords in a dumped dict
    """
    config = ConfigObject()
    config.read(os.path.expanduser('~/.afpy.cfg'))
    conn = ldap.get_conn()
    api_key = config.get('api_keys', 'maps.google.com')
    filename = '/tmp/google.maps.coords.dump'
    users = []
    for i in range(1, 10):
        users.extend(
            conn.search_nodes(filter='(&(postalCode=%s*)(street=*))' % i,
                              attrs=['postalCode', 'st']))

    addresses = {}
    for user in users:
        try:
            short_address = '%s, %s' % (user.postalCode.strip(),
                                        user.st.strip())
            addresses[short_address] = ''
        except:
            pass

    if os.path.isfile(filename):
        coords = cPickle.load(open(filename))
    else:
        coords = {}

    opener = urllib2.build_opener()

    for address in addresses:
        if address in coords:
            continue
        cp, country = address.split(', ')
        url = 'http://ws.geonames.org/postalCodeLookupJSON?postalcode=%s&country=%s' % (
            cp, country)
        request = urllib2.Request(url)
        request.add_header('User-Agent', 'Mozilla Firefox')
        datas = None
        while not datas:
            try:
                datas = opener.open(request).read()
            except:
                time.sleep(4)
        coord = eval(datas)
        if coord and coord.get('postalcodes'):
            codes = coord.get('postalcodes')
            if codes:
                coords[address] = codes[0]
    cPickle.dump(coords, open(filename, 'w'))
Esempio n. 6
0
 def __call__(self, environ, start_response):
     req = Request(environ)
     resp = Response()
     filename = req.path_info.strip('/')
     lfilename = filename.lower()
     if not req.path_info.strip('/') or os.path.isdir(filename):
         if filename:
             filename = path(filename, 'index.html')
         else:
             filename = 'index.html'
         body = open(filename, 'rb').read()
         resp.body = body
     elif os.path.isfile(filename):
         if req.method.lower() == 'delete':
             sh.rm(filename + '*', shell=True)
             resp = exc.HTTPNoContent()
             return resp(environ, start_response)
         if req.path_info.endswith('.metadata'):
             cfg = ConfigObject(filename=filename)
             if req.method.lower() == 'get':
                 resp.content_type = 'application/json'
             elif req.method.lower() == 'put':
                 data = json.loads(req.body)
                 cfg.metadata.update(data)
                 cfg.write()
             metadata = dict(cfg.metadata.items())
             metadata.update(tags=cfg.metadata.tags.as_list())
             resp.body = json.dumps(metadata)
         elif req.path_info.endswith('.js'):
             resp.content_type = 'text/javascript'
         elif req.path_info.endswith('.json'):
             resp.content_type = 'application/json'
         elif req.path_info.endswith('.css'):
             resp.content_type = 'text/css'
         elif lfilename.endswith('.jpg'):
             resp.charset = None
             resp.content_type = 'image/jpeg'
         print(filename)
         if not resp.content_length:
             resp.app_iter = fd(filename)
     elif req.path_info.startswith('/delete/'):
         filename = req.path_info[8:-1]
         self.delete(filename)
         resp.status_int = 302
         resp.location = '/' + path.dirname(filename)
     else:
         resp.body = str(req.path_info)
     resp.last_modified = datetime.now()
     return resp(environ, start_response)
Esempio n. 7
0
def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    from ConfigObject import ConfigObject
    cfg = ConfigObject(filename=os.path.expanduser('~/.afpy.cfg'))
    app_conf['beaker.session.secret'] = '%s' % cfg.authtkt.shared_secret

    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='members', paths=paths)

    config['routes.map'] = make_map()
    config['pylons.app_globals'] = app_globals.Globals()
    config['pylons.h'] = members.lib.helpers

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8',
        output_encoding='utf-8',
        imports=['from webhelpers.html import escape'],
        default_filters=['escape'])

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    config['pylons.strict_tmpl_context'] = False
Esempio n. 8
0
 def __init__(self, filename=None, name=None):
     if name is None:
         name, _ = os.path.splitext(os.path.basename(filename))
     h = md5(name).hexdigest()
     data = os.path.expanduser(os.path.join('~/.freeboxtv', 'data',
                                     h[:2], h[2:4], h[4:6], h))
     if not os.path.isdir(os.path.dirname(data)):
         os.makedirs(os.path.dirname(data))
     self.config = ConfigObject(filename=data)
     self.data = data = self.config.data
     self.write = self.config.write
     if not self.file and filename:
         data.name = name
         data.file = filename
         self.write()
Esempio n. 9
0
def pics(args):
    """
    Usage: %prog (update|serve) [options]
           %prog add [options] <image>...
           %prog set [options] <key> <value>
           %prog (addtag|deltag) [options] <tag>...

    Options:

    -u URL, --url=URL   Absolute url to use
    -t, --thumbs        Generate thumbs
    -d, --directory     A directory containing images [default: .]
    %options
    """
    env.photos = pwd()
    env.build_path = build_path = os.path.abspath('build')
    pics = Index(build_path=build_path)
    if args['--thumbs']:
        pics.resize()
    url = args['--url'] or ''
    env.url = url.strip('/')
    if args['serve']:
        pics.get_resources()
        os.chdir(pics.build_path)
        from serve import serve
        serve()
    elif args['update']:
        pics.generate()
        pics.clean()
    elif args['deltag']:
        for filename in find('-name *.metadata'):
            filename = filename.strip()
            config = ConfigObject(filename=filename)
            tags = config.metadata.tags.as_list()
            tags = [t for t in tags if t not in args['<tag>']]
            config.metadata.tags = tags
            config.write()
    elif args['addtag']:
        for filename in find('-name *.metadata'):
            filename = filename.strip()
            config = Photo(filename=filename)
            tags = config.metadata.tags.as_list()
            tags.extend([t for t in args['<tag>'] if t not in tags])
            config.metadata.tags = tags
            config.write()
    elif args['set']:
        for filename in find('-name *.metadata'):
            filename = filename.strip()
            config = ConfigObject(filename=filename)
            if not config.metadata.date:
                now = datetime.now()
                config.metadata.date = now.strftime('%Y-%m-%d')
            section = 'metadata'
            key = args['<key>']
            if key.lower() in ('exif.date_and_time', 'exif.date'):
                key = 'exif.Date_and_Time'
            if '.' in key:
                section, key = key.split('.')
            value = args['<value>']
            config[section][key] = value
            if key == 'Date_and_Time':
                config.metadata.date = value

            config.write()
    elif args['add']:
        for filename in args['<image>']:
            filename = path.expanduser(filename.strip())
            if path.splitext(filename)[1].lower() not in ('.jpg',):
                continue
            if path.isfile(filename + '.metadata'):
                continue
            new_filename = path.basename(filename).replace(' ', '_')
            config = Photo(filename=new_filename)
            config.rotate(original=filename)
            config.write()
DLG_LOGIN_WIDTH = 300;
DLG_LOGIN_HEIGHT = 150;
DLG_SEMESTER_WIDTH = 400;
DLG_SEMESTER_HEIGHT = 200;

USE_FIREFOX = 1;
USE_CHROME = 1;
USE_IE = 1;
USE_IE_64 = 1;

USERNAME = "";
PASSWORD = "";
DOWNLOAD_PATH = "";

print("读取配置文件\"%s\"..." % FILENAME_CONFIG);
config = ConfigObject(filename=FILENAME_CONFIG);
for section in config.sections():
    for (k,v) in config[section].items():
        k = k.upper();
        if globals().get(k) is not None and iskeyword(k) == False:
            if section.lower() == "strings" and str(type(globals()[k])) == "<class 'str'>":
                globals()[k] = str(v);
            elif section.lower() == "numbers" and (str(type(globals()[k])) == "<class 'float'>" or str(type(globals()[k])) == "<class 'int'>"):
                globals()[k] = float(v);
            elif section.lower() == "boolean" and str(type(globals()[k])) == "<class 'int'>":
                globals()[k] = int(v);
            else:
                continue;
            print("已设置变量:%s = %s" % (k, v));

Esempio n. 11
0
def get_config():
    filename = join(os.path.dirname(__file__), 'config.ini')
    return ConfigObject(filename=filename)
Esempio n. 12
0
# -*- coding: utf-8 -*-
from ConfigObject import ConfigObject
import feedparser
import os

config = ConfigObject(defaults=dict(here=os.getcwd()))
config.read(os.path.expanduser('~/.alainrc'))
cred = config.plone.user


def awaiting():
    feed = feedparser.parse(
        'http://%[email protected]/search_rss?review_state=pending' % cred)
    entries = [str(e.id) for e in feed.entries]
    entries = [e for e in entries if '/forums/' not in e]
    if entries:
        return 'Hey! Il y a des trucs à modérer: %s' % ' - '.join(entries)
    return ''


if __name__ == '__main__':
    print awaiting()
Esempio n. 13
0
# -*- coding: utf-8 -*-
from ConfigObject import ConfigObject
import sys
import os

filename = os.path.expanduser(os.path.join('~/.freeboxtv', 'config.ini'))
dirname = os.path.dirname(filename)
if not os.path.isdir(dirname):
    os.makedirs(dirname)

config = ConfigObject(filename=filename)
config.__name__ = __name__
config.__file__ = __file__
config.__path__ = __file__
sys.modules[__name__] = config


Esempio n. 14
0
# -*- coding: utf-8 -*-
from ConfigObject import ConfigObject
import sys
import os

filename = os.path.expanduser(os.path.join("~/.freeboxtv", "config.ini"))
dirname = os.path.dirname(filename)
if not os.path.isdir(dirname):
    os.makedirs(dirname)

config = ConfigObject(filename=filename)
config.__name__ = __name__
config.__file__ = __file__
config.__path__ = __file__
sys.modules[__name__] = config