Exemple #1
0
def parse_args():
    """
    Parses command line options and arguments
    """
    config = ConfigFile()

    ap = ArgumentParser(usage="usage: %prog [opts]")

    ap.add_argument("-t",
                    "--test",
                    dest="test",
                    default=False,
                    action="store_true",
                    help="executes the test suite")

    ap.add_argument("-f",
                    "--fullscreen",
                    dest="fullscreen",
                    default=config.get_bool("fullscreen", False),
                    action="store_true",
                    help="starts the application in fullscreen mode")

    ap.add_argument("-v",
                    "--version",
                    dest="version",
                    default=False,
                    action="store_true",
                    help="displays the current version of the application")

    return ap.parse_args()
def get_asterisk_conf():
    localtest_root = os.getenv("AST_TEST_ROOT")
    if localtest_root:
        # The default etc directory for Asterisk
        default_etc_directory = os.path.join(localtest_root, "etc/asterisk")
    else:
        # The default etc directory for Asterisk
        default_etc_directory = "/etc/asterisk"

    # Find the system installed asterisk.conf
    ast_confs = [
        os.path.join(default_etc_directory, "asterisk.conf"),
        "/usr/local/etc/asterisk/asterisk.conf",
    ]
    _ast_conf = None
    for config in ast_confs:
        if os.path.exists(config):
            _ast_conf = ConfigFile(config)
            break
    if _ast_conf is None:
        msg = "Unable to locate asterisk.conf in any known location"
        LOGGER.error(msg)
        raise Exception(msg)

    # Get the Asterisk directories from the Asterisk config file
    _ast_conf.directories = {};
    for cat in _ast_conf.categories:
        if cat.name == "directories":
            for (var, val) in cat.options:
                _ast_conf.directories[var] = val

    return _ast_conf
Exemple #3
0
    def __init__(self, account):          #Account and password are instagram account and password
        self.config_file = ConfigFile(account)
        self.sub_list = self.config_file.get("Reddit", "Subreddits")
        self.account = account
        self.ibot =  InstagramBot(account)
        self.rbot = RedditBot(account)
        self.obot = osManager(int(self.config_file.get("Time", "imagelifetime")))
        self.db = dbManager()
        self.numPosts = int(self.ibot.getNumberOfPosts())
        #Make this self and remove all of the member variables and instead call the dicionary when needed
        times = self.config_file.get("Time")
        for k,v in times.items():
            times[k] = int(v)

        self.scrape_time = times["scrapetime"]
        self.upload_time_MAX = times["uploadtimemax"]
        self.upload_time_MIN = times["uploadtimemin"]
        self.expire_time = times["expiretime"]
        self.retry_upload_delay = times["retryuploaddelay"]
        #Keep this however when deleting for convenience
        self.slow_hours_start = datetime.time(times["slowhourstart"], 0, 0)
        self.slow_hours_end = datetime.time(times["slowhourend"], 0, 0)
        self.slow_hours_delay = times["slowhourdelay"]
        self.follow_time_MAX = times["followtimemax"]
        self.follow_time_MIN = times["followtimemin"]
        self.like_time_MAX = times["liketimemax"]
        self.like_time_MIN = times["liketimemin"]
 def test_CF_save(self):
     assert not Path(self.save_path).is_file()
     try:
         self.init_config.path = self.save_path
         self.init_config.save()
         save_config = ConfigFile(self.save_path)
         self.assertEqual(save_config, self.init_config)
     finally:
         if Path(self.save_path).is_file():
             Path(self.save_path).unlink()
Exemple #5
0
 def _globalConfSettings(self):
     zenhome = os.environ.get('ZENHOME')
     if zenhome:
         with open(os.path.join(zenhome, 'etc/global.conf'), 'r') as fp:
             globalConf = ConfigFile(fp)
             settings = {}
             for line in globalConf.parse():
                 if line.setting:
                     key, val = line.setting
                     settings[key] = val
             return settings
Exemple #6
0
 def __init__(self, iusername):
     self.config_file = ConfigFile(iusername)
     self.reddit = praw.Reddit(
         client_id=self.config_file.get("Reddit", "client_id"),
         client_secret=self.config_file.get("Reddit", "client_secret"),
         password=self.config_file.get("Reddit", "password"),
         user_agent=self.config_file.get("Reddit", "user_agent"),
         username=self.config_file.get("Reddit", "username"))
     self.redditURL = 'www.reddit.com/r/'
     self.db = dbManager()
     self.osMan = osManager()
     self.videoDurationMax = int(
         self.config_file.get("Time", "videodurationmax"))
    def setUp(self):
        self.root_path = PurePath("test")
        self.init_path = self._prep_path(PurePath("test.json"))
        self.init_config = ConfigFile(self.init_path)
        self.init_config_static = ConfigFile(self.init_path)
        self.empty_config = ConfigFile()

        with open(str(self.init_path)) as f:
            self.init_json = json.load(f)

        self.save_path = self._prep_path(PurePath("save.json"))
        self.schema_path = self._prep_path(PurePath("test.schema.json"))

        self.new_key = "zzz"
        self.new_data = {"foo": "bar", "baz": ["qux"]}
        self.new_json = self.init_json.copy()
        self.new_json[self.new_key] = self.new_data

        self.list_key = "list_config"
        self.dict_key = "dict_config"
        self.list_copy_key = "list_config_copy"
        self.nested_key = "nested_dict_config"
 def test_CF_overwrite_on(self):
     assert not Path(self.save_path).is_file()
     try:
         self.init_config.path = self.save_path
         self.init_config.overwrite_on()
         self.init_config.save()
         self.init_config[self.new_key] = self.new_data
         self.init_config.save()
         save_config = ConfigFile(self.save_path)
         self.assertNotEqual(save_config, self.init_config_static)
         self.assertEqual(save_config, self.init_config)
     finally:
         if Path(self.save_path).is_file():
             Path(self.save_path).unlink()
Exemple #9
0
 def __init__(self, account):
     self.config_file = ConfigFile(account)
     self.account = account.strip()
     self.password = self.config_file.get("Instagram", "password").strip()
     self.db = dbManager()
     self.hashtags = self.config_file.get("Hashtags")
     self.titles = self.config_file.get("Instagram", "Titles")
     self.follow_amount_min = int(
         self.config_file.get("Instagram", "followamountmin"))
     self.follow_amount_max = int(
         self.config_file.get("Instagram", "followamountmax"))
     self.unfollow_days = int(self.config_file.get("Time", "unfollowdays"))
     self.like_ammount_max = int(
         self.config_file.get("Instagram", "likeamountmax"))
     self.like_ammount_min = int(
         self.config_file.get("Instagram", "likeamountmin"))
     print("Created Instagram Bot!")
Exemple #10
0
 def _getParamsFromGlobalConf(self, defaultDb):
     zenhome = os.environ.get('ZENHOME')
     if not zenhome:
         raise ZenDBError('No $ZENHOME set. In order to use default '
                          'configurations, $ZENHOME must point to the '
                          'Zenoss install.')
     else:
         with open(os.path.join(zenhome, 'etc/global.conf'), 'r') as fp:
             globalConf = ConfigFile(fp)
             settings = {}
             for line in globalConf.parse():
                 if line.setting:
                     key, val = line.setting
                     if key.startswith(defaultDb + '-'):
                         key = key[len(defaultDb) + 1:]
                         settings[key] = val
             return settings
    def test_CF_schema(self):
        try:
            schema_config = ConfigFile(self.init_path, self.schema_path)
        except jsonschema.ValidationError as e:
            self.fail()

        assert not Path(self.save_path).is_file()
        try:
            schema_config.path = self.save_path
            schema_config.overwrite_off()
            schema_config.save()
            schema_config[self.new_key] = self.new_data
            schema_config.save()
        except jsonschema.ValidationError as e:
            self.fail()
        finally:
            if Path(self.save_path).is_file():
                Path(self.save_path).unlink()
Exemple #12
0
    def check_voicemail_property(self,
                                 context,
                                 mailbox,
                                 msgnum,
                                 property_name,
                                 property_value,
                                 folder=inbox_folder_name):
        """Check if a voicemail has the property specified

        Keyword Arguments:
        context         The context of the mailbox
        mailbox         The mailbox
        msgnum          The 1-based index of the voicemail to check for
        property_name   The name of the property to check
        property_value  The value to check for
        folder          The folder to check under; default to the default inbox
                        name

        Returns:
        True if the voicemail has the property and value specified
        False otherwise
        """
        list_formats = []
        if not self.check_voicemail_exists(context, mailbox, msgnum,
                                           list_formats, folder):
            return False

        msg_name = 'msg%(msgnum)04d' % {"msgnum": msgnum}
        msg_name = msg_name + ".txt"
        msg_path = (self.__ast.base + "%(vd)s/%(c)s/%(m)s/%(f)s/%(n)s" % {
            'vd': self.voicemail_directory,
            'c': context,
            'm': mailbox,
            'f': folder,
            'n': msg_name
        })

        config_file = ConfigFile(msg_path)
        for cat in config_file.categories:
            if cat.name == 'message':
                for kvp in cat.options:
                    if kvp[0] == property_name and kvp[1] == property_value:
                        return True
        return False
Exemple #13
0
    def get_sqlite_config(self, ast_instance):
        """Retrieve necessary SQLite3 config parameters from the config file

        Keyword Arguments:
        ast_instance The instance of Asterisk that used the config file

        Returns:
        Tuple of (table, columns)
        """
        sqlite_config_file = (
            "%s/%s/cdr_sqlite3_custom.conf" %
            (ast_instance.base, ast_instance.directories['astetcdir']))

        sqlite_config = ConfigFile(sqlite_config_file)
        for option in sqlite_config.categories[0].options:
            if option[0] == 'table':
                table = option[1]
            elif option[0] == 'columns':
                columns = [col.strip() for col in option[1].split(',')]
        return (table, columns)
Exemple #14
0
    def get_user_object(self, context, mailbox, source_file="voicemail.conf"):
        """Gets user information from the voicemail configuration file

        Keyword Arguments:
        context     The context of the mailbox
        mailbox     The mailbox
        source_file The file containing the user information to pull from.
                    Defaults to voicemail.conf

        Returns:
        A VoiceMailMailboxManagement.UserObject object, populated with the
        user's values, or an empty object
        """

        file_path = (self.__ast.base + self.__ast.directories['astetcdir'] +
                     "/" + source_file)

        config_file = ConfigFile(file_path)
        user_object = VoiceMailMailboxManagement.UserObject()
        for cat in config_file.categories:
            if cat.name == context:
                for kvp in cat.options:
                    if kvp[0] == mailbox:
                        tokens = kvp[1].split(',')
                        i = 0
                        for token in tokens:
                            if i == 0:
                                user_object.password = token
                            elif i == 1:
                                user_object.fullname = token
                            elif i == 2:
                                user_object.emailaddress = token
                            elif i == 3:
                                user_object.pageraddress = token
                            i += 1
                        return user_object
        return user_object
Exemple #15
0
        except:
            continue
        if stat.S_ISDIR(st[stat.ST_MODE]):
            dirs.append(fn)
        else:
            dbfile[fn] = read_data(pp)
            nfiles = nfiles + 1
    dbfile.sync()
    dbfile.close()
    print('%s files, %s subdirs' % (nfiles, len(dirs)))
    for dn in dirs:
        cvtDirRec(old_root, new_root, lpath + '/' + dn)


if __name__ == '__main__':
    cfg = ConfigFile(os.environ['DFARM_CONFIG'])
    old_dbroot = cfg.getValue('vfssrv', '*', 'db_root')
    if not old_dbroot:
        print(
            'VFS Database root directory is not defined in the configuration')
        sys.exit(1)
    one_up = '/'.join(old_dbroot.split('/')[:-1])
    new_dbroot = one_up + '/new_dbroot'
    save_dbroot = one_up + '/db_saved'
    cvtDirRec(old_dbroot, new_dbroot, '/')
    os.mkdir(new_dbroot + '/.cellinx')
    os.rename(old_dbroot, save_dbroot)
    os.rename(new_dbroot, old_dbroot)

    print('VFS Database conversion is complete.')
    print('Old database is renamed into %s' % save_dbroot)
Exemple #16
0
    def __init__(self, base=None, ast_conf_options=None, host="127.0.0.1",
                 remote_config=None):
        """Construct an Asterisk instance.

        Keyword Arguments:
        base -- This is the root of the files associated with this instance of
                Asterisk. By default, the base is "/tmp/asterisk-testsuite"
                directory. Given a base, it will be appended to the default base
                directory.
        ast_conf_options -- Configuration overrides for asterisk.conf.
        host -- The IP address the Asterisk instance runs on
        remote_config -- Configuration section that defines this as a remote
                         Asterisk instance. If provided, base and
                         ast_conf_options are generally ignored, and the
                         Asterisk instance's configuration is treated as
                         immutable on some remote machine defined by 'host'

        Example Usage:
        self.asterisk = Asterisk(base="manager/login")
        """
        self._start_deferred = None
        self._stop_deferred = None
        self._stop_cancel_tokens = []
        self.directories = {}
        self.protocol = None
        self.process = None
        self.astetcdir = ""
        self.original_astmoddir = ""
        self.ast_version = None
        self.remote_config = remote_config

        # If the process is remote, don't bother
        if not self.remote_config:
            self.ast_version = AsteriskVersion()

        valgrind_env = os.getenv("VALGRIND_ENABLE") or ""
        self.valgrind_enabled = True if "true" in valgrind_env else False

        if base is not None:
            self.base = base
        else:
            self.base = Asterisk.test_suite_root
        if self.localtest_root:
            self.ast_binary = self.localtest_root + "/usr/sbin/asterisk"
        else:
            ast_binary = test_suite_utils.which("asterisk")
            self.ast_binary = ast_binary or "/usr/sbin/asterisk"
        self.host = host

        self._ast_conf_options = ast_conf_options

        if self.remote_config:
            # Pretend as if we made the structure
            self._directory_structure_made = True
            self._configs_installed = True
            self._configs_set_up = True

            # And assume we've got /etc/asterisk/ where we expect it to be
            self.astetcdir = "/etc/asterisk"
        else:
            self._directory_structure_made = False
            self._configs_installed = False
            self._configs_set_up = False

            # Find the system installed asterisk.conf
            ast_confs = [
                os.path.join(self.default_etc_directory, "asterisk.conf"),
                "/usr/local/etc/asterisk/asterisk.conf",
            ]
            self._ast_conf = None
            for config in ast_confs:
                if os.path.exists(config):
                    self._ast_conf = ConfigFile(config)
                    break
            if self._ast_conf is None:
                msg = "Unable to locate asterisk.conf in any known location"
                LOGGER.error(msg)
                raise Exception(msg)

            # Set which astxxx this instance will be
            i = 1
            while True:
                if not os.path.isdir("%s/ast%d" % (self.base, i)):
                    self.base = "%s/ast%d" % (self.base, i)
                    break
                i += 1

            # Get the Asterisk directories from the Asterisk config file
            for cat in self._ast_conf.categories:
                if cat.name == "directories":
                    for (var, val) in cat.options:
                        self.directories[var] = val

            # self.original_astmoddir is for dependency checking only
            if "astmoddir" in self.directories:
                if self.localtest_root:
                    self.original_astmoddir = "%s%s" % (
                        self.localtest_root, self.directories["astmoddir"])
                else:
                    self.original_astmoddir = self.directories["astmoddir"]
Exemple #17
0
    def __init__(self, base=None, ast_conf_options=None, host="127.0.0.1"):
        """Construct an Asterisk instance.

        Keyword Arguments:
        base -- This is the root of the files associated with this instance of
        Asterisk.  By default, the base is "/tmp/asterisk-testsuite" directory.
        Given a base, it will be appended to the default base directory.

        Example Usage:
        self.asterisk = Asterisk(base="manager/login")
        """
        self._start_deferred = None
        self._stop_deferred = None
        self._stop_cancel_tokens = []
        self.directories = {}
        self.ast_version = AsteriskVersion()
        self.process_protocol = None
        self.process = None
        self.astetcdir = ""
        self.original_astmoddir = ""

        if base is not None:
            self.base = base
        else:
            self.base = Asterisk.test_suite_root
        if self.localtest_root:
            self.ast_binary = self.localtest_root + "/usr/sbin/asterisk"
        else:
            ast_binary = test_suite_utils.which("asterisk")
            self.ast_binary = ast_binary or "/usr/sbin/asterisk"
        self.host = host

        self._ast_conf_options = ast_conf_options
        self._directory_structure_made = False
        self._configs_installed = False
        self._configs_set_up = False

        # Find the system installed asterisk.conf
        ast_confs = [
            os.path.join(self.default_etc_directory, "asterisk.conf"),
            "/usr/local/etc/asterisk/asterisk.conf",
        ]
        self._ast_conf = None
        for config in ast_confs:
            if os.path.exists(config):
                self._ast_conf = ConfigFile(config)
                break
        if self._ast_conf is None:
            msg = "Unable to locate asterisk.conf in any known location"
            LOGGER.error(msg)
            raise Exception(msg)

        # Set which astxxx this instance will be
        i = 1
        while True:
            if not os.path.isdir("%s/ast%d" % (self.base, i)):
                self.base = "%s/ast%d" % (self.base, i)
                break
            i += 1

        # Get the Asterisk directories from the Asterisk config file
        for cat in self._ast_conf.categories:
            if cat.name == "directories":
                for (var, val) in cat.options:
                    self.directories[var] = val

        # self.original_astmoddir is for dependency checking only
        if "astmoddir" in self.directories:
            if self.localtest_root:
                self.original_astmoddir = "%s%s" % (
                    self.localtest_root, self.directories["astmoddir"])
            else:
                self.original_astmoddir = self.directories["astmoddir"]
Exemple #18
0
#
# Author: Soufian Salim <*****@*****.**>
#
# URL: <http://github.com/bolaft/diannotator>
"""
Grapical User Interface
"""

from tkinter import Tk, StringVar, Text, Menu, messagebox, BOTH, DISABLED, END, LEFT, BOTTOM, NORMAL, N, X, WORD, SUNKEN, INSERT, SEL, NSEW
from tkinter.ttk import Button, Entry, Frame, Label, Scrollbar
from ttkthemes import ThemedStyle

from config import ConfigFile
from strings import Strings

config = ConfigFile()  # INI configuration file


class GraphicalUserInterface(Frame):
    """
    Graphical User Interface class
    """
    # constant tag names
    STRONG = "STRONG"
    ITALIC = "ITALIC"
    HIGHLIGHT = "HIGHLIGHT"

    window_title = "DiAnnotator"  # window title

    padding = config.get_int("padding", 25)  # padding for text area")
    wrap_length = config.get_int(
Exemple #19
0
def main():
    parser = argparse.ArgumentParser(
        description="manage and report time allocation",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=textwrap.dedent("""
			DURATIONs
			  Spans of time can be provided in a concise format, a series of integers or
			  floats each appended with a unit: d, h, m. Whitespace between each component
			  is optional. Fractions less than 1 require a leading 0.

			  Note that a day is 8 hours.

			  Examples:
				15m
				0.5h
				1.5h
				1d 4.5h
				1d 4h 30m
				1d4h30m

			  Note that, while whitespace is optional, if you do specify a duration on the
			  command line and it includes whitespace, you"ll have to quote it.

			DATEs
			  Dates should be provided in the form YYYY-MM-DD.

			TIMEs
			  Times should be provided in the form HH:MM. All times used, including "now",
			  have their seconds zeroed out. All times provided on the command line are
			  assumed to occur today.

			Config File:
			  ~/.worklog/config.json - Can be created to store username and password to avoid
			  being prompted to type in your credentials for Jira authentication.

			  Example File:
				{ "username" : "jsmith" }

			  WARNING:
				Uploading multiple times in one calendar day will cause inconsistencies with time tracking
				on the server side.
		"""),
    )
    sub_parser = parser.add_subparsers(dest='command')

    common_parser = argparse.ArgumentParser(add_help=False)
    common_parser.add_argument(
        '--day', '-d', help='manage the worklog for DATE, defaults to today')

    blurb = 'start a new task, closing the currently open task if any'
    start_parser = sub_parser.add_parser('start',
                                         help=blurb,
                                         description=blurb,
                                         parents=[common_parser])
    start_parser.add_argument(
        '--ago',
        metavar='DURATION',
        help='start the task DURATION time ago, instead of now')
    start_parser.add_argument('--at',
                              metavar='TIME',
                              help='start the task at TIME, instead of now')
    start_parser.add_argument('-t',
                              '--ticket',
                              metavar='TICKET',
                              help='the TICKET associated with the task')
    start_parser.add_argument(
        'description',
        metavar='DESCRIPTION',
        nargs=argparse.REMAINDER,
        help="specify the task's description on the command line")

    blurb = 'like start, but reuse the description from a previous task in this worklog by seleting it from a list'
    resume_parser = sub_parser.add_parser('resume',
                                          help=blurb,
                                          description=blurb,
                                          parents=[common_parser])
    resume_parser.add_argument(
        '--ago',
        metavar='DURATION',
        help='start the task DURATION time ago, instead of now')
    resume_parser.add_argument('--at',
                               metavar='TIME',
                               help='start the task at TIME, instead of now')

    blurb = 'close the currently open task'
    stop_parser = sub_parser.add_parser('stop',
                                        help=blurb,
                                        description=blurb,
                                        parents=[common_parser])
    stop_parser.add_argument(
        '--ago',
        metavar='DURATION',
        help='close the open task DURATION time ago, instead of now')
    stop_parser.add_argument(
        '--at',
        metavar='TIME',
        help='close the open task at TIME, instead of now')

    blurb = 'report the current state of the worklog'
    report_parser = sub_parser.add_parser('report',
                                          help=blurb,
                                          description=blurb,
                                          parents=[common_parser])

    blurb = 'uploads worklog time to jira'
    upload_parser = sub_parser.add_parser('upload',
                                          help=blurb,
                                          description=blurb,
                                          parents=[common_parser])

    args = parser.parse_args()
    config_path = os.path.expanduser('~/.worklog/config.json')
    config = ConfigFile(config_path)
    color.ENABLED = config.features.colorize
    try:
        handler = globals()["on_{}".format(args.command)]
    except KeyError:
        parser.print_help()
    else:
        if isinstance(handler, Callable):
            handler(args, config)
        else:
            parser.error("unrecognized command: '{}'".format(args.command))
 def test_CF_eq(self):
     config_copy = ConfigFile(self.init_path)
     self.assertEqual(config_copy, self.init_config)
Exemple #21
0
    return
    if '_id' in obj.__dict__:
        orig_obj = (method)(collection, obj._id)
        logger.info("Saving %s.\nCurrent:\n%s\nNew:\n%s\n" %
                    (str(obj.__class__), pprint.pformat(
                        orig_obj.__dict__), pprint.pformat(obj.__dict__)))
    else:
        logger.info("Saving %s.\nFirst time:\n%s" %
                    (str(obj.__class__), pprint.pformat(obj.__dict__)))
    print "Saved by:"
    for n in traceback.format_list(traceback.extract_stack()[12:]):
        print "%s\n" % n


if __name__ == "__main__":
    l = local_logger('my_app', './log_test.log', logging.DEBUG)

    # "application" code
    l.debug("debug message")
    l.info("info message")
    l.warn("warn message")
    l.error("error message")
    l.critical("critical message")

    from config import ConfigFile
    config = ConfigFile()
    l.setSMTP(config.smtp.server, config.smtp.port, config.smtp.login,
              config.smtp.password, config.smtp.tls, config.smtp.debug_level,
              config.smtp.from_addr, config.smtp.to_addrs)
    l.critical("critical message")