def do_shutdown(self):
        Gtk.Application.do_shutdown(self)

        #   Dump file
        if self.changed and self.saved_settings:
            with open(get_local('user_settings.json'), 'w') as file:
                json.dump(self.us_se, file, indent=4)
            exit_message = 'Successfully saved settings'
        else:
            exit_message = 'No changes were made'

        logger.info(exit_message)
示例#2
0
def get_next_run():
    import pickle
    import tzlocal
    import pytz
    try:
        with open(get_local('sun_times'), 'rb') as file:
            sunrise, sunset = pickle.load(file)
    except FileNotFoundError:
        import sys
        logger.error('Could not find times file, exiting...')
        sys.exit()

    now = datetime.now(pytz.utc).astimezone(tzlocal.get_localzone()).time()
    sunrise, sunset = (sunrise.astimezone(tzlocal.get_localzone()).time(),
                       sunset.astimezone(tzlocal.get_localzone()).time())

    if sunrise < now < sunset:
        return ':'.join(str(sunset).split(':')[:-1])
    else:
        return ':'.join(str(sunrise).split(':')[:-1])
示例#3
0
def main():

    check_root()

    import automathemely

    from automathemely.autoth_tools import argmanager, extratools, envspecific, updsuntimes

    from automathemely import __version__ as version
    from automathemely.autoth_tools.utils import get_resource, get_local, update_dict

    #   Set workspace as the directory of the script
    workspace = Path(__file__).resolve().parent
    chdir(str(workspace))
    sys.path.append('..')

    first_time_run = False

    #   Test for settings file and if it doesn't exist copy it from defaults
    if not Path(get_local('user_settings.json')).is_file():
        shutil.copy2(get_resource('default_user_settings.json'),
                     get_local('user_settings.json'))
        # By default notifications are enabled
        from automathemely import notifier_handler
        logging.getLogger().addHandler(notifier_handler)
        logger.info('No valid config file found, creating one...')
        first_time_run = True

    try:
        with open(get_local('user_settings.json'), 'r') as f:
            user_settings = json.load(f)
    except json.decoder.JSONDecodeError:
        user_settings = dict()

    #   If settings files versions don't match (in case of an update for instance), overwrite values of
    #   default_settings with user_settings and use that instead

    logger.debug('Program version = {}'.format(version))
    logger.debug('File version = {}'.format(str(user_settings['version'])))
    if 'version' not in user_settings or str(
            user_settings['version']) != version:
        with open(get_resource('default_user_settings.json'), 'r') as f:
            default_settings = json.load(f)

        from pkg_resources import parse_version

        # Hardcoded attempt to try to import old structure to new structure...
        if parse_version(str(
                user_settings['version'])) <= parse_version('1.2'):
            logger.debug('Lower version!')
            user_settings['themes']['gnome'] = dict()
            user_settings['themes']['gnome']['light'], user_settings['themes'][
                'gnome']['dark'] = dict(), dict()
            user_settings['themes']['gnome']['light']['gtk'] = user_settings[
                'themes'].pop('light', '')
            user_settings['themes']['gnome']['dark']['gtk'] = user_settings[
                'themes'].pop('dark', '')

        user_settings = update_dict(default_settings, user_settings)
        user_settings['version'] = version

    if user_settings['misc']['notifications']:
        # Not exactly sure why this is needed but alright...
        automathemely.notifier_handler.setFormatter(
            logging.Formatter(automathemely.default_simple_format))
        # Add the notification handler to the root logger
        logging.getLogger().addHandler(automathemely.notifier_handler)

    #   If any argument is given, pass it/them to the arg manager module
    t_color = None
    if len(sys.argv) > 1:
        t_color = automathemely.autoth_tools.argmanager.main(user_settings)
        if not t_color:
            return

    # We don't want to proceed until we have given the user the chance to review its settings
    if first_time_run:
        return

    if not Path(get_local('sun_times')).is_file():
        logger.info('No valid times file found, creating one...')
        output = updsuntimes.main(user_settings)
        if output:
            with open(get_local('sun_times'), 'wb') as file:
                pkl.dump(output, file, protocol=pkl.HIGHEST_PROTOCOL)

    local_tz = tzlocal.get_localzone()

    with open(get_local('sun_times'), 'rb') as file:
        sunrise, sunset = pkl.load(file)

    #   Convert to local timezone and ignore date
    now = datetime.now(pytz.utc).astimezone(local_tz).time()
    sunrise, sunset = sunrise.astimezone(local_tz).time(), sunset.astimezone(
        local_tz).time()

    if t_color:
        pass
    elif sunrise < now < sunset:
        t_color = 'light'
    else:
        t_color = 'dark'

    logger.info('Switching to {} themes...'.format(t_color))

    #   Change desktop environment theme
    desk_env = user_settings['desktop_environment']
    if desk_env != 'custom':
        for t_type in user_settings['themes'][desk_env][t_color]:
            theme = user_settings['themes'][desk_env][t_color][t_type]
            envspecific.set_theme(desk_env, t_type, theme)

    #   Run user scripts
    s_time = 'sunrise' if t_color == 'light' else 'sunset'
    extratools.run_scripts(
        user_settings['extras']['scripts'][s_time],
        notifications_enabled=user_settings['misc']['notifications'])

    #   Change extra themes
    for k, v in user_settings['extras'].items():
        if k != 'scripts' and v['enabled']:
            extratools.set_extra_theme(user_settings, k, t_color)
示例#4
0
def main(us_se):
    args = parser.parse_args()

    #   LIST
    if args.list:
        logger.info('Printing current settings...')
        print('')
        print_list(us_se)
        return

    #   SET
    elif args.setting:
        if not args.setting.count('=') == 1:
            logger.error('Invalid string (None or more than one "=" signs)')
            return

        setts = args.setting.split('=')
        to_set_key = setts[0].strip()
        to_set_val = setts[1].strip()

        if to_set_key == '':
            logger.error('Invalid string (Empty key)')
        elif to_set_key[-1] == '.':
            logger.error('Invalid string (Key ends in dot)')
        if not to_set_val:
            logger.error('Invalid string (Empty value)')
        elif to_set_val.lower() in ['t', 'true']:
            to_set_val = True
        elif to_set_val.lower() in ['f', 'false']:
            to_set_val = False
        else:
            try:
                to_set_val = int(to_set_val)
            except ValueError:
                try:
                    to_set_val = float(to_set_val)
                except ValueError:
                    pass

        if to_set_key.count('.') > 0:
            key_list = [s.strip() for s in to_set_key.split('.')]
        else:
            key_list = [to_set_key]

        if read_dict(us_se, key_list) is not None:
            write_dic(us_se, key_list, to_set_val)

            with open(get_local('user_settings.json'), 'w') as file:
                json.dump(us_se, file, indent=4)

            # Warning if user disables auto by --setting
            if 'enabled' in to_set_key and not to_set_val:
                logger.warning('Remember to set all the necessary values with either --settings or --manage')
            logger.info('Successfully set key "{}" as "{}"'.format(to_set_key, to_set_val))
            exit()

        else:
            logger.error('Key "{}" not found'.format(to_set_key))

        return

    #   MANAGE
    elif args.manage:
        from . import settsmanager
        #   From here on the manager takes over 'til exit
        settsmanager.main(us_se)
        return

    #   UPDATE
    elif args.update:
        from . import updsuntimes
        output = updsuntimes.main(us_se)
        if output:
            with open(get_local('sun_hours.time'), 'wb') as file:
                pkl.dump(output, file, protocol=pkl.HIGHEST_PROTOCOL)
            logger.info('Sun hours successfully updated')
        return

    #   RESTART
    elif args.restart:
        from automathemely.autoth_tools.utils import pgrep, get_bin
        from subprocess import Popen, DEVNULL
        if pgrep(['autothscheduler.py'], use_full=True):
            Popen(['pkill', '-f', 'autothscheduler.py']).wait()
        Popen(['python3', get_bin('autothscheduler.py')], start_new_session=True, stdout=DEVNULL, stderr=DEVNULL)
        logger.info('Restarted the scheduler')
    elif args.theme:
        return args.theme
示例#5
0
    # We don't need these two
    root_logger.removeHandler(main_file_handler)
    root_logger.removeHandler(notifier_handler)
    # Log here instead
    root_logger.addHandler(updsun_file_handler)

    # Format the remaining handlers to display time
    for handler in root_logger.handlers[:]:
        handler.setFormatter(logging.Formatter(timed_details_format))

    # This logger is specifically for displaying a notification if something went wrong
    run_as_main_logger = logging.getLogger('updsuntimes.py')

    notifier_handler.setLevel(logging.WARNING)
    notifier_handler.setFormatter(logging.Formatter(default_simple_format))
    run_as_main_logger.addHandler(notifier_handler)

    with open(get_local('user_settings.json'), 'r') as f:
        user_settings = json.load(f)

    output = main(user_settings)
    if output:
        with open(get_local('sun_times'), 'wb') as file:
            pkl.dump(output, file, protocol=pkl.HIGHEST_PROTOCOL)
    else:
        if verify_desktop_session():
            run_as_main_logger.warning(
                'There were some errors while updating the sunrise and sunset times, check {} '
                'for more details'.format(get_local('.updsuntimes.log')))
示例#6
0
import logging
from pathlib import Path
from sys import stdout, stderr
from automathemely.autoth_tools.utils import get_local, notify

_ROOT = str(Path(__file__).resolve().parent)
__version__ = "1.3.0-dev1"


# Move/rename older local config directory name to the new lowercase one
if Path.home().joinpath('.config', 'AutomaThemely').is_dir():
    import shutil
    shutil.move(str(Path.home().joinpath('.config', 'AutomaThemely')), get_local())

# Create user config dir if it doesn't exist already
Path(get_local()).mkdir(parents=True, exist_ok=True)


# Custom Handler to pass logs as notifications
class NotifyHandler(logging.StreamHandler):
    def emit(self, record):
        message = self.format(record)
        notify(message)


# noinspection SpellCheckingInspection
default_simple_format = '%(levelname)s: %(message)s'
# noinspection SpellCheckingInspection
timed_details_format = '(%(asctime)s) (%(filename)s:%(funcName)s:%(lineno)s) %(levelname)s: %(message)s'

# Setup logging levels/handlers