def action_csearch(self):
     self.succeeded = True
     self.end_of_directory()
     _id = self.args.get(SC.ITEM_ID)
     home_win.setProperty('SC.search', '{}'.format(_id))
     search = dinput('', '', xbmcgui.INPUT_TYPE_TEXT)
     home_win.clearProperty('SC.search')
     info('search string: {}'.format(search))
     if search == '':
         exec_build_in('Action(Back)')
         return
     query = {'search': search, SC.ITEM_ID: _id}
     if _id.startswith('search-people'):
         query.update({'ms': '1'})
     st = List(_id)
     st.add(search)
     debug('SEARCH: _ID "{}" search for "{}" people "{}"'.format(
         _id, search, 1 if 'ms' in query else 0))
     url = '/Search/{}?{}'.format(_id, urlencode(query))
     info('search url: {}'.format(url))
     self.url = url
     self.call_url()
     if 'msgERROR' in self.response.get('system', {}):
         self.msg_error()
         exec_build_in('Action(Back)')
         return
     plugin_url = create_plugin_url({'url': url})
     container_update(plugin_url)
     return
    def check_trakt(self, force=False):
        if TraktAPI.can_check() or force:
            home_win.setProperty('check_trakt', '1')
            if self.initialized is False:
                self.initialize()
            # debug('check trakt')
            data = self.get_last_activities()
            if data is None:
                debug('trakt data is NONE')
                self.clean_prop()
                return None

            for check in CHECK_SYNC.items():
                synced = False
                item = data.get(check[0])
                for a, i in enumerate(item):
                    if i in check[1]:
                        key = 'sync.{}'.format(check[0])
                        if self.storage[key].get(i) != item.get(i):
                            debug('zmena {}[{}] z {} na {}'.format(
                                key, i, self.storage[key].get(i), item.get(i)))
                            if not synced:
                                synced = True
                                try:
                                    if self.sync_local(
                                            check[0],
                                            self.storage[key].get(i),
                                            force=force):
                                        self.storage[key].update(
                                            {i: item.get(i)})
                                except:
                                    debug('TRAKT ERR: {}'.format(
                                        traceback.format_exc()))
                                    pass
            self.clean_prop()
    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 play(self):
     try:
         item = SCItem(self.response)
         url, li, status, selected = item.get()
         if SC.ACTION in self.args and SC.ACTION_DOWNLOAD in self.args[
                 SC.ACTION]:
             filename = selected.get('stream_info', {}).get('filename')
             if filename is None:
                 dok(Strings.txt(Strings.RESOLVE_ERROR_H1),
                     Strings.txt(Strings.RESOLVE_ERROR_L1))
                 return
             from threading import Thread
             worker = Thread(target=download,
                             args=(url, get_setting('download.path'),
                                   filename))
             worker.start()
             return
         debug(
             '----------------------------------------------------------------------------------------------------'
         )
         debug('play url: {}'.format(self.url))
         debug('play selected: {}'.format(dumps(selected)))
         # debug('play response: {}'.format(dumps(self.response)))
         # debug('play item: {}'.format(li))
         debug(
             '----------------------------------------------------------------------------------------------------'
         )
         self.response['strms'] = selected
         home_win.setProperty('SC.play_item', dumps(self.response))
         if params.handle == -1:
             debug('HANDLE -1')
             xbmc.Player().play(url, li)
         else:
             debug('HANDLE {}'.format(params.handle))
             self.succeeded = True
             self.cache_to_disc = False
             xbmcplugin.setResolvedUrl(params.handle, True, li)
             self.end_of_directory()
     except:
         # dok('ERROR', 'Chyba pri prehravani')
         info("ERR: {}".format(str(traceback.format_exc())))
         self.end_of_directory()
    def run(self):

        if SC.ITEM_URL in self.args:
            self.url = self.args.get(SC.ITEM_URL)

        if self.url == '/' and xbmc.Player().isPlayingVideo(
        ) and home_win.getProperty('{}.play'.format(ADDON_ID)):
            container_update('special://home', True)
            self.succeeded = False
            self.end_of_directory()
            return

        if SC.ITEM_URL in self.args and self.args.get(
                SC.ITEM_URL).startswith('http'):
            self.args.update({SC.ITEM_ACTION: SC.ACTION_PLAY_URL})

        info('Start: {} [{}]'.format(str(self.args), self.url))

        if 'title' in self.args:
            home_win.setProperty('SCTitle', self.args.get('title'))
        else:
            home_win.clearProperty('SCTitle')

        if SC.ACTION in self.args:
            exit_code = self.action()
            if exit_code is True:
                return
        elif 'play' in self.args:
            '''
            stara URL zo SC CS&SK pre play aby fungovala kniznica
            '''
            self.url = self.args.get('play')
            self.call_url_and_response()
        else:
            self.call_url_and_response()
        self.end()
    def resolve(self):
        data = self.data
        del (data[SC.ITEM_URL])
        self.streams = self.input.get(SC.ITEM_STRMS)
        self.filter()

        items = []
        matrix = []
        for s in self.streams:
            debug('ideme vytvorit listItems zo streamov')
            s.update(data)
            itm = SCStreamSelect(s)
            x = itm.get()
            title_items = [
                '[B]{}[/B] - '.format(s.get(SC.ITEM_LANG)),
                '[B]{}[/B] '.format(s.get(SC.ITEM_QUALITY)),
                '{} '.format(s.get(SC.ITEM_SIZE)),
                '{}{}'.format(s.get(SC.ITEM_VIDEO_INFO),
                              s.get(SC.ITEM_AUDIO_INFO)),
            ]
            matrix.append(title_items)
            items.append(x[1])
        # matrix = make_table(matrix)
        # info('matrix: {}'.format(matrix))
        for i, itm in enumerate(items):
            itm.setProperty('old_title', itm.getLabel())
            itm.setLabel(' '.join(matrix[i]))

        if len(
                items
        ) > 1 or SC.ACTION_SELECT_STREAM in self.params or SC.ACTION_DOWNLOAD in self.params:
            pos = dselect(items,
                          heading=items[0].getProperty('old_title'),
                          use_details=True)
            # info('post: {} | {}'.format(pos, json.dumps(self.data)))
            if pos is False or pos == -1:
                raise BaseException
            res = items[pos]
            self.selected = self.streams[pos]
        elif len(items) == 1:
            res = items[0]
            self.selected = self.streams[
                0] if self.selected is None else self.selected
        else:
            raise BaseException

        url = res.getPath()
        # info('vybrany stream: {} / {}'.format(res.getPath(), self.selected))
        if res.getProperty(SC.ITEM_PROVIDER) == SC.PROVIDER:
            resp = Sc.get(res.getPath())
            kr = Kraska()
            try:
                ident = resp.get(SC.ITEM_IDENT)
                debug('ideme resolvovat ident {} na kra.sk'.format(ident))
                url = kr.resolve(ident)
            except ResolveException as e:
                dok(Strings.txt(Strings.RESOLVE_ERROR_H1),
                    Strings.txt(Strings.RESOLVE_ERROR_L1))
                raise BaseException
            except:
                raise BaseException
            if res.getProperty(SC.ITEM_SUBS):
                debug('subor ma titulky, tak ich natahujem')
                part = res.getProperty(SC.ITEM_SUBS).split('/file/')
                self.item.setSubtitles([kr.resolve(part[1])])
            else:
                info('nemame titulky')

        info('resolve: {}'.format(url))
        if 'lid' in data:
            lid = 'p-{}'.format(
                data.get('lid')) if parental_history() else data.get('lid')
            st = List(lid, max_items=20)
            st.add(res.getProperty(SC.ITEM_ID))
        self.item.setPath(url)
        self.item.setLabel(res.getProperty('original_title'))
        # home_win.setProperty('SC-lite-item', '{}'.format(res.getProperty(SC.ITEM_ID)))

        if 'unique_ids' in self.input.get(SC.ITEM_INFO):
            unique_ids = self.input.get(SC.ITEM_INFO).get('unique_ids')
            home_win.setProperty('script.trakt.ids',
                                 '{}'.format(dumps(unique_ids)))
            home_win.setProperty('{}.ids'.format(ADDON_ID),
                                 '{}'.format(dumps(unique_ids)))