Example #1
0
    def _load(self, account):
        self.account = account

        # Create home directory
        utils.make_dir(utils.to_config_path())
        self.configfile = utils.to_config_path('config.json')

        # Create user directory
        userfolder = "%s.%s" % (account['username'], account['api'])
        utils.make_dir(utils.to_data_path(userfolder))

        self.msg.info(self.name, 'Trackma v{0} - using account {1}({2}).'.format(
            utils.VERSION, account['username'], account['api']))
        self.msg.info(self.name, 'Reading config files...')
        try:
            self.config = utils.parse_config(
                self.configfile, utils.config_defaults)
        except IOError:
            raise utils.EngineFatal("Couldn't open config file.")

        # Expand media directories and ignore those that don't exist
        if isinstance(self.config['searchdir'], str):
            # Compatibility: Turn a string of a single directory into a list
            self.msg.debug(self.name, "Fixing string searchdir to list.")
            self.config['searchdir'] = [self.config['searchdir']]

        self.searchdirs = [path for path in utils.expand_paths(
            self.config['searchdir']) if self._searchdir_exists(path)]
Example #2
0
    def _load(self, account):
        self.account = account

        # Create home directory
        utils.make_dir(utils.to_config_path())
        self.configfile = utils.to_config_path('config.json')

        # Create user directory
        userfolder = "%s.%s" % (account['username'], account['api'])
        utils.make_dir(utils.to_data_path(userfolder))

        self.msg.info(self.name, 'Trackma v{0} - using account {1}({2}).'.format(
            utils.VERSION, account['username'], account['api']))
        self.msg.info(self.name, 'Reading config files...')
        try:
            self.config = utils.parse_config(self.configfile, utils.config_defaults)
        except IOError:
            raise utils.EngineFatal("Couldn't open config file.")

        # Expand media directories and ignore those that don't exist
        if isinstance(self.config['searchdir'], str):
            # Compatibility: Turn a string of a single directory into a list
            self.msg.debug(self.name, "Fixing string searchdir to list.")
            self.config['searchdir'] = [self.config['searchdir']]

        self.searchdirs = [path for path in utils.expand_paths(self.config['searchdir']) if self._searchdir_exists(path)]
Example #3
0
 def __init__(self, messenger, tracker_list, process_name, watch_dirs,
              interval, update_wait, update_close, not_found_prompt):
     self.config = utils.parse_config(utils.to_config_path('config.json'),
                                      utils.config_defaults)
     self.host_port = self.config['plex_host'] + ":" + self.config[
         'plex_port']
     self.update_wait = update_wait
     self.status_log = [None, None]
     self.token = self._get_plex_token()
     super().__init__(messenger, tracker_list, process_name, watch_dirs,
                      interval, update_wait, update_close, not_found_prompt)
Example #4
0
    def __init__(self, debug=False):
        Gtk.ApplicationWindow.__init__(self)
        self.init_template()

        self._debug = debug
        self._configfile = utils.to_config_path('ui-Gtk.json')
        self._config = utils.parse_config(self._configfile, utils.gtk_defaults)

        self._main_view = None
        self._account = None
        self._engine = None

        self._init_widgets()
        self.present()
Example #5
0
    def __init__(self, app, debug=False):
        Gtk.ApplicationWindow.__init__(self, application=app)
        self.init_template()

        self._debug = debug
        self._configfile = utils.to_config_path('ui-Gtk.json')
        self._config = utils.parse_config(self._configfile, utils.gtk_defaults)

        self.statusicon = None
        self._main_view = None
        self._modals = []

        self._account = None
        self._engine = None
        self.close_thread = None
        self.hidden = False

        self._init_widgets()
Example #6
0
    def __init__(self, config, debug=False):
        Gtk.Box.__init__(self)
        self.init_template()

        self._configfile = utils.to_config_path('ui-Gtk.json')
        self._config = config
        self._engine = None
        self._account = None
        self._debug = debug

        self._image_thread = None
        self._current_page = None
        self.statusbox_handler = None
        self.notebook_switch_handler = None
        self._pages = {}
        self._page_handler_ids = {}

        self._init_widgets()
        self._init_signals()
Example #7
0
    def start(self):
        """
        Starts the engine.
        This function should be called before doing anything with the engine,
        as it initializes the data handler.
        """
        if self.loaded:
            raise utils.TrackmaError("Already loaded.")

        # Start the data handler
        try:
            (self.api_info, self.mediainfo) = self.data_handler.start()
        except utils.DataError as e:
            raise utils.DataFatal(str(e))
        except utils.APIError as e:
            raise utils.APIFatal(str(e))

        # Load redirection file if supported
        api = self.api_info['shortname']
        mediatype = self.data_handler.userconfig['mediatype']
        if redirections.supports(api, mediatype):
            if utils.file_exists(utils.to_config_path('anime-relations.txt')):
                fname = utils.to_config_path('anime-relations.txt')
                self.msg.debug(self.name, "Using user-provided redirection file.")
            else:
                fname = utils.to_data_path('anime-relations.txt')
                if self.config['redirections_time'] and (
                        not utils.file_exists(fname) or
                        utils.file_older_than(fname, self.config['redirections_time'] * 86400)):
                    self.msg.info(self.name, "Syncing redirection file...")
                    self.msg.debug(self.name, "Syncing from: %s" % self.config['redirections_url'])
                    utils.sync_file(fname, self.config['redirections_url'])

            if not utils.file_exists(fname):
                self.msg.debug(self.name, "Defaulting to repo provided redirections file.")
                fname = utils.DATADIR + '/anime-relations/anime-relations.txt'

            self.msg.info(self.name, "Parsing redirection file...")
            try:
                self.redirections = redirections.parse_anime_relations(fname, api)
            except Exception as e:
                self.msg.warn(self.name, "Error parsing anime-relations.txt!")
                self.msg.debug(self.name, "{}".format(e))

        # Rescan library if necessary
        if self.config['library_autoscan']:
            try:
                self.scan_library()
            except utils.TrackmaError as e:
                self.msg.warn(
                    self.name, "Can't auto-scan library: {}".format(e))

        # Load hook files
        if self.config['use_hooks']:
            hooks_dir = utils.to_config_path('hooks')
            if os.path.isdir(hooks_dir):
                import pkgutil

                self.msg.info(self.name, "Importing user hooks...")
                for loader, name, ispkg in pkgutil.iter_modules([hooks_dir]):
                    # List all the hook files in the hooks folder, import them
                    # and call the init() function if they have them
                    # We build the list "hooks available" with the loaded modules
                    # for later calls.
                    try:
                        self.msg.debug(
                            self.name, "Importing hook {}...".format(name))
                        module = loader.find_module(name).load_module(name)
                        if hasattr(module, 'init'):
                            module.init(self)
                        self.hooks_available.append(module)
                    except ImportError:
                        self.msg.warn(
                            self.name, "Error importing hook {}.".format(name))
                        import traceback
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        for line in traceback.format_exception(exc_type, exc_value, exc_traceback):
                            self.msg.debug(self.name, line.rstrip())

        # Start tracker
        if self.mediainfo.get('can_play') and self.config['tracker_enabled']:
            self.msg.debug(self.name, "Initializing tracker...")
            try:
                TrackerClass = self._get_tracker_class(
                    self.config['tracker_type'])

                self.tracker = TrackerClass(self.msg,
                                            self._get_tracker_list(),
                                            self.config,
                                            self.searchdirs,
                                            self.redirections,
                                            )
                self.tracker.connect_signal('detected', self._tracker_detected)
                self.tracker.connect_signal('removed', self._tracker_removed)
                self.tracker.connect_signal('playing', self._tracker_playing)
                self.tracker.connect_signal('update', self._tracker_update)
                self.tracker.connect_signal(
                    'unrecognised', self._tracker_unrecognised)
                self.tracker.connect_signal('state', self._tracker_state)
            except ImportError:
                self.msg.warn(self.name, "Couldn't import specified tracker: {}".format(
                    self.config['tracker_type']))

        self.loaded = True
        return True
Example #8
0
    def start(self):
        """
        Starts the engine.
        This function should be called before doing anything with the engine,
        as it initializes the data handler.
        """
        if self.loaded:
            raise utils.TrackmaError("Already loaded.")

        # Start the data handler
        try:
            (self.api_info, self.mediainfo) = self.data_handler.start()
        except utils.DataError as e:
            raise utils.DataFatal(str(e))
        except utils.APIError as e:
            raise utils.APIFatal(str(e))

        # Rescan library if necessary
        if self.config['library_autoscan']:
            try:
                self.scan_library()
            except utils.TrackmaError as e:
                self.msg.warn(self.name,
                              "Can't auto-scan library: {}".format(e))

        # Load hook files
        if self.config['use_hooks']:
            hooks_dir = utils.to_config_path('hooks')
            if os.path.isdir(hooks_dir):
                import sys
                import pkgutil

                self.msg.info(self.name, "Importing user hooks...")
                for loader, name, ispkg in pkgutil.iter_modules([hooks_dir]):
                    # List all the hook files in the hooks folder, import them
                    # and call the init() function if they have them
                    # We build the list "hooks available" with the loaded modules
                    # for later calls.
                    try:
                        self.msg.debug(self.name,
                                       "Importing hook {}...".format(name))
                        module = loader.find_module(name).load_module(name)
                        if hasattr(module, 'init'):
                            module.init(self)
                        self.hooks_available.append(module)
                    except ImportError:
                        self.msg.warn(self.name,
                                      "Error importing hook {}.".format(name))

        # Start tracker
        if self.mediainfo.get('can_play') and self.config['tracker_enabled']:
            self.msg.debug(self.name, "Initializing tracker...")
            try:
                TrackerClass = self._get_tracker_class(
                    self.config['tracker_type'])

                self.tracker = TrackerClass(
                    self.msg,
                    self._get_tracker_list(),
                    self.config['tracker_process'],
                    self.searchdirs,
                    int(self.config['tracker_interval']),
                    int(self.config['tracker_update_wait_s']),
                    self.config['tracker_update_close'],
                    self.config['tracker_not_found_prompt'],
                )
                self.tracker.connect_signal('detected', self._tracker_detected)
                self.tracker.connect_signal('removed', self._tracker_removed)
                self.tracker.connect_signal('playing', self._tracker_playing)
                self.tracker.connect_signal('update', self._tracker_update)
                self.tracker.connect_signal('unrecognised',
                                            self._tracker_unrecognised)
                self.tracker.connect_signal('state', self._tracker_state)
            except ImportError:
                self.msg.warn(
                    self.name, "Couldn't import specified tracker: {}".format(
                        self.config['tracker_type']))

        self.loaded = True
        return True
Example #9
0
    def __init__(self):
        """Creates main widgets and creates mainloop"""
        self.config = utils.parse_config(utils.to_config_path('ui-curses.json'), utils.curses_defaults)
        keymap = utils.curses_defaults['keymap']
        keymap.update(self.config['keymap'])
        self.keymap_str = self.get_keymap_str(keymap)
        self.keymapping = self.map_key_to_func(keymap)

        palette = []
        for k, color in self.config['palette'].items():
            palette.append( (k, color[0], color[1]) )

        # Prepare header
        sys.stdout.write("\x1b]0;Trackma-curses "+utils.VERSION+"\x07");
        self.header_title = urwid.Text('Trackma-curses ' + utils.VERSION)
        self.header_api = urwid.Text('API:')
        self.header_filter = urwid.Text('Filter:')
        self.header_sort = urwid.Text('Sort:title')
        self.header_order = urwid.Text('Order:d')
        self.header = urwid.AttrMap(urwid.Columns([
            self.header_title,
            ('fixed', 30, self.header_filter),
            ('fixed', 17, self.header_sort),
            ('fixed', 16, self.header_api)]), 'status')

        top_pile = [self.header]

        if self.config['show_help']:
            top_text = "{help}:Help  {sort}:Sort  " + \
                       "{update}:Update  {play}:Play  " + \
                       "{status}:Status  {score}:Score  " + \
                       "{quit}:Quit"
            top_text = top_text.format(**self.keymap_str)
            top_pile.append(urwid.AttrMap(urwid.Text(top_text), 'status'))

        self.top_pile = urwid.Pile(top_pile)

        # Prepare status bar
        self.status_text = urwid.Text('Trackma-curses '+utils.VERSION)
        self.status_queue = urwid.Text('Q:N/A')
        self.status_tracker = urwid.Text('T:N/A')
        self.statusbar = urwid.AttrMap(urwid.Columns([
            self.status_text,
            ('fixed', 10, self.status_tracker),
            ('fixed', 6, self.status_queue),
            ]), 'status')

        self.listheader = urwid.AttrMap(
            urwid.Columns([
                ('weight', 1, urwid.Text('Title')),
                ('fixed', 10, urwid.Text('Progress')),
                ('fixed', 7, urwid.Text('Score')),
            ]), 'header')

        self.listwalker = ShowWalker([])
        self.listbox = urwid.ListBox(self.listwalker)
        self.listframe = urwid.Frame(self.listbox, header=self.listheader)

        self.viewing_info = False

        self.view = urwid.Frame(self.listframe, header=self.top_pile, footer=self.statusbar)
        self.mainloop = urwid.MainLoop(self.view, palette, unhandled_input=self.keystroke, screen=urwid.raw_display.Screen())
Example #10
0
    def start(self):
        """
        Starts the engine.
        This function should be called before doing anything with the engine,
        as it initializes the data handler.
        """
        if self.loaded:
            raise utils.TrackmaError("Already loaded.")

        # Start the data handler
        try:
            (self.api_info, self.mediainfo) = self.data_handler.start()
        except utils.DataError as e:
            raise utils.DataFatal(str(e))
        except utils.APIError as e:
            raise utils.APIFatal(str(e))

        # Load redirection file if any
        anime_relations_file = utils.try_files([
            utils.to_config_path('anime-relations.txt'),
            utils.DATADIR + '/anime-relations/anime-relations.txt',
        ])

        if anime_relations_file:
            from trackma.extras import redirections

            api = self.api_info['shortname']
            mediatype = self.data_handler.userconfig['mediatype']

            self.msg.info(self.name, "Parsing redirection file (anime-relations.txt)...")
            try:
                self.redirections = redirections.parse_anime_relations(anime_relations_file, api, mediatype)
            except Exception as e:
                self.msg.warn(self.name, "Error parsing anime-relations.txt!")
                self.msg.debug(self.name, "{}".format(e))

        # Rescan library if necessary
        if self.config['library_autoscan']:
            try:
                self.scan_library()
            except utils.TrackmaError as e:
                self.msg.warn(self.name, "Can't auto-scan library: {}".format(e))

        # Load hook files
        if self.config['use_hooks']:
            hooks_dir = utils.to_config_path('hooks')
            if os.path.isdir(hooks_dir):
                import pkgutil

                self.msg.info(self.name, "Importing user hooks...")
                for loader, name, ispkg in pkgutil.iter_modules([hooks_dir]):
                    # List all the hook files in the hooks folder, import them
                    # and call the init() function if they have them
                    # We build the list "hooks available" with the loaded modules
                    # for later calls.
                    try:
                        self.msg.debug(self.name, "Importing hook {}...".format(name))
                        module = loader.find_module(name).load_module(name)
                        if hasattr(module, 'init'):
                            module.init(self)
                        self.hooks_available.append(module)
                    except ImportError:
                        self.msg.warn(self.name, "Error importing hook {}.".format(name))

        # Start tracker
        if self.mediainfo.get('can_play') and self.config['tracker_enabled']:
            self.msg.debug(self.name, "Initializing tracker...")
            try:
                TrackerClass = self._get_tracker_class(self.config['tracker_type'])

                self.tracker = TrackerClass(self.msg,
                                            self._get_tracker_list(),
                                            self.config,
                                            self.searchdirs,
                                            self.redirections,
                                           )
                self.tracker.connect_signal('detected', self._tracker_detected)
                self.tracker.connect_signal('removed', self._tracker_removed)
                self.tracker.connect_signal('playing', self._tracker_playing)
                self.tracker.connect_signal('update', self._tracker_update)
                self.tracker.connect_signal('unrecognised', self._tracker_unrecognised)
                self.tracker.connect_signal('state', self._tracker_state)
            except ImportError:
                self.msg.warn(self.name, "Couldn't import specified tracker: {}".format(self.config['tracker_type']))

        self.loaded = True
        return True
Example #11
0
 def __init__(self):
     utils.make_dir(utils.to_config_path())
     self.filename = utils.to_config_path('accounts.dict')
     self._load()
Example #12
0
 def __init__(self):
     utils.make_dir(utils.to_config_path())
     self.filename = utils.to_config_path('accounts.dict')
     self._load()
Example #13
0
    def __init__(self):
        """Creates main widgets and creates mainloop"""
        self.config = utils.parse_config(utils.to_config_path('ui-curses.json'), utils.curses_defaults)
        keymap = utils.curses_defaults['keymap']
        keymap.update(self.config['keymap'])
        self.keymap_str = self.get_keymap_str(keymap)
        self.keymapping = self.map_key_to_func(keymap)

        palette = []
        for k, color in self.config['palette'].items():
            palette.append( (k, color[0], color[1]) )

        # Prepare header
        sys.stdout.write("\x1b]0;Trackma-curses "+utils.VERSION+"\x07");
        self.header_title = urwid.Text('Trackma-curses ' + utils.VERSION)
        self.header_api = urwid.Text('API:')
        self.header_filter = urwid.Text('Filter:')
        self.header_sort = urwid.Text('Sort:title')
        self.header_order = urwid.Text('Order:d')
        self.header = urwid.AttrMap(urwid.Columns([
            self.header_title,
            ('fixed', 30, self.header_filter),
            ('fixed', 17, self.header_sort),
            ('fixed', 16, self.header_api)]), 'status')

        top_pile = [self.header]

        if self.config['show_help']:
            top_text = "{help}:Help  {sort}:Sort  " + \
                       "{update}:Update  {play}:Play  " + \
                       "{status}:Status  {score}:Score  " + \
                       "{quit}:Quit"
            top_text = top_text.format(**self.keymap_str)
            top_pile.append(urwid.AttrMap(urwid.Text(top_text), 'status'))

        self.top_pile = urwid.Pile(top_pile)

        # Prepare status bar
        self.status_text = urwid.Text('Trackma-curses '+utils.VERSION)
        self.status_queue = urwid.Text('Q:N/A')
        self.status_tracker = urwid.Text('T:N/A')
        self.statusbar = urwid.AttrMap(urwid.Columns([
            self.status_text,
            ('fixed', 10, self.status_tracker),
            ('fixed', 6, self.status_queue),
            ]), 'status')

        self.listheader = urwid.AttrMap(
            urwid.Columns([
                ('weight', 1, urwid.Text('Title')),
                ('fixed', 10, urwid.Text('Progress')),
                ('fixed', 7, urwid.Text('Score')),
            ]), 'header')

        self.listwalker = ShowWalker([])
        self.listbox = urwid.ListBox(self.listwalker)
        self.listframe = urwid.Frame(self.listbox, header=self.listheader)

        self.viewing_info = False

        self.view = urwid.Frame(self.listframe, header=self.top_pile, footer=self.statusbar)
        self.mainloop = urwid.MainLoop(self.view, palette, unhandled_input=self.keystroke, screen=urwid.raw_display.Screen())
Example #14
0
    manager.set_default(1)
else:
    account_exists = False
    for num, account in manager.get_accounts():
        if account["username"] == username and account["api"] == api:
            account_exists = True
            if account["password"] != password:
                print("Account password mismatch, updating...")
                manager.edit_account(num, username, password, api)
            if manager.get_default() != manager.get_account(num):
                print("Setting account as default")
                manager.set_default(num)
            break
    if not account_exists:
        print ("Could not find account, adding account...")
        manager.add_account(username, password, api)
        manager.set_default(len(manager.get_accounts()))

config_path = utils.to_config_path('config.json')

try:
    config = utils.parse_config(config_path, utils.config_defaults)
except IOError:
    raise utils.EngineFatal("Couldn't open config file.")

for key, value in config.items():
    config[key] = env(key.upper(), cast=type(value), default=value)

utils.save_config(config, config_path)