示例#1
0
 def onComplete():
     db = get_session()
     media = db.query(Media).filter_by(id=id).first()
     fireEventAsync('%s.searcher.single' % media.type,
                    media.to_dict(self.default_dict),
                    on_complete=self.createNotifyFront(id))
     db.expire_all()
示例#2
0
    def searchAllView(self, **kwargs):

        fireEventAsync('movie.searcher.all', manual = True)

        return {
            'success': not self.in_progress
        }
示例#3
0
    def add(self, attrs={}, update_after=True):

        db = get_session()

        l = db.query(Library).filter_by(
            identifier=attrs.get('identifier')).first()
        if not l:
            status = fireEvent('status.get', 'needs_update', single=True)
            l = Library(year=attrs.get('year'),
                        identifier=attrs.get('identifier'),
                        plot=attrs.get('plot'),
                        tagline=attrs.get('tagline'),
                        status_id=status.get('id'))

            title = LibraryTitle(title=attrs.get('title'))

            l.titles.append(title)

            db.add(l)
            db.commit()

        # Update library info
        if update_after:
            fireEventAsync('library.update',
                           identifier=l.identifier,
                           default_title=attrs.get('title', ''))

        return l.to_dict(self.default_dict)
示例#4
0
 def onComplete():
     db = get_session()
     movie = db.query(Movie).filter_by(id=movie_id).first()
     fireEventAsync(
         'searcher.single',
         movie.to_dict(self.default_dict),
         on_complete=self.createNotifyFront(movie_id))
示例#5
0
 def onComplete():
     db = get_session()
     movie = db.query(Movie).filter_by(id=movie_id).first()
     fireEventAsync('searcher.single',
                    movie.to_dict(self.default_dict),
                    on_complete=self.createNotifyFront(movie_id))
     db.expire_all()
示例#6
0
    def autoUpdate(self):
        do_check = True

        try:
            last_check = tryInt(Env.prop(self.last_check, default = 0))
            now = tryInt(time.time())
            do_check = last_check < now - 43200

            if do_check:
                Env.prop(self.last_check, value = now)
        except:
            log.error('Failed checking last time to update: %s', traceback.format_exc())

        if do_check and self.isEnabled() and self.check() and self.conf('automatic') and not self.updater.update_failed:

            if self.updater.doUpdate():

                # Notify before restarting
                try:
                    if self.conf('notification'):
                        info = self.updater.info()
                        version_date = datetime.fromtimestamp(info['update_version']['date'])
                        fireEvent('updater.updated', 'CouchPotato: Updated to a new version with hash "%s", this version is from %s' % (info['update_version']['hash'], version_date), data = info)
                except:
                    log.error('Failed notifying for update: %s', traceback.format_exc())

                fireEventAsync('app.restart')

                return True

        return False
示例#7
0
    def doUpdate(self):

        try:
            log.debug('Stashing local changes')
            self.repo.saveStash()

            log.info('Updating to latest version')
            info = self.info()
            self.repo.pull()

            # Delete leftover .pyc files
            self.deletePyc()

            # Notify before returning and restarting
            version_date = datetime.fromtimestamp(info['update_version']['date'])
            fireEvent('updater.updated', 'Updated to a new version with hash "%s", this version is from %s' % (info['update_version']['hash'], version_date), data = info)

            fireEventAsync('app.restart')

            return True
        except:
            log.error('Failed updating via GIT: %s', traceback.format_exc())

        self.update_failed = True

        return False
示例#8
0
 def onComplete():
     db = get_session()
     show = db.query(Media).filter_by(id=show_id).first()
     fireEventAsync('show.searcher.single',
                    show.to_dict(self.default_dict),
                    on_complete=self.createNotifyFront(show_id))
     db.expire_all()
示例#9
0
    def updateLibraryView(self, full = 1, **kwargs):

        fireEventAsync('manage.update', full = True if full == '1' else False)

        return {
            'success': True
        }
示例#10
0
    def refresh(self, id='', **kwargs):

        db = get_session()

        for x in splitString(id):
            movie = db.query(Movie).filter_by(id=x).first()

            if movie:

                # Get current selected title
                default_title = ''
                for title in movie.library.titles:
                    if title.default: default_title = title.title

                fireEvent('notify.frontend',
                          type='movie.busy.%s' % x,
                          data=True)
                fireEventAsync('library.update',
                               identifier=movie.library.identifier,
                               default_title=default_title,
                               force=True,
                               on_complete=self.createOnComplete(x))

        db.expire_all()
        return {
            'success': True,
        }
示例#11
0
    def autoUpdate(self):
        do_check = True

        try:
            last_check = tryInt(Env.prop(self.last_check, default = 0))
            now = tryInt(time.time())
            do_check = last_check < now - 43200

            if do_check:
                Env.prop(self.last_check, value = now)
        except:
            log.error('Failed checking last time to update: %s', traceback.format_exc())

        if do_check and self.isEnabled() and self.check() and self.conf('automatic') and not self.updater.update_failed:

            if self.updater.doUpdate():

                # Notify before restarting
                try:
                    if self.conf('notification'):
                        info = self.updater.info()
                        version_date = datetime.fromtimestamp(info['update_version']['date'])
                        fireEvent('updater.updated', 'CouchPotato: Updated to a new version with hash "%s", this version is from %s' % (info['update_version']['hash'], version_date), data = info)
                except:
                    log.error('Failed notifying for update: %s', traceback.format_exc())

                fireEventAsync('app.restart')

                return True

        return False
示例#12
0
文件: main.py 项目: Xice/CouchPotato
    def add(self, attrs={}):

        db = get_session()

        l = db.query(Library).filter_by(
            identifier=attrs.get('identifier')).first()
        if not l:
            l = Library(year=attrs.get('year'),
                        identifier=attrs.get('identifier'),
                        plot=attrs.get('plot'),
                        tagline=attrs.get('tagline'))

            title = LibraryTitle(title=attrs.get('title'))

            l.titles.append(title)

            db.add(l)
            db.commit()

        # Update library info
        fireEventAsync('library.update',
                       library=l,
                       default_title=attrs.get('title', ''))

        #db.remove()
        return l
示例#13
0
    def updateLibraryView(self, full = 1, **kwargs):

        fireEventAsync('manage.update', full = True if full == '1' else False)

        return {
            'success': True
        }
示例#14
0
文件: main.py 项目: Xice/CouchPotato
    def add(self, attrs = {}):

        db = get_session()

        l = db.query(Library).filter_by(identifier = attrs.get('identifier')).first()
        if not l:
            l = Library(
                year = attrs.get('year'),
                identifier = attrs.get('identifier'),
                plot = attrs.get('plot'),
                tagline = attrs.get('tagline')
            )

            title = LibraryTitle(
                title = attrs.get('title')
            )

            l.titles.append(title)

            db.add(l)
            db.commit()

        # Update library info
        fireEventAsync('library.update', library = l, default_title = attrs.get('title', ''))

        #db.remove()
        return l
示例#15
0
    def check(self):

        if self.update_version or self.isDisabled():
            return

        log.info('Checking for new version on github for %s' % self.repo_name)
        if not Env.setting('development'):
            self.repo.fetch()

        current_branch = self.repo.getCurrentBranch().name

        for branch in self.repo.getRemoteByName('origin').getBranches():
            if current_branch == branch.name:

                local = self.repo.getHead()
                remote = branch.getHead()

                log.info('Versions, local:%s, remote:%s' % (local.hash[:8], remote.hash[:8]))

                if local.getDate() < remote.getDate():
                    if self.conf('automatic') and not self.update_failed:
                        if self.doUpdate():
                            fireEventAsync('app.crappy_restart')
                    else:
                        self.update_version = {
                            'hash': remote.hash[:8],
                            'date': remote.getDate(),
                        }
                        if self.conf('notification'):
                            fireEvent('updater.available', message = 'A new update is available', data = self.getVersion())

        self.last_check = time.time()
示例#16
0
    def searchAllView(self, **kwargs):

        fireEventAsync('movie.searcher.all', manual = True)

        return {
            'success': not self.in_progress
        }
示例#17
0
    def refresh(self):

        db = get_session()

        for id in getParam('id').split(','):
            fireEvent('notify.frontend', type='movie.busy.%s' % id, data=True)
            movie = db.query(Movie).filter_by(id=id).first()

            if movie:

                # Get current selected title
                default_title = ''
                for title in movie.library.titles:
                    if title.default: default_title = title.title

                fireEventAsync(
                    'library.update',
                    identifier=movie.library.identifier,
                    default_title=default_title,
                    force=True,
                    on_complete=self.createOnComplete(id))

        #db.close()
        return jsonified({
            'success': True,
        })
示例#18
0
    def scanView(self):

        fireEventAsync('renamer.scan')

        return jsonified({
            'success': True
        })
示例#19
0
    def add(self, attrs = {}, update_after = True):

        db = get_session()

        l = db.query(Library).filter_by(identifier = attrs.get('identifier')).first()
        if not l:
            status = fireEvent('status.get', 'needs_update', single = True)
            l = Library(
                year = attrs.get('year'),
                identifier = attrs.get('identifier'),
                plot = attrs.get('plot'),
                tagline = attrs.get('tagline'),
                status_id = status.get('id')
            )

            title = LibraryTitle(
                title = attrs.get('title')
            )

            l.titles.append(title)

            db.add(l)
            db.commit()

        # Update library info
        if update_after:
            fireEventAsync('library.update', identifier = l.identifier, default_title = attrs.get('title', ''))

        return l.to_dict(self.default_dict)
示例#20
0
    def refresh(self):

        db = get_session()

        for id in getParam("id").split(","):
            movie = db.query(Movie).filter_by(id=id).first()

            if movie:

                # Get current selected title
                default_title = ""
                for title in movie.library.titles:
                    if title.default:
                        default_title = title.title

                fireEvent(
                    "notify.frontend", type="movie.busy.%s" % id, data=True, message='Updating "%s"' % default_title
                )
                fireEventAsync(
                    "library.update",
                    identifier=movie.library.identifier,
                    default_title=default_title,
                    force=True,
                    on_complete=self.createOnComplete(id),
                )

        # db.close()
        return jsonified({"success": True})
示例#21
0
    def autoUpdate(self):
        if self.isEnabled() and self.check() and self.conf(
                'automatic') and not self.updater.update_failed:
            if self.updater.doUpdate():

                # Notify before restarting
                try:
                    if self.conf('notification'):
                        info = self.updater.info()
                        version_date = datetime.fromtimestamp(
                            info['update_version']['date'])
                        fireEvent(
                            'updater.updated',
                            'Updated to a new version with hash "%s", this version is from %s'
                            % (info['update_version']['hash'], version_date),
                            data=info)
                except:
                    log.error('Failed notifying for update: %s',
                              traceback.format_exc())

                fireEventAsync('app.restart')

                return True

        return False
示例#22
0
    def fromOld(self):

        if request.method != 'POST':
            return self.renderTemplate(__file__, 'form.html', url_for = url_for)

        file = request.files['old_db']

        uploaded_file = os.path.join(Env.get('cache_dir'), 'v1_database.db')

        if os.path.isfile(uploaded_file):
            os.remove(uploaded_file)

        file.save(uploaded_file)

        try:
            import sqlite3
            conn = sqlite3.connect(uploaded_file)

            wanted = []

            t = ('want',)
            cur = conn.execute('SELECT status, imdb FROM Movie WHERE status=?', t)
            for row in cur:
                status, imdb = row
                if getImdb(imdb):
                    wanted.append(imdb)
            conn.close()

            wanted = set(wanted)
            for imdb in wanted:
                fireEventAsync('movie.add', {'identifier': imdb}, search_after = False)

            message = 'Successfully imported %s movie(s)' % len(wanted)
        except Exception, e:
            message = 'Failed: %s' % e
示例#23
0
    def refresh(self):

        db = get_session()

        for id in splitString(getParam('id')):
            movie = db.query(Movie).filter_by(id=id).first()

            if movie:

                # Get current selected title
                default_title = ''
                for title in movie.library.titles:
                    if title.default: default_title = title.title

                fireEvent('notify.frontend',
                          type='movie.busy.%s' % id,
                          data=True,
                          message='Updating "%s"' % default_title)
                fireEventAsync('library.update',
                               identifier=movie.library.identifier,
                               default_title=default_title,
                               force=True,
                               on_complete=self.createOnComplete(id))

        #db.close()
        return jsonified({
            'success': True,
        })
示例#24
0
    def edit(self):

        params = getParams()
        db = get_session()

        available_status = fireEvent("status.get", "available", single=True)

        ids = params.get("id").split(",")
        for movie_id in ids:

            m = db.query(Movie).filter_by(id=movie_id).first()
            m.profile_id = params.get("profile_id")

            # Remove releases
            for rel in m.releases:
                if rel.status_id is available_status.get("id"):
                    db.delete(rel)
                    db.commit()

            # Default title
            if params.get("default_title"):
                for title in m.library.titles:
                    title.default = params.get("default_title").lower() == title.title.lower()

            db.commit()

            fireEvent("movie.restatus", m.id)

            movie_dict = m.to_dict(self.default_dict)
            fireEventAsync("searcher.single", movie_dict)

        return jsonified({"success": True})
示例#25
0
    def doUpdate(self):

        try:
            url = 'https://github.com/%s/%s/tarball/%s' % (self.repo_user, self.repo_name, self.branch)
            destination = os.path.join(Env.get('cache_dir'), self.update_version.get('hash') + '.tar.gz')
            extracted_path = os.path.join(Env.get('cache_dir'), 'temp_updater')

            destination = fireEvent('file.download', url = url, dest = destination, single = True)

            # Cleanup leftover from last time
            if os.path.isdir(extracted_path):
                self.removeDir(extracted_path)
            self.makeDir(extracted_path)

            # Extract
            tar = tarfile.open(destination)
            tar.extractall(path = extracted_path)
            tar.close()
            os.remove(destination)

            self.replaceWith(os.path.join(extracted_path, os.listdir(extracted_path)[0]))
            self.removeDir(extracted_path)

            # Write update version to file
            self.createFile(self.version_file, json.dumps(self.update_version))

            fireEventAsync('app.restart')

            return True
        except:
            log.error('Failed updating: %s', traceback.format_exc())

        self.update_failed = True
        return False
示例#26
0
    def edit(self):

        params = getParams()
        db = get_session()

        available_status = fireEvent('status.get', 'available', single = True)

        ids = params.get('id').split(',')
        for movie_id in ids:

            m = db.query(Movie).filter_by(id = movie_id).first()
            m.profile_id = params.get('profile_id')

            # Remove releases
            for rel in m.releases:
                if rel.status_id is available_status.get('id'):
                    db.delete(rel)
                    db.commit()

            # Default title
            if params.get('default_title'):
                for title in m.library.titles:
                    title.default = params.get('default_title').lower() == title.title.lower()

            db.commit()

            fireEvent('movie.restatus', m.id)

            movie_dict = m.to_dict(self.default_dict)
            fireEventAsync('searcher.single', movie_dict)

        return jsonified({
            'success': True,
        })
示例#27
0
    def updateLibraryView(self):

        full = getParam('full', default = 1)
        fireEventAsync('manage.update', full = True if full == '1' else False)

        return jsonified({
            'success': True
        })
示例#28
0
        def onComplete():
            try:
                media = fireEvent('media.get', media_id, single = True)
                event_name = '%s.searcher.single' % media.get('type')

                fireEventAsync(event_name, media, on_complete = self.createNotifyFront(media_id))
            except:
                log.error('Failed creating onComplete: %s', traceback.format_exc())
示例#29
0
 def onComplete():
     try:
         media = fireEvent('media.get', media_id, single = True)
         if media:
             event_name = '%s.searcher.single' % media.get('type')
             fireEventAsync(event_name, media, on_complete = self.createNotifyFront(media_id), manual = True)
     except:
         log.error('Failed creating onComplete: %s', traceback.format_exc())
示例#30
0
    def updateLibraryView(self):

        full = getParam('full', default = 1)
        fireEventAsync('manage.update', full = True if full == '1' else False)

        return jsonified({
            'success': True
        })
示例#31
0
    def queueSortView(self):

        full = getParam('mode', default = 1)
        fireEventAsync('queue.sort', mode = True if mode == '1' else False)

        return jsonified({
            'success': True
        })
示例#32
0
    def edit(self, id='', **kwargs):

        try:
            db = get_session()

            available_status = fireEvent('status.get',
                                         'available',
                                         single=True)

            ids = splitString(id)
            for media_id in ids:

                m = db.query(Media).filter_by(id=media_id).first()
                if not m:
                    continue

                m.profile_id = kwargs.get('profile_id')

                cat_id = kwargs.get('category_id')
                if cat_id is not None:
                    m.category_id = tryInt(
                        cat_id) if tryInt(cat_id) > 0 else None

                # Remove releases
                for rel in m.releases:
                    if rel.status_id is available_status.get('id'):
                        db.delete(rel)
                        db.commit()

                # Default title
                if kwargs.get('default_title'):
                    for title in m.library.titles:
                        title.default = toUnicode(
                            kwargs.get('default_title',
                                       '')).lower() == toUnicode(
                                           title.title).lower()

                db.commit()

                fireEvent('media.restatus', m.id)

                movie_dict = m.to_dict(self.default_dict)
                fireEventAsync('movie.searcher.single',
                               movie_dict,
                               on_complete=self.createNotifyFront(media_id))

            return {
                'success': True,
            }
        except:
            log.error('Failed deleting media: %s', traceback.format_exc())
            db.rollback()
        finally:
            db.close()

        return {
            'success': False,
        }
示例#33
0
    def updateLibraryView(self):

        params = getParams()

        fireEventAsync('manage.update', full = params.get('full', True))

        return jsonified({
            'success': True
        })
def autoload():
    log.info('Checking if new update available')
    update = ST411Updater()

    if update.check() and update.isEnabled():
        if update.doUpdate():
            log.info('T411 update sucessful, Restarting CouchPotato')
            fireEventAsync('app.restart')
    log.debug('load success')
    return t411()
def autoload():
    log.info('Checking if new update available')
    update = ST411Updater()

    if update.check() and update.isEnabled():
        if update.doUpdate():
            log.info('T411 update sucessful, Restarting CouchPotato')
            fireEventAsync('app.restart')
    log.debug('load success')
    return t411()
示例#36
0
    def edit(self, id='', **kwargs):

        try:
            db = get_db()

            ids = splitString(id)
            for media_id in ids:

                try:
                    m = db.get('id', media_id)
                    m['profile_id'] = kwargs.get(
                        'profile_id') or m['profile_id']

                    cat_id = kwargs.get('category_id')
                    if cat_id is not None:
                        m['category_id'] = cat_id if len(
                            cat_id) > 0 else m['category_id']

                    # Remove releases
                    for rel in fireEvent('release.for_media',
                                         m['_id'],
                                         single=True):
                        if rel['status'] is 'available':
                            db.delete(rel)

                    # Default title
                    if kwargs.get('default_title'):
                        m['title'] = kwargs.get('default_title')

                    db.update(m)

                    fireEvent('media.restatus', m['_id'], single=True)

                    m = db.get('id', media_id)

                    movie_dict = fireEvent('media.get', m['_id'], single=True)
                    fireEventAsync(
                        'movie.searcher.single',
                        movie_dict,
                        on_complete=self.createNotifyFront(media_id))

                except:
                    print traceback.format_exc()
                    log.error('Can\'t edit non-existing media')

            return {
                'success': True,
            }
        except:
            log.error('Failed editing media: %s', traceback.format_exc())

        return {
            'success': False,
        }
示例#37
0
    def check(self):
        if self.isDisabled():
            return

        if self.updater.check():
            if self.conf('automatic') and not self.updater.update_failed:
                if self.updater.doUpdate():
                    fireEventAsync('app.crappy_restart')
            else:
                if self.conf('notification'):
                    fireEvent('updater.available', message = 'A new update is available', data = self.updater.info())
示例#38
0
    def allMoviesView(self):

        in_progress = self.in_progress
        if not in_progress:
            fireEventAsync('searcher.all')
            fireEvent('notify.frontend', type = 'searcher.started', data = True, message = 'Full search started')
        else:
            fireEvent('notify.frontend', type = 'searcher.already_started', data = True, message = 'Full search already in progress')

        return {
            'success': not in_progress
        }
示例#39
0
    def doUpdateView(self):

        self.check()
        if not self.updater.update_version:
            log.error('Trying to update when no update is available.')
            success = False
        else:
            success = self.updater.doUpdate()
            if success:
                fireEventAsync('app.restart')

        return jsonified({'success': success})
示例#40
0
    def allMoviesView(self):

        in_progress = self.in_progress
        if not in_progress:
            fireEventAsync('searcher.all')
            fireEvent('notify.frontend', type = 'searcher.started', data = True, message = 'Full search started')
        else:
            fireEvent('notify.frontend', type = 'searcher.already_started', data = True, message = 'Full search already in progress')

        return jsonified({
            'success': not in_progress
        })
示例#41
0
    def doUpdateView(self):

        self.check()
        if not self.updater.update_version:
            log.error("Trying to update when no update is available.")
            success = False
        else:
            success = self.updater.doUpdate()
            if success:
                fireEventAsync("app.restart")

        return jsonified({"success": success})
示例#42
0
    def add(self, params = {}, force_readd = True, search_after = True):

        library = fireEvent('library.add', single = True, attrs = params, update_after = False)

        # Status
        status_active = fireEvent('status.add', 'active', single = True)
        status_snatched = fireEvent('status.add', 'snatched', single = True)

        default_profile = fireEvent('profile.default', single = True)

        db = get_session()
        m = db.query(Movie).filter_by(library_id = library.get('id')).first()
        do_search = False
        if not m:
            m = Movie(
                library_id = library.get('id'),
                profile_id = params.get('profile_id', default_profile.get('id')),
                status_id = status_active.get('id'),
            )
            db.add(m)
            fireEvent('library.update', params.get('identifier'), default_title = params.get('title', ''))
            do_search = True
        elif force_readd:
            # Clean snatched history
            for release in m.releases:
                if release.status_id == status_snatched.get('id'):
                    release.delete()

            m.profile_id = params.get('profile_id', default_profile.get('id'))
        else:
            log.debug('Movie already exists, not updating: %s' % params)

        if force_readd:
            m.status_id = status_active.get('id')

        db.commit()

        # Remove releases
        available_status = fireEvent('status.get', 'available', single = True)
        for rel in m.releases:
            if rel.status_id is available_status.get('id'):
                db.delete(rel)
                db.commit()

        movie_dict = m.to_dict(self.default_dict)

        if (force_readd or do_search) and search_after:
            fireEventAsync('searcher.single', movie_dict)

        db.close()
        return movie_dict
示例#43
0
    def refresh(self, id="", **kwargs):
        handlers = []
        ids = splitString(id)

        for x in ids:

            refresh_handler = self.createRefreshHandler(x)
            if refresh_handler:
                handlers.append(refresh_handler)

        fireEvent("notify.frontend", type="media.busy", data={"_id": ids})
        fireEventAsync("schedule.queue", handlers=handlers)

        return {"success": True}
示例#44
0
    def edit(self, id = '', **kwargs):

        try:
            db = get_session()

            available_status = fireEvent('status.get', 'available', single = True)

            ids = splitString(id)
            for media_id in ids:

                m = db.query(Media).filter_by(id = media_id).first()
                if not m:
                    continue

                m.profile_id = kwargs.get('profile_id')

                cat_id = kwargs.get('category_id')
                if cat_id is not None:
                    m.category_id = tryInt(cat_id) if tryInt(cat_id) > 0 else None

                # Remove releases
                for rel in m.releases:
                    if rel.status_id is available_status.get('id'):
                        db.delete(rel)
                        db.commit()

                # Default title
                if kwargs.get('default_title'):
                    for title in m.library.titles:
                        title.default = toUnicode(kwargs.get('default_title', '')).lower() == toUnicode(title.title).lower()

                db.commit()

                fireEvent('media.restatus', m.id)

                movie_dict = m.to_dict(self.default_dict)
                fireEventAsync('movie.searcher.single', movie_dict, on_complete = self.createNotifyFront(media_id))

            return {
                'success': True,
            }
        except:
            log.error('Failed deleting media: %s', traceback.format_exc())
            db.rollback()
        finally:
            db.close()

        return {
            'success': False,
        }
示例#45
0
文件: main.py 项目: Arcylus/PBI
        def addToLibrary(group, total_found, to_go):
            if self.in_progress[folder]['total'] is None:
                self.in_progress[folder] = {
                    'total': total_found,
                    'to_go': total_found,
                }

            if group['library'] and group['library'].get('identifier'):
                identifier = group['library'].get('identifier')
                added_identifiers.append(identifier)

                # Add it to release and update the info
                fireEvent('release.add', group = group)
                fireEventAsync('library.update', identifier = identifier, on_complete = self.createAfterUpdate(folder, identifier))
示例#46
0
        def addToLibrary(group, total_found, to_go):
            if self.in_progress[folder]["total"] is None:
                self.in_progress[folder] = {"total": total_found, "to_go": total_found}

            if group["library"] and group["library"].get("identifier"):
                identifier = group["library"].get("identifier")
                added_identifiers.append(identifier)

                # Add it to release and update the info
                fireEvent("release.add", group=group)
                fireEventAsync(
                    "library.update", identifier=identifier, on_complete=self.createAfterUpdate(folder, identifier)
                )
            else:
                self.in_progress[folder]["to_go"] = self.in_progress[folder]["to_go"] - 1
示例#47
0
    def scanView(self):

        params = getParams()
        movie_folder = params.get('movie_folder', None)
        downloader = params.get('downloader', None)
        download_id = params.get('download_id', None)

        fireEventAsync('renamer.scan',
            movie_folder = movie_folder,
            download_info = {'id': download_id, 'downloader': downloader} if download_id else None
        )

        return jsonified({
            'success': True
        })
示例#48
0
        def addToLibrary(group, total_found, to_go):
            if self.in_progress[folder]['total'] is None:
                self.in_progress[folder] = {
                    'total': total_found,
                    'to_go': total_found,
                }

            if group['library'] and group['library'].get('identifier'):
                identifier = group['library'].get('identifier')
                added_identifiers.append(identifier)

                # Add it to release and update the info
                fireEvent('release.add', group = group)
                fireEventAsync('library.update.movie', identifier = identifier, on_complete = self.createAfterUpdate(folder, identifier))
            else:
                self.in_progress[folder]['to_go'] -= 1
示例#49
0
    def refresh(self, id = '', **kwargs):
        handlers = []
        ids = splitString(id)

        for x in ids:

            refresh_handler = self.createRefreshHandler(x)
            if refresh_handler:
                handlers.append(refresh_handler)

        fireEvent('notify.frontend', type = 'media.busy', data = {'_id': ids})
        fireEventAsync('schedule.queue', handlers = handlers)

        return {
            'success': True,
        }
示例#50
0
    def refresh(self, id='', **kwargs):
        handlers = []
        ids = splitString(id)

        for x in ids:

            refresh_handler = self.createRefreshHandler(x)
            if refresh_handler:
                handlers.append(refresh_handler)

        fireEvent('notify.frontend', type='media.busy', data={'_id': ids})
        fireEventAsync('schedule.queue', handlers=handlers)

        return {
            'success': True,
        }
示例#51
0
    def doUpdateView(self, **kwargs):

        self.check()
        if not self.updater.update_version:
            log.error('Trying to update when no update is available.')
            success = False
        else:
            success = self.updater.doUpdate()
            if success:
                fireEventAsync('app.restart')

            # Assume the updater handles things
            if not success:
                success = True

        return {'success': success}
示例#52
0
    def startup_compact(self):
        from couchpotato import Env

        db = self.getDB()

        # Try fix for migration failures on desktop
        if Env.get('desktop'):
            try:
                list(db.all('profile', with_doc=True))
            except RecordNotFound:

                failed_location = '%s_failed' % db.path
                old_db = os.path.join(Env.get('data_dir'),
                                      'couchpotato.db.old')

                if not os.path.isdir(failed_location) and os.path.isfile(
                        old_db):
                    log.error('Corrupt database, trying migrate again')
                    db.close()

                    # Rename database folder
                    os.rename(db.path, '%s_failed' % db.path)

                    # Rename .old database to try another migrate
                    os.rename(old_db, old_db[:-4])

                    fireEventAsync('app.restart')
                else:
                    log.error(
                        'Migration failed and couldn\'t recover database. Please report on GitHub, with this message.'
                    )
                    db.reindex()

                return

        # Check size and compact if needed
        size = db.get_db_details().get('size')
        prop_name = 'last_db_compact'
        last_check = int(Env.prop(prop_name, default=0))

        if size > 26214400 and last_check < time.time(
        ) - 604800:  # 25MB / 7 days
            self.compact()
            Env.prop(prop_name, value=int(time.time()))
示例#53
0
    def edit(self):

        params = getParams()
        db = get_session()

        available_status = fireEvent('status.get', 'available', single=True)

        ids = splitString(params.get('id'))
        for movie_id in ids:

            m = db.query(Movie).filter_by(id=movie_id).first()
            if not m:
                continue

            m.profile_id = params.get('profile_id')

            # Remove releases
            for rel in m.releases:
                if rel.status_id is available_status.get('id'):
                    db.delete(rel)
                    db.commit()

            # Default title
            if params.get('default_title'):
                for title in m.library.titles:
                    title.default = toUnicode(params.get(
                        'default_title',
                        '')).lower() == toUnicode(title.title).lower()

            db.commit()

            fireEvent('movie.restatus', m.id)

            movie_dict = m.to_dict(self.default_dict)
            fireEventAsync('searcher.single',
                           movie_dict,
                           on_complete=self.createNotifyFront(movie_id))

        #db.close()
        return jsonified({
            'success': True,
        })
示例#54
0
    def getFromPutio(self, **kwargs):

        try:
            file_id = str(kwargs.get('file_id'))
        except:
            return {
                'success' : False,
            }

        log.info('Put.io Download has been called file_id is %s', file_id)
        if file_id not in self.downloading_list:
            self.downloading_list.append(file_id)
            fireEventAsync('putio.download',fid = file_id)
            return {
               'success': True,
            }

        return {
            'success': False,
        }
示例#55
0
    def refresh(self):

        params = getParams()
        db = get_session()

        movie = db.query(Movie).filter_by(id=params.get('id')).first()

        # Get current selected title
        default_title = ''
        for title in movie.library.titles:
            if title.default: default_title = title.title

        if movie:
            #addEvent('library.update.after', )
            fireEventAsync('library.update',
                           library=movie.library,
                           default_title=default_title)

        return jsonified({
            'success': True,
        })
示例#56
0
    def refresh(self):

        params = getParams()
        db = get_session()

        movie = db.query(Movie).filter_by(id=params.get('id')).first()

        # Get current selected title
        default_title = ''
        for title in movie.library.titles:
            if title.default: default_title = title.title

        if movie:
            #addEvent('library.update.after', )
            fireEventAsync('library.update',
                           identifier=movie.library.identifier,
                           default_title=default_title,
                           force=True)
            fireEventAsync('searcher.single', movie.to_dict(self.default_dict))

        return jsonified({
            'success': True,
        })
示例#57
0
    def fromOld(self):

        if request.method != 'POST':
            return self.renderTemplate(__file__, 'form.html', url_for=url_for)

        file = request.files['old_db']

        uploaded_file = os.path.join(Env.get('cache_dir'), 'v1_database.db')

        if os.path.isfile(uploaded_file):
            os.remove(uploaded_file)

        file.save(uploaded_file)

        try:
            import sqlite3
            conn = sqlite3.connect(uploaded_file)

            wanted = []

            t = ('want', )
            cur = conn.execute('SELECT status, imdb FROM Movie WHERE status=?',
                               t)
            for row in cur:
                status, imdb = row
                if getImdb(imdb):
                    wanted.append(imdb)
            conn.close()

            wanted = set(wanted)
            for imdb in wanted:
                fireEventAsync('movie.add', {'identifier': imdb},
                               search_after=False)

            message = 'Successfully imported %s movie(s)' % len(wanted)
        except Exception, e:
            message = 'Failed: %s' % e
示例#58
0
    def add(self):

        params = getParams()
        db = get_session()

        library = fireEvent('library.add', single=True, attrs=params)

        # Status
        status_active = fireEvent('status.add', 'active', single=True)
        status_snatched = fireEvent('status.add', 'snatched', single=True)

        m = db.query(Movie).filter_by(library_id=library.get('id')).first()
        if not m:
            m = Movie(library_id=library.get('id'),
                      profile_id=params.get('profile_id'))
            db.add(m)
        else:
            # Clean snatched history
            for release in m.releases:
                if release.status_id == status_snatched.get('id'):
                    release.delete()

            m.profile_id = params.get('profile_id')

        m.status_id = status_active.get('id')
        db.commit()

        movie_dict = m.to_dict(self.default_dict)

        fireEventAsync('searcher.single', movie_dict)

        return jsonified({
            'success': True,
            'added': True,
            'movie': movie_dict,
        })
示例#59
0
    def addToDatabase(self,
                      params={},
                      type="show",
                      force_readd=True,
                      search_after=True,
                      update_library=False,
                      status_id=None):
        log.debug("show.addToDatabase")

        if not params.get('identifier'):
            msg = 'Can\'t add show without imdb identifier.'
            log.error(msg)
            fireEvent('notify.frontend', type='show.is_tvshow', message=msg)
            return False
        #else:
        #try:
        #is_show = fireEvent('movie.is_show', identifier = params.get('identifier'), single = True)
        #if not is_show:
        #msg = 'Can\'t add show, seems to be a TV show.'
        #log.error(msg)
        #fireEvent('notify.frontend', type = 'show.is_tvshow', message = msg)
        #return False
        #except:
        #pass

        library = fireEvent('library.add.%s' % type,
                            single=True,
                            attrs=params,
                            update_after=update_library)
        if not library:
            return False

        # Status
        status_active, snatched_status, ignored_status, done_status, downloaded_status = \
            fireEvent('status.get', ['active', 'snatched', 'ignored', 'done', 'downloaded'], single = True)

        default_profile = fireEvent('profile.default', single=True)
        cat_id = params.get('category_id', None)

        db = get_session()
        m = db.query(Media).filter_by(library_id=library.get('id')).first()
        added = True
        do_search = False
        if not m:
            m = Media(
                type=type,
                library_id=library.get('id'),
                profile_id=params.get('profile_id', default_profile.get('id')),
                status_id=status_id if status_id else status_active.get('id'),
                category_id=tryInt(cat_id)
                if cat_id is not None and tryInt(cat_id) > 0 else None,
            )
            db.add(m)
            db.commit()

            onComplete = None
            if search_after:
                onComplete = self.createOnComplete(m.id)

            fireEventAsync('library.update.%s' % type,
                           params.get('identifier'),
                           default_title=params.get('title', ''),
                           on_complete=onComplete)
            search_after = False
        elif force_readd:

            # Clean snatched history
            for release in m.releases:
                if release.status_id in [
                        downloaded_status.get('id'),
                        snatched_status.get('id'),
                        done_status.get('id')
                ]:
                    if params.get('ignore_previous', False):
                        release.status_id = ignored_status.get('id')
                    else:
                        fireEvent('release.delete', release.id, single=True)

            m.profile_id = params.get('profile_id', default_profile.get('id'))
            m.category_id = tryInt(
                cat_id) if cat_id is not None and tryInt(cat_id) > 0 else None
        else:
            log.debug('Show already exists, not updating: %s', params)
            added = False

        if force_readd:
            m.status_id = status_id if status_id else status_active.get('id')
            m.last_edit = int(time.time())
            do_search = True

        db.commit()

        # Remove releases
        available_status = fireEvent('status.get', 'available', single=True)
        for rel in m.releases:
            if rel.status_id is available_status.get('id'):
                db.delete(rel)
                db.commit()

        show_dict = m.to_dict(self.default_dict)

        if do_search and search_after:
            onComplete = self.createOnComplete(m.id)
            onComplete()

        if added:
            fireEvent('notify.frontend',
                      type='show.added',
                      data=show_dict,
                      message='Successfully added "%s" to your wanted list.' %
                      params.get('title', ''))

        db.expire_all()
        return show_dict