Ejemplo n.º 1
0
 def __init__(self, name, defaults=None, type=None, choices=None, help='', loader_srcs=None, loader_opts=None):
     '''
     name        - name of option.
     defaults    - default values which can be specified as a dict with keys 
                 specify different default values of corresponding platform,
                 e.g. {'win32': True, 'linux': False, 'darwin': False, '*': True}
                 name of platforms are defined as in sys.platform and '*' stands for
                 unspecified platforms which is equivalent to assigning value directly
                 to defaults. That is, 'default=1' works same as 'default={'*':1}'
     type        - the type to which the parameter should be converted, e.g.
                 "type=int" employes int() on loaded values by loader.
     choices     - a container of the allowable values for the parameter. a
                 ValueError will be raised if type converted value not a member of
                 not-none choices container
     help        - human readable message describe meaning of this parameter
     loader_srcs - list of supported sources from which this parameter could be loaded
                   'all' is a reserved name for all known loader sources;
                   other source names are decided by certain loaders
     loader_opts - options specified as dict will be used by certain loaders
                   read document of loaders for available options
     '''
     self.logger = log.getChild(self.__class__.__name__)
     self.name = str(name)
     self.validate_name()
     self.defaults = defaults if isinstance(defaults, dict) else {'*': defaults}
     if type is not None: self.type = type
     if choices is not None: self.choices = choices
     self.help = help
     self.loader_opts = loader_opts if loader_opts is not None else dict()
     self.loader_srcs = loader_srcs if loader_srcs is not None else ['all']
     self.logger.debug('parameter %s created', self)
Ejemplo n.º 2
0
def load_ext_setters(path):
    logger = log.getChild('load_ext_setters')
    for i in glob.iglob(os.path.join(path, '*setter.py')):
        if os.path.basename(i) == 'setter.py': continue
        logger.debug('"%s" seems like a setter', i)
        name, ext = os.path.splitext(os.path.basename(i))
        try:
            logger.debug('loading %s', name)
            import_module(name)
        except:
            logger.warning('cannot loading setter %s', name, exc_info=1)
Ejemplo n.º 3
0
from os.path import expanduser, join as pathjoin, isfile, isdir, splitext
from os.path import basename, dirname, abspath
import log
import webutil
import bingwallpaper
import record
import setter
import sched
import config

NAME = 'pybingwallpaper'
REV  = '1.4.3'
LINK = 'https://github.com/genzj/pybingwallpaper'
HISTORY_FILE = pathjoin(expanduser('~'), 'bing-wallpaper-history.json')

_logger = log.getChild('main')

class CannotLoadImagePage(Exception):
    pass

def load_setters():
    if platform == 'win32':
        return ['no', 'win']
    else:
        return ['no', 'gnome3', 'gnome2']

def prepare_config_db():
    params = []

    setters = load_setters()
Ejemplo n.º 4
0
import yaml
import lya
import sys
import subprocess
import os
import json
import log
from io import BytesIO
from datetime import timedelta
from math import ceil

logger = log.getChild('clipper')
ffmpeglogger = log.getChild('ffmpeg')
ffprobelogger = log.getChild('ffprobe')

def prepare_output_dir(proj):
    proj.outdir = os.path.abspath(os.path.join(
                 proj.output.dir,
                 proj.title))
    outdir = proj.outdir
    try:
        logger.info('preparing output folder %s', outdir)
        os.makedirs(outdir)
    except Exception as err:
        logger.debug('makedirs returns error %s', err)

    if not os.path.isdir(outdir):
        raise Exception('%s is not a dir'%(outdir,))
    elif not os.access(outdir, os.F_OK):
        raise Exception('fail to create dir %s'%(outdir,))
    elif not os.access(outdir, os.R_OK | os.W_OK):
Ejemplo n.º 5
0
 def __init__(self, prog, description = None, parameters = None):
     self.logger = log.getChild(self.__class__.__name__)
     self.prog = prog
     self.description = description
     self.parameters = list(parameters) if parameters is not None else list()
Ejemplo n.º 6
0
#!/usr/bin/env python3
import log
import json
import datetime
import sqlite3
from os.path import isfile
from collections import UserDict

_logger = log.getChild('record')
#_logger.setLevel(log.DEBUG)


class DownloadRecord(dict):
    def __init__(self,
                 url,
                 local_file,
                 description,
                 download_time=None,
                 raw=None,
                 is_accompany=False,
                 market=''):
        UserDict.__init__(self)
        if download_time is None:
            download_time = datetime.datetime.utcnow()
        timestr = download_time.isoformat()

        self['url'] = url
        self['local_file'] = local_file
        self['description'] = description
        self['time'] = timestr
        self['raw'] = raw
Ejemplo n.º 7
0
#!/usr/bin/env python3
import log
import json
import time
import datetime
from os.path import isfile
from collections import UserDict

_logger = log.getChild("record")
# _logger.setLevel(log.DEBUG)


class DownloadRecord(dict):
    def __init__(self, url, local_file, download_time=None):
        UserDict.__init__(self)
        if download_time is None:
            download_time = datetime.datetime.fromtimestamp(time.time())
        timestr = download_time.isoformat()

        self["url"] = url
        self["local_file"] = local_file
        self["time"] = timestr


class DownloadRecordManager(dict):
    def __init__(self, name):
        dict.__init__(self)
        self.name = name
        self.clear()

    def save(self, f):
Ejemplo n.º 8
0
#!/usr/bin/env python3
import log
import json
import time
import datetime
from os.path import isfile
from collections import UserDict

_logger = log.getChild('record')
#_logger.setLevel(log.DEBUG)

class DownloadRecord(dict):
    def __init__(self, url, local_file, download_time=None):
        UserDict.__init__(self)
        if download_time is None:
            download_time = datetime.datetime.fromtimestamp(time.time())
        timestr = download_time.isoformat()

        self['url'] = url
        self['local_file'] = local_file
        self['time'] = timestr

null_record = DownloadRecord('', '', datetime.datetime.fromtimestamp(0))

class DownloadRecordManager(dict):
    def __init__(self, name):
        dict.__init__(self)
        self.name = name
        self.clear()

    def save(self, f):
Ejemplo n.º 9
0
#!/usr/bin/env python3
import re
import log
import webutil
from urllib.parse import urljoin

_logger = log.getChild('ngphoto')


def _property_need_loading(f):
    def wrapper(*args, **kwargs):
        args[0]._assert_load(f.__name__)
        return f(*args, **kwargs)

    return wrapper


class NgPhotoPage:
    def __init__(self, url):
        self.update(url)

    def update(self, url):
        if hasattr(self, 'url') and self.url == url:
            return
        self.reset()
        self.url = url

    def reset(self):
        self.__loaded = False
        self.__isphoto = False
        self.content = ''
Ejemplo n.º 10
0
#!/usr/bin/env python
import sys
import log
from importlib import import_module
import gzip
from io import BytesIO

_logger = log.getChild('webutil')

if sys.version_info[:2] < (3, 0):
    _logger.debug('importing libs for python 2.x')
    _urllib = import_module('urllib')
    _urllib2 = import_module('urllib2')
    _urlparse = import_module('urlparse')
    urlparse = _urlparse.urlparse
    urlencode = _urllib.urlencode
    unquote = _urllib.urlencode
    Request = _urllib2.Request
    urlopen2 = _urllib2.urlopen
else:
    _logger.debug('importing libs for python 3.x')
    _urlparse = import_module('urllib.parse')
    _urlrequest = import_module('urllib.request')
    urlparse = _urlparse.urlparse
    urlencode = _urlparse.urlencode
    Request = _urlrequest.Request
    urlopen2 = _urlrequest.urlopen


def _ungzip(html):
    if html[:6] == b'\x1f\x8b\x08\x00\x00\x00':
Ejemplo n.º 11
0
#!/usr/bin/env python3
import re
import log
import webutil
from urllib.parse import urljoin

_logger = log.getChild('ngphoto')

def _property_need_loading(f):
    def wrapper(*args, **kwargs):
        args[0]._assert_load(f.__name__)
        return f(*args, **kwargs)
    return wrapper

class NgPhotoPage:
    def __init__(self, url):
        self.update(url)

    def update(self, url):
        if hasattr(self, 'url') and self.url == url:
            return
        self.reset()
        self.url = url

    def reset(self):
        self.__loaded = False
        self.__isphoto = False
        self.content = ''
        self.__title = ''
        self.__img_link = None
        self.__wallpaper_link = None
Ejemplo n.º 12
0
#!/usr/bin/env python3
import re
import log
import webutil
import json

_logger = log.getChild('bingwallpaper')

def _property_need_loading(f):
    def wrapper(*args, **kwargs):
        args[0]._assert_load(f.__name__)
        return f(*args, **kwargs)
    return wrapper

class HighResolutionSetting:
    settings = dict()
    def getPicUrl(self, rooturl, imgurlbase, fallbackurl, has_wp, *args, **kwargs):
        raise NotImplementedError()

    @staticmethod
    def getByName(name):
        if name not in HighResolutionSetting.settings:
            raise ValueError('{} is not a legal resolution setting'.format(name))
        return HighResolutionSetting.settings[name]

class PreferHighResolution(HighResolutionSetting):
    def getPicUrl(self, rooturl, imgurlbase, fallbackurl, has_wp, *args, **kwargs):
        if has_wp:
            wplink = webutil.urljoin(rooturl, '_'.join([imgurlbase,'1920x1200.jpg'])) 
            _logger.debug('in prefer mode, get high resolution url %s', wplink)
        else:
Ejemplo n.º 13
0
#!/usr/bin/env python3
import re
import log
import webutil
import json

_logger = log.getChild("bingwallpaper")


def _property_need_loading(f):
    def wrapper(*args, **kwargs):
        args[0]._assert_load(f.__name__)
        return f(*args, **kwargs)

    return wrapper


class HighResolutionSetting:
    settings = dict()

    def getPicUrl(self, rooturl, imgurlbase, fallbackurl, has_wp, *args, **kwargs):
        raise NotImplementedError()

    @staticmethod
    def getByName(name):
        if name not in HighResolutionSetting.settings:
            raise ValueError("{} is not a legal resolution setting".format(name))
        return HighResolutionSetting.settings[name]


class PreferHighResolution(HighResolutionSetting):
Ejemplo n.º 14
0
 def __init__(self):
     self._logger = log.getChild(self.__class__.__name__)
Ejemplo n.º 15
0
from os.path import expanduser, join as pathjoin, isfile, isdir, splitext
from os.path import basename, dirname, abspath
import log
import webutil
import bingwallpaper
import record
import setter
import sched
import config

NAME = 'pybingwallpaper'
REV  = '1.4.4'
LINK = 'https://github.com/genzj/pybingwallpaper'
HISTORY_FILE = pathjoin(expanduser('~'), 'bing-wallpaper-history.json')

_logger = log.getChild('main')

class CannotLoadImagePage(Exception):
    pass

def load_setters():
    if platform == 'win32':
        return ['no', 'win']
    else:
        return ['no', 'gnome3', 'gnome2']

def prepare_config_db():
    params = []

    setters = load_setters()
Ejemplo n.º 16
0
 def __init__(self):
     self._logger = log.getChild(self.__class__.__name__)
     self._logger.setLevel(loglevel)
Ejemplo n.º 17
0
#!/usr/bin/env python3
import re
import log
import webutil
import json

_logger = log.getChild('bingwallpaper')

def _property_need_loading(f):
    def wrapper(*args, **kwargs):
        args[0]._assert_load(f.__name__)
        return f(*args, **kwargs)
    return wrapper

class HighResolutionSetting:
    PREFER = 1
    INSIST = 2
    NEVER = 3
    @staticmethod
    def getByName(name):
        k = {'prefer': HighResolutionSetting.PREFER,
             'insist': HighResolutionSetting.INSIST,
             'never' : HighResolutionSetting.NEVER
             }
        if name not in k:
            raise ValueError('{} is not a legal resolution setting'.format(name))
        return k[name]

class BingWallpaperPage:
    BASE_URL='http://www.bing.com'
    IMAGE_API='/HPImageArchive.aspx?format=js&idx={idx}&n={n}'
Ejemplo n.º 18
0
 def __init__(self):
     self._logger = log.getChild(self.__class__.__name__)
Ejemplo n.º 19
0
#!/usr/bin/env python3
import log
from log import PAGEDUMP
import argparse
import sys
import io
from argparse import Namespace
from copy import copy

_logger = log.getChild('config')


def _dumpconfig(parser, level=PAGEDUMP):
    _logger.log(level, 'a config file parsed as:')
    for section_name, section in parser.items():
        _logger.log(level, '  + section %s', section_name)
        _logger.log(level, '  |')
        for key, value in section.items():
            _logger.log(level, '  +-- %s = %s', key, value)
        _logger.log(level, '')


str_to_bool = lambda x: True if bool(x) and x.lower() != 'false' else False


class ConfigParameter:
    ''' 
        ConfigParameter is an abstract of configuration data which integrate config file
        and commandline-like argument data models.
    '''
    def __init__(self,
Ejemplo n.º 20
0
#!/usr/bin/env python3
import log
from log import PAGEDUMP
import argparse
import sys
import io
from argparse import Namespace
from copy import copy

_logger = log.getChild('config')

def _dumpconfig(parser, level=PAGEDUMP):
    _logger.log(level, 'a config file parsed as:')
    for section_name, section in parser.items():
        _logger.log(level, '  + section %s', section_name)
        _logger.log(level, '  |')
        for key, value in section.items():
            _logger.log(level, '  +-- %s = %s', key, value)
        _logger.log(level, '')

str_to_bool = lambda x: True if bool(x) and x.lower() != 'false' else False

class ConfigParameter:
    ''' 
        ConfigParameter is an abstract of configuration data which integrate config file
        and commandline-like argument data models.
    '''
    def __init__(self, name, defaults=None, type=None, choices=None, help='', loader_srcs=None, loader_opts=None):
        '''
        name        - name of option.
        defaults    - default values which can be specified as a dict with keys 
Ejemplo n.º 21
0
#!/usr/bin/env python
import sys
import log
from importlib import import_module
import gzip
from io import BytesIO

_logger = log.getChild('webutil')

if sys.version_info[:2] < (3, 0):
    _logger.debug('importing libs for python 2.x')
    _urllib = import_module('urllib')
    _urllib2 = import_module('urllib2')
    _urlparse = import_module('urlparse')
    urlparse = _urlparse.urlparse
    urlencode = _urllib.urlencode
    unquote = _urllib.urlencode
    Request = _urllib2.Request
    urlopen2 = _urllib2.urlopen
else:
    from ntlmauth import HTTPNtlmAuthHandler
    _logger.debug('importing libs for python 3.x')
    _urlparse = import_module('urllib.parse')
    _urlrequest = import_module('urllib.request')
    urlparse = _urlparse.urlparse
    urlencode = _urlparse.urlencode
    Request = _urlrequest.Request
    urlopen2 = _urlrequest.urlopen

    def setup_proxy(proxy_protocols, proxy_url, proxy_port, sites, username="", password=""):
        proxy_dict = {p:'%s:%s'%(proxy_url, proxy_port) for p in proxy_protocols}
Ejemplo n.º 22
0
#!/usr/bin/env python
import sys
import log
from importlib import import_module
import gzip
from io import BytesIO

_logger = log.getChild("webutil")

if sys.version_info[:2] < (3, 0):
    _logger.debug("importing libs for python 2.x")
    _urllib = import_module("urllib")
    _urllib2 = import_module("urllib2")
    _urlparse = import_module("urlparse")
    urlparse = _urlparse.urlparse
    urlencode = _urllib.urlencode
    unquote = _urllib.urlencode
    Request = _urllib2.Request
    urlopen2 = _urllib2.urlopen
    URLError = _urllib2.URLError
else:
    from ntlmauth import HTTPNtlmAuthHandler

    _logger.debug("importing libs for python 3.x")
    _urllib = import_module("urllib")
    _urlparse = import_module("urllib.parse")
    _urlrequest = import_module("urllib.request")
    urlparse = _urlparse.urlparse
    urlencode = _urlparse.urlencode
    Request = _urlrequest.Request
    urlopen2 = _urlrequest.urlopen