Ejemplo n.º 1
0
 def onCreate(self):
     self._nullPIX()
     for key in self.dictPIX:
         try:
             pixFile = self.ICONS_FILESNAMES.get(key, None)
             if None != pixFile: self.dictPIX[key] = LoadPixmap(cached=True, path=GetIconDir(pixFile))
         except Exception: printExc()
Ejemplo n.º 2
0
 def __init__(self, session, params={}):
     # params: movie_title, sub_list: [{'title':'', 'lang':'', 'url':''}]
     self.session = session
     Screen.__init__(self, session)
     
     self.params = params
     
     self.onShown.append(self.onStart)
     self.onClose.append(self.__onClose)
     
     self["title"]         = Label(" ")
     self["console"]       = Label(" ")
     
     self["label_red"]     = Label(_("Cancel"))
     self["label_yellow"]  = Label(_("Move group"))
     self["label_green"]   = Label(_("Apply"))
     
     self["icon_red"]     = Cover3()
     self["icon_green"]   = Cover3()
     
     self["list"] = IPTVMainNavigatorList()
     self["list"].connectSelChanged(self.onSelectionChanged)
     
     self["actions"] = ActionMap(["ColorActions", "SetupActions", "WizardActions", "ListboxActions"],
         {
             "cancel": self.keyExit,
             "ok"    : self.keyOK,
             "red"   : self.keyRed,
             "green" : self.keyGreen,
         }, -2)
     
     self.iconPixmap = {}
     for icon in ['red', 'green']:
         self.iconPixmap[icon] = LoadPixmap(GetIconDir(icon+'.png'))
         
     self.movieTitle = ''
     self.stackList  = []
     self.stackItems = []
     
     self.defaultLanguage = GetDefaultLang()
 
     self.listMode = False
     self.downloadedSubFilePath = ""
     self.currItem = {}
     self.downloader = None
     self.cleanDownloader()
     self.workconsole = None
class IPTVFavouritesMainWidget(Screen):
    sz_w = 1980 - 190
    sz_h = getDesktop(0).size().height() - 195
    if sz_h < 500:
        sz_h += 4
    skin = """
        <screen name="IPTVFavouritesMainWidget" position="center,center" title="%s" size="%d,%d">
         <ePixmap position="5,9"   zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
         <ePixmap position="335,9" zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
         <ePixmap position="665,9" zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
         
         <widget name="label_red"     position="45,9"  size="300,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
         <widget name="label_green"   position="375,9" size="300,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
         <widget name="label_yellow"  position="705,9" size="300,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />

         <widget name="list"  position="5,80"  zPosition="2" size="%d,%d" scrollbarMode="showOnDemand" transparent="1"  backgroundColor="#00000000" enableWrapAround="1" />
         <widget name="title" position="5,47"  zPosition="1" size="%d,23" font="Regular;20"            transparent="1"  backgroundColor="#00000000"/>
        </screen>""" % (
        _("Favourites manager"),
        sz_w,
        sz_h,  # size
        GetIconDir("red.png"),
        GetIconDir("green.png"),
        GetIconDir("yellow.png"),
        sz_w - 10,
        sz_h - 105,  # size list
        sz_w - 135,  # size title
    )

    def __init__(self, session):
        self.session = session
        Screen.__init__(self, session)

        self.onShown.append(self.onStart)
        self.onClose.append(self.__onClose)
        self.favourites = None
        self.started = False
        self.menu = ":groups:"  # "items"
        self.modified = False

        self.IDS_ENABLE_REORDERING = _('Enable reordering')
        self.IDS_DISABLE_REORDERING = _('Disable reordering')
        self.reorderingMode = False

        self["title"] = Label(_("Favourites groups"))
        self["label_red"] = Label(_("Remove group"))
        self["label_yellow"] = Label(self.IDS_ENABLE_REORDERING)
        self["label_green"] = Label(_("Add new group"))

        self["list"] = IPTVMainNavigatorList()
        self["list"].connectSelChanged(self.onSelectionChanged)

        self["actions"] = ActionMap(
            ["ColorActions", "WizardActions", "ListboxActions"], {
                "back": self.keyExit,
                "cancel": self.keyExit,
                "ok": self.keyOK,
                "red": self.keyRed,
                "yellow": self.keyYellow,
                "green": self.keyGreen,
                "up": self.keyUp,
                "down": self.keyDown,
                "left": self.keyLeft,
                "right": self.keyRight,
                "moveUp": self.keyDrop,
                "moveDown": self.keyDrop,
                "moveTop": self.keyDrop,
                "moveEnd": self.keyDrop,
                "home": self.keyDrop,
                "end": self.keyDrop,
                "pageUp": self.keyDrop,
                "pageDown": self.keyDrop
            }, -2)

        self.prevIdx = 0
        self.duringMoving = False

    def __onClose(self):
        self["list"].disconnectSelChanged(self.onSelectionChanged)

    def onStart(self):
        self.onShown.remove(self.onStart)
        self.favourites = IPTVFavourites(GetFavouritesDir())
        sts = self.favourites.load(groupsOnly=True)
        if not sts:
            self.session.openWithCallback(self.iptvDoFinish,
                                          MessageBox,
                                          self.favourites.getLastError(),
                                          type=MessageBox.TYPE_ERROR,
                                          timeout=10)
            return
        self.displayList()

    def iptvDoFinish(self, ret=None):
        self.close()

    def displayList(self):
        list = []
        if ":groups:" == self.menu:
            groups = self.favourites.getGroups()
            for item in groups:
                dItem = CDisplayListItem(name=item['title'],
                                         type=CDisplayListItem.TYPE_CATEGORY)
                dItem.privateData = item['group_id']
                list.append((dItem, ))
        else:
            if not self.loadGroupItems(self.menu): return
            sts, items = self.favourites.getGroupItems(self.menu)
            if not sts:
                self.session.open(MessageBox,
                                  self.favourites.getLastError(),
                                  type=MessageBox.TYPE_ERROR,
                                  timeout=10)
                return
            for idx in range(len(items)):
                item = items[idx]
                dItem = CDisplayListItem(name=item.name, type=item.type)
                dItem.privateData = idx
                list.append((dItem, ))
        self["list"].setList(list)

    def loadGroupItems(self, groupId):
        sts = self.favourites.loadGroupItems(groupId)
        if not sts:
            self.session.open(MessageBox,
                              self.favourites.getLastError(),
                              type=MessageBox.TYPE_ERROR,
                              timeout=10)
            return False
        return True

    def onSelectionChanged(self):
        pass

    def keyExit(self):
        if ":groups:" == self.menu:
            if self.duringMoving: self._changeMode()
            if self.modified: self.askForSave()
            else: self.close(False)
        else:
            self["title"].setText(_("Favourites groups"))
            self["label_red"].setText(_("Remove group"))
            self["label_green"].setText(_("Add new group"))

            self.menu = ":groups:"
            self.displayList()
            try:
                self["list"].moveToIndex(self.prevIdx)
            except Exception:
                pass

    def askForSave(self):
        self.session.openWithCallback(self.save,
                                      MessageBox,
                                      text=_("Save changes?"),
                                      type=MessageBox.TYPE_YESNO)

    def save(self, ret):
        if ret:
            if not self.favourites.save():
                self.session.openWithCallback(self.closeAfterSave,
                                              MessageBox,
                                              self.favourites.getLastError(),
                                              type=MessageBox.TYPE_ERROR,
                                              timeout=10)
                return
            self.closeAfterSave()
        self.close(False)

    def closeAfterSave(self):
        self.close(True)

    def keyOK(self):
        if self.reorderingMode:
            if None != self.getSelectedItem():
                self._changeMode()
            return
        if ":groups:" == self.menu:
            sel = self.getSelectedItem()
            if None == sel: return

            self.menu = sel.privateData
            try:
                self["title"].setText(
                    _("Items in group \"%s\"") %
                    self.favourites.getGroup(self.menu)['title'])
            except Exception:
                printExc()
            self["label_red"].setText(_("Remove item"))
            self["label_green"].setText(_("Add item to group"))

            try:
                self.prevIdx = self["list"].getCurrentIndex()
            except Exception:
                self.prevIdx = 0
            self.displayList()
            try:
                self["list"].moveToIndex(0)
            except Exception:
                pass

    def keyRed(self):
        if self.duringMoving: return
        sel = self.getSelectedItem()
        if None == sel: return
        sts = True
        if ":groups:" == self.menu:
            sts = self.favourites.delGroup(sel.privateData)
        else:
            sts = self.favourites.delGroupItem(sel.privateData, self.menu)
        if not sts:
            self.session.open(MessageBox,
                              self.favourites.getLastError(),
                              type=MessageBox.TYPE_ERROR,
                              timeout=10)
            return
        self.modified = True
        self.displayList()

    def keyYellow(self):
        if None != self.getSelectedItem():
            if self.reorderingMode:
                self.reorderingMode = False
                self["label_yellow"].setText(self.IDS_ENABLE_REORDERING)
            else:
                self.reorderingMode = True
                self["label_yellow"].setText(self.IDS_DISABLE_REORDERING)

            if self.duringMoving and not self.reorderingMode:
                self._changeMode()
            elif not self.duringMoving and self.reorderingMode:
                self._changeMode()

    def keyGreen(self):
        printDBG(
            ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> keyGreen 1"
        )
        if ":groups:" == self.menu:
            self.session.openWithCallback(self._groupAdded,
                                          IPTVFavouritesAddNewGroupWidget,
                                          self.favourites)
        else:
            if None == self.getSelectedItem(): return
            if not self.loadGroupItems(self.menu): return
            sts, items = self.favourites.getGroupItems(self.menu)
            if not sts:
                self.session.open(MessageBox,
                                  self.favourites.getLastError(),
                                  type=MessageBox.TYPE_ERROR,
                                  timeout=10)
                return
            favItem = items[self["list"].getCurrentIndex()]
            self.session.openWithCallback(self._itemCloned,
                                          IPTVFavouritesAddItemWidget, favItem,
                                          self.favourites, False, [self.menu])

    def _groupAdded(self, group):
        if None != group:
            self.modified = True
            self.displayList()
            try:
                self["list"].moveToIndex(len(self.favourites.getGroups()) - 1)
            except Exception:
                pass

    def _itemCloned(self, ret):
        if ret: self.modified = True

    def _changeMode(self):
        if not self.duringMoving:
            self["list"].instance.setForegroundColorSelected(gRGB(0xFF0505))
            self.duringMoving = True
        else:
            self["list"].instance.setForegroundColorSelected(gRGB(0xFFFFFF))
            self.duringMoving = False
        self.displayList()

    def moveItem(self, key):
        if self["list"].instance is not None:
            if self.duringMoving:
                curIndex = self["list"].getCurrentIndex()
                self["list"].instance.moveSelection(key)
                newIndex = self["list"].getCurrentIndex()
                if ":groups:" == self.menu:
                    sts = self.favourites.moveGroup(curIndex, newIndex)
                else:
                    sts = self.favourites.moveGroupItem(
                        curIndex, newIndex, self.menu)
                if sts:
                    self.modified = True
                    self.displayList()
            else:
                self["list"].instance.moveSelection(key)

    def keyUp(self):
        if self["list"].instance is not None:
            self.moveItem(self["list"].instance.moveUp)

    def keyDown(self):
        if self["list"].instance is not None:
            self.moveItem(self["list"].instance.moveDown)

    def keyLeft(self):
        if self["list"].instance is not None:
            self.moveItem(self["list"].instance.pageUp)

    def keyRight(self):
        if self["list"].instance is not None:
            self.moveItem(self["list"].instance.pageDown)

    def keyDrop(self):
        pass

    def getSelectedItem(self):
        sel = None
        try:
            sel = self["list"].l.getCurrentSelection()[0]
        except Exception:
            pass
        return sel
 def __init__(self, session, artItem, addParams):
     self.session = session
     self.artItem = artItem
     
     #############################################
     # calculate num of rich desc items and pages
     #############################################
     self.richDesc = {'items_count': 0, 'pages_count': 0, 'page': 0, 'avalable_params':[] }
     for item in ArticleContent.RICH_DESC_PARAMS:
         if item in artItem.richDescParams:
             self.richDesc['items_count'] += 1
             self.richDesc['avalable_params'].append(item)
     # yes I know, len(self.richDesc['avalable_params']) == self.richDesc['items_count']
     
     self.richDesc['pages_count'] = self.richDesc['items_count'] / self.MAX_RICH_DESC_ROW_NUM
     if self.richDesc['items_count'] % self.MAX_RICH_DESC_ROW_NUM > 0:
         self.richDesc['pages_count'] += 1
     if self.richDesc['items_count'] < self.MAX_RICH_DESC_ROW_NUM:
         self.richDesc['rows_count'] = self.richDesc['items_count']
     else: self.richDesc['rows_count'] = self.MAX_RICH_DESC_ROW_NUM
     #############################################
     
     self.__prepareSkin()
     Screen.__init__(self, session)
         
     for idx in range(self.richDesc['rows_count']):
         self["dsc_label_{0}".format(idx+1)] = Label("")
         self["dsc_text_{0}".format(idx+1)]  = Label("")
     
     self["title"] = Label("")
     self["text"] = ScrollLabel(" ")
     self["page_marker"] = Cover3()
     #############################################
     # COVER 
     #############################################
     self["cover"] = Cover()
     self.cover = {'src':'', 'downloader':None, 'files_to_remove':[], 'image_path':''}
     try:
         self.cover['image_path'] = os.path.join(addParams['buffering_path'], '.iptv_buffering.jpg')
     except Exception: printExc()
     #############################################
     
     #############################################
     # SPINER 
     #############################################
     try:
         for idx in range(5):
             spinnerName = "spinner"
             if idx: spinnerName += '_%d' % idx 
             self[spinnerName] = Cover3()
     except Exception: printExc()
     self.spinner = {}
     self.spinner["pixmap"] = [LoadPixmap(GetIconDir('radio_button_on.png')), LoadPixmap(GetIconDir('radio_button_off.png'))]
     # spinner timer
     self.spinner["timer"] = eTimer()
     self.spinner["timer_conn"] = eConnectCallback(self.spinner["timer"].timeout, self.updateSpinner) 
     self.spinner["timer_interval"] = 200
     self.spinner["enabled"] = False
     #############################################
    
     self["actions"] = ActionMap(['IPTVAlternateVideoPlayer', 'MoviePlayerActions', 'MediaPlayerActions', 'WizardActions', 'DirectionActions'],
     {
         "ok":    self.key_ok,
         "back":  self.key_back,
         "left":  self.key_left,
         "right": self.key_right,
         "up":    self.key_up,
         "down":  self.key_down,
     }, -1)
     
     self.onClose.append(self.__onClose)
     #self.onShow.append(self.onStart)
     self.onLayoutFinish.append(self.onStart)
    def __prepareSkin(self):
        skin =  """
                    <screen name="IPTVArticleRichVisualizerWidget" position="center,center" size="1050,625" title="Info...">
                        <widget name="title" position="5,10"  zPosition="1" size="1040,70"  font="Regular;30" halign="center" valign="center"   transparent="1" backgroundColor="transparent" foregroundColor="#000E83F5" shadowColor="black" shadowOffset="-1,-1" />
                        <widget name="cover"     zPosition="1" position="10,110"  size="236,357" alphatest="blend" borderWidth="2" borderColor="white" backgroundColor="black" />
                        <widget name="spinner"   zPosition="3" position="98,232"  size="16,16"   transparent="1"  alphatest="blend" />
                        <widget name="spinner_1" zPosition="2" position="98,232"  size="16,16"   transparent="1"  alphatest="blend" />
                        <widget name="spinner_2" zPosition="2" position="114,232" size="16,16"   transparent="1"  alphatest="blend" />
                        <widget name="spinner_3" zPosition="2" position="130,232" size="16,16"   transparent="1"  alphatest="blend" />
                        <widget name="spinner_4" zPosition="2" position="146,232" size="16,16"   transparent="1"  alphatest="blend" />
                """
        # adds rows items
        self.richDesc['row_label_x'] = 260
        self.richDesc['row_label_w'] = 190
        self.richDesc['row_text_x']  = 455
        self.richDesc['row_text_w']  = 590
        self.richDesc['row_y']       = 110
        self.richDesc['row_h']       = 30
        
        y = self.richDesc['row_y'] 
        for idx in range(self.richDesc['rows_count']):
            skin += """<widget name="dsc_label_%d" noWrap="1" position="%d,%d"  zPosition="1" size="%d,%d"  font="Regular;20" halign="right" valign="center"   transparent="1" backgroundColor="transparent" foregroundColor="#000E83F5" shadowColor="black" shadowOffset="-1,-1" />""" % (idx+1, self.richDesc['row_label_x'], y, self.richDesc['row_label_w'], self.richDesc['row_h'])
            skin += """<widget name="dsc_text_%d"  noWrap="1" position="%d,%d"  zPosition="1" size="%d,%d"  font="Regular;20" halign="left"  valign="center"   transparent="1" backgroundColor="transparent" foregroundColor="#00EFEFEF" shadowColor="black" shadowOffset="-1,-1" />""" % (idx+1, self.richDesc['row_text_x'], y, self.richDesc['row_text_w'], self.richDesc['row_h'])
            y += self.richDesc['row_h']
        if y != self.richDesc['row_y']: y += self.richDesc['row_h']
        skin += """<widget name="text"        position="260,%d" zPosition="1" size="780,%d" font="Regular;26" halign="left"  valign="top"      transparent="1" backgroundColor="transparent" foregroundColor="#00EFEFEF" />""" % (y, 625 - y - 5)
        
        # adds pagination items
        if self.richDesc['pages_count'] > 1:
            x1 = self.richDesc['row_label_x']
            x2 = self.richDesc['row_text_x'] + self.richDesc['row_text_w'] - self.richDesc['row_label_x']
            
            self.richDesc['page_item_size']    = 16
            self.richDesc['page_item_start_x'] = x1 + (x2-x1 - (self.richDesc['page_item_size'] * self.richDesc['pages_count']))/2
            self.richDesc['page_item_start_y'] = self.richDesc['row_y'] - 20

            for idx in range(self.richDesc['pages_count']):
                pageItemX = self.richDesc['page_item_start_x'] + idx * self.richDesc['page_item_size']
                if 0 == idx: skin += """<widget name="page_marker" zPosition="3" position="%d,%d" size="%d,%d" transparent="1" alphatest="blend" />""" % (pageItemX, self.richDesc['page_item_start_y'], self.richDesc['page_item_size'], self.richDesc['page_item_size'] )
                skin += """<ePixmap zPosition="2" position="%d,%d" size="%d,%d" pixmap="%s" transparent="1" alphatest="blend" />\n""" % (pageItemX, self.richDesc['page_item_start_y'], self.richDesc['page_item_size'], self.richDesc['page_item_size'], GetIconDir('radio_button_off.png') )
        skin += '</screen>'
        self.skin = skin
        self.skinName = "IPTVArticleRichVisualizerWidget"
    def __init__(self, session, params={}):

        # Skin generator
        maxWidth = 0
        pX = 40
        pY = 60
        dY = 10
        skinItems = ''
        self.icons = []
        self.list = params['list']
        self.withAcceptButton = params.get('with_accept_button', False)
        self.statusText = params.get('status_text', '')
        statusTextHight = params.get('status_text_hight', 80)
        # calcl maxWidth size
        for idx in range(len(self.list)):
            item = self.list[idx]
            if item['label_size'][0] > maxWidth:
                maxWidth = item['label_size'][0]
            if item['input_size'][0] > maxWidth:
                maxWidth = item['input_size'][0]
        maxWidth += pX * 2

        if len(self.statusText):
            skinItems = '<widget name="statustext"   position="10,%d"  zPosition="2" size="%d,%d"  valign="center" halign="center" font="Regular;22" transparent="1" />' % (
                pY + dY, maxWidth - 20, statusTextHight)
            pY += statusTextHight + dY * 2

        for idx in range(len(self.list)):
            item = self.list[idx]
            if 'icon_path' in item:
                self["cover_%d" % idx] = Cover2()
                self.icons.append({
                    'name': "cover_%d" % idx,
                    'path': item['icon_path']
                })
            else:
                self["text_%d" % idx] = Label(item.get('title', ''))
            self["input_%d" % idx] = Input(**item['input'])
            self["border_%d" % idx] = Label("")
            if item.get('useable_chars', None) is not None:
                self["input_%d" % idx].setUseableChars(item['useable_chars'])

            if 'icon_path' in item:
                skinItems += '<widget name="cover_%d" position="%d,%d" size="%d,%d" zPosition="8" />' % (
                    idx, (maxWidth - item['label_size'][0]) / 2, pY,
                    item['label_size'][0], item['label_size'][1])
            else:
                skinItems += '<widget name="text_%d" position="%d,%d" size="%d,%d" font="%s" zPosition="2" />' % (
                    idx, 10, pY, item['label_size'][0], item['label_size'][1],
                    item['label_font'])

            pY += dY + item['label_size'][1]
            skinItems += '<widget name="input_%d" position="%d,%d" size="%d,%d" font="%s" zPosition="2" />' % (
                idx, pX, pY, item['input_size'][0], item['input_size'][1],
                item['input_font'])
            skinItems += '<widget name="border_%d" position="%d,%d" size="%d,%d" font="%s" zPosition="1" transparent="0" backgroundColor="#331F93B9" />' % (
                idx, pX - 5, pY - 5, item['input_size'][0] + 10,
                item['input_size'][1] + 10, item['input_font'])
            if 0 == idx:
                self['marker'] = Cover3()
                skinItems += '<widget name="marker" zPosition="2" position="10,%d" size="16,16" transparent="1" alphatest="blend" />' % (
                    pY + (item['input_size'][1] - 16) / 2)
            skinItems += '<widget name="marker_%d" zPosition="1" position="10,%d" size="16,16" transparent="1" alphatest="blend" />' % (
                idx, pY + (item['input_size'][1] - 16) / 2)
            self['marker_%d' % idx] = Cover3()
            pY += dY * 2 + item['input_size'][1]

        if self.withAcceptButton:
            skinItems += '<widget name="accept_button"  position="10,%d"  zPosition="2" size="%d,50"  valign="center" halign="center" font="Regular;22" foregroundColor="#00FFFFFF" backgroundColor="#320F0F0F" />' % (
                pY, maxWidth - 20)
            pY += dY * 2 + 50
        self.skin = """
        <screen name="IPTVMultipleInputBox" position="center,center" size="%d,%d" title="%s">
            <widget name="key_red"   position="10,10" zPosition="2" size="%d,35" valign="center" halign="left"   font="Regular;22" transparent="1" foregroundColor="red" />
            <widget name="key_ok"    position="10,10" zPosition="2" size="%d,35" valign="center" halign="center" font="Regular;22" transparent="1" foregroundColor="white" />
            <widget name="key_green" position="10,10" zPosition="2" size="%d,35" valign="center" halign="right"  font="Regular;22" transparent="1" foregroundColor="green" />
            %s
        </screen>
        """ % (maxWidth, pY, params.get('title', _("Input")), maxWidth - 20,
               maxWidth - 20, maxWidth - 20, skinItems)

        self["key_green"] = Label(params.get('accep_label', _("Save")))
        self["key_ok"] = Label(_("OK"))
        self["key_red"] = Label(_("Cancel"))
        if len(self.statusText):
            self["statustext"] = Label(str(self.statusText))
        if self.withAcceptButton:
            self["accept_button"] = Label(
                params.get('accep_label', _("Verify")))

        self.params = params

        Screen.__init__(self, session)
        self.onShown.append(self.onStart)
        self.onClose.append(self.__onClose)

        self["actions"] = NumberActionMap(
            [
                "ColorActions", "WizardActions", "InputBoxActions",
                "InputAsciiActions", "KeyboardInputActions"
            ], {
                "gotAsciiCode": self.gotAsciiCode,
                "green": self.keySave,
                "ok": self.keyOK,
                "red": self.keyCancel,
                "back": self.keyCancel,
                "left": self.keyLeft,
                "right": self.keyRight,
                "up": self.keyUp,
                "down": self.keyDown,
                "right": self.keyRight,
                "home": self.keyHome,
                "end": self.keyEnd,
                "deleteForward": self.keyDelete,
                "deleteBackward": self.keyBackspace,
                "tab": self.keyTab,
                "toggleOverwrite": self.keyInsert,
                "1": self.keyNumberGlobal,
                "2": self.keyNumberGlobal,
                "3": self.keyNumberGlobal,
                "4": self.keyNumberGlobal,
                "5": self.keyNumberGlobal,
                "6": self.keyNumberGlobal,
                "7": self.keyNumberGlobal,
                "8": self.keyNumberGlobal,
                "9": self.keyNumberGlobal,
                "0": self.keyNumberGlobal
            }, -1)

        self.idx = 0
        self.activeInput = "input_0"
        self.markerPixmap = [
            LoadPixmap(GetIconDir('radio_button_on.png')),
            LoadPixmap(GetIconDir('radio_button_off.png'))
        ]

        self.started = False
class IPTVDMWidget(Screen):

    sz_w = 1980 - 190
    sz_h = getDesktop(0).size().height() - 195
    if sz_h < 500:
        sz_h += 4
    skin = """
        <screen name="IPTVDMWidget" position="center,center" title="%s" size="%d,%d">
         <ePixmap position="5,9"   zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
         <ePixmap position="180,9" zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
         <ePixmap position="385,9" zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
         <ePixmap position="590,9" zPosition="4" size="35,30" pixmap="%s" transparent="1" alphatest="on" />
         <widget render="Label" source="key_red"    position="45,9"  size="140,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
         <widget render="Label" source="key_green"  position="225,9" size="300,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />            
         <widget render="Label" source="key_yellow" position="425,9" size="300,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />            
         <widget render="Label" source="key_blue"   position="635,9" size="300,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />            
         <widget name="list" position="5,100" zPosition="2" size="%d,%d" scrollbarMode="showOnDemand" transparent="0"  backgroundColor="#00000000" enableWrapAround="1" />
         <widget name="titel" position="5,47" zPosition="1" size="%d,23" font="Regular;20" transparent="1"  backgroundColor="#00000000"/>
        </screen>""" %(_("IPTV Player download manager"),
            sz_w, sz_h, # size
            GetIconDir('red.png'), GetIconDir('green.png'), GetIconDir('yellow.png'), GetIconDir('blue.png'),
            sz_w - 10, sz_h - 20, # size list
            sz_w - 135, # size titel
            )
        # <widget render="Label" source="key_yellow" position="220,9" size="180,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
        # <widget render="Label" source="key_blue" position="630,9" size="140,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" /> 
    def __init__(self, session, downloadmanager):
        self.session = session
        Screen.__init__(self, session)
        
        self.currentService = self.session.nav.getCurrentlyPlayingServiceReference()
        self.session.nav.event.append(self.__event)

        self["key_red"]    = StaticText(_("Stop"))
        self["key_green"]  = StaticText(_("Start"))
        self["key_yellow"] = StaticText(_("Archive"))
        self["key_blue"]   = StaticText(_("Downloads"))

        self["list"] = IPTVDownloadManagerList()
        self["list"].connectSelChanged(self.onSelectionChanged)
        self["actions"] = ActionMap(["WizardActions", "DirectionActions", "ColorActions"],
        {
            "ok": self.ok_pressed,
            "back": self.back_pressed,
            "red": self.red_pressed,
            "green": self.green_pressed,
            "yellow": self.yellow_pressed,
            "blue": self.blue_pressed,
           
        }, -1)

        self["titel"] = Label()
        
        self.DM = downloadmanager
        self.DM.connectListChanged(self.onListChanged)
        self.DM.setUpdateProgress(True)
        self.setManagerStatus()
        
        self.started = 0
        global gIPTVDM_listChanged
        gIPTVDM_listChanged = True
        
        self.onClose.append(self.__onClose)
        self.onShow.append(self.onStart)
            
        #main Timer to refresh liar
        self.mainTimer = eTimer()
        self.mainTimer_conn = eConnectCallback(self.mainTimer.timeout, self.reloadList)
        # every 500ms Proxy Queue will be checked  
        self.mainTimer.start(500)
        
        self.localMode = False
        self.localFiles = []
        self.console = eConsoleAppContainer()
        self.console_appClosed_conn   = eConnectCallback(self.console.appClosed, self.refreshFinished)
        self.console_stderrAvail_conn = eConnectCallback(self.console.stderrAvail, self.refreshNewData)
        self.underRefreshing = False
        
        self.iptvclosing = False
        self.currList = []
        
    #end def __init__(self, session):
    
    def refreshFinished(self, code):
        printDBG("IPTVDMWidget.refreshFinished")
        if self.iptvclosing: return
        self.localFiles = []
        self.tmpList.sort(key=lambda x: x.fileName.lower())
        self.localFiles = self.tmpList
        self.tmpList = []
        self.tmpData = ''
        self.underRefreshing = False
        self.reloadList(True)
        
    def refreshNewData(self, data):
        printDBG("IPTVDMWidget.refreshNewData")
        if self.iptvclosing: return
        self.tmpData += data
        newFiles = self.tmpData.split('\n')
        if not self.tmpData.endswith('\n'): 
            self.tmpData = newFiles[-1]
            del newFiles[-1]
        else: self.tmpData = ''

        for item in newFiles:
            params = item.split('//')
            if 4 > len(params): continue
            if item.startswith('.'): continue # do not list hidden items
            if len(params[0]) > 3 and params[0].lower()[-4:] in ['.flv', '.mp4']:
                fileName = os_path.join(config.plugins.iptvplayer.NaszaSciezka.value, params[0])
                skip = False
                for item2 in self.currList:  
                    printDBG("AAA:[%s]\nBBB:[%s]" % (item2.fileName, fileName) )
                    if fileName == item2.fileName.replace('//', '/'): 
                        skip = True
                        break
                if skip: continue
                listItem = DMItemBase(url=fileName, fileName=fileName)
                try: listItem.downloadedSize = os_path.getsize(fileName)
                except Exception: listItem.downloadedSize = 0
                listItem.status      = DMHelper.STS.DOWNLOADED
                listItem.downloadIdx = -1
                self.tmpList.append( listItem )
    
    def leaveMoviePlayer(self, answer=None, position=None, *args, **kwargs):
        self.DM.setUpdateProgress(True)
        self.session.nav.playService(self.currentService)
        return
    
    def setManagerStatus(self):
        status = _("Manager status: ")
        if self.DM.isRunning(): self["titel"].setText(status + _("STARTED"))
        else: self["titel"].setText(status + _("STOPPED"))
    
    def onListChanged(self):
        global gIPTVDM_listChanged
        gIPTVDM_listChanged = True
        return
        
    def __del__(self):
        printDBG("IPTVDMWidget.__del__ ---------------------------------------")
    
    def __onClose(self):
        # unsubscribe callback functions and break cycles references
        self.iptvclosing = True
        if None != self.console:
            self.console_appClosed_conn   = None
            self.console_stderrAvail_conn = None
            self.console_stdoutAvail_conn = None
            self.console.sendCtrlC()
            self.console = None
        self.DM.disconnectListChanged(self.onListChanged)
        self.DM.setUpdateProgress(False)
        self.DM = None
        try:
            self.mainTimer_conn = None
            self.mainTimer.stop()
            self.mainTimer = None
        except Exception: printExc()
        try:
            self.currentService = None
            self.session.nav.event.remove(self.__event)
            self["list"].disconnectSelChanged(self.onSelectionChanged)

            self.onClose.remove(self.__onClose)
            self.onShow.remove(self.onStart)
        except Exception: printExc()
        
    def red_pressed(self):
        self.DM.stopWorkThread()
        self.setManagerStatus()
        return

    def green_pressed(self):
        self.DM.runWorkThread()
        self.setManagerStatus()
        return

    def yellow_pressed(self):
        if self.iptvclosing: return
        if not self.underRefreshing: 
            self.underRefreshing = True
            self.tmpList = []
            self.tmpData = ''
            lsdirPath = GetBinDir("lsdir")
            try: os_chmod(lsdirPath, 0777)
            except Exception: printExc()
            cmd = '%s "%s" rl r' % (lsdirPath, config.plugins.iptvplayer.NaszaSciezka.value)
            printDBG("cmd[%s]" % cmd)
            self.console.execute( E2PrioFix( cmd ) )
        
        self.localMode = True
        self.reloadList(True)
        return
 
    def blue_pressed(self):
        if self.iptvclosing: return
        self.localMode = False
        self.reloadList(True)
        return  
    
    def onSelectionChanged(self):      
        return
 
    def back_pressed(self):
        if self.console: self.console.sendCtrlC()
        self.close()
        return

    def ok_pressed(self): 
        if self.iptvclosing: return
        
        
        # wszystkie dostepne opcje
        play = []
        play.append((_('Play with [%s] player') % GetMoviePlayer(True, False).getText(), 'play', GetMoviePlayer(True, False).value))
        play.append((_('Play with [%s] player') % GetMoviePlayer(True, True).getText(), 'play', GetMoviePlayer(True, True).value))
        
        cont   = ((_('Continue downloading'), 'continue'),)
        retry  = ((_('Download again'), 'retry'),)
        stop   = ((_('Stop downloading'), 'stop'),)
        remove = ((_('Remove file'), 'remove'),)
        delet  = ((_('Remove item'), 'delet'),)
        move   = ((_('Promote item'), 'move'),)
            
        options = []
        item = self.getSelItem()
        if item != None:
            if self.localMode:
                options.extend(play)
                options.extend(remove)
            elif DMHelper.STS.DOWNLOADED == item.status:
                options.extend(play)
                options.extend(remove)
                options.extend(retry)
            elif DMHelper.STS.INTERRUPTED == item.status:
                options.extend(play)
                #options.extend(cont)
                options.extend(retry)
                options.extend(remove)
            elif DMHelper.STS.DOWNLOADING == item.status:
                options.extend(play)
                options.extend(stop)
            elif DMHelper.STS.WAITING == item.status:
                options.extend(move)
                options.extend(delet)
            elif DMHelper.STS.ERROR == item.status:
                options.extend(retry)
                options.extend(remove)
            
            self.session.openWithCallback(self.makeActionOnDownloadItem, ChoiceBox, title=_("Select action"), list=options)
        
        return
        
    def makeActionOnDownloadItem(self, ret):
        item = self.getSelItem()
        if None != ret and None != item:
            printDBG("makeActionOnDownloadItem " + ret[1] + (" for downloadIdx[%d]" % item.downloadIdx) )
            if ret[1] == "play":
                title = item.fileName
                try:
                    title = os_path.basename(title)
                    title = os_path.splitext(title)[0]
                except Exception:
                    printExc()
                # when we watch we no need update sts
                self.DM.setUpdateProgress(False)
                player = ret[2]
                if "mini" == player:
                    self.session.openWithCallback(self.leaveMoviePlayer, IPTVMiniMoviePlayer, item.fileName, title)
                elif player in ["exteplayer", "extgstplayer"]:
                    additionalParams = {}
                    if item.fileName.split('.')[-1] in ['mp3', 'm4a', 'ogg', 'wma', 'fla', 'wav', 'flac']:
                        additionalParams['show_iframe'] = config.plugins.iptvplayer.show_iframe.value
                        additionalParams['iframe_file_start'] = config.plugins.iptvplayer.iframe_file.value
                        additionalParams['iframe_file_end'] = config.plugins.iptvplayer.clear_iframe_file.value
                        if 'sh4' == config.plugins.iptvplayer.plarform.value:
                            additionalParams['iframe_continue'] = True
                        else:
                            additionalParams['iframe_continue'] = False
                        
                    if "exteplayer" == player:
                        self.session.openWithCallback(self.leaveMoviePlayer, IPTVExtMoviePlayer, item.fileName, title, None, 'eplayer', additionalParams)
                    else:
                        self.session.openWithCallback(self.leaveMoviePlayer, IPTVExtMoviePlayer, item.fileName, title, None, 'gstplayer', additionalParams)
                else:
                    self.session.openWithCallback(self.leaveMoviePlayer, IPTVStandardMoviePlayer, item.fileName, title)
            elif self.localMode:
                if ret[1] == "remove": 
                    try: 
                        os_remove(item.fileName)
                        for idx in range(len(self.localFiles)):
                            if item.fileName == self.localFiles[idx].fileName:
                                del self.localFiles[idx]
                                self.reloadList(True)
                                break
                    except Exception: printExc()
            elif ret[1] == "continue":
                self.DM.continueDownloadItem(item.downloadIdx)
            elif ret[1] == "retry":
                self.DM.retryDownloadItem(item.downloadIdx)
            elif ret[1] == "stop":
                self.DM.stopDownloadItem(item.downloadIdx)
            elif ret[1] == "remove":
                self.DM.removeDownloadItem(item.downloadIdx)
            elif ret[1] == "delet":
                self.DM.deleteDownloadItem(item.downloadIdx)
            elif ret[1] == "move":
                self.DM.moveToTopDownloadItem(item.downloadIdx)   
 
    def getSelIndex(self):
        currSelIndex = self["list"].getCurrentIndex()
        return currSelIndex

    def getSelItem(self):
        currSelIndex = self["list"].getCurrentIndex()
        if not self.localMode: list = self.currList
        else: list = self.localFiles
        if len(list) <= currSelIndex:
            printDBG("ERROR: getSelItem there is no item with index: %d, listOfItems.len: %d" % (currSelIndex, len(list)))
            return None
        return list[currSelIndex]
        
    def getSelectedItem(self):
        sel = None
        try:
            sel = self["list"].l.getCurrentSelection()[0]
        except Exception:return None
        return sel
        
    def onStart(self):
        if self.started == 0:
            # pobierz liste
            self.started = 1
        return

    def reloadList(self, force=False):
        if not self.localMode:
            global gIPTVDM_listChanged
            if True == gIPTVDM_listChanged or force:
                printDBG("IPTV_DM_UI reload downloads list")
                self["list"].hide()
                gIPTVDM_listChanged = False
                # get current List from api
                self.currList = self.DM.getList()
                self["list"].setList([ (x,) for x in self.currList])
                self["list"].show()
        elif force:
            printDBG("IPTV_DM_UI reload archive list")
            self["list"].hide()
            self["list"].setList([ (x,) for x in self.localFiles])
            self["list"].show()
    #end reloadList

    def hideWindow(self):
        self.visible = False
        self.hide()

    def showWindow(self):
        self.visible = True
        self.show()          

    def Error(self, error = None):
        pass
        
    def __event(self, ev):
        pass
Ejemplo n.º 8
0
    def __init__(self,
                 session,
                 imgFilePath,
                 message,
                 title,
                 additionalParams={}):
        printDBG(
            "UnCaptchaReCaptchaWidget.__init__ --------------------------")

        self.params = additionalParams
        self.imgFilePath = imgFilePath
        self.numOfRow = self.params.get('rows', 3)
        self.numOfCol = self.params.get('cols', 3)
        self.markerWidth = self.params.get('marker_width', 100)
        self.markerHeight = self.params.get('marker_height', 100)
        self.offsetCoverX = 100
        self.offsetCoverY = 100

        windowWidth = self.markerWidth * self.numOfCol + self.offsetCoverX * 2
        windowHeight = self.markerWidth * self.numOfRow + self.offsetCoverY + 70

        coversSkin = ''
        self.coversSelection = []
        for x in range(self.numOfCol):
            self.coversSelection.append([])
            for y in range(self.numOfRow):
                coversSkin += """<widget name="cover_%s%s" zPosition="5" position="%d,%d" size="%d,%d" transparent="1" alphatest="blend" />""" % (
                    x,
                    y,
                    (self.offsetCoverX + self.markerWidth * x),  # pos X image
                    (self.offsetCoverY + self.markerHeight * y),  # pos Y image
                    self.markerWidth,
                    self.markerHeight)
                self.coversSelection[x].append(
                    False)  # at start no icon is selected

        self.skin = """
        <screen position="center,center" size="%d,%d" title="%s">
            <widget name="statustext"   position="0,10"  zPosition="2" size="%d,80"  valign="center" halign="center" font="Regular;22" transparent="1" />
            <widget name="puzzle_image" position="%d,%d" size="%d,%d" zPosition="3" transparent="1" alphatest="blend" />
            <widget name="marker"       position="%d,%d" size="%d,%d" zPosition="4" transparent="1" alphatest="blend" />
            <widget name="accept"       position="10,%d"  zPosition="2" size="%d,50"  valign="center" halign="center" font="Regular;22" foregroundColor="#00FFFFFF" backgroundColor="#FFFFFFFF" />
            %s
        </screen>
        """ % (
            windowWidth,
            windowHeight,
            title,
            windowWidth,
            self.offsetCoverX,  # puzzle x
            self.offsetCoverY,  # puzzle y
            self.markerWidth * self.numOfCol,  # puzzle image width
            self.markerHeight * self.numOfRow,  # puzzle image height
            self.offsetCoverX,
            self.offsetCoverY,
            self.markerWidth,
            self.markerHeight,
            self.offsetCoverY + self.markerWidth * self.numOfCol + 10,
            windowWidth - 20,
            coversSkin)

        self.session = session
        Screen.__init__(self, session)

        self["actions"] = ActionMap(
            ["WizardActions", "DirectionActions", "ColorActions"], {
                "left": self.keyLeft,
                "right": self.keyRight,
                "up": self.keyUp,
                "down": self.keyDown,
                "ok": self.keyOK,
                "back": self.keyCancel,
            }, -1)

        self.markerPixmap = LoadPixmap(GetIconDir('markerCaptchaV2.png'))
        self.selectPixmap = LoadPixmap(GetIconDir('selectCaptchaV2.png'))

        self["statustext"] = Label(str(message))
        self["accept"] = Label(self.params.get('accep_label', _("Verify")))

        self['puzzle_image'] = Cover2()
        self["marker"] = Cover3()

        for x in range(self.numOfCol):
            for y in range(self.numOfRow):
                strIndex = "cover_%s%s" % (x, y)
                self[strIndex] = Cover3()

        self.currX = 0
        self.currY = 0
        self.focusOnAcceptButton = False
        self.onLayoutFinish.append(self.onStart)
    def __init__(self,
                 session,
                 inList,
                 outList,
                 numOfLockedItems=0,
                 groupName='',
                 groupObj=None):
        printDBG(
            "PlayerSelectorWidget.__init__ --------------------------------")
        screenwidth = 1980
        iconSize = GetAvailableIconSize()
        if len(
                inList
        ) >= 30 and iconSize == 100 and screenwidth and screenwidth > 1100:
            numOfRow = 4
            numOfCol = 8
        elif len(inList) > 16 and iconSize == 100:
            numOfRow = 4
            numOfCol = 5
        elif len(inList) > 12 and iconSize == 100:
            numOfRow = 4
            numOfCol = 4
        elif len(inList) > 9:
            if screenwidth and screenwidth == 1920:
                numOfRow = 4
                numOfCol = 8
            else:
                numOfRow = 3
                numOfCol = 4
        elif len(inList) > 6:
            numOfRow = 3
            numOfCol = 3
        elif len(inList) > 3:
            numOfRow = 2
            numOfCol = 3
        else:
            numOfRow = 1
            numOfCol = 3

        try:
            confNumOfRow = int(config.plugins.iptvplayer.numOfRow.value)
            confNumOfCol = int(config.plugins.iptvplayer.numOfCol.value)
            # 0 - means AUTO
            if confNumOfRow > 0: numOfRow = confNumOfRow
            if confNumOfCol > 0: numOfCol = confNumOfCol
        except Exception:
            pass

        # position of first img
        offsetCoverX = 25
        if screenwidth and screenwidth == 1920:
            offsetCoverY = 100
        else:
            offsetCoverY = 80

        # image size
        coverWidth = iconSize
        coverHeight = iconSize

        # space/distance between images
        disWidth = int(coverWidth / 3)
        disHeight = int(coverHeight / 4)

        # marker size should be larger than img
        markerWidth = 45 + coverWidth
        markerHeight = 45 + coverHeight

        # position of first marker
        offsetMarkerX = offsetCoverX - (markerWidth - coverWidth) / 2
        offsetMarkerY = offsetCoverY - (markerHeight - coverHeight) / 2

        # how to calculate position of image with indexes indxX, indxY:
        #posX = offsetCoverX + (coverWidth + disWidth) * indxX
        #posY = offsetCoverY + (coverHeight + disHeight) * indxY

        # how to calculate position of marker for image with posX, posY
        #markerPosX = posX - (markerWidth - coverWidth)/2
        #markerPosY = posY - (markerHeight - coverHeight)/2

        tmpX = coverWidth + disWidth
        tmpY = coverHeight + disHeight

        self.numOfRow = numOfRow
        self.numOfCol = numOfCol
        # position of first cover
        self.offsetCoverX = offsetCoverX
        self.offsetCoverY = offsetCoverY
        # space/distance between images
        self.disWidth = disWidth
        self.disHeight = disHeight
        # image size
        self.coverWidth = coverWidth
        self.coverHeight = coverHeight
        # marker size should be larger than img
        self.markerWidth = markerWidth
        self.markerHeight = markerHeight

        self.inList = list(inList)
        self.currList = self.inList
        self.outList = outList

        self.groupName = groupName
        self.groupObj = groupObj
        self.numOfLockedItems = numOfLockedItems

        self.IconsSize = iconSize  #do ladowania ikon
        self.MarkerSize = self.IconsSize + 45

        self.lastSelection = PlayerSelectorWidget.LAST_SELECTION.get(
            self.groupName, 0)
        self.calcDisplayVariables()

        # pagination
        self.pageItemSize = 16
        self.pageItemStartX = (offsetCoverX + tmpX * numOfCol + offsetCoverX -
                               disWidth -
                               self.numOfPages * self.pageItemSize) / 2
        if screenwidth and screenwidth == 1920:
            self.pageItemStartY = 60
        else:
            self.pageItemStartY = 40

        if screenwidth and screenwidth == 1920:
            skin = """
            <screen name="IPTVPlayerPlayerSelectorWidget" position="center,center" title="IPTV Player HD %s" size="%d,%d">
            <widget name="statustext" position="0,0" zPosition="1" size="%d,50" font="Regular;36" halign="center" valign="center" transparent="1"/>
            <widget name="marker" zPosition="2" position="%d,%d" size="%d,%d" transparent="1" alphatest="blend" />
            <widget name="page_marker" zPosition="3" position="%d,%d" size="%d,%d" transparent="1" alphatest="blend" />
            <widget name="menu" zPosition="3" position="%d,10" size="70,30" transparent="1" alphatest="blend" />
            """ % (
                GetIPTVPlayerVerstion(),
                offsetCoverX + tmpX * numOfCol + offsetCoverX -
                disWidth,  # width of window
                offsetCoverY + tmpY * numOfRow + offsetCoverX -
                disHeight,  # height of window
                offsetCoverX + tmpX * numOfCol + offsetCoverX -
                disWidth,  # width of status line
                offsetMarkerX,
                offsetMarkerY,  # first marker position
                markerWidth,
                markerHeight,  # marker size
                self.pageItemStartX,
                self.pageItemStartY,  # pagination marker
                self.pageItemSize,
                self.pageItemSize,
                offsetCoverX + tmpX * numOfCol + offsetCoverX - disWidth - 70,
            )
        else:
            skin = """
            <screen name="IPTVPlayerPlayerSelectorWidget" position="center,center" title="IPTV Player %s" size="%d,%d">
            <widget name="statustext" position="0,0" zPosition="1" size="%d,50" font="Regular;26" halign="center" valign="center" transparent="1"/>
            <widget name="marker" zPosition="2" position="%d,%d" size="%d,%d" transparent="1" alphatest="blend" />
            <widget name="page_marker" zPosition="3" position="%d,%d" size="%d,%d" transparent="1" alphatest="blend" />
            <widget name="menu" zPosition="3" position="%d,10" size="70,30" transparent="1" alphatest="blend" />
            """ % (
                GetIPTVPlayerVerstion(),
                offsetCoverX + tmpX * numOfCol + offsetCoverX -
                disWidth,  # width of window
                offsetCoverY + tmpY * numOfRow + offsetCoverX -
                disHeight,  # height of window
                offsetCoverX + tmpX * numOfCol + offsetCoverX -
                disWidth,  # width of status line
                offsetMarkerX,
                offsetMarkerY,  # first marker position
                markerWidth,
                markerHeight,  # marker size
                self.pageItemStartX,
                self.pageItemStartY,  # pagination marker
                self.pageItemSize,
                self.pageItemSize,
                offsetCoverX + tmpX * numOfCol + offsetCoverX - disWidth - 70,
            )

        for y in range(1, numOfRow + 1):
            for x in range(1, numOfCol + 1):
                skinCoverLine = """<widget name="cover_%s%s" zPosition="4" position="%d,%d" size="%d,%d" transparent="1" alphatest="blend" />""" % (
                    x,
                    y,
                    (offsetCoverX + tmpX * (x - 1)),  # pos X image
                    (offsetCoverY + tmpY * (y - 1)),  # pos Y image
                    coverWidth,
                    coverHeight)
                skin += '\n' + skinCoverLine

        # add pagination items
        for pageItemOffset in range(self.numOfPages):
            pageItemX = self.pageItemStartX + pageItemOffset * self.pageItemSize
            skinCoverLine = """<ePixmap zPosition="2" position="%d,%d" size="%d,%d" pixmap="%s" transparent="1" alphatest="blend" />""" % (
                pageItemX, self.pageItemStartY, self.pageItemSize,
                self.pageItemSize, GetIconDir('radio_button_off.png'))
            skin += '\n' + skinCoverLine
        skin += '</screen>'
        self.skin = skin

        self.session = session
        Screen.__init__(self, session)

        self.session.nav.event.append(self.__event)
        self.onClose.append(self.__onClose)

        # load icons
        self.pixmapList = []
        for idx in range(0, self.numOfItems):
            self.pixmapList.append(
                LoadPixmap(
                    GetIconDir('PlayerSelector/' + self.currList[idx][1] +
                               '%i.png' % self.IconsSize)))

        self.markerPixmap = LoadPixmap(
            GetIconDir('PlayerSelector/marker%i.png' % self.MarkerSize))
        self.markerPixmapSel = LoadPixmap(
            GetIconDir('PlayerSelector/markerSel%i.png' % self.MarkerSize))
        self.pageMarkerPixmap = LoadPixmap(GetIconDir('radio_button_on.png'))
        self.menuPixmap = LoadPixmap(GetIconDir('menu.png'))

        self["actions"] = ActionMap(
            [
                "WizardActions", "DirectionActions", "ColorActions",
                "IPTVPlayerListActions"
            ], {
                "ok": self.ok_pressed,
                "back": self.back_pressed,
                "left": self.keyLeft,
                "right": self.keyRight,
                "up": self.keyUp,
                "down": self.keyDown,
                "blue": self.keyBlue,
                "menu": self.keyMenu,
            }, -1)

        self["marker"] = Cover3()
        self["page_marker"] = Cover3()
        self["menu"] = Cover3()

        for y in range(1, self.numOfRow + 1):
            for x in range(1, self.numOfCol + 1):
                strIndex = "cover_%s%s" % (x, y)
                self[strIndex] = Cover3()

        self["statustext"] = Label(self.currList[0][0])

        self.onLayoutFinish.append(self.onStart)
        self.visible = True
        self.reorderingMode = False
        self.reorderingItemSelected = False
Ejemplo n.º 10
0
 def readIcons(self):
     for itF in ['n', 'y']:
         for itS in ['n', 'y']:
             self.icoDict['F' + itF + 'S' + itS] = LoadPixmap(
                 GetIconDir('Pin/PinF%sS%s.png' % (itF, itS)))
Ejemplo n.º 11
0
    def __init__(self, session, params={}):
        # params: vk_title, movie_title
        printDBG(
            "IPTVSubDownloaderWidget.__init__ desktop IPTV_VERSION[%s]\n" %
            (IPTVSubDownloaderWidget.IPTV_VERSION))
        self.session = session
        path = GetSkinsDir(
            config.plugins.iptvplayer.skin.value) + "/subplaylist.xml"
        if os_path.exists(path):
            try:
                with open(path, "r") as f:
                    self.skin = f.read()
                    f.close()
            except Exception:
                printExc("Skin read error: " + path)

        Screen.__init__(self, session)

        self["key_red"] = StaticText(_("Cancel"))

        self["list"] = IPTVMainNavigatorList()
        self["list"].connectSelChanged(self.onSelectionChanged)
        self["statustext"] = Label("Loading...")
        self["actions"] = ActionMap(
            [
                "IPTVPlayerListActions", "WizardActions", "DirectionActions",
                "ColorActions", "NumberActions"
            ], {
                "red": self.red_pressed,
                "green": self.green_pressed,
                "yellow": self.yellow_pressed,
                "blue": self.blue_pressed,
                "ok": self.ok_pressed,
                "back": self.back_pressed,
            }, -1)

        self["headertext"] = Label()
        self["console"] = Label()
        self["sequencer"] = Label()

        try:
            for idx in range(5):
                spinnerName = "spinner"
                if idx: spinnerName += '_%d' % idx
                self[spinnerName] = Cover3()
        except Exception:
            printExc()

        self.spinnerPixmap = [
            LoadPixmap(GetIconDir('radio_button_on.png')),
            LoadPixmap(GetIconDir('radio_button_off.png'))
        ]
        self.showHostsErrorMessage = True

        self.onClose.append(self.__onClose)
        #self.onLayoutFinish.append(self.onStart)
        self.onShow.append(self.onStart)

        #Defs
        self.params = dict(params)
        self.params['discover_info'] = self.discoverInfoFromTitle()
        self.params['movie_url'] = strwithmeta(self.params.get(
            'movie_url', ''))
        self.params['url_params'] = self.params['movie_url'].meta
        self.movieTitle = self.params['discover_info']['movie_title']

        self.workThread = None
        self.host = None
        self.hostName = ''

        self.nextSelIndex = 0
        self.currSelIndex = 0

        self.prevSelList = []
        self.categoryList = []

        self.currList = []
        self.currItem = CDisplayListItem()

        self.visible = True

        #################################################################
        #                      Inits for Proxy Queue
        #################################################################

        # register function in main Queue
        if None == asynccall.gMainFunctionsQueueTab[1]:
            asynccall.gMainFunctionsQueueTab[
                1] = asynccall.CFunctionProxyQueue(self.session)
        asynccall.gMainFunctionsQueueTab[1].clearQueue()
        asynccall.gMainFunctionsQueueTab[1].setProcFun(
            self.doProcessProxyQueueItem)

        #main Queue
        self.mainTimer = eTimer()
        self.mainTimer_conn = eConnectCallback(self.mainTimer.timeout,
                                               self.processProxyQueue)
        # every 100ms Proxy Queue will be checked
        self.mainTimer_interval = 100
        self.mainTimer.start(self.mainTimer_interval, True)

        # spinner timer
        self.spinnerTimer = eTimer()
        self.spinnerTimer_conn = eConnectCallback(self.spinnerTimer.timeout,
                                                  self.updateSpinner)
        self.spinnerTimer_interval = 200
        self.spinnerEnabled = False

        #################################################################

        self.downloadedSubItems = []
Ejemplo n.º 12
0
class IPTVSubDownloaderWidget(Screen):
    IPTV_VERSION = GetIPTVPlayerVerstion()
    screenwidth = 1980
    if screenwidth and screenwidth == 1920:
        skin = """
                    <screen name="IPTVSubDownloaderWidget" position="center,center" size="1590,825" title="IPTV Player HD v%s">
                            <ePixmap position="5,9" zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
                            <widget render="Label" source="key_red" position="45,9" size="140,32" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;32" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
                            <widget name="headertext" position="15,55" zPosition="1" size="1580,30" font="Regular;30" transparent="1" backgroundColor="#00000000" />
                            <widget name="statustext" position="15,148" zPosition="1" size="1580,180" font="Regular;30" halign="center" valign="center" transparent="1" backgroundColor="#00000000" />
                            <widget name="list" position="5,115" zPosition="2" size="1580,410" enableWrapAround="1" scrollbarMode="showOnDemand" transparent="1" backgroundColor="#00000000" />
                            <widget name="console" position="5,570" zPosition="1" size="1580,140" font="Regular;26" transparent="1" backgroundColor="#00000000" />
                            <ePixmap zPosition="4" position="5,535" size="1580,5" pixmap="%s" transparent="1" />
                            <widget name="spinner"   zPosition="2" position="508,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_1" zPosition="1" position="508,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_2" zPosition="1" position="524,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_3" zPosition="1" position="540,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_4" zPosition="1" position="556,240" size="16,16" transparent="1" alphatest="blend" />
                    </screen>
                """ % (IPTV_VERSION, GetIconDir('red.png'),
                       GetIconDir('line.png'))
    else:
        skin = """
                    <screen name="IPTVSubDownloaderWidget" position="center,center" size="1090,525" title="IPTV Player v%s">
                            <ePixmap position="30,9" zPosition="4" size="30,30" pixmap="%s" transparent="1" alphatest="on" />
                            <widget render="Label" source="key_red"    position="65,9"  size="210,27" zPosition="5" valign="center" halign="left" backgroundColor="black" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
                            <widget name="headertext" position="5,47" zPosition="1" size="1080,23" font="Regular;20" transparent="1" backgroundColor="#00000000" />
                            <widget name="statustext" position="5,140" zPosition="1" size="1080,180" font="Regular;20" halign="center" valign="center" transparent="1" backgroundColor="#00000000" />
                            <widget name="list" position="5,100" zPosition="2" size="1080,280" enableWrapAround="1" scrollbarMode="showOnDemand" transparent="1" backgroundColor="#00000000" />
                            <widget name="console" position="5,400" zPosition="1" size="1080,170" font="Regular;20" transparent="1" backgroundColor="#00000000" />
                            <ePixmap zPosition="4" position="5,395" size="1080,5" pixmap="%s" transparent="1" />
                            <widget name="spinner"   zPosition="2" position="508,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_1" zPosition="1" position="508,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_2" zPosition="1" position="524,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_3" zPosition="1" position="540,240" size="16,16" transparent="1" alphatest="blend" />
                            <widget name="spinner_4" zPosition="1" position="556,240" size="16,16" transparent="1" alphatest="blend" />
                    </screen>
                """ % (IPTV_VERSION, GetIconDir('red.png'),
                       GetIconDir('line.png'))

    def __init__(self, session, params={}):
        # params: vk_title, movie_title
        printDBG(
            "IPTVSubDownloaderWidget.__init__ desktop IPTV_VERSION[%s]\n" %
            (IPTVSubDownloaderWidget.IPTV_VERSION))
        self.session = session
        path = GetSkinsDir(
            config.plugins.iptvplayer.skin.value) + "/subplaylist.xml"
        if os_path.exists(path):
            try:
                with open(path, "r") as f:
                    self.skin = f.read()
                    f.close()
            except Exception:
                printExc("Skin read error: " + path)

        Screen.__init__(self, session)

        self["key_red"] = StaticText(_("Cancel"))

        self["list"] = IPTVMainNavigatorList()
        self["list"].connectSelChanged(self.onSelectionChanged)
        self["statustext"] = Label("Loading...")
        self["actions"] = ActionMap(
            [
                "IPTVPlayerListActions", "WizardActions", "DirectionActions",
                "ColorActions", "NumberActions"
            ], {
                "red": self.red_pressed,
                "green": self.green_pressed,
                "yellow": self.yellow_pressed,
                "blue": self.blue_pressed,
                "ok": self.ok_pressed,
                "back": self.back_pressed,
            }, -1)

        self["headertext"] = Label()
        self["console"] = Label()
        self["sequencer"] = Label()

        try:
            for idx in range(5):
                spinnerName = "spinner"
                if idx: spinnerName += '_%d' % idx
                self[spinnerName] = Cover3()
        except Exception:
            printExc()

        self.spinnerPixmap = [
            LoadPixmap(GetIconDir('radio_button_on.png')),
            LoadPixmap(GetIconDir('radio_button_off.png'))
        ]
        self.showHostsErrorMessage = True

        self.onClose.append(self.__onClose)
        #self.onLayoutFinish.append(self.onStart)
        self.onShow.append(self.onStart)

        #Defs
        self.params = dict(params)
        self.params['discover_info'] = self.discoverInfoFromTitle()
        self.params['movie_url'] = strwithmeta(self.params.get(
            'movie_url', ''))
        self.params['url_params'] = self.params['movie_url'].meta
        self.movieTitle = self.params['discover_info']['movie_title']

        self.workThread = None
        self.host = None
        self.hostName = ''

        self.nextSelIndex = 0
        self.currSelIndex = 0

        self.prevSelList = []
        self.categoryList = []

        self.currList = []
        self.currItem = CDisplayListItem()

        self.visible = True

        #################################################################
        #                      Inits for Proxy Queue
        #################################################################

        # register function in main Queue
        if None == asynccall.gMainFunctionsQueueTab[1]:
            asynccall.gMainFunctionsQueueTab[
                1] = asynccall.CFunctionProxyQueue(self.session)
        asynccall.gMainFunctionsQueueTab[1].clearQueue()
        asynccall.gMainFunctionsQueueTab[1].setProcFun(
            self.doProcessProxyQueueItem)

        #main Queue
        self.mainTimer = eTimer()
        self.mainTimer_conn = eConnectCallback(self.mainTimer.timeout,
                                               self.processProxyQueue)
        # every 100ms Proxy Queue will be checked
        self.mainTimer_interval = 100
        self.mainTimer.start(self.mainTimer_interval, True)

        # spinner timer
        self.spinnerTimer = eTimer()
        self.spinnerTimer_conn = eConnectCallback(self.spinnerTimer.timeout,
                                                  self.updateSpinner)
        self.spinnerTimer_interval = 200
        self.spinnerEnabled = False

        #################################################################

        self.downloadedSubItems = []

    #end def __init__(self, session):

    def __del__(self):
        printDBG("IPTVSubDownloaderWidget.__del__ --------------------------")

    def __onClose(self):
        self["list"].disconnectSelChanged(self.onSelectionChanged)
        self.mainTimer_conn = None
        self.mainTimer = None
        self.spinnerTimer_conn = None
        self.spinnerTimer = None

        try:
            asynccall.gMainFunctionsQueueTab[1].setProcFun(None)
            asynccall.gMainFunctionsQueueTab[1].clearQueue()
        except Exception:
            printExc()

    def onStart(self):
        self.onShow.remove(self.onStart)
        #self.onLayoutFinish.remove(self.onStart)
        self.loadSpinner()
        self.hideSpinner()
        #self.hideButtons()
        self.confirmMovieTitle()

    def confirmMovieTitle(self):
        # first ask user to provide movie title
        self.session.openWithCallback(
            self.confirmMovieTitleCallBack,
            VirtualKeyBoard,
            title=(_("Confirm the title of the movie")),
            text=self.movieTitle)

    def confirmMovieTitleCallBack(self, text=None):
        if isinstance(text, basestring):
            self.movieTitle = text
            self.listSubtitlesProviders()
        else:
            self.close()

    def hideButtons(self, buttons=['green', 'yellow', 'blue']):
        try:
            for button in buttons:
                self['icon_' + button].hide()
                self['label_' + button].hide()
        except Exception:
            printExc()

    def red_pressed(self):
        self.close(None)

    def green_pressed(self):
        pass

    def yellow_pressed(self):
        pass

    def blue_pressed(self):
        pass

    def back_pressed(self):
        printDBG("IPTVSubDownloaderWidget.back_pressed")
        try:
            if self.isInWorkThread():
                if self.workThread.kill():
                    self.workThread = None
                    self["statustext"].setText(_("Operation aborted!"))
                return
        except Exception:
            return
        if self.visible:
            if len(self.prevSelList) > 0:
                self.nextSelIndex = self.prevSelList.pop()
                self.categoryList.pop()
                printDBG("back_pressed prev sel index %s" % self.nextSelIndex)
                if len(self.prevSelList) > 0:
                    self.requestListFromHost('Previous')
                else:
                    self.listSubtitlesProviders()
            else:
                #There is no prev categories, so exit
                self.confirmMovieTitle()
        else:
            self.showWindow()

    #end back_pressed(self):

    def ok_pressed(self):
        if self.visible:
            sel = None
            try:
                sel = self["list"].l.getCurrentSelection()[0]
            except Exception:
                self.getRefreshedCurrList()
                return
            if sel is None:
                printDBG("ok_pressed sel is None")
                return

            elif len(self.currList) <= 0:
                printDBG("ok_pressed list is empty")
                self.getRefreshedCurrList()
                return
            else:
                printDBG("ok_pressed selected item: %s" % (sel.name))

                item = self.getSelItem()
                self.currItem = item

                #Get current selection
                currSelIndex = self["list"].getCurrentIndex()
                #remember only prev categories
                if item.type in [CDisplayListItem.TYPE_SUB_PROVIDER]:
                    try:
                        self.hostName = item.privateData['sub_provider']
                        self.loadHost()
                    except Exception:
                        printExc()
                elif item.type in [CDisplayListItem.TYPE_SUBTITLE]:
                    self.requestListFromHost('ForDownloadSubFile',
                                             currSelIndex, '')
                elif item.type == CDisplayListItem.TYPE_CATEGORY:
                    printDBG("ok_pressed selected TYPE_CATEGORY")
                    self.currSelIndex = currSelIndex
                    self.requestListFromHost('ForItem', currSelIndex, '')
                elif item.type == CDisplayListItem.TYPE_MORE:
                    printDBG("ok_pressed selected TYPE_MORE")
                    self.currSelIndex = currSelIndex
                    self.requestListFromHost('ForMore', currSelIndex, '')
        else:
            self.showWindow()

    #end ok_pressed(self):

    def loadHost(self):
        try:
            _temp = __import__(
                'Plugins.Extensions.IPTVPlayer.subproviders.subprov_' +
                self.hostName, globals(), locals(), ['IPTVSubProvider'], -1)
            params = dict(self.params)
            params['confirmed_title'] = self.movieTitle
            self.host = _temp.IPTVSubProvider(params)
            if not isinstance(self.host, ISubProvider):
                printDBG("Host [%r] does not inherit from ISubProvider" %
                         self.hostName)
                self.close()
                return
        except Exception:
            printExc('Cannot import class IPTVSubProvider for host [%r]' %
                     self.hostName)
            self.close()
            return
        # request initial list from host
        self.getInitialList()

    def loadSpinner(self):
        try:
            if "spinner" in self:
                self["spinner"].setPixmap(self.spinnerPixmap[0])
                for idx in range(4):
                    spinnerName = 'spinner_%d' % (idx + 1)
                    self[spinnerName].setPixmap(self.spinnerPixmap[1])
        except Exception:
            printExc()

    def showSpinner(self):
        if None != self.spinnerTimer:
            self._setSpinnerVisibility(True)
            self.spinnerTimer.start(self.spinnerTimer_interval, True)

    def hideSpinner(self):
        self._setSpinnerVisibility(False)

    def _setSpinnerVisibility(self, visible=True):
        self.spinnerEnabled = visible
        try:
            if "spinner" in self:
                for idx in range(5):
                    spinnerName = "spinner"
                    if idx: spinnerName += '_%d' % idx
                    self[spinnerName].visible = visible
        except Exception:
            printExc()

    def updateSpinner(self):
        try:
            if self.spinnerEnabled and None != self.workThread:
                if self.workThread.isAlive():
                    if "spinner" in self:
                        x, y = self["spinner"].getPosition()
                        x += self["spinner"].getWidth()
                        if x > self["spinner_4"].getPosition()[0]:
                            x = self["spinner_1"].getPosition()[0]
                        self["spinner"].setPosition(x, y)
                    if None != self.spinnerTimer:
                        self.spinnerTimer.start(self.spinnerTimer_interval,
                                                True)
                        return
                elif not self.workThread.isFinished():
                    message = _(
                        "It seems that the subtitle's provider \"%s\" has crashed. Do you want to report this problem?"
                    ) % self.hostName
                    message += "\n"
                    message += _(
                        '\nMake sure you are using the latest version of the plugin.'
                    )
                    message += _(
                        '\nYou can also report problem here: \nhttps://gitlab.com/iptvplayer-for-e2/iptvplayer-for-e2/issues\nor here: [email protected]'
                    )
                    self.session.openWithCallback(self.reportHostCrash,
                                                  MessageBox,
                                                  text=message,
                                                  type=MessageBox.TYPE_YESNO)
            self.hideSpinner()
        except Exception:
            printExc()

    def reportHostCrash(self, ret):
        try:
            if ret:
                try:
                    exceptStack = self.workThread.getExceptStack()
                    reporter = GetPluginDir('iptvdm/reporthostcrash.py')
                    msg = urllib_quote(
                        '%s|%s|%s|%s' %
                        ('HOST_CRASH', IPTVSubDownloaderWidget.IPTV_VERSION,
                         self.hostName, self.getCategoryPath()))
                    self.crashConsole = iptv_system(
                        'python "%s" "http://iptvplayer.vline.pl/reporthostcrash.php?msg=%s" "%s" 2&>1 > /dev/null'
                        % (reporter, msg, exceptStack))
                    printDBG(msg)
                except Exception:
                    printExc()
            self.workThread = None
            self.prevSelList = []
            self.back_pressed()
        except Exception:
            printExc()

    def processProxyQueue(self):
        if None != self.mainTimer:
            asynccall.gMainFunctionsQueueTab[1].processQueue()
            self.mainTimer.start(self.mainTimer_interval, True)
        return

    def doProcessProxyQueueItem(self, item):
        try:
            if None == item.retValue[0] or self.workThread == item.retValue[0]:
                if isinstance(item.retValue[1], asynccall.CPQParamsWrapper):
                    getattr(self, method)(*item.retValue[1])
                else:
                    getattr(self, item.clientFunName)(item.retValue[1])
            else:
                printDBG(
                    '>>>>>>>>>>>>>>> doProcessProxyQueueItem callback from old workThread[%r][%s]'
                    % (self.workThread, item.retValue))
        except Exception:
            printExc()

    def getCategoryPath(self):
        def _getCat(cat, num):
            if '' == cat: return ''
            cat = ' > ' + cat
            if 1 < num: cat += (' (x%d)' % num)
            return cat

        if len(self.categoryList):
            str = self.hostName
        else:
            str = _("Select subtitles provider:")
        prevCat = ''
        prevNum = 0
        for cat in self.categoryList:
            if prevCat != cat:
                str += _getCat(prevCat, prevNum)
                prevCat = cat
                prevNum = 1
            else:
                prevNum += 1
        str += _getCat(prevCat, prevNum)
        return str

    def getRefreshedCurrList(self):
        currSelIndex = self["list"].getCurrentIndex()
        self.requestListFromHost('Refresh', currSelIndex)

    def getInitialList(self):
        self.nexSelIndex = 0
        self.prevSelList = []
        self.categoryList = []
        self.currList = []
        self.currItem = CDisplayListItem()
        self["headertext"].setText(self.getCategoryPath())
        self.requestListFromHost('Initial')

    def requestListFromHost(self, type, currSelIndex=-1, privateData=''):

        if not self.isInWorkThread():
            self["list"].hide()

            if type not in ['ForDownloadSubFile']:
                #hide bottom panel
                self["console"].setText('')

            if type in ['ForItem', 'Initial']:
                self.prevSelList.append(self.currSelIndex)
                self.categoryList.append(self.currItem.name)
                #new list, so select first index
                self.nextSelIndex = 0

            selItem = None
            if currSelIndex > -1 and len(self.currList) > currSelIndex:
                selItem = self.currList[currSelIndex]
                if selItem.itemIdx > -1 and len(
                        self.currList) > selItem.itemIdx:
                    currSelIndex = selItem.itemIdx

            dots = ""  #_("...............")
            IDS_DOWNLOADING = _("Downloading") + dots
            IDS_LOADING = _("Loading") + dots
            IDS_REFRESHING = _("Refreshing") + dots
            try:
                if type == 'Refresh':
                    self["statustext"].setText(IDS_REFRESHING)
                    self.workThread = asynccall.AsyncMethod(
                        self.host.getCurrentList,
                        boundFunction(self.callbackGetList, {
                            'refresh': 1,
                            'selIndex': currSelIndex
                        }), True)(1)
                elif type == 'ForMore':
                    self["statustext"].setText(IDS_DOWNLOADING)
                    self.workThread = asynccall.AsyncMethod(
                        self.host.getMoreForItem,
                        boundFunction(self.callbackGetList, {
                            'refresh': 2,
                            'selIndex': currSelIndex
                        }), True)(currSelIndex)
                elif type == 'Initial':
                    self["statustext"].setText(IDS_DOWNLOADING)
                    self.workThread = asynccall.AsyncMethod(
                        self.host.getInitList,
                        boundFunction(self.callbackGetList, {}), True)()
                elif type == 'Previous':
                    self["statustext"].setText(IDS_DOWNLOADING)
                    self.workThread = asynccall.AsyncMethod(
                        self.host.getPrevList,
                        boundFunction(self.callbackGetList, {}), True)()
                elif type == 'ForItem':
                    self["statustext"].setText(IDS_DOWNLOADING)
                    self.workThread = asynccall.AsyncMethod(
                        self.host.getListForItem,
                        boundFunction(self.callbackGetList, {}),
                        True)(currSelIndex, 0)
                elif type == 'ForDownloadSubFile':
                    self["statustext"].setText(IDS_DOWNLOADING)
                    self.workThread = asynccall.AsyncMethod(
                        self.host.downloadSubtitleFile,
                        boundFunction(self.downloadSubtitleFileCallback, {}),
                        True)(currSelIndex)
                else:
                    printDBG('requestListFromHost unknown list type: ' + type)
                self["headertext"].setText(self.getCategoryPath())
                self.showSpinner()
            except Exception:
                printExc('The current host crashed')

    #end requestListFromHost(self, type, currSelIndex = -1, privateData = ''):

    def callbackGetList(self, addParam, thread, ret):
        asynccall.gMainFunctionsQueueTab[1].addToQueue(
            "reloadList", [thread, {
                'add_param': addParam,
                'ret': ret
            }])

    def downloadSubtitleFileCallback(self, addParam, thread, ret):
        asynccall.gMainFunctionsQueueTab[1].addToQueue(
            "subtitleFileDownloaded",
            [thread, {
                'add_param': addParam,
                'ret': ret
            }])

    def subtitleFileDownloaded(self, params):
        printDBG("IPTVSubDownloaderWidget.subtitleFileDownloaded")
        self["statustext"].setText("")
        self["list"].show()
        ret = params['ret']

        if ret.status != RetHost.OK or 1 != len(ret.value):
            disMessage = _('Download subtiles failed.') + '\n'
            if ret.message and ret.message != '':
                disMessage += ret.message
            lastErrorMsg = GetIPTVPlayerLastHostError()
            if lastErrorMsg != '':
                disMessage += "\n" + _('Last error: "%s"') % lastErrorMsg
            self.session.open(MessageBox,
                              disMessage,
                              type=MessageBox.TYPE_ERROR)
        else:
            # subtitle downloaded, ask for finish
            ret = ret.value[0]
            self.downloadedSubItems.append(ret)
            message = _('Subtitles \"%s\" downloaded correctly.') % ret.path
            message += '\n' + _('Do you want to finish?')
            self.session.openWithCallback(self.askFinishCallback,
                                          MessageBox,
                                          text=message,
                                          type=MessageBox.TYPE_YESNO)

    def askFinishCallback(self, ret):
        try:
            if ret:
                item = self.downloadedSubItems[-1]
                track = {
                    'title': item.name,
                    'lang': item.lang,
                    'path': item.path,
                    'id': item.imdbid
                }
                self.close(track)
        except Exception:
            printExc()

    def reloadList(self, params):
        printDBG("IPTVSubDownloaderWidget.reloadList")
        refresh = params['add_param'].get('refresh', 0)
        selIndex = params['add_param'].get('selIndex', 0)
        ret = params['ret']
        printDBG(
            "IPTVSubDownloaderWidget.reloadList refresh[%s], selIndex[%s]" %
            (refresh, selIndex))
        if 0 < refresh and 0 < selIndex:
            self.nextSelIndex = selIndex

        if ret.status != RetHost.OK:
            printDBG("++++++++++++++++++++++ reloadList ret.status = %s" %
                     ret.status)

        self.currList = ret.value
        self["list"].setList([(x, ) for x in self.currList])

        self["headertext"].setText(self.getCategoryPath())
        if len(self.currList) <= 0:
            disMessage = _("No item to display. \nPress OK to refresh.\n")
            if ret.message and ret.message != '':
                disMessage += ret.message
            lastErrorMsg = GetIPTVPlayerLastHostError()
            if lastErrorMsg != '':
                disMessage += "\n" + _('Last error: "%s"') % lastErrorMsg
            disMessage += '\n\n' + _('Simplify the title and try again.')

            self["statustext"].setText(disMessage)
            self["list"].hide()
        else:
            #restor previus selection
            if len(self.currList) > self.nextSelIndex:
                self["list"].moveToIndex(self.nextSelIndex)
            #else:
            #selection will not be change so manualy call
            self.changeBottomPanel()

            self["statustext"].setText("")
            self["list"].show()

    #end reloadList(self, ret):

    def listSubtitlesProviders(self):
        printDBG("IPTVSubDownloaderWidget.listSubtitlesProviders")
        subProvidersList = []
        napisy24pl = {'title': "Napisy24.pl", 'sub_provider': 'napisy24pl'}
        openSubtitles = {
            'title': "OpenSubtitles.org API",
            'sub_provider': 'opensubtitlesorg'
        }
        openSubtitles2 = {
            'title': "OpenSubtitles.org WWW",
            'sub_provider': 'opensubtitlesorg2'
        }
        openSubtitles3 = {
            'title': "OpenSubtitles.org REST",
            'sub_provider': 'opensubtitlesorg3'
        }
        napiprojektpl = {
            'title': "Napiprojekt.pl",
            'sub_provider': 'napiprojektpl'
        }
        podnapisinet = {
            'title': "Podnapisi.net",
            'sub_provider': 'podnapisinet'
        }
        titlovi = {'title': "Titlovi.com", 'sub_provider': 'titlovicom'}
        subscene = {'title': "Subscene.com", 'sub_provider': 'subscenecom'}
        youtube = {'title': "Youtube.com", 'sub_provider': 'youtubecom'}
        popcornsubtitles = {
            'title': "PopcornSubtitles.com",
            'sub_provider': 'popcornsubtitles'
        }
        subtitlesgr = {'title': "Subtitles.gr", 'sub_provider': 'subtitlesgr'}
        prijevodi = {
            'title': "Prijevodi-Online.org",
            'sub_provider': 'prijevodi'
        }
        subsro = {'title': "Subs.ro", 'sub_provider': 'subsro'}

        defaultLang = GetDefaultLang()

        if 'youtube_id' in self.params['url_params'] and '' != self.params[
                'url_params']['youtube_id']:
            subProvidersList.append(youtube)

        if 'popcornsubtitles_url' in self.params[
                'url_params'] and '' != self.params['url_params'][
                    'popcornsubtitles_url']:
            subProvidersList.append(popcornsubtitles)

        if 'hr' == defaultLang:
            subProvidersList.append(prijevodi)

        if 'el' == defaultLang:
            subProvidersList.append(subtitlesgr)

        if 'ro' == defaultLang:
            subProvidersList.append(subsro)

        if 'pl' == defaultLang:
            subProvidersList.append(napisy24pl)
            if IsSubtitlesParserExtensionCanBeUsed():
                subProvidersList.append(napiprojektpl)

        subProvidersList.append(openSubtitles2)
        subProvidersList.append(openSubtitles3)
        subProvidersList.append(openSubtitles)
        subProvidersList.append(podnapisinet)
        subProvidersList.append(titlovi)
        subProvidersList.append(subscene)

        if 'pl' != defaultLang:
            subProvidersList.append(napisy24pl)
            if IsSubtitlesParserExtensionCanBeUsed():
                subProvidersList.append(napiprojektpl)

        if 'el' != defaultLang:
            subProvidersList.append(subtitlesgr)

        if 'hr' != defaultLang:
            subProvidersList.append(prijevodi)

        if 'ro' != defaultLang:
            subProvidersList.append(subsro)

        self.currList = []
        for item in subProvidersList:
            params = CDisplayListItem(item['title'], item.get('desc', ''),
                                      CDisplayListItem.TYPE_SUB_PROVIDER)
            params.privateData = {'sub_provider': item['sub_provider']}
            self.currList.append(params)

        idx = 0
        selIndex = 0
        for idx in range(len(self.currList)):
            if self.hostName == self.currList[idx].privateData['sub_provider']:
                selIndex = idx
                break

        self["list"].setList([(x, ) for x in self.currList])
        #restor previus selection
        if len(self.currList) > selIndex:
            self["list"].moveToIndex(selIndex)
        self.changeBottomPanel()
        self["headertext"].setText(self.getCategoryPath())
        self["statustext"].setText("")
        self["list"].show()

    def changeBottomPanel(self):
        selItem = self.getSelItem()
        if selItem and selItem.description != '':
            data = selItem.description
            sData = data.replace('\n', '')
            sData = data.replace('[/br]', '\n')
            self["console"].setText(sData)
        else:
            self["console"].setText(
                _('Searching subtitles for "%s"') % self.params['movie_title'])

    def onSelectionChanged(self):
        self.changeBottomPanel()

    def isInWorkThread(self):
        return None != self.workThread and (not self.workThread.isFinished()
                                            or self.workThread.isAlive())

    def getSelItem(self):
        currSelIndex = self["list"].getCurrentIndex()
        if len(self.currList) <= currSelIndex:
            printDBG(
                "ERROR: getSelItem there is no item with index: %d, listOfItems.len: %d"
                % (currSelIndex, len(self.currList)))
            return None
        return self.currList[currSelIndex]

    def hideWindow(self):
        self.visible = False
        self.hide()

    def showWindow(self):
        self.visible = True
        self.show()

    def discoverInfoFromTitle(self, movieTitle=None):
        dInfo = {'movie_title': None, 'season': None, 'episode': None}
        if movieTitle == None:
            movieTitle = self.params.get('movie_title', '')

        # discovered information
        dInfo = {'movie_title': None, 'season': None, 'episode': None}
        dInfo['movie_title'] = CParsingHelper.getNormalizeStr(movieTitle)
        # try to guess season and episode number
        try:
            tmp = CParsingHelper.getSearchGroups(
                ' ' + dInfo['movie_title'] + ' ', 's([0-9]+?)e([0-9]+?)[^0-9]',
                2)
            dInfo.update({'season': int(tmp[0]), 'episode': int(tmp[1])})
        except Exception:
            try:
                tmp = CParsingHelper.getSearchGroups(
                    ' ' + dInfo['movie_title'] + ' ',
                    '[^0-9]([0-9]+?)x([0-9]+?)[^0-9]', 2)
                dInfo.update({'season': int(tmp[0]), 'episode': int(tmp[1])})
            except Exception:
                pass
        return dInfo
    def __init__(self,
                 session,
                 url,
                 pathForRecordings,
                 pictureTitle,
                 addParams={}):
        self.session = session
        Screen.__init__(self, session)
        self.onStartCalled = False

        self.recordingPath = pathForRecordings
        try:
            self.filePath = os.path.join(pathForRecordings,
                                         '.iptv_buffering.jpg')
        except Exception:
            self.filePath = ''
            printExc()

        self.addParams = {'seq_mode': False}
        self.addParams.update(addParams)

        self.url = url
        self.pictureTitle = pictureTitle
        self.audioUrl = strwithmeta(url).meta.get("iptv_audio_url", '')

        self["actions"] = ActionMap(
            [
                'IPTVAlternateVideoPlayer', 'MoviePlayerActions',
                'MediaPlayerActions', 'WizardActions', 'DirectionActions'
            ], {
                'leavePlayer': self.key_exit,
                'play': self.key_play,
                'pause': self.key_pause,
                'exit': self.key_exit,
                'back': self.key_exit,
                'ok': self.key_ok,
            }, -1)

        self["status"] = Label()
        self["console"] = Label()
        self["icon"] = SimpleAnimatedCover()
        self["picture"] = Cover()

        # prepare icon frames path
        frames = []
        for idx in range(1, self.NUM_OF_ICON_FRAMES + 1):
            frames.append(GetIconDir('/buffering/buffering_%d.png' % idx))
        self["icon"].loadFrames(frames)

        #main Timer
        self.mainTimer = eTimer()
        self.mainTimerEnabled = False

        if self.addParams['seq_mode']:
            self.canAutoClose = True
            self.mainTimer_conn = eConnectCallback(self.mainTimer.timeout,
                                                   self.closeAfterTimeout)
            self.mainTimerInterval = 1000 * 10  #10s
        else:
            self.mainTimer_conn = eConnectCallback(self.mainTimer.timeout,
                                                   self.updateDisplay)
            self.mainTimerInterval = 100  # by default 0,1s
        # download
        self.downloader = DownloaderCreator(self.url)

        self.onClose.append(self.__onClose)
        self.onShow.append(self.doStart)
        #self.onLayoutFinish.append(self.doStart)

        self.autoRefresh = False
        self.refreshPostfixes = ['_0', '_1']
        self.refreshCount = 0
        self.refreshing = False

        if len(self.audioUrl) and len(
                config.plugins.iptvplayer.gstplayerpath.value):
            self.audioPlayer = IPTVSimpleAudioPlayer()
        else:
            self.audioPlayer = None
    def __init__(self, session, title="", text="", additionalParams={}):
        winWidth = 590
        self.skin = '''<screen position="center,center" size="%d,500" title="" >
                           <widget name="captcha" position="%d,%d" size="%d,%d" zPosition="2" transparent="1" alphatest="on" />
                           
                           <widget name="key_red"   position="10,10" zPosition="2" size="%d,35" valign="center" halign="left"   font="Regular;22" transparent="1" foregroundColor="red" />
                           <widget name="key_ok"    position="10,10" zPosition="2" size="%d,35" valign="center" halign="center" font="Regular;22" transparent="1" foregroundColor="white" />
                           <widget name="key_green" position="10,10" zPosition="2" size="%d,35" valign="center" halign="right"  font="Regular;22" transparent="1" foregroundColor="green" />
                           
                           <ePixmap pixmap="%s"  position="25,195" size="542,80" zPosition="-4" alphatest="on" />
                           <widget name="header" position="25,160" size="500,26" transparent="1" noWrap="1" font="Regular;20" valign="top"/>
                           <widget name="text"   position="25,200" size="536,34" transparent="1" noWrap="1" font="Regular;26" valign="center" halign="right" />
                           <widget name="list"   position="25,250" size="550,225" selectionDisabled="1" transparent="1" />
                       </screen>
                    ''' % ( winWidth, 10, 55, \
                            winWidth - 20, 100, \
                            winWidth-20, \
                            winWidth-20, \
                            winWidth-20, \
                            GetIconDir("vk/vkey_text.png"))
        
        Screen.__init__(self, session)
        self.keys_list = []
        self.shiftkeys_list = []
        self.shiftMode = additionalParams.get('shift_mode', False)
        self.selectedKey = 0
        self.smsChar = None
        self.sms = NumericalTextInput(self.smsOK)
        
        self.key_bg        = LoadPixmap(GetIconDir("vk/vkey_bg.png"))
        self.key_sel       = LoadPixmap(GetIconDir("vk/vkey_sel.png"))
        self.key_backspace = LoadPixmap(GetIconDir("vk/vkey_backspace.png"))
        self.key_all       = LoadPixmap(GetIconDir("vk/vkey_all.png"))
        self.key_clr       = LoadPixmap(GetIconDir("vk/vkey_clr.png"))
        self.key_esc       = LoadPixmap(GetIconDir("vk/vkey_esc.png"))
        self.key_ok        = LoadPixmap(GetIconDir("vk/vkey_ok.png"))
        self.key_shift     = LoadPixmap(GetIconDir("vk/vkey_shift.png"))
        self.key_shift_sel = LoadPixmap(GetIconDir("vk/vkey_shift_sel.png"))
        self.key_space     = LoadPixmap(GetIconDir("vk/vkey_space.png"))
        self.key_left      = LoadPixmap(GetIconDir("vk/vkey_left.png"))
        self.key_right     = LoadPixmap(GetIconDir("vk/vkey_right.png"))

        self.keyImages =  {
                "BACKSPACE": self.key_backspace,
                "CLEAR":     self.key_clr,
                "ALL":       self.key_all,
                "EXIT":      self.key_esc,
                "OK":        self.key_ok,
                "SHIFT":     self.key_shift,
                "SPACE":     self.key_space,
                "LEFT":      self.key_left,
                "RIGHT":     self.key_right
            }
        self.keyImagesShift = {
                "BACKSPACE": self.key_backspace,
                "CLEAR":     self.key_clr,
                "ALL":       self.key_all,
                "EXIT":      self.key_esc,
                "OK":        self.key_ok,
                "SHIFT":     self.key_shift_sel,
                "SPACE":     self.key_space,
                "LEFT":      self.key_left,
                "RIGHT":     self.key_right
            }
            
        self["key_green"] = Label(_("Accept"))
        self["key_ok"]    = Label(_("OK"))
        self["key_red"]   = Label(_("Cancel"))
        
        self["header"] = Label(title)
        self["text"]   = Input(text=text.decode("utf-8",'ignore'))
        self["list"]   = VirtualKeyBoardList([])
        
        self["actions"] = NumberActionMap(["OkCancelActions", "WizardActions", "ColorActions", "KeyboardInputActions", "InputBoxActions", "InputAsciiActions"],
            {
                "gotAsciiCode": self.keyGotAscii,
                "ok":     self.okClicked,
                "cancel": self.exit,
                "left":   self.left,
                "right":  self.right,
                "up":     self.up,
                "down":   self.down,
                "red":    self.exit,
                "green":  self.ok,
                "yellow": self.switchLang,
                "blue":   self.shiftClicked,
                "deleteBackward": self.backClicked,
                "deleteForward":  self.forwardClicked,
                "back":     self.exit,
                "pageUp":   self.cursorRight,
                "pageDown": self.cursorLeft,
                "1": self.keyNumberGlobal,
                "2": self.keyNumberGlobal,
                "3": self.keyNumberGlobal,
                "4": self.keyNumberGlobal,
                "5": self.keyNumberGlobal,
                "6": self.keyNumberGlobal,
                "7": self.keyNumberGlobal,
                "8": self.keyNumberGlobal,
                "9": self.keyNumberGlobal,
                "0": self.keyNumberGlobal,
            }, -2)
        self.startText = text
        self.setLang(additionalParams)
        self.onExecBegin.append(self.setKeyboardModeAscii)
        self.onLayoutFinish.append(self.buildVirtualKeyBoard)
        
        self.captchaPath = additionalParams['captcha_path']
        self['captcha'] = Cover2()
        self.onShown.append(self.loadCaptcha)