Beispiel #1
0
    def set_item(self, item=None):
        self.up_next = False
        # self.item = item
        if not self.win.getProperty('SC.play_item'):
            return
        item_data = loads(self.win.getProperty('SC.play_item'))
        self.win.clearProperty('SC.play_item')
        self.item = item_data.get('info')
        debug('ITEM: {}'.format(self.item.get('info', {}).get('unique_ids')))
        linfo = item_data.get('strms').get('linfo')
        ids = self.win.getProperty('{}.ids'.format(ADDON_ID))
        self.win.clearProperty('{}.ids'.format(ADDON_ID))
        self.ids = loads(ids) if ids else {}
        self.my_id = self.ids.get('sc') if self.ids.get('sc') else None
        debug('my ids: {}'.format(self.ids))
        if self.my_id is not None:
            self.win.setProperty('{}.play'.format(ADDON_ID), '1')
            debug('je to moj plugin')
            self.is_my_plugin = True
            series = self.item['info'].get('season')
            episode = self.item['info'].get('episode')
            self.movie = SCKODIItem(self.my_id,
                                    series=series,
                                    episode=episode,
                                    trakt=self.ids.get('trakt'))
            self.movie.scrobble(self.percent_played(),
                                SCKODIItem.SCROBBLE_START)
            audio = self.getAvailableAudioStreams()
            if len(audio) == 1:
                debug('Nemame na vyber, mame len jednu audio stopu')
                return

            if linfo:
                audio = linfo
            debug('AvailableAudioStreams {}'.format(len(audio)))
            lang1 = settings.get_setting('stream.lang1').lower()
            lang2 = settings.get_setting('stream.lang2').lower()
            if Sc.parental_control_is_active():
                lang1 = settings.get_setting('parental.control.lang1').lower()
                lang2 = settings.get_setting('parental.control.lang2').lower()

            plf = Storage(SC.ITEM_PREFERRED_LANG)
            plf.load(True)
            debug('PREF LANGS: {} / {}'.format(self.my_id, plf.data))
            force_lang = plf.get(self.my_id)
            force = False
            if force_lang is not None:
                lang = force_lang.lower()
                debug('mame force lang {}'.format(force_lang))
                force = self.try_audio(lang, audio)

            if force is False and self.try_audio(lang1, audio) is False:
                self.try_audio(lang2, audio)
    def system_after(self):
        data = self.response.get(SC.ITEM_SYSTEM, {})
        if 'setContent' in data:  # and settings.get_setting_bool('gui.views.enabled'):
            xbmcplugin.setContent(params.handle, data['setContent'])
            # view_mode = data["setContent"].lower()
            # view_code = settings.get_setting_int('gui.views.{0}'.format(view_mode))
            # if view_code > 0:
            #     xbmc.executebuiltin("Container.SetViewMode(%d)" % view_code)

        if 'SetSortMethod' in data:
            #method = SORT_METHODS[int(data.get('SetSortMethod'))]
            #xbmc.executebuiltin('Container.SetSortMethod(%d)' % method)
            pass

        if SC.ITEM_FOCUS in data:
            try:
                control = cur_win.getControl(cur_win.getFocusId())
                control.selectItem(int(data[SC.ITEM_FOCUS]))
            except:
                pass

        check_last_key = '{}.last_series'.format(ADDON_ID)
        if 'checkLast' in data and get_setting_as_bool(
                'stream.autoplay.episode'):
            check_last = data['checkLast']
            stop = home_win.getProperty('{}.stop'.format(ADDON_ID))
            debug('Mame check last data: {} / {}'.format(stop, check_last))
            item_id = int(check_last.get('id', 0))
            ki = SCKODIItem(int(item_id))
            last_ep = ki.get_last_ep()
            if item_id > 0 and last_ep:
                win_last_series = home_win.getProperty(check_last_key)
                home_win.setProperty(check_last_key, str(item_id))
                debug('last {} cur {}'.format(win_last_series, item_id))
                if win_last_series == '' or win_last_series != str(item_id):
                    debug('last ep: {}'.format(last_ep))
                    try:
                        data = Sc.up_next(item_id, last_ep[0], last_ep[1])
                        d = SCUpNext(data)
                        debug('NEXT EP: {}'.format(d.get().get('play_info')))
                        cmd = 'PlayMedia({})'.format(
                            create_plugin_url(d.get().get('play_info')))
                        if stop is None or stop == '':
                            debug('play: {}'.format(cmd))
                            exec_build_in(cmd)
                    except:
                        debug('chyba: {}'.format(traceback.format_exc()))
                        pass
        else:
            home_win.clearProperty(check_last_key)
        # upraceme po sebe
        home_win.clearProperty('{}.stop'.format(ADDON_ID))
    def sync_local_episodes(self, last=0, force=False):
        last_at = TraktAPI.utc2timestamp(last)
        dialog = dprogressgb()
        dialog.create('sync_local_episodes Trakt.TVShow')
        debug('sync local episodes {} / {}'.format(last, last_at))
        if force:
            data = self.get_shows_watched({})
        else:
            data = self.get_shows_history(datetime.utcfromtimestamp(last_at))
        if data == []:
            dialog.close()
            return True
        items = {}
        for trid, num, eps in data:
            if self.abortRequested():
                dialog.close()
                return False
            items.update({trid: eps})
        res, items = self.trakt2sc(items, 3)
        pos = 0
        total = len(res)
        for scid, trid in res.items():
            if self.abortRequested():
                dialog.close()
                return False
            pos += 1
            max_time = 0
            last_ep = None
            debug('episodes: {}%'.format(int(pos / total * 100)))
            dialog.update(int(pos / total * 100))
            item = SCKODIItem(scid)
            debug('ITEM: {}'.format(item.data))
            for s, e, watched_at in items[int(trid['trakt'])]:
                item.series = s
                item.episode = e
                if self.abortRequested():
                    dialog.close()
                    return False
                wa = TraktAPI.utc2timestamp(watched_at)

                if int(wa) >= int(max_time):
                    ''' ak su epizody vsetky oznacene ako videne v rovnaky cas alebo novsie '''
                    max_time = wa
                    last_ep = (s, e)

                old = item.get_play_count()
                if force or old is None or last_at is None or wa >= last_at:
                    debug('SCID ADD {} {}x{}'.format(scid, s, e))
                    item.set_play_count('1')

            if item and last_ep is not None:
                item.set_last_ep(last_ep[0], last_ep[1], max_time)
        dialog.close()
        return True
    def update_items(self):
        query = 'select item_key, item_value from storage where item_key like ? and item_value like ?'
        search = '{}-%'.format(SCKODIItem.ITEM_NAME)
        # debug('search: {}'.format(search))
        res = self.list._db.execute(query, search, '%"last_ep"%').fetchall()
        total = len(res)
        skip_list = self.get()
        debug('NEXTEP: {} z {} ({})'.format(len(skip_list), total, total - len(skip_list)))
        dialog = dprogressgb()
        dialog.create('Next Ep in progress')
        pos = 0
        for i in res:
            if monitor.abortRequested() or player.isPlayback():
                dialog.close()
                return False
            pos += 1
            _, item_id = i[0].split('-')
            if item_id in skip_list:
                debug('ITEM {} uz ma nextep, nepotrebujeme update'.format(item_id))
                continue
            item = SCKODIItem(item_id)
            last_ep = item.get_last_ep()
            debug('Next Ep in progress: {}%'.format(int(pos / total * 100)))
            dialog.update(int(pos / total * 100), message='{} - {}x{}'.format(item_id, last_ep[0], last_ep[1]))
            try:
                debug('last {}x{}'.format(last_ep[0], last_ep[1]))
                info = Sc.up_next(item_id, last_ep[0], last_ep[1])
                if 'error' in info or ('info' in info and info.get('info') is None):
                    debug('nemame data k next EP')
                    continue
                new = {
                    's': last_ep[0],
                    'e': last_ep[1],
                    't': int(time()),
                }
                cur = self.list.get(item_id)
                if cur is None or (cur and str(cur.get('e')) != str(new.get('e'))):
                    debug('nextep update {} -> {}'.format(item_id, last_ep))
                    self.list[item_id] = new
                else:
                    debug('nezmenene {} -> {}'.format(item_id, last_ep))
            except:
                debug('mazem serial zo zoznamu {}'.format(item_id))
                del(self.list[item_id])
                pass

        dialog.close()
        debug('LIST NEXT EP: {}'.format(self.list._data))
        return True
    def _set_info(self, item_info):
        if self.debug:
            debug('set_info {}'.format(item_info))
        self.info.update(item_info)
        try:
            if SC.ITEM_TITLE in item_info:
                title = '{}'.format(item_info.get(SC.ITEM_TITLE))
                self.item.setLabel(title)

            if self.data.get('play'):
                if 'otitle' in item_info:
                    item_info.update({SC.ITEM_TITLE: item_info['otitle']})
                    del item_info['otitle']

                if 'epname' in item_info:
                    item_info.update({SC.ITEM_TITLE: item_info['epname']})
                    del item_info['epname']
            else:
                if 'epname' in item_info:
                    del item_info['epname']

                if 'otitle' in item_info:
                    del item_info['otitle']

            for i, e in enumerate(item_info):
                # debug('set info {} {}'.format(i, e))
                self.item.setProperty(e, '{}'.format(item_info[e]))

            if item_info.get('mediatype',
                             '') == 'season' and item_info.get('episode'):
                item = SCKODIItem(self.data.get(SC.ITEM_ID))
                data = item.data
                total_episodes = item_info.get('episode')
                watched = len(
                    data.get('series:{}'.format(item_info.get('season')), {}))
                debug('Mame seriu {} s {}/{} epizodami'.format(
                    item_info.get('season'), watched, total_episodes))
                if watched >= total_episodes:
                    item_info.update({'playcount': '1'})

            self.item.setInfo('video', item_info)
            self.item.setProperty('original_title',
                                  item_info.get('originaltitle'))
            self.info_set = True
        except Exception as e:
            import traceback
            info(
                '-----------------------------------------------------------------'
            )
            info('set info error [{}]'.format(str(traceback.format_exc())))
            info(
                '-----------------------------------------------------------------'
            )
    def __init__(self, data):
        trakt = data['unique_ids'][
            'trakt'] if 'unique_ids' in data and 'trakt' in data[
                'unique_ids'] else None
        self.movie = SCKODIItem(data.get(SC.ITEM_ID),
                                series=data.get('info', {}).get('season'),
                                episode=data.get('info', {}).get('episode'),
                                trakt=trakt)
        internal_info = {}
        play_count = self.movie.get_play_count()
        if play_count is not None and int(play_count) > 0:
            internal_info.update({'playcount': play_count})
        last_played = self.movie.get_last_played()
        if last_played:
            internal_info.update({'lastplayed': last_played})
        if internal_info != {}:
            # debug('update info: {}'.format(internal_info))
            data.get(SC.ITEM_INFO).update(internal_info)

        SCBaseItem.__init__(self, data)
        self.set_properties()
        self.gen_context()
 def sync_local_movies(self, last):
     self.sync_playback_movies(last)
     data = self.get_movies_watched({})
     res, movies = self.sync_get_list(data, 1)
     debug('res: {}'.format(len(res)))
     all_items = self.storage['watched.movies'].get()[:]
     # debug('na zaciatku {}'.format(all_items))
     dialog = dprogressgb()
     dialog.create('sync_local_movies Trakt.Movies 1')
     pos = 0
     max = len(res)
     for scid, trid in res.items():
         if self.monitor.abortRequested():
             return False
         pos += 1
         dialog.update(int(pos / max * 100))
         # debug('SCID: {}'.format(scid))
         # debug('w {}'.format(self.storage['watched.{}'.format(type)]))
         item = SCKODIItem(scid)
         if scid not in all_items:
             debug('pridavam do zoznamu {}'.format(scid))
             self.storage['watched.movies'].add(scid)
             item.set_play_count('1')
         else:
             all_items.remove(scid)
         pass
         # debug('{} -> {}'.format(scid, movies.get(trid)))
     dialog.close()
     dialog.create('sync_local_movies Trakt.Movies 2')
     # debug('Zostali nam po synchre: {}'.format(all_items))
     if len(all_items) > 0:
         max = len(all_items)
         pos = 0
         for scid in all_items:
             if self.monitor.abortRequested():
                 return False
             pos += 1
             dialog.update(int(pos / max * 100))
             # debug('mazem {}'.format(scid))
             self.storage['watched.movies'].add(scid, remove_only=True)
             item = SCKODIItem(scid)
             item.set_play_count(None)
     dialog.close()
     return True
    def sync_playback_movies(self, last=0):
        last_at = TraktAPI.utc2timestamp(last)
        playback = self.get_playback_movies({})
        debug('paused at {}'.format(len(playback)))
        sync = {}
        tr = []
        for m in playback:
            paused_at = TraktAPI.utc2timestamp(m['paused_at'])
            if paused_at is None or last_at is None or paused_at >= last_at:
                sync.update({m['movie']['ids']['trakt']: m})
                tr.append(m['movie']['ids']['trakt'])
        if len(sync):
            res = Sc.post('/Ftrakt2sc', data={'trakt': dumps(tr), 't': 1})
            debug('sync {} / {}     {}'.format(len(sync), len(res), res))
            max = len(res)
            dialog = dprogressgb()
            dialog.create('sync_playback_movies Trakt.Movies')
            for pos, scid in enumerate(res):
                if self.monitor.abortRequested():
                    return

                debug('trakt {}%'.format(int(pos / max * 100)))
                dialog.update(int(pos / max * 100))
                itm = res.get(scid)
                item = SCKODIItem(scid, trakt=itm['trakt'])
                tr = sync.get(int(itm['trakt']))
                progress = float(sync.get(int(itm['trakt']))['progress'])
                try:
                    watched = int(
                        float(itm['duration']) * float(progress / 100))
                except:
                    watched = 0
                debug('itm {} {} {} {} {} {}'.format(scid, itm,
                                                     itm['duration'], watched,
                                                     progress, tr))
                item.set_watched(watched)
                d = datetime.fromtimestamp(
                    self.utc2timestamp(tr.get('paused_at')))
                item.set_last_played(d.strftime('%Y-%m-%d %H:%M:%S'))
            dialog.close()
        pass
class SCVideo(SCBaseItem):
    def __init__(self, data):
        trakt = data['unique_ids'][
            'trakt'] if 'unique_ids' in data and 'trakt' in data[
                'unique_ids'] else None
        self.movie = SCKODIItem(data.get(SC.ITEM_ID),
                                series=data.get('info', {}).get('season'),
                                episode=data.get('info', {}).get('episode'),
                                trakt=trakt)
        internal_info = {}
        play_count = self.movie.get_play_count()
        if play_count is not None and int(play_count) > 0:
            internal_info.update({'playcount': play_count})
        last_played = self.movie.get_last_played()
        if last_played:
            internal_info.update({'lastplayed': last_played})
        if internal_info != {}:
            # debug('update info: {}'.format(internal_info))
            data.get(SC.ITEM_INFO).update(internal_info)

        SCBaseItem.__init__(self, data)
        self.set_properties()
        self.gen_context()

    def get(self):
        if self.info_set is False:
            self._set_info({SC.MEDIA_TYPE: SC.MEDIA_TYPE_VIDEO})
        return self.item.getPath(), self.item, False

    def set_properties(self):
        self.item.setContentLookup(False)
        self.item.setProperty('IsPlayable', 'true')
        item_info = self.data.get(SC.ITEM_INFO, {})
        if 'duration' in item_info:
            duration = item_info.get('duration')
            resume_time = self.movie.get(self._key('watched'))
            if resume_time and 0 < resume_time < duration:
                self.item.setProperty('ResumeTime', '{}'.format(resume_time))
                self.item.setProperty(
                    'PercentPlayed', '{}'.format(
                        (resume_time / duration) * 100))

    def gen_context(self):
        menu = []

        if 'listType' in params.args:
            menu.append([
                Strings.txt(Strings.CONTEXT_REMOVE), 'RunPlugin({})'.format(
                    create_plugin_url({
                        SC.ACTION:
                        SC.ACTION_REMOVE_FROM_LIST,
                        SC.ITEM_ID:
                        self.data.get(SC.ITEM_ID),
                        SC.ITEM_PAGE:
                        get_history_item_name(self.data.get('lid'))
                    }))
            ])

        if get_setting('download.path'):
            menu.append([
                Strings.txt(Strings.CONTEXT_DOWNLOAD), 'RunPlugin({})'.format(
                    create_plugin_url({
                        SC.ACTION:
                        SC.ACTION_DOWNLOAD,
                        SC.ACTION_DOWNLOAD:
                        self.data.get(SC.ITEM_URL),
                    }))
            ])

        menu.append([
            Strings.txt(Strings.CONTEXT_SELECT_STREAM), 'PlayMedia({})'.format(
                create_plugin_url({
                    SC.ACTION_SELECT_STREAM: '1',
                    SC.ITEM_URL: self.data.get(SC.ITEM_URL),
                }))
        ])

        if get_setting_as_bool('stream.autoselect'):
            mediatype = self.data.get(SC.ITEM_INFO, {}).get('mediatype')
            if mediatype == 'tvshow' or mediatype == 'movie':
                item_id = self.data.get(SC.ITEM_ID)
                st = preferred_lang_list
                if st.get(item_id) is not None:
                    menu.append(
                        (Strings.txt(Strings.CONTEXT_DEL_PREF_LANG).format(
                            st[item_id]), 'RunPlugin({})'.format(
                                create_plugin_url({
                                    SC.ITEM_ACTION:
                                    SC.ACTION_DEL_PREFERRED_LANGUAGE,
                                    SC.ITEM_ID:
                                    self.data.get(SC.ITEM_ID)
                                }))))
                else:
                    menu.append((Strings.txt(Strings.CONTEXT_ADD_PREF_LANG),
                                 'RunPlugin({})'.format(
                                     create_plugin_url({
                                         SC.ITEM_ACTION:
                                         SC.ACTION_SET_PREFERRED_LANGUAGE,
                                         SC.ITEM_ID:
                                         self.data.get(SC.ITEM_ID)
                                     }))))

        if self.data.get(SC.ITEM_INFO, {}).get('trailer'):
            menu.append([
                'Trailer', 'PlayMedia({})'.format(
                    self.data.get(SC.ITEM_INFO, {}).get('trailer'))
            ])

        self.item.addContextMenuItems(items=menu)

    def _key(self, name):
        nfo = self.data.get(SC.ITEM_INFO)
        if 'season' in nfo:
            return '{}:{}:{}'.format(name, nfo.get('season'),
                                     nfo.get('episode'))
        return name
Beispiel #10
0
class SCPlayer(Player):
    def __init__(self):
        self.settings = settings
        self.win = home_win
        self.current_time = 0
        self.item = None
        self.is_my_plugin = False
        self.movie = None
        self.my_id = None
        self.total_time = 0
        self.ids = {}
        self.watched = False
        self.up_next = False

    def onPlayBackStarted(self):
        self.onAVStarted()

    def set_item(self, item=None):
        self.up_next = False
        # self.item = item
        if not self.win.getProperty('SC.play_item'):
            return
        item_data = loads(self.win.getProperty('SC.play_item'))
        self.win.clearProperty('SC.play_item')
        self.item = item_data.get('info')
        debug('ITEM: {}'.format(self.item.get('info', {}).get('unique_ids')))
        linfo = item_data.get('strms').get('linfo')
        ids = self.win.getProperty('{}.ids'.format(ADDON_ID))
        self.win.clearProperty('{}.ids'.format(ADDON_ID))
        self.ids = loads(ids) if ids else {}
        self.my_id = self.ids.get('sc') if self.ids.get('sc') else None
        debug('my ids: {}'.format(self.ids))
        if self.my_id is not None:
            self.win.setProperty('{}.play'.format(ADDON_ID), '1')
            debug('je to moj plugin')
            self.is_my_plugin = True
            series = self.item['info'].get('season')
            episode = self.item['info'].get('episode')
            self.movie = SCKODIItem(self.my_id,
                                    series=series,
                                    episode=episode,
                                    trakt=self.ids.get('trakt'))
            self.movie.scrobble(self.percent_played(),
                                SCKODIItem.SCROBBLE_START)
            audio = self.getAvailableAudioStreams()
            if len(audio) == 1:
                debug('Nemame na vyber, mame len jednu audio stopu')
                return

            if linfo:
                audio = linfo
            debug('AvailableAudioStreams {}'.format(len(audio)))
            lang1 = settings.get_setting('stream.lang1').lower()
            lang2 = settings.get_setting('stream.lang2').lower()
            if Sc.parental_control_is_active():
                lang1 = settings.get_setting('parental.control.lang1').lower()
                lang2 = settings.get_setting('parental.control.lang2').lower()

            plf = Storage(SC.ITEM_PREFERRED_LANG)
            plf.load(True)
            debug('PREF LANGS: {} / {}'.format(self.my_id, plf.data))
            force_lang = plf.get(self.my_id)
            force = False
            if force_lang is not None:
                lang = force_lang.lower()
                debug('mame force lang {}'.format(force_lang))
                force = self.try_audio(lang, audio)

            if force is False and self.try_audio(lang1, audio) is False:
                self.try_audio(lang2, audio)

    def try_audio(self, lang, streams):
        if lang == 'sk':
            language_list = ['slo', 'sk', 'slk', 'SK']
        elif lang == 'cz':
            language_list = ['cze', 'cz', 'ces', 'CZ']
        elif lang == 'en':
            language_list = ['eng', 'en', 'EN']
        else:
            debug("iny jazyk {}".format(lang))
            language_list = [lang.lower(), lang.upper()]

        for i in language_list:
            if i in streams:
                debug("mame audio: {} pre jazyk {}".format(i, lang))
                stream_number = streams.index(i)
                self.setAudioStream(stream_number)
                # dnotify(lang, '', time=1000, sound=False)
                return True
        return False

    def onAVStarted(self):
        debug('player onAVStarted')
        for i in range(0, 500):
            if self.isPlayback():
                break
            else:
                debug('not playing')
                sleep(1000)
        self.set_item()

    def onAVChange(self):
        debug('player onAVChange')
        if self.is_my_plugin is True:
            debug('moj plugin')

    def onPlayBackEnded(self):
        debug('player onPlayBackEnded')
        self.end_playback()

    def onPlayBackStopped(self):
        debug('player onPlayBackStopped')
        self.end_playback()

    def onPlayBackError(self):
        debug('player onPlayBackError')
        self.end_playback()

    def onPlayBackPaused(self):
        debug('player onPlayBackPaused')
        self.end_playback()

    def onPlayBackResumed(self):
        debug('player onPlayBackResumed')
        if self.movie is not None:
            self.movie.scrobble(self.percent_played(),
                                SCKODIItem.SCROBBLE_START)

    def onQueueNextItem(self):
        debug('player onQueueNextItem')

    def onPlayBackSpeedChanged(self, speed):
        debug('player onPlayBackSpeedChanged {}'.format(speed))

    def onPlayBackSeek(self, time, seekOffset):
        debug('player onPlayBackSeek {} {}'.format(time, seekOffset))

    def onPlayBackSeekChapter(self, chapter):
        debug('player onPlayBackSeekChapter {}'.format(chapter))

    def clean(self):
        debug('player SCPlayer Clean')
        #
        self.win.clearProperty('{}.play'.format(ADDON_ID))
        self.current_time = 0
        self.ids = {}
        self.is_my_plugin = False
        self.item = None
        self.movie = None
        self.my_id = None
        self.up_next = False
        self.total_time = 0
        self.watched = False

    def end_playback(self):
        self.set_watched()
        self.clean()

    def percent_played(self):
        try:
            return self.current_time / self.total_time * 100
        except:
            return 0

    def set_watched(self):
        if self.is_my_plugin:
            self.win.setProperty('{}.stop'.format(ADDON_ID), '1')
            percent_played = self.percent_played()

            self.movie.scrobble(percent_played, SCKODIItem.SCROBBLE_STOP)

            if percent_played > 80:
                play_count = self.movie.get_play_count()
                play_count = int(
                    play_count) + 1 if play_count is not None else 1
                debug('playcount {}'.format(play_count))
                d = datetime.fromtimestamp(time())
                self.movie.set_play_count(play_count, True)
                self.movie.set_last_played(d.strftime('%Y-%m-%d %H:%M:%S'))
            if 3 < percent_played < 80:
                debug('watched {}'.format(self.current_time))
                self.movie.set_watched(self.current_time)

    def check_up_next(self, percent_played):
        return gcv('System.hasAddon(service.upnext)'
                   ) and self.item and self.item['info'].get(
                       'episode') is not None and self.up_next is False

    def send_up_next(self):
        try:
            series = self.item['info'].get('season')
            episode = self.item['info'].get('episode')
            url = '/upNext/{}/{}/{}'.format(self.my_id, series, episode)
            debug('upnext call {}'.format(url))
            data = Sc.get(url)
            if 'info' in data:
                debug('Mame next item: {}'.format(data))
                d = SCUpNext(data)
                # sleep(3 * 1000)
                upnext_signal(ADDON_ID, d.get())
        except:
            debug('send_up_next ERR {}'.format(traceback.format_exc()))

    def run(self):
        debug('START player bg service')
        m = Monitor()
        while not m.abortRequested():
            sleep(1000)
            try:
                self.periodical_check()
            except:
                debug('player bg service ERR {}'.format(
                    traceback.format_exc()))
        debug('END player bg service')

    def getTime1(self):  # type: () -> float
        try:
            return self.getTime()
        except:
            return 0

    def isPlayingVideo1(self):  # type: () -> bool
        try:
            return self.isPlayingVideo()
        except:
            return False

    def periodical_check(self):
        if not self.isPlayback() or self.is_my_plugin is False:
            return

        self.current_time = self.getTime()
        self.total_time = self.getTotalTime()
        try:
            percent_played = self.current_time / self.total_time * 100
        except:
            percent_played = 0
        # debug('self.watched: {} {}'.format(self.watched, percent_played))
        if percent_played >= 80 and not self.watched:
            self.set_watched()
            self.watched = True
        if self.check_up_next(percent_played):
            debug('Mame upnext nainstalovane')
            try:
                self.send_up_next()
            except:
                pass
            self.up_next = True

    def isPlayback(self):  # type: () -> bool
        return self.isPlaying() and self.isPlayingVideo(
        ) and self.getTime() >= 0