예제 #1
0
파일: content.py 프로젝트: m1ngr/archivczsk
 def updateAddonGUI(self):
     image = None
     title = author = version = description = ""
     item = self.getSelectedItem()
     if item is not None:
         title = item.name and toString(item.name) or ""
         imagePath = item.image and toString(item.image) or ""
         if imagePath:
             try:
                 image = LoadPixmap(path=imagePath, cached=False)
             except Exception as e:
                 print '[ArchivCZSKContent] error when loading image', e
         try:  # addon
             author = item.author and toString(item.author) or ""
             version = item.version and toString(item.version) or ""
             description = item.description and toString(item.description) or ""
         except AttributeError:  # category
             pass
     self["title"].setText(title.strip())
     if author:
         self["author"].setText(_("Author: ") + author.strip())
     else:
         self["author"].setText("")
     if version:
         self["version"].setText(_("Version: ") + version.strip())
     else:
         self["version"].setText("")
     self["about"].setText(description.strip())
     self["image"].instance.setPixmap(image)
예제 #2
0
 def updateAddonGUI(self):
     image = None
     title = author = version = description = ""
     item = self.getSelectedItem()
     if item is not None:
         title = item.name and toString(item.name) or ""
         imagePath = item.image and toString(item.image) or ""
         if imagePath:
             try:
                 image = LoadPixmap(path=imagePath, cached=False)
             except Exception as e:
                 print '[ArchivCZSKContent] error when loading image', e
         try:  # addon
             author = item.author and toString(item.author) or ""
             version = item.version and toString(item.version) or ""
             description = item.description and toString(
                 item.description) or ""
         except AttributeError:  # category
             pass
     self["title"].setText(title.strip())
     if author:
         self["author"].setText(_("Author: ") + author.strip())
     else:
         self["author"].setText("")
     if version:
         self["version"].setText(_("Version: ") + version.strip())
     else:
         self["version"].setText("")
     self["about"].setText(description.strip())
     self["image"].instance.setPixmap(image)
예제 #3
0
 def create_xml_item(self, item):
     log.debug("{0} create xml item - {1}".format(self, toString(item)))
     if item.id:
         log.debug(
             '{0} create xml item - {1} already exists, skipping'.format(
                 self, toString(item)))
         return
     item_id = item.get_id()
     if self.find_item_by_id(item_id):
         log.debug(
             '{0} create xml item - {1} already exists, skipping'.format(
                 self, toString(item)))
         return
     addon_id = item.addon_id
     xml_item = SubElement(self.xml_root_element.find('items'), 'item')
     xml_item.set('id', toUnicode(item_id))
     xml_item.set('ctime', str(datetime.now()))
     if addon_id:
         xml_item.set('addon_id', toUnicode(addon_id))
     name = SubElement(xml_item, 'name')
     name.text = toUnicode(item.name)
     params = SubElement(xml_item, 'params')
     for key, value in item.params.iteritems():
         params.set(toUnicode(key), toUnicode(value))
     item.id = item_id
     return xml_item
예제 #4
0
 def remove_item(self, item):
     xml_items = self.xml_root_element.find('items')
     xml_item = self.find_item_by_id(item.id)
     if xml_item is None:
         log.debug('{0} remove_item - {1} not found'.format(self, toString(item)))
     else:
         xml_items.remove(xml_item)
         log.debug('{0} remove_item - {1} successfully removed'.format(self, toString(item)))
     item.id = None
예제 #5
0
def getListInput(session, list, title=""):
    def getListInputCB(selected=None):
        if selected is not None:
            d.callback(newlist.index(selected))
        else:
            d.callback(-1)
    d = defer.Deferred()
    newlist = [(toString(name), ) for name in list]
    session.openWithCallback(getListInputCB, ChoiceBox, toString(title), newlist, skin_name="ArchivCZSKChoiceBox")
    return d
예제 #6
0
파일: client.py 프로젝트: Luky68/archivczsk
def getListInput(session, list, title=""):
    def getListInputCB(selected=None):
        if selected is not None:
            d.callback(newlist.index(selected))
        else:
            d.callback(-1)
    d = defer.Deferred()
    newlist = [(toString(name), ) for name in list]
    session.openWithCallback(getListInputCB, ChoiceBox, toString(title), newlist, skin_name="ArchivCZSKChoiceBox")
    return d
예제 #7
0
    def play_stream(self,
                    play_url,
                    play_settings=None,
                    subtitles_url=None,
                    title=None,
                    wholeItem=None):
        log.info("play_stream(%s, %s, %s, %s)" %
                 (play_url, play_settings, subtitles_url, title))
        log.logDebug("play_stream(%s, %s, %s, %s)" %
                     (play_url, play_settings, subtitles_url, title))
        if play_url.startswith("rtmp"):
            rtmp_timeout = int(self.settings.rtmpTimeout.value)
            rtmp_buffer = int(self.settings.rtmpBuffer.value)
            if ' timeout=' not in play_url:
                play_url = "%s timeout=%d" % (play_url, rtmp_timeout)
            if ' buffer=' not in play_url:
                play_url = "%s buffer=%d" % (play_url, rtmp_buffer)
        headers = {}
        if play_settings.get("user-agent"):
            headers["User-Agent"] = play_settings["user-agent"]
        if play_settings.get("extra-headers"):
            headers.update(play_settings["extra-headers"])
        if headers:
            play_url += "#" + "&".join("%s=%s" % (k, v)
                                       for k, v in headers.iteritems())

        service_ref = eServiceReference(play_settings.get("stype", 4097), 0,
                                        toString(play_url))

        if self.video_player is None:
            self.video_player = self.session.openWithCallback(
                self.player_exit_callback, ArchivCZSKMoviePlayer,
                self.player_callback)

        # set infobar text
        titleSet = False
        if wholeItem is not None:
            try:
                if 'title' in wholeItem.info:
                    service_ref.setName(toString(wholeItem.info["title"]))
                    self.video_player.setInfoBarText(
                        toString(wholeItem.info["title"]))
                    titleSet = True
            except:
                log.logError("Set title from item failed (set default).\n%s" %
                             traceback.format_exc())

        if not titleSet:
            service_ref.setName(toString(title))
            self.video_player.setInfoBarText(toString(title))

        self.video_player.play_service_ref(
            service_ref, self._play_item.subs,
            play_settings.get("resume_time_sec"))
예제 #8
0
 def remove_item(self, item):
     xml_items = self.xml_root_element.find('items')
     xml_item = self.find_item_by_id(item.id)
     if xml_item is None:
         log.debug('{0} remove_item - {1} not found'.format(
             self, toString(item)))
     else:
         xml_items.remove(xml_item)
         log.debug('{0} remove_item - {1} successfully removed'.format(
             self, toString(item)))
     item.id = None
예제 #9
0
def showWarningMessage(session, message, timeout=3, cb=None):
    if cb is not None:
        session.openWithCallback(cb,
                                 MessageBox,
                                 text=toString(message),
                                 timeout=timeout,
                                 type=MessageBox.TYPE_WARNING)
    else:
        session.open(MessageBox,
                     text=toString(message),
                     timeout=timeout,
                     type=MessageBox.TYPE_WARNING)
예제 #10
0
def showErrorMessage(session, message, timeout=3, cb=None):
    if cb is not None:
        session.openWithCallback(cb,
                                 MessageBox,
                                 text=toString(message),
                                 timeout=timeout,
                                 type=MessageBox.TYPE_ERROR)
    else:
        session.open(MessageBox,
                     text=toString(message),
                     timeout=timeout,
                     type=MessageBox.TYPE_ERROR)
예제 #11
0
    def createDownload(self, name, url, destination, filename=None, live=False, startCB=None, finishCB=None, stream=None, quiet=False, playDownload=False, headers=None, mode=""):
        log.info("Downloader.createDownload(url=%s,mode=%s"%(toString(url), mode))
        #log.logDebug("Creating download\name=%s\nurl=%s\ndestination=%s\nfilename=%s\nheaders=%s\nmode=%s" % (name, url, destination, filename, headers, mode))
        d = None
        if headers is None:
            headers = {}
        try:
            headers = headers.copy()
        except:
            log.logError("Copy headers for download failed, continute download.\n%s"%traceback.format_exc())
            headers = {}
            pass
        from Plugins.Extensions.archivCZSK.settings import USER_AGENT
        headers.setdefault('User-Agent', USER_AGENT)
        filename, length = getFilenameAndLength(url, headers, filename)
        log.info("Downloader.createDownload() filename=%s, length=%s", toString(filename), length)
        if (((url[0:4] == 'rtmp' and mode in ('auto', 'gstreamer')) or
              (url[0:4] == 'http' and mode  in ('auto', 'gstreamer') and isHLSUrl(url)) or
              (url[0:4] == 'http' and mode in ('auto', 'gstreamer') and playDownload) or
              (url[0:4] == 'http' and mode in ('gstreamer',))) and GST_LAUNCH is not None):
            d = GstDownload(url = url, name = name, destDir = destination, filename=filename, headers=headers)
        elif url[0:4]  == 'rtmp' and mode in ('auto', 'rtmpdump'):
            urlList = url.split()
            rtmp_url = []
            for url in urlList[1:]:
                rtmp = url.split('=', 1)
                rtmp_url.append(' --' + rtmp[0])
                rtmp_url.append("'%s'" % rtmp[1])
            url = "'%s'" % urlList[0] + ' '.join(rtmp_url)
            if not live:
                realtime = True
            else:
                realtime = False
            d = RTMPDownloadE2(url=url, name=name, destDir=destination, 
                    filename=filename, live=live, quiet=quiet, realtime=realtime)
        elif url[0:4] == 'http':
            if isHLSUrl(url):
                raise NotSupportedProtocolError('HLS')
            d = HTTPDownloadE2(name=name, url=url, filename=filename, 
                    destDir=destination, quiet=quiet, headers=headers)
        else:
            protocol = url.split('://')[0].upper()
            log.error('Downloader.createDownload() - not supported protocol %s' % toString(protocol))
            raise NotSupportedProtocolError(protocol)

        if startCB is not None:
            d.onStartCB.append(startCB)
        if finishCB is not None:
            d.onFinishCB.append(finishCB)
        d.status = DownloadStatus(d)
        d.length = length or 0
        return d
예제 #12
0
    def top(self, url):
        result = []
        doc = MarkizaCache().get_data_cached(url, self.useCache, 8)

        for section in doc.findAll('section', 'b-main-section my-sm-5'):
            if toString(section.div.h3.getText(" ")) == 'TOP relácie':
                for article in section.findAll('article'):
                    url = toString(article.a['href'])
                    title = toString(article.a['title'])
                    thumb = toString(article.a.div.img['data-original'])
                    result.append(self.addDir(title, url, 3,thumb))

        return result
예제 #13
0
    def recommended(self, url):
        result = []
        doc = MarkizaCache().get_data_cached(url, self.useCache, 8)

        for section in doc.findAll('section', 'b-main-section b-section-articles b-section-articles-primary my-5'):
            if toString(section.div.h3.getText(" ")) == 'Odporúčame':
                for article in section.findAll('article'):
                    url = toString(article.a['href'])
                    title1 = toString(article.h3.getText(" "))
                    title2 = toString(article.find('span', 'e-text').getText(" "))
                    title = str(title1) + ' - ' + str(title2)
                    thumb = toString(article.a.div.img['data-original'])
                    result.append(self.addDir(title, url, 3, thumb))
        return result
예제 #14
0
    def newEpisodes(self, url):
        result = []
        doc = MarkizaCache().get_data_cached(url, self.useCache, 3)

        for section in doc.findAll('section', 'b-main-section b-section-articles my-5'):
            if toString(section.div.h3.getText(" ")) == 'Najnovšie epizódy':
                for article in section.findAll('article'):
                    url = toString(article.a['href'])
                    title1 = toString(article.h3.getText(" "))
                    title2 = toString(article.find('span', 'e-text').getText(" "))
                    title = str(title1) + ' - ' + str(title2)
                    thumb = toString(article.a.div.img['data-original'])
                    result.append(self.addDir(title, url, 3, thumb))

        return result
예제 #15
0
파일: addon.py 프로젝트: puntik1/archivczsk
    def _remove_addon(self, addon):
        def remove_addon_callback(remove):
            if (remove):
                log.info("removing addon: %s" % addon.id)
                try:
                    shutil.rmtree(addon.path)
                except Exception as e:
                    log.error("cannot remove addon: %s" % str(e))
                    message = ("Unable to remove addon")
                    self.session.open(MessageBox,
                                      message,
                                      type=MessageBox.TYPE_WARNING)

                log.info("addon was removed: %s" % addon.id)

                from Plugins.Extensions.archivCZSK.archivczsk import ArchivCZSK
                ArchivCZSK.remove_addon(addon)
                self.content_screen.workingStarted()
                self.content_screen.refreshList()
                self.content_screen.workingFinished()

        message = _("Do you want to remove") + " " + util.toString(addon.name)
        self.session.openWithCallback(
            remove_addon_callback,
            MessageBox,
            message,
            type=MessageBox.TYPE_YESNO,
        )
예제 #16
0
def PanelListDownloadEntry(name, download):
    res = [(name)]
    res.append(
        MultiContentEntryText(pos=(0, 5),
                              size=(640, 30),
                              font=Font.REGULAR_MEDIUM,
                              flags=RT_HALIGN_LEFT,
                              text=toString(name)))
    if download.state == 'success_finished':
        res.append(
            MultiContentEntryText(pos=(0, 5),
                                  size=(850, 30),
                                  font=Font.REGULAR_MEDIUM,
                                  flags=RT_HALIGN_RIGHT,
                                  text=download.textState,
                                  color=0x00FF00))
    elif download.state == 'error_finished':
        res.append(
            MultiContentEntryText(pos=(0, 5),
                                  size=(850, 30),
                                  font=Font.REGULAR_MEDIUM,
                                  flags=RT_HALIGN_RIGHT,
                                  text=download.textState,
                                  color=0xff0000))
    elif download.state == 'downloading':
        res.append(
            MultiContentEntryText(pos=(0, 5),
                                  size=(850, 30),
                                  font=Font.REGULAR_MEDIUM,
                                  flags=RT_HALIGN_RIGHT,
                                  text=download.textState))
    return res
예제 #17
0
        def ask_if_download():
            filename[0], size_bytes = getFilenameAndLength(item.url, headers, filename[0])
            size_mbytes = size_bytes and util.BtoMB(size_bytes) or "???"
            free_bytes = util.get_free_space(destination[0])
            free_mbytes = free_bytes and util.BtoMB(free_bytes) or "???"

            message = "%s:\n\n%s:\n%s - %sMB\n\n%s:\n%s - %sMB %s\n\n%s:\n%s"%(
                    _("Do you want to download"),
                    _("Source"), toString(item.name), str(size_mbytes),
                    _("Destination"), toString(destination[0]), str(free_mbytes), _("free"),
                    _("Filename"), toString(filename[0]))
            choices = [ (_("yes"), "yes"), (_("no"), "no"), 
                    (_("Change location"), "change"), (_("Edit filename"), "filename") ]

            session.openWithCallback(ask_if_download_callback,
                    MessageBox, message, MessageBox.TYPE_YESNO, list=choices)
예제 #18
0
 def start(self):
     if not os.path.exists(self.destDir):
         os.makedirs(self.destDir)
     self._startCB()
     cmd = toString(self._buildCmd())
     log.info("Download.start \"%s\"" % cmd)
     self.pp.execute(cmd)
예제 #19
0
        def ask_if_download():
            filename[0], size_bytes = getFilenameAndLength(item.url, headers, filename[0])
            size_mbytes = size_bytes and util.BtoMB(size_bytes) or "???"
            free_bytes = util.get_free_space(destination[0])
            free_mbytes = free_bytes and util.BtoMB(free_bytes) or "???"

            message = "%s:\n\n%s:\n%s - %sMB\n\n%s:\n%s - %sMB %s\n\n%s:\n%s"%(
                    _("Do you want to download"),
                    _("Source"), toString(item.name), str(size_mbytes),
                    _("Destination"), toString(destination[0]), str(free_mbytes), _("free"),
                    _("Filename"), toString(filename[0]))
            choices = [ (_("yes"), "yes"), (_("no"), "no"), 
                    (_("Change location"), "change"), (_("Edit filename"), "filename") ]

            session.openWithCallback(ask_if_download_callback,
                    MessageBox, message, MessageBox.TYPE_YESNO, list=choices)
예제 #20
0
def PanelListDownloadEntry_SD(name, download):
    res = [(name)]
    res.append(
        MultiContentEntryText(pos=(0, resize(5)),
                              size=(resize(610), resize(30)),
                              font=Font.REGULAR_MEDIUM,
                              flags=RT_HALIGN_LEFT,
                              text=toString(name)))
    if download.state == 'success_finished':
        res.append(
            MultiContentEntryText(pos=(0, resize(5)),
                                  size=(resize(570), resize(30)),
                                  font=Font.REGULAR_MEDIUM,
                                  flags=RT_HALIGN_RIGHT,
                                  text=_('finished'),
                                  color=0x00FF00))
    elif download.state == 'error_finished':
        res.append(
            MultiContentEntryText(pos=(0, resize(5)),
                                  size=(resize(570), resize(30)),
                                  font=Font.REGULAR_MEDIUM,
                                  flags=RT_HALIGN_RIGHT,
                                  text=_('finished with errors'),
                                  color=0xff0000))
    elif download.state == 'downloading':
        res.append(
            MultiContentEntryText(pos=(0, resize(5)),
                                  size=(resize(570), resize(30)),
                                  font=Font.REGULAR_MEDIUM,
                                  flags=RT_HALIGN_RIGHT,
                                  text=_('downloading')))
    return res
예제 #21
0
 def open_item_success_cb(result):
     self.content_screen.stopLoading()
     self.content_screen.showList()
     list_items, __, __ = result
     self._filter_by_quality(list_items)
     if len(list_items) > 1:
         choices = []
         for i in list_items:
             name = i.name
             # TODO remove workaround of embedding
             # quality in title in addons
             if i.quality and i.quality not in i.name:
                 if "[???]" in i.name:
                     name = i.name.replace("[???]","[%s]"%(i.quality))
                 else:
                     name = "[%s] %s"%(i.quality, i.name)
             choices.append((toString(name), i))
         self.session.openWithCallback(selected_source,
                 ChoiceBox, _("Please select source"),
                 list = choices,
                 skin_name = ["ArchivCZSKVideoSourceSelection"])
     elif len(list_items) == 1:
         item = list_items[0]
         callback(item)
     else: # no video
         self.content_screen.workingFinished()
예제 #22
0
 def start(self):
     if not os.path.exists(self.destDir):
         os.makedirs(self.destDir)
     self._startCB()
     cmd = toString(self._buildCmd())
     log.info("Download.start \"%s\"" % cmd)
     self.pp.execute(cmd)
예제 #23
0
    def create_xml_item(self, item):
        log.logDebug("%s create xml item - %s"%(self,item))
        log.debug("{0} create xml item - {1}".format(self, toString(item)))

        import time
        from datetime import datetime
        t = datetime.now()
        t1 = t.timetuple()
        uid = int(time.mktime(t1))
        if item.id:
            item.id = uid
            #log.logDebug("%s create xml item - %s already exists, skipping"%(self,item))
            #log.debug('{0} create xml item - {1} already exists, skipping'.format(self, toString(item)))
            #return
        item_id = item.get_id()
        if self.find_item_by_id(item_id):
            item_id = uid
            item.id = uid
            #log.logDebug("%s create xml item - %s already exists (2), skipping"%(self,item))
            #log.debug('{0} create xml item - {1} already exists, skipping'.format(self, toString(item)))
            #return
        addon_id = item.addon_id
        xml_item = SubElement(self.xml_root_element.find('items'), 'item')
        xml_item.set('id', toUnicode(item_id))
        xml_item.set('ctime', str(datetime.now()))
        if addon_id:
            xml_item.set('addon_id', toUnicode(addon_id))
        name = SubElement(xml_item, 'name')
        name.text = toUnicode(item.name)
        params = SubElement(xml_item, 'params')
        for key, value in item.params.iteritems():
            params.set(toUnicode(key), toUnicode(value))
        item.id = item_id
        return xml_item
예제 #24
0
 def setInfoBarText(self, title):
     try:
         self.setTitle(toString(title))
     except:
         log.logError("Set info bar text failed.\n%s" %
                      traceback.format_exc())
         pass
예제 #25
0
 def _decode_image(self, path):
     wsize = self.poster_widget.instance.size()
     sc = AVSwitch().getFramebufferScale()
     self.picload.setPara((wsize.width(), wsize.height(), sc[0], sc[1],
                           False, 1, "#ff000000"))
     self.last_decoded_url = None
     return 0 == self.picload.startDecode(util.toString(path))
예제 #26
0
    def create_xml_item(self, item):
        log.logDebug("%s create xml item - %s" % (self, item))
        log.debug("{0} create xml item - {1}".format(self, toString(item)))

        import time
        from datetime import datetime
        t = datetime.now()
        t1 = t.timetuple()
        uid = int(time.mktime(t1))
        if item.id:
            item.id = uid
            #log.logDebug("%s create xml item - %s already exists, skipping"%(self,item))
            #log.debug('{0} create xml item - {1} already exists, skipping'.format(self, toString(item)))
            #return
        item_id = item.get_id()
        if self.find_item_by_id(item_id):
            item_id = uid
            item.id = uid
            #log.logDebug("%s create xml item - %s already exists (2), skipping"%(self,item))
            #log.debug('{0} create xml item - {1} already exists, skipping'.format(self, toString(item)))
            #return
        addon_id = item.addon_id
        xml_item = SubElement(self.xml_root_element.find('items'), 'item')
        xml_item.set('id', toUnicode(item_id))
        xml_item.set('ctime', str(datetime.now()))
        if addon_id:
            xml_item.set('addon_id', toUnicode(addon_id))
        name = SubElement(xml_item, 'name')
        name.text = toUnicode(item.name)
        params = SubElement(xml_item, 'params')
        for key, value in item.params.iteritems():
            params.set(toUnicode(key), toUnicode(value))
        item.id = item_id
        return xml_item
예제 #27
0
    def _resolve_video_items(self, result):
        def all_done(result_list):
            for __, (data, item) in result_list:
                tmp_list = []
                for stream_dict in get_streams_from_manifest(item.url, data):
                    video_item = PVideoResolved()
                    video_item.subs = item.subs
                    video_item.settings = item.settings.copy()
                    video_item.url = stream_dict['url']
                    video_item.quality = "%s b/s" % stream_dict['bandwidth']
                    video_item.bandwidth = int(stream_dict['bandwidth'])
                    if 'resolution' in stream_dict:
                        video_item.quality = stream_dict['resolution'].split(
                            'x')[1] + "p"
                    # TODO remove workaround of embedding
                    # quality in title in addons
                    video_item.name = name = item.name
                    quality = video_item.quality
                    if quality and quality not in name:
                        if "[???]" in name:
                            video_item.name = name.replace(
                                "[???]", "[%s]" % (quality))
                        else:
                            video_item.name = "[%s] %s" % (i.quality, i.name)
                    tmp_list.append(video_item)
                tmp_list.sort(key=operator.attrgetter('bandwidth'),
                              reverse=True)
                if tmp_list:
                    log.info("%s __resolve_video_items: found %d streams" %
                             (self, len(tmp_list)))
                    item_list.remove(item)
                    item_list.extend(tmp_list)
            return result

        def get_result(res, item):
            if isinstance(res, failure.Failure):
                log.error("%s _resolve_video_items: %s - %s" %
                          (self, item.url, res.value))
            else:
                log.debug("%s _resolve_video_items: %s - %dB" %
                          (self, item.url, len(res)))
            return res, item

        item_list, __, __ = result
        video_list = [
            i for i in item_list
            if isinstance(i, PVideoResolved) and is_hls_url(i.url)
        ]
        log.debug("%s _resolve_video_items: found %d resolvable video items" %
                  (self, len(video_list)))
        d_list = []
        for item in video_list:
            d = url_get_data_async(toString(item.url),
                                   headers=item.settings["extra-headers"],
                                   timeout=5)
            d.addBoth(get_result, item)
            d_list.append(d)
        return defer.DeferredList(d_list,
                                  consumeErrors=True).addCallback(all_done)
예제 #28
0
def PanelColorListEntry2(name, value, colorName, colorValue, sizePanelX):
    res = [(name)]
    res.append(
        MultiContentEntryText(pos=(0, 5),
                              size=(sizePanelX, 30),
                              font=Font.REGULAR_MEDIUM,
                              flags=RT_HALIGN_LEFT,
                              text=toString(name),
                              color=colorName))
    res.append(
        MultiContentEntryText(pos=(0, 5),
                              size=(sizePanelX, 30),
                              font=Font.REGULAR_MEDIUM,
                              flags=RT_HALIGN_RIGHT,
                              text=toString(value),
                              color=colorValue))
    return res
예제 #29
0
 def ask_add_shortcut(self, item):
     self.item = item
     self.session.openWithCallback(
         self.add_shortcut_cb,
         MessageBox,
         text="%s %s %s" %
         (_("Do you want to add"), toString(item.name), _("shortcut?")),
         type=MessageBox.TYPE_YESNO)
예제 #30
0
    def episodes(self, url):
        result = []
        doc = MarkizaCache().get_data_cached(url, self.useCache, 1)

        for article in doc.findAll('article', 'b-article b-article-text b-article-inline'):
            url = toString(article.a['href'])
            thumb = toString(article.a.div.img['data-original'])
            title1 = toString(article.a['title'])
            title2 = toString(article.find('div', 'e-date').span.getText(" "))
            title = str(title1) + ' - ' + str(title2)
            result.append(self.addDir(title,url,3, thumb))

        main = doc.find('main')
        for section in main.findAll('section'):
            titleSection = toString(section.find('h3','e-articles-title').getText(" "))
            result.append(self.addDir(titleSection, url, 4))

        return result
예제 #31
0
def getYesNoInput(session, text):
    def getYesNoInputCB(callback=None):
        if callback:
            d.callback(True)
        else:
            d.callback(False)
    d = defer.Deferred()
    session.openWithCallback(getYesNoInputCB, MessageBox, text=toString(text), type=MessageBox.TYPE_YESNO)
    return d
예제 #32
0
파일: client.py 프로젝트: m1ngr/archivczsk
def getYesNoInput(session, text):
    def getYesNoInputCB(callback=None):
        if callback:
            d.callback(True)
        else:
            d.callback(False)
    d = defer.Deferred()
    session.openWithCallback(getYesNoInputCB, MessageBox, text=toString(text), type=MessageBox.TYPE_YESNO)
    return d
예제 #33
0
 def updateMenuList(self, index=0):
     itemList = []
     itemColor = 0xffffff
     for item in self.lst_items:
         if getattr(item, "addon", False) and item.addon.get_info('broken'):
             itemColor = 0xff0000
         else:
             itemColor = 0xffffff
         itemList.append((toString(item.name), itemColor))
     self["menu"].list = itemList
     self["menu"].index = index
예제 #34
0
파일: content.py 프로젝트: m1ngr/archivczsk
 def updateMenuList(self, index=0):
     itemList = []
     itemColor = 0xffffff
     for item in self.lst_items:
         if getattr(item, "addon", False) and item.addon.get_info('broken'):
             itemColor = 0xff0000
         else:
             itemColor = 0xffffff
         itemList.append((toString(item.name), itemColor))
     self["menu"].list = itemList
     self["menu"].index = index
예제 #35
0
파일: player.py 프로젝트: mx3L/archivczsk
    def play_stream(self, play_url, play_settings=None, subtitles_url=None, title=None, wholeItem=None):
        log.info("play_stream(%s, %s, %s, %s)"%(play_url, play_settings, subtitles_url, title))
        log.logDebug("play_stream(%s, %s, %s, %s)"%(play_url, play_settings, subtitles_url, title))
        if play_url.startswith("rtmp"):
            rtmp_timeout = int(self.settings.rtmpTimeout.value)
            rtmp_buffer = int(self.settings.rtmpBuffer.value)
            if ' timeout=' not in play_url:
                play_url = "%s timeout=%d" % (play_url, rtmp_timeout)
            if ' buffer=' not in play_url:
                play_url = "%s buffer=%d" % (play_url, rtmp_buffer)
        headers = {}
        if play_settings.get("user-agent"):
            headers["User-Agent"] = play_settings["user-agent"]
        if play_settings.get("extra-headers"):
            headers.update(play_settings["extra-headers"])
        if headers:
            play_url += "#" + "&".join("%s=%s"%(k,v) for k,v in headers.iteritems())

        service_ref = eServiceReference(play_settings.get("stype", 4097), 0, toString(play_url))
        
        if self.video_player is None:
            self.video_player = self.session.openWithCallback(self.player_exit_callback,
                    ArchivCZSKMoviePlayer, self.player_callback)

        # set infobar text
        titleSet = False
        if wholeItem is not None:
            try:
                if 'title' in  wholeItem.info:
                    service_ref.setName(toString(wholeItem.info["title"]))
                    self.video_player.setInfoBarText(toString(wholeItem.info["title"]))
                    titleSet = True
            except:
                log.logError("Set title from item failed (set default).\n%s"%traceback.format_exc())

        if not titleSet:
            service_ref.setName(toString(title))
            self.video_player.setInfoBarText(toString(title))
        
        self.video_player.play_service_ref(service_ref, 
                self._play_item.subs, play_settings.get("resume_time_sec"))
예제 #36
0
파일: info.py 프로젝트: mx3L/archivczsk
    def __init__(self, session, title, text=None):
        BaseArchivCZSKScreen.__init__(self, session)
        self.changelog = ""

        try:
            from Plugins.Extensions.archivCZSK.engine.tools.util import toString
            if text is not None:
                self.changelog = toString(text)
            self.title = toString(title) + ' changelog'
        except:
            self.changelog = "failed"
            log.logError("Convert log file text failed.\n%s"%traceback.format_exc())
            pass
        self["changelog"] = ScrollLabel(self.changelog)
        
        self["actions"] = NumberActionMap(["archivCZSKActions"],
        {
            "cancel": self.close,
            "up": self.pageUp,
            "down": self.pageDown,
        }, -2)	
예제 #37
0
 def __init__(self, name, url, destDir, filename, quiet):
     self.url = url
     self.name = toString(filename) #name
     self.filename = toString(filename)
     self.destDir = destDir
     self.local = os.path.join(destDir, filename).encode('ascii', 'ignore')
     self.length = 0
     self.quiet = quiet
     self.start_time = time.time()
     self.finish_time = None
     self.running = False
     self.paused = False
     self.downloaded = False
     self.outputCB = self.__runOutputCB
     self.onOutputCB = []
     self.startCB = self.__runStartCB
     self.onStartCB = []
     self.finishCB = self.__runFinishCB
     self.onFinishCB = []
     self.state = 'unknown'
     self.textState = _('unknown')
예제 #38
0
 def create_item(self, xml_item):
     log.debug("{0} create item - {1}".format(self, toString(xml_item)))
     item = self._get_item_cls(xml_item)()
     item.id = xml_item.attrib.get('id')
     item.addon_id = xml_item.attrib.get('addon_id')
     item.ctime = xml_item.attrib.get('ctime')
     item.name = xml_item.findtext('name')
     item.params = {}
     params = xml_item.find('params')
     for key, value in params.items():
         item.params[key] = value
     return self._update_item(item, xml_item)
예제 #39
0
 def __init__(self, name, url, destDir, filename, quiet):
     self.url = url
     self.name = toString(filename)  #name
     self.filename = toString(filename)
     self.destDir = destDir
     self.local = os.path.join(destDir, filename).encode('ascii', 'ignore')
     self.length = 0
     self.quiet = quiet
     self.start_time = time.time()
     self.finish_time = None
     self.running = False
     self.paused = False
     self.downloaded = False
     self.outputCB = self.__runOutputCB
     self.onOutputCB = []
     self.startCB = self.__runStartCB
     self.onStartCB = []
     self.finishCB = self.__runFinishCB
     self.onFinishCB = []
     self.state = 'unknown'
     self.textState = _('unknown')
예제 #40
0
 def create_item(self, xml_item):
     log.debug("{0} create item - {1}".format(self, toString(xml_item)))
     item = self._get_item_cls(xml_item)()
     item.id = xml_item.attrib.get('id')
     item.addon_id = xml_item.attrib.get('addon_id')
     item.ctime = xml_item.attrib.get('ctime')
     item.name = xml_item.findtext('name')
     item.params = {}
     params = xml_item.find('params')
     for key, value in params.items():
         item.params[key] = value
     return self._update_item(item, xml_item)
예제 #41
0
    def updateAddonGUI(self):
        try:
            item = self.getSelectedItem()
            idur = ""
            irat = ""
            iplot = ""

            if isinstance(item, PVideoNotResolved) or isinstance(
                    item, PFolder):
                if self.showImageEnabled:
                    if not isinstance(item, (PSearch, PSearchItem)):
                        self.poster.set_image(item.image)
                try:
                    if 'rating' in item.info:
                        if float(item.info['rating']) > 0:
                            irat = str(item.info['rating'])
                except:
                    log.logError("Rating parse failed..\n%s" %
                                 traceback.format_exc())
                try:
                    if 'duration' in item.info:
                        durSec = float(item.info['duration'])
                        if durSec > 0:
                            hours = int(durSec / 60 / 60)
                            minutes = int((durSec - hours * 60 * 60) / 60)
                            if len(str(minutes)) == 1:
                                if hours > 0:
                                    idur = str(hours) + 'h' + '0' + str(
                                        minutes) + 'min'
                                else:
                                    idur = '0' + str(minutes) + 'min'
                            else:
                                if hours > 0:
                                    idur = str(hours) + 'h' + str(
                                        minutes) + 'min'
                                else:
                                    idur = str(minutes) + 'min'
                except:
                    log.logError("Duration parse failed..\n%s" %
                                 traceback.format_exc())
                try:
                    if 'plot' in item.info:
                        iplot = toString(item.info['plot'])[0:800]
                except:
                    log.logError("Plot parse failed..\n%s" %
                                 traceback.format_exc())

            self["movie_duration"].setText(idur)
            self["movie_rating"].setText(irat)
            self["movie_plot"].setText(iplot)

        except:
            log.logError("updateAddonGUI fail...\n%s" % traceback.format_exc())
예제 #42
0
파일: info.py 프로젝트: 1801/archivczsk
    def __init__(self, session, title, text=None):
        BaseArchivCZSKScreen.__init__(self, session)
        self.changelog = ""

        try:
            from Plugins.Extensions.archivCZSK.engine.tools.util import toString
            if text is not None:
                self.changelog = toString(text)
            self.title = toString(title) + ' changelog'
        except:
            self.changelog = "failed"
            log.logError("Convert log file text failed.\n%s" %
                         traceback.format_exc())
            pass
        self["changelog"] = ScrollLabel(self.changelog)

        self["actions"] = NumberActionMap(["archivCZSKActions"], {
            "cancel": self.close,
            "up": self.pageUp,
            "down": self.pageDown,
        }, -2)
예제 #43
0
 def __init__(self, session, playlist, title, index=0):
     self.playlist = playlist
     self.index = index
     Screen.__init__(self, session)
     self.skinName = ["ArchivCZSKPlaylistScreen"]
     self["title"] = StaticText(toString(title))
     self["list"] = List(self.buildPlaylist())
     self["actions"] = ActionMap(["OkCancelActions"], {
         "ok": self.ok,
         "cancel": boundFunction(self.close, None),
     }, -1)
     self.onLayoutFinish.append(self.setPlaylistIndex)
예제 #44
0
 def list(self, url):
     result = []
     name, url, mode = self.getMode(url)
     try:
         markizalog.logDebug('list hit name=%s, mode=%s, url=%s'%(name, mode, url))
         if mode==5:
             # az
             doc = MarkizaCache().get_data_cached(url, self.useCache, 8)
             for article in doc.findAll('article'):
                 url = toString(article.a['href'])
                 title = toString(article.a['title'])
                 thumb = toString(article.a.div.img['data-original'])
                 result.append(self.addDir(title,url,2, thumb))
         elif mode==4:
             # podsekce na strance
             doc = MarkizaCache().get_data_cached(url, self.useCache, 8)
             sectionName = doc.find('h3', 'e-articles-title', text=name)
             section = sectionName.findParent('section')
             for article in section.findAll('article'):
                 url = toString(article.a['href'])
                 title1 = toString(article.a['title'])
                 title2 = toString(article.find('div', 'e-date').span.getText(" "))
                 title = str(title1) + ' - ' + str(title2)
                 thumb = toString(article.a.div.img['data-original'])
                 result.append(self.addDir(title, url, 3, thumb))
         elif mode==2:
             # episodes
             result = self.episodes(url)
             pass
         elif mode==9:
             # top relacie
             result = self.top(url)
             pass
         elif mode==8:
             # new epizody
             result = self.newEpisodes(url)
             pass
         elif mode==6:
             # najsledovanejsie
             result = self.mostViewed(url)
             pass
         elif mode==7:
             # odporucane
             result = self.recommended(url)
             pass
         elif mode==3:
             # video link
             result = self.videoLink(url)
     except:
         markizalog.logError("Nacitanie zoznamu mode=%s zlyhalo. (Pojebany server ala markiza)\n%s"%(mode, traceback.format_exc()))
         result.append(self.addDir('FAILED','xxxx',0, ''))
         #self.showMsg('Nacitanie zoznamu zlyhalo.\n%s'%toString(traceback.format_exc())[:100], 30, True, True)
         self.showMsg('Nacitanie zoznamu zlyhalo.\nSkuste znova neskor (vypadok na strane markiza.sk).', 15, True, True)
         
     return result
예제 #45
0
파일: player.py 프로젝트: mx3L/archivczsk
 def __init__(self, session, playlist, title, index=0):
     self.playlist = playlist
     self.index = index
     Screen.__init__(self, session)
     self.skinName = ["ArchivCZSKPlaylistScreen"]
     self["title"] = StaticText(toString(title))
     self["list"] = List(self.buildPlaylist())
     self["actions"] = ActionMap(["OkCancelActions"],
             {
                 "ok": self.ok,
                 "cancel": boundFunction(self.close, None),
             }, -1 )
     self.onLayoutFinish.append(self.setPlaylistIndex)
예제 #46
0
파일: content.py 프로젝트: m1ngr/archivczsk
 def updatePath(self):
     current_stack_len = len(self.stack)
     parent_name = self.parent_it.name
     if current_stack_len <= self.old_stack_len:
         if len(self.path) > 0:
             self.path.pop()
     elif current_stack_len > self.old_stack_len:
         self.path.append(parent_name)
     if len(self.path) == 0:
         path_text = ' / '
     else:
         path_text = ' / ' + ' / '.join(self.path)
     self["path_label"].setText(toString(path_text))
예제 #47
0
    def _resolve_video_items(self, result):

        def all_done(result_list):
            for __, (data, item) in result_list:
                tmp_list = []
                for stream_dict in get_streams_from_manifest(item.url, data):
                    video_item = PVideoResolved()
                    video_item.subs = item.subs
                    video_item.settings = item.settings.copy()
                    video_item.url = stream_dict['url']
                    video_item.quality = "%s b/s"%stream_dict['bandwidth']
                    video_item.bandwidth = int(stream_dict['bandwidth'])
                    if 'resolution' in stream_dict:
                        video_item.quality = stream_dict['resolution'].split('x')[1] + "p"
                    # TODO remove workaround of embedding
                    # quality in title in addons
                    video_item.name = name = item.name
                    quality = video_item.quality
                    if quality and quality not in name:
                        if "[???]" in name:
                            video_item.name = name.replace("[???]","[%s]"%(quality))
                        else:
                            video_item.name = "[%s] %s"%(i.quality, i.name)
                    tmp_list.append(video_item)
                tmp_list.sort(key=operator.attrgetter('bandwidth'), reverse=True)
                if tmp_list:
                    log.info("%s __resolve_video_items: found %d streams"%(self, len(tmp_list)))
                    item_list.remove(item)
                    item_list.extend(tmp_list)
            return result

        def get_result(res, item):
            if isinstance(res, failure.Failure):
                log.error("%s _resolve_video_items: %s - %s"%(
                    self, item.url, res.value))
            else:
                log.debug("%s _resolve_video_items: %s - %dB"%(
                    self, item.url, len(res)))
            return res, item

        item_list,__,__ = result
        video_list = [i for i in item_list if isinstance(i, PVideoResolved) and is_hls_url(i.url)]
        log.debug("%s _resolve_video_items: found %d resolvable video items"%(self, len(video_list)))
        d_list = []
        for item in video_list:
            d = url_get_data_async(toString(item.url),
                    headers=item.settings["extra-headers"], timeout=5)
            d.addBoth(get_result, item)
            d_list.append(d)
        return defer.DeferredList(d_list, consumeErrors=True).addCallback(all_done)
예제 #48
0
파일: player.py 프로젝트: mx3L/archivczsk
 def __pts_available(self):
     if getPlayPositionPts(self.session) is None:
         self.__timer.start(500, True)
     else:
         if self.__resume_time_sec is not None:
             duration_sec = getDurationInSeconds(self.session)
             if (self.__resume_time_sec > 0 and 
                     duration_sec and duration_sec > 0 and
                     self.__resume_time_sec < duration_sec):
                 self.doSeek(self.__resume_time_sec * 90000)
             self.__resume_time_sec = None
             RemovePopup(self.RESUME_POPUP_ID)
         if self.__subtitles_url:
             self.loadSubs(toString(self.__subtitles_url))
예제 #49
0
    def videoLink(self, url):
        result = []
        doc = ''
        try:
            cacheTime = 1
            # this shit can failed <main> not contain <iframe> ... clear cache workaround not help, no-cache also .. f*****g markiza server
            doc = MarkizaCache().get_data_cached(url, self.useCache, -1) # special
            main = doc.find('main')
            url = main.find('iframe')['src']
            httpdata = MarkizaCache().get_data_cached(url, self.useCache, 1, False)

            httpdata = httpdata.replace("\r","").replace("\n","").replace("\t","")

            playlist = {}
            src = re.search('src = ({.+?});',httpdata,re.DOTALL).group(1)
            videoUrl = json.loads(src)
            if videoUrl:
                thumb = re.compile('<meta property="og:image" content="(.+?)">').findall(httpdata)
                thumb = thumb[0] if len(thumb) > 0 else ''
                desc = re.compile('<meta name="description" content="(.+?)">').findall(httpdata)
                desc = desc[0] if len(desc) > 0 else ''
                name = re.compile('<meta property="og:title" content="(.+?)">').findall(httpdata)
                name = name[0] if len(name) > 0 else '?'
                item = []
                item.append({'bitrates': videoUrl, 'contentTitle': toString(name), 'contentDescription': toString(desc), 'thumbnail': thumb})
                playlist['playlist'] = item;
            else:
                url = re.search('relatedLoc: "(.+?)",',httpdata,re.DOTALL).group(1).replace('\/','/')
                jsonData = MarkizaCache().get_data_cached(url, self.useCache, 1, False)
                playlist = json.loads(jsonData)
                # not working correctly on VTi 11
                # maybe @TODO
                # result.append(self.addLink('PREHRAŤ VŠETKO',url))

            if playlist and len(playlist['playlist']) > 0:
                # sort by title
                data = sorted(playlist['playlist'], key=lambda i: removeDiac(i['contentTitle']))
                for url in data:
                    result.append(self.addLink(url['contentTitle'],url['bitrates']['hls'],url['thumbnail']))
            else:
                raise Exception('Chyba - Video nejde prehrat')
        except:
            MarkizaCache().clear_cache(self.useCache) # special
            #markizalog.logDebug('########## POJEBANY REPSPONSE (<iframe>):\n%s'%doc)
            raise Exception("Ziskanie videolinku zlyhalo (clear cache).\n%s"%traceback.format_exc())
        return result
예제 #50
0
파일: content.py 프로젝트: m1ngr/archivczsk
 def updateMenuList(self, index=0):
     itemList = []
     itemColor = 0xffffff
     addonState = _("enabled")
     for item in self.lst_items:
         addon = item.addon
         if addon.get_info('broken'):
             itemColor = 0xff0000
             addonState = _("broken")
         elif not addon.get_setting('enabled'):
             itemColor = 0xffff00
             addonState = _("disabled")
         else:
             itemColor = 0x00ff00
             addonState = _("enabled")
         itemList.append((toString(item.name), addonState, itemColor))
     self["menu"].list = itemList
     self["menu"].index = index
예제 #51
0
    def resolve(self, item, captcha_cb=None, select_cb=None):
        markizalog.logDebug('resolve hit ...')
        result = []
        if 'chapters' in item['url']:
            ## @@TODO
            ## tu by trebalo vytiahnut len resolvnute URLky v jednej kvalite a tak to poskladat do playlistu vid. default.py
            markizalog.logDebug('resolve hit (chapters)...%s'%item['url'])
            jsonData = MarkizaCache().get_data_cached(item['url'], self.useCache, 30, False)
            playlist = json.loads(jsonData)

            if playlist and len(playlist['playlist']) > 0:
                for index,url in enumerate(playlist['playlist']):
                    markizalog.logDebug('chunklist=%s'%url)
                    itm = self.video_item()
                    itm['url'] = url['bitrates']['hls']
                    itm['surl'] =  url['contentTitle']
                    itm['title'] = url['contentTitle']
                    result.append(itm)
        else:
            # '/master.m3u8'
            baseUrl = item['url'][:item['url'].index('master.m3u8')]
            manifest = toString(MarkizaCache().get_data_cached(item['url'], self.useCache, 3, False) )
            markizalog.logDebug("item manifest= %s"%manifest)
            for m in re.finditer('#EXT-X-STREAM-INF:PROGRAM-ID=\d+,BANDWIDTH=(?P<bandwidth>\d+),RESOLUTION=.+,FRAME-RATE=.+,CODECS=".+"\s(?P<chunklist>.+$\s)', manifest, re.MULTILINE):
                itm = self.video_item()
                itm['title'] = item['title']
                bandwidth = int(m.group('bandwidth'))
                itm['bandwidth'] = bandwidth
                if bandwidth < 1500000:
                    itm['quality'] = "360p"
                elif bandwidth >= 1500000 and bandwidth < 2000000:
                    itm['quality'] = "480p"
                else:
                    itm['quality'] = "720p"
                itm['url'] = baseUrl+m.group('chunklist').replace('\n','')
                itm['surl'] = itm['title']
                markizalog.logDebug("item=%s"%itm)
                result.append(itm)
            result = sorted(result,key=lambda i:i['bandwidth'], reverse = True)
            
        result = resolver.filter_by_quality(result, self.quality)
        if len(result) > 0 and select_cb:
            return select_cb(result)
        return result
예제 #52
0
파일: common.py 프로젝트: mx3L/archivczsk
    def tabEntry(self, tab, x, active):
        if active:
            font      = 0
            color     = parseColor(self.tab_params['foregroundColorActive']).argb()
            backcolor = parseColor(self.tab_params['backgroundColorActive']).argb()
        else:
            font      = 1
            color     = parseColor(self.tab_params['foregroundColorInactive']).argb()
            backcolor = parseColor(self.tab_params['backgroundColorInactive']).argb()

        return MultiContentEntryText(
            pos       = (x, 0),
            size      = (self.tab_params['size'][0], self.tab_params['size'][1]),
            font      = font,
            text      = toString(tab),
            #tab.encode('utf-8'),
            flags     = RT_HALIGN_CENTER | RT_VALIGN_CENTER | RT_WRAP,
            color     = color,
            backcolor = backcolor)
예제 #53
0
파일: player.py 프로젝트: mx3L/archivczsk
    def play_item(self, item = None, idx = None):
        log.info("play_item(%s, %s)"%(item,toString(idx)))
        play_item = None
        if item is not None:
            idx = idx or 0
            if isinstance(item, PPlaylist):
                self.playlist_item = item
                self.playlist = item.playlist
                play_item = item.playlist[idx]
            elif isinstance(item, PVideo):
                if item not in self.playlist:
                    self.playlist_item = None
                    self.playlist = [item]
                play_item = item
        elif idx is not None and self.playlist and idx >= 0 and idx < len(self.playlist):
            play_item = self.playlist[idx]

        if play_item is not None and self._play_item != play_item:
            self._play_item = play_item
            self.curr_idx = self.playlist.index(play_item)
            self.play_stream(play_item.url, play_item.settings, play_item.subs, play_item.name, play_item)
예제 #54
0
파일: media.py 프로젝트: mx3L/archivczsk
 def continue_cb(res):
     self._filter_by_quality(list_items)
     if len(list_items) > 1:
         choices = []
         for i in list_items:
             name = i.name
             # TODO remove workaround of embedding
             # quality in title in addons
             if i.quality and i.quality not in i.name:
                 if "[???]" in i.name:
                     name = i.name.replace("[???]","[%s]"%(i.quality))
                 else:
                     name = "[%s] %s"%(i.quality, i.name)
             choices.append((toString(name), i))
         self.session.openWithCallback(selected_source,
                 ChoiceBox, _("Please select source"),
                 list = choices,
                 skin_name = ["ArchivCZSKVideoSourceSelection"])
     elif len(list_items) == 1:
         item = list_items[0]
         callback(item)
     else: # no video
         self.content_screen.workingFinished()
예제 #55
0
파일: content.py 프로젝트: m1ngr/archivczsk
 def updateMenuList(self, index=0):
     self["menu"].list = [(LoadPixmap(toString(item.thumb)), toString(item.name)) for item in self.lst_items]
     self["menu"].index = index
예제 #56
0
 def remove_download(self, item):
     if item is not None:
         log.debug('removing item %s from disk' % item.name)
         os.remove(toString(item.path))