Example #1
0
    def readConfig(self):
        self.log('readConfig')
        # Sleep setting is in 30 minute incriments...so multiply by 30, and then 60 (min to sec)
        self.sleepTimeValue = int(REAL_SETTINGS.getSetting('AutoOff')) * 1800
        self.log('Auto off is ' + str(self.sleepTimeValue))
        self.infoOnChange = REAL_SETTINGS.getSetting("InfoOnChange") == "true"
        self.log('Show info label on channel change is ' + str(self.infoOnChange))
        self.showChannelBug = REAL_SETTINGS.getSetting("ShowChannelBug") == "true"
        self.log('Show channel bug - ' + str(self.showChannelBug))
        self.forceReset = REAL_SETTINGS.getSetting('ForceChannelReset') == "true"
        self.channelResetSetting = REAL_SETTINGS.getSetting('ChannelResetSetting')
        self.log("Channel reset setting - " + str(self.channelResetSetting))
        self.channelLogos = xbmc.translatePath(REAL_SETTINGS.getSetting('ChannelLogoFolder'))

        if os.path.exists(self.channelLogos) == False:
            self.channelLogos = IMAGES_LOC

        self.log('Channel logo folder - ' + self.channelLogos)
        self.startupTime = time.time()
        chn = ChannelList()
        self.background.setVisible(True)
        self.channels = chn.setupList()

        if self.channels is None:
            self.log('readConfig No channel list returned')
            self.end()
            return False

        self.Player.stop()
        self.log('readConfig return')
        return True
 def __init__(self):
     threading.Thread.__init__(self)
     self.myOverlay = None
     sys.setcheckinterval(25)
     self.chanlist = ChannelList()
     self.paused = False
     self.fullUpdating = True
 def __init__(self):
     threading.Thread.__init__(self)
     self.myOverlay = None
     sys.setcheckinterval(25)
     self.chanlist = ChannelList()
     self.paused = False
     self.fullUpdating = True
 def __init__(self):
     threading.Thread.__init__(self)
     self.myOverlay = None
     self.shouldExit = False
     sys.setcheckinterval(25)
     self.chanlist = ChannelList()
     self.chanlist.sleepTime = 0.1
Example #5
0
    def readConfig(self):
        self.log('readConfig')
        # Sleep setting is in 30 minute incriments...so multiply by 30, and then 60 (min to sec)
        self.sleepTimeValue = int(ADDON.getSetting('AutoOff')) * 1800
        self.log('Auto off is ' + str(self.sleepTimeValue))
        self.infoOnChange = ADDON.getSetting("InfoOnChange") == "true"
        self.infoDuration = INFO_DUR[int(ADDON.getSetting("InfoLength"))]
        self.log('Show info label on channel change is ' +
                 str(self.infoOnChange))
        self.showChannelBug = ADDON.getSetting("ShowChannelBug") == "true"
        self.channelBugPosition = CHANNELBUG_POS[int(
            ADDON.getSetting("ChannelBugPosition"))]
        self.log('Show channel bug - ' + str(self.showChannelBug))
        self.forceReset = ADDON.getSetting('ForceChannelReset') == "true"
        self.channelResetSetting = ADDON.getSetting('ChannelResetSetting')
        self.log("Channel reset setting - " + str(self.channelResetSetting))
        self.channelLogos = xbmc.translatePath(
            ADDON.getSetting('ChannelLogoFolder'))
        self.backgroundUpdating = int(ADDON.getSetting("ThreadMode"))
        self.log("Background updating - " + str(self.backgroundUpdating))
        self.showNextItem = ADDON.getSetting("EnableComingUp") == "true"
        self.log("Show Next Item - " + str(self.showNextItem))
        self.hideShortItems = ADDON.getSetting("HideClips") == "true"
        self.log("Hide Short Items - " + str(self.hideShortItems))
        self.shortItemLength = SHORT_CLIP_ENUM[int(
            ADDON.getSetting("ClipLength"))]
        self.seekForward = SEEK_FORWARD[int(ADDON.getSetting("SeekForward"))]
        self.seekBackward = SEEK_BACKWARD[int(
            ADDON.getSetting("SeekBackward"))]
        self.log("Short item length - " + str(self.shortItemLength))

        if FileAccess.exists(self.channelLogos) == False:
            self.channelLogos = LOGOS_LOC

        self.log('Channel logo folder - ' + self.channelLogos)
        self.channelList = ChannelList()
        self.channelList.myOverlay = self
        self.channels = self.channelList.setupList()

        if self.channels is None:
            self.log('readConfig No channel list returned')
            self.end()
            return False

        self.Player.stop()
        self.log('readConfig return')
        return True
Example #6
0
    def readConfig(self):
        self.log('readConfig')
        # Sleep setting is in 30 minute incriments...so multiply by 30, and then 60 (min to sec)
        self.sleepTimeValue = int(REAL_SETTINGS.getSetting('AutoOff')) * 1800
        self.log('Auto off is ' + str(self.sleepTimeValue))
        self.infoOnChange = REAL_SETTINGS.getSetting("InfoOnChange") == "true"
        self.log('Show info label on channel change is ' +
                 str(self.infoOnChange))
        self.showChannelBug = REAL_SETTINGS.getSetting(
            "ShowChannelBug") == "true"
        self.log('Show channel bug - ' + str(self.showChannelBug))
        self.forceReset = REAL_SETTINGS.getSetting(
            'ForceChannelReset') == "true"
        self.channelResetSetting = REAL_SETTINGS.getSetting(
            'ChannelResetSetting')
        self.log("Channel reset setting - " + str(self.channelResetSetting))
        self.channelLogos = xbmc.translatePath(
            REAL_SETTINGS.getSetting('ChannelLogoFolder'))
        self.backgroundUpdating = int(REAL_SETTINGS.getSetting("ThreadMode"))
        self.log("Background updating - " + str(self.backgroundUpdating))
        self.showNextItem = REAL_SETTINGS.getSetting(
            "EnableComingUp") == "true"
        self.log("Show Next Item - " + str(self.showNextItem))
        self.hideShortItems = REAL_SETTINGS.getSetting("HideClips") == "true"
        self.log("Hide Short Items - " + str(self.hideShortItems))
        self.shortItemLength = SHORT_CLIP_ENUM[int(
            REAL_SETTINGS.getSetting("ClipLength"))]
        self.log("Short item length - " + str(self.shortItemLength))
        self.channelDelay = int(REAL_SETTINGS.getSetting("ChannelDelay")) * 250

        if FileAccess.exists(self.channelLogos) == False:
            self.channelLogos = IMAGES_LOC

        self.log('Channel logo folder - ' + self.channelLogos)
        chn = ChannelList()
        chn.myOverlay = self
        self.channels = chn.setupList()

        if self.channels is None:
            self.log('readConfig No channel list returned')
            self.end()
            return False

        self.Player.stop()
        self.log('readConfig return')
        return True
Example #7
0
    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        xbmc.executebuiltin("ActivateWindow(busydialog)")
        chnlst = ChannelList()
        chnlst.fillTVInfo()
        chnlst.fillMovieInfo()
        self.mixedGenreList = chnlst.makeMixedList(chnlst.showGenreList,
                                                   chnlst.movieGenreList)
        self.networkList = chnlst.networkList
        self.studioList = chnlst.studioList
        self.showGenreList = chnlst.showGenreList
        self.movieGenreList = chnlst.movieGenreList

        for i in range(len(chnlst.showList)):
            self.showList.append(chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())
        self.listcontrol = self.getControl(102)

        for i in range(999):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)

        self.updateListing()
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        self.getControl(105).setVisible(True)
        self.getControl(106).setVisible(False)
        self.setFocusId(102)
        self.log("prepareConfig return")
Example #8
0
    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        BUSY.create()
        chnlst = ChannelList()
        chnlst.fillTVInfo()
        chnlst.fillMovieInfo()
        self.mixedGenreList = chnlst.makeMixedList(chnlst.showGenreList, chnlst.movieGenreList)
        self.networkList = chnlst.networkList
        self.studioList = chnlst.studioList
        self.showGenreList = chnlst.showGenreList
        self.movieGenreList = chnlst.movieGenreList

        for i in range(len(chnlst.showList)):
            self.showList.append(chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())
        self.listcontrol = self.getControl(102)

        for i in range(999):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)

        self.updateListing()
        BUSY.close()
        self.getControl(105).setVisible(True)
        self.getControl(106).setVisible(False)
        self.setFocusId(102)
        self.log("prepareConfig return")
Example #9
0
    def readConfig(self):
        self.log('readConfig')
        # Sleep setting is in 30 minute incriments...so multiply by 30, and then 60 (min to sec)
        self.sleepTimeValue = int(REAL_SETTINGS.getSetting('AutoOff')) * 1800
        self.log('Auto off is ' + str(self.sleepTimeValue))
        self.infoOnChange = REAL_SETTINGS.getSetting("InfoOnChange") == "true"
        self.log('Show info label on channel change is ' + str(self.infoOnChange))
        self.showChannelBug = REAL_SETTINGS.getSetting("ShowChannelBug") == "true"
        self.log('Show channel bug - ' + str(self.showChannelBug))
        self.forceReset = REAL_SETTINGS.getSetting('ForceChannelReset') == "true"
        self.channelResetSetting = REAL_SETTINGS.getSetting('ChannelResetSetting')
        self.log("Channel reset setting - " + str(self.channelResetSetting))
        self.channelLogos = xbmc.translatePath(REAL_SETTINGS.getSetting('ChannelLogoFolder'))
        self.backgroundUpdating = int(REAL_SETTINGS.getSetting("ThreadMode"))
        self.log("Background updating - " + str(self.backgroundUpdating))
        self.showNextItem = REAL_SETTINGS.getSetting("EnableComingUp") == "true"
        self.log("Show Next Item - " + str(self.showNextItem))
        self.hideShortItems = REAL_SETTINGS.getSetting("HideClips") == "true"
        self.log("Hide Short Items - " + str(self.hideShortItems))
        self.shortItemLength = SHORT_CLIP_ENUM[int(REAL_SETTINGS.getSetting("ClipLength"))]
        self.log("Short item length - " + str(self.shortItemLength))
        self.channelDelay = int(REAL_SETTINGS.getSetting("ChannelDelay")) * 250

        if FileAccess.exists(self.channelLogos) == False:
            self.channelLogos = IMAGES_LOC

        self.log('Channel logo folder - ' + self.channelLogos)
        chn = ChannelList()
        chn.myOverlay = self
        self.channels = chn.setupList()

        if self.channels is None:
            self.log('readConfig No channel list returned')
            self.end()
            return False

        self.Player.stop()
        self.log('readConfig return')
        return True
Example #10
0
class ConfigWindow(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.log("__init__")
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        self.setCoordinateResolution(1)
        self.showingList = True
        self.channel = 0
        self.channel_type = 9999
        self.setting1 = ''
        self.setting2 = ''
        ### TV TIME ###
        self.setting3 = ''
        self.setting4 = ''
        self.setting5 = ''
        self.setting6 = ''
        self.setting7 = ''
        self.setting8 = ''
        self.setting9 = ''        
        ###############
        self.doModal()
        self.log("__init__ return")


    def log(self, msg, level = xbmc.LOGDEBUG):
        log('ChannelConfig: ' + msg, level)


    def onInit(self):
        self.log("onInit")

        ### TV TIME ###
        self.getControl(105).setVisible(False) # Channel Listing Control Group
        self.getControl(106).setVisible(False) # Channel Settings Control Group        
        ###############

        for i in range(NUMBER_CHANNEL_TYPES):
            self.getControl(120 + i).setVisible(False)

        migrate()
        self.prepareConfig()
        self.log("onInit return")


    def onFocus(self, controlId):
        pass


    def onAction(self, act):
        action = act.getId()

        if action == ACTION_PREVIOUS_MENU:
            if self.showingList == False:
                self.cancelChan()
                self.hideChanDetails()
            else:
                self.close()


    def saveSettings(self):
        self.log("saveSettings channel " + str(self.channel))
        chantype = 9999
        chan = str(self.channel)
        set1 = ''
        set2 = ''

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + chan + "_type"))
        except:
            self.log("Unable to get channel type")

        setting1 = "Channel_" + chan + "_1"
        setting2 = "Channel_" + chan + "_2"
        ### TV TIME ###
        setting3 = "Channel_" + chan + "_3" # Channel Name
        setting4 = "Channel_" + chan + "_4" # 
        setting5 = "Channel_" + chan + "_5"
        setting6 = "Channel_" + chan + "_6"
        setting7 = "Channel_" + chan + "_7"
        setting8 = "Channel_" + chan + "_8"
        setting9 = "Channel_" + chan + "_9"        
        ###############
        if chantype == 0:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(130).getLabel2())
            ### TV TIME ###
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(130).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            ###############
        elif chantype == 1:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(142).getLabel())
            ### TV TIME ###
            if self.getControl(349).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(142).getLabel()))
            if self.getControl(346).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(347).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(343).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            if self.getControl(348).isSelected():
                ADDON_SETTINGS.setSetting(setting9, str(MODE_RANDOM_FILELISTS))
            else:
                ADDON_SETTINGS.setSetting(setting9, 0)
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
            ###############
        elif chantype == 2:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(152).getLabel())
            ### TV TIME ###
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(152).getLabel()))
            if self.getControl(356).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, self.getControl(353).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
            ###############
        elif chantype == 3:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(162).getLabel())
            ### TV TIME ###
            if self.getControl(369).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(162).getLabel()) + ' TV')
            if self.getControl(366).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(367).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(363).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
            ###############            
        elif chantype == 4:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(172).getLabel())
            ### TV TIME ###
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(172).getLabel()) + ' Movies')
            if self.getControl(376).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, self.getControl(373).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
            ###############            
        elif chantype == 5:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(182).getLabel())
            ### TV TIME ###
            if self.getControl(389).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(182).getLabel()) + ' Mix')
            if self.getControl(386).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(387).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(383).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
            ###############            
        elif chantype == 6:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(192).getLabel())

            ### TV TIME ###
            #if self.getControl(194).isSelected():
            #    ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            if self.getControl(194).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(192).getLabel()))
            if self.getControl(396).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(397).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(393).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
            ###############            
        ### TV TIME ###
        if chantype == 7: # folder
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(200).getLabel2()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(200).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
        if chantype == 8: # music
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(212).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(212).getLabel()) + ' Music')
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')
        if chantype == 9: # live
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(222).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(222).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')        
        ###############            
        elif chantype == 9999:
            ADDON_SETTINGS.setSetting(setting1, '')
            ADDON_SETTINGS.setSetting(setting2, '')
            ### TV TIME ###
            ADDON_SETTINGS.setSetting(setting3, '')
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            #ADDON_SETTINGS.setSetting(settingtime, 0)
            #ADDON_SETTINGS.setSetting(playlist, '')
            #ADDON_SETTINGS.setSetting(totalDuration, '')            
            ###############            

        # Check to see if the user changed anything
        set1 = ''
        set2 = ''
        ### TV TIME ###
        set3 = ''
        set4 = ''
        set5 = ''
        set6 = ''
        set7 = ''
        set8 = ''
        set9 = ''
        ###############            

        try:
            set1 = ADDON_SETTINGS.getSetting(setting1)
            set2 = ADDON_SETTINGS.getSetting(setting2)
            ### TV TIME ###
            set3 = ADDON_SETTINGS.getSetting(setting3)
            set4 = ADDON_SETTINGS.getSetting(setting4)
            set5 = ADDON_SETTINGS.getSetting(setting5)
            set6 = ADDON_SETTINGS.getSetting(setting6)
            set7 = ADDON_SETTINGS.getSetting(setting7)
            set8 = ADDON_SETTINGS.getSetting(setting8)
            set9 = ADDON_SETTINGS.getSetting(setting9)            
            ###############            
        except:
            pass


        ### TV TIME ###
        #if chantype != self.channel_type or set1 != self.setting1 or set2 != self.setting2:
        #    ADDON_SETTINGS.setSetting('Channel_' + chan + '_changed', 'True')
        if ( chantype != self.channel_type or 
            set1 != self.setting1 or 
            set2 != self.setting2 or 
            set3 != self.setting3 or 
            set4 != self.setting4 or 
            set5 != self.setting5 or 
            set6 != self.setting6 or 
            set7 != self.setting7 or 
            set8 != self.setting8 or 
            set9 != self.setting9
            ):
            ADDON_SETTINGS.setSetting('Channel_' + chan + '_changed', 'True')

        ADDON_SETTINGS.writeSettings()
        
        self.log("saveSettings return")


    def cancelChan(self):
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_type", str(self.channel_type))
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_1", self.setting1)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_2", self.setting2)
        ### TV TIME ###
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_3", self.setting3)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_4", self.setting4)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_5", self.setting5)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_6", self.setting6)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_7", self.setting7)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_8", self.setting8)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_9", self.setting9)
        ###############
        

    def hideChanDetails(self):
        self.getControl(106).setVisible(False)

        for i in range(NUMBER_CHANNEL_TYPES):
            self.getControl(120 + i).setVisible(False)

        self.setFocusId(102)
        self.getControl(105).setVisible(True)
        self.showingList = True
        self.updateListing(self.channel)
        self.listcontrol.selectItem(self.channel - 1)


    def onClick(self, controlId):
        self.log("onClick " + str(controlId))

        if controlId == 102:
            self.getControl(105).setVisible(False)
            self.getControl(106).setVisible(True)
            self.channel = self.listcontrol.getSelectedPosition() + 1
            self.changeChanType(self.channel, 0)
            self.setFocusId(110)
            self.showingList = False
        elif controlId == 110:
            self.changeChanType(self.channel, -1)
        elif controlId == 111:
            self.changeChanType(self.channel, 1)
        elif controlId == 112:
            self.saveSettings()
            self.hideChanDetails()
        elif controlId == 113:
            self.cancelChan()
            self.hideChanDetails()
        elif controlId == 130:
            dlg = xbmcgui.Dialog()
            retval = dlg.browse(1, "Channel " + str(self.channel) + " Playlist", "files", ".xsp", False, False, "special://videoplaylists/")

            if retval != "special://videoplaylists/":
                self.getControl(130).setLabel(self.getSmartPlaylistName(retval), label2=retval)
        elif controlId == 140:
            self.changeListData(self.networkList, 142, -1)
        elif controlId == 141:
            self.changeListData(self.networkList, 142, 1)
        elif controlId == 150:
            self.changeListData(self.studioList, 152, -1)
        elif controlId == 151:
            self.changeListData(self.studioList, 152, 1)
        elif controlId == 160:
            self.changeListData(self.showGenreList, 162, -1)
        elif controlId == 161:
            self.changeListData(self.showGenreList, 162, 1)
        elif controlId == 170:
            self.changeListData(self.movieGenreList, 172, -1)
        elif controlId == 171:
            self.changeListData(self.movieGenreList, 172, 1)
        elif controlId == 180:
            self.changeListData(self.mixedGenreList, 182, -1)
        elif controlId == 181:
            self.changeListData(self.mixedGenreList, 182, 1)
        elif controlId == 190:
            self.changeListData(self.showList, 192, -1)
        elif controlId == 191:
            self.changeListData(self.showList, 192, 1)
        ### TV TIME ###
        elif controlId == 200: # Folder Channel
            dlg = xbmcgui.Dialog()
            # need to replace this with folder instead of file
            retval = dlg.browse(0, "Channel " + str(self.channel) + " Folder", "files", "*.*", False, False, "")
            if retval != "":
                # smb isn't supported at this time but it is here
                # as a placeholder if a solution can be found
                # for connecting to smb shares from python
                if retval.find("smb://") == -1:
                    ps = retval.split(os.sep)
                else:
                    ps = retval.split('/')
                chanName = ""
                for i in range(len(ps)-1):
                    chanName = ps[i]
                self.getControl(200).setLabel(chanName, label2=retval)        
        elif controlId == 210: # Music Based Channel
            self.changeListData(self.musicGenreList, 212, -1)
        elif controlId == 211:
            self.changeListData(self.musicGenreList, 212, 1)
        elif controlId == 220: # Live Channel
            self.changeListData(self.feedList, 222, -1)
        elif controlId == 221:
            self.changeListData(self.feedList, 222, 1)
        elif controlId == 344:
            self.changeListData(self.resolutionList, 343, -1)
        elif controlId == 345:
            self.changeListData(self.resolutionList, 343, 1)
        elif controlId == 354:
            self.changeListData(self.resolutionList, 353, -1)
        elif controlId == 355:
            self.changeListData(self.resolutionList, 353, 1)
        elif controlId == 364:
            self.changeListData(self.resolutionList, 363, -1)
        elif controlId == 365:
            self.changeListData(self.resolutionList, 363, 1)
        elif controlId == 374:
            self.changeListData(self.resolutionList, 373, -1)
        elif controlId == 375:
            self.changeListData(self.resolutionList, 373, 1)
        elif controlId == 384:
            self.changeListData(self.resolutionList, 383, -1)
        elif controlId == 385:
            self.changeListData(self.resolutionList, 383, 1)
        elif controlId == 394:
            self.changeListData(self.resolutionList, 393, -1)
        elif controlId == 395:
            self.changeListData(self.resolutionList, 393, 1)
        elif controlId == 489:
            self.changeListData(self.showseqList, 488, -1)
        elif controlId == 490:
            self.changeListData(self.showseqList, 488, 1)
        elif controlId == 492:
            self.changeListData(self.movieseqList, 491, -1)
        elif controlId == 493:
            self.changeListData(self.movieseqList, 491, 1)        
        ###############
        
        self.log("onClick return")


    def changeListData(self, thelist, controlid, val):
        self.log("changeListData " + str(controlid) + ", " + str(val))
        curval = self.getControl(controlid).getLabel()
        found = False
        index = 0
        
        if len(thelist) == 0:
            self.getControl(controlid).setLabel('')
            self.log("changeListData return Empty list")
            return

        for item in thelist:
            if item == curval:
                found = True
                break

            index += 1

        if found == True:
            index += val

        while index < 0:
            index += len(thelist)

        while index >= len(thelist):
            index -= len(thelist)

        self.getControl(controlid).setLabel(thelist[index])
        self.log("changeListData return")


    def getSmartPlaylistName(self, fle):
        self.log("getSmartPlaylistName " + fle)
        fle = xbmc.translatePath(fle)

        try:
            xml = open(fle, "r")
        except:
            self.log('Unable to open smart playlist')
            return ''

        try:
            dom = parse(xml)
        except:
            xml.close()
            self.log("getSmartPlaylistName return unable to parse")
            return ''

        xml.close()

        try:
            plname = dom.getElementsByTagName('name')
            self.log("getSmartPlaylistName return " + plname[0].childNodes[0].nodeValue)
            return plname[0].childNodes[0].nodeValue
        except:
            self.playlisy('Unable to find element name')

        self.log("getSmartPlaylistName return")


    def changeChanType(self, channel, val):
        self.log("changeChanType " + str(channel) + ", " + str(val))
        chantype = 9999

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_type"))
        except:
            self.log("Unable to get channel type")

        if val != 0:
            chantype += val

            if chantype < 0:
                chantype = 9999
            elif chantype == 10000:
                chantype = 0
            elif chantype == 9998:
                chantype = NUMBER_CHANNEL_TYPES - 1
            elif chantype == NUMBER_CHANNEL_TYPES:
                chantype = 9999

            ADDON_SETTINGS.setSetting("Channel_" + str(channel) + "_type", str(chantype))
        else:
            self.channel_type = chantype
            self.setting1 = ''
            self.setting2 = ''
            ### TV TIME ###
            self.setting3 = ''
            self.setting4 = ''
            self.setting5 = ''
            self.setting6 = ''
            self.setting7 = ''
            self.setting8 = ''
            self.setting9 = ''            
            ###############

            try:
                self.setting1 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_1")
                self.setting2 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_2")
                ### TV TIME ###
                self.setting3 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_3")
                self.setting4 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_4")
                self.setting5 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_5")
                self.setting6 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_6")
                self.setting7 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_7")
                self.setting8 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_8")
                self.setting9 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_9")
                ###############
            except:
                pass

        for i in range(NUMBER_CHANNEL_TYPES):
            if i == chantype:
                self.getControl(120 + i).setVisible(True)
                self.getControl(110).controlDown(self.getControl(120 + ((i + 1) * 10)))

                try:
                    self.getControl(111).controlDown(self.getControl(120 + ((i + 1) * 10 + 1)))
                except:
                    self.getControl(111).controlDown(self.getControl(120 + ((i + 1) * 10)))
            else:
                self.getControl(120 + i).setVisible(False)

        self.fillInDetails(channel)
        self.log("changeChanType return")


    def fillInDetails(self, channel):
        self.log("fillInDetails " + str(channel))
        self.getControl(104).setLabel("Channel " + str(channel))
        chantype = 9999
        chansetting1 = ''
        chansetting2 = ''
        ### TV TIME ###
        chansetting3 = ''
        chansetting4 = ''
        chansetting5 = ''
        chansetting6 = ''
        chansetting7 = ''
        chansetting8 = ''
        chansetting9 = ''
        ###############

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_type"))
            chansetting1 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_1")
            chansetting2 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_2")
            ### TV TIME ###
            chansetting3 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_3")
            chansetting4 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_4")
            chansetting5 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_5")
            chansetting6 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_6")
            chansetting7 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_7")
            chansetting8 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_8")
            chansetting9 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_9")
            ###############
        except:
            self.log("Unable to get some setting")

        ### TV TIME ###
        if chansetting2 == "": chansetting2 = 0
        if chansetting4 == "": chansetting4 = 0
        if chansetting5 == "": chansetting5 = 0
        if chansetting6 == "": chansetting6 = "All"
        #if chansetting7 == "": chansetting7 = 0
        #if chansetting8 == "": chansetting8 = 0
        if chansetting9 == "": chansetting9 = 0
        ###############

        self.getControl(109).setLabel(self.getChanTypeLabel(chantype))

        if chantype == 0:
            plname = self.getSmartPlaylistName(chansetting1)

            if len(plname) == 0:
                chansetting1 = ''

            self.getControl(130).setLabel(self.getSmartPlaylistName(chansetting1), label2=chansetting1)
        elif chantype == 1:
            self.getControl(142).setLabel(self.findItemInList(self.networkList, chansetting1))
            ### TV TIME ###
            self.getControl(343).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(349).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(346).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(347).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            if chansetting9 <> "":
                self.getControl(348).setSelected(int(chansetting9) == int(MODE_RANDOM_FILELISTS))            
            ###############
        elif chantype == 2:
            self.getControl(152).setLabel(self.findItemInList(self.studioList, chansetting1))
            ### TV TIME ###
            self.getControl(353).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(356).setSelected(int(chansetting4) == int(MODE_UNWATCHED))            
            ###############
        elif chantype == 3:
            self.getControl(162).setLabel(self.findItemInList(self.showGenreList, chansetting1))
            ### TV TIME ###
            self.getControl(363).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(369).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(366).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(367).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))            
            ###############
        elif chantype == 4:
            self.getControl(172).setLabel(self.findItemInList(self.movieGenreList, chansetting1))
            ### TV TIME ###
            self.getControl(373).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(376).setSelected(int(chansetting4) == int(MODE_UNWATCHED))            
            ###############
        elif chantype == 5:
            self.getControl(182).setLabel(self.findItemInList(self.mixedGenreList, chansetting1))
            ### TV TIME ###
            self.getControl(383).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(389).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(386).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(387).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            self.getControl(488).setLabel(self.findItemInList(self.showseqList, chansetting7))
            self.getControl(491).setLabel(self.findItemInList(self.movieseqList, chansetting8))            
            ###############
        elif chantype == 6:
            self.getControl(192).setLabel(self.findItemInList(self.showList, chansetting1))
            self.getControl(194).setSelected(chansetting2 == str(MODE_SERIAL))
            ### TV TIME ###
            self.getControl(393).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(396).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(397).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))            
            ###############
        ### TV TIME ###
        elif chantype == 7: # folder
            fldname = chansetting3
            if len(fldname) == 0:
                chansetting1 = ''
            self.getControl(200).setLabel(fldname, label2=self.chnlst.uncleanString(chansetting1))
        elif chantype == 8: # music
            self.getControl(212).setLabel(self.findItemInList(self.musicGenreList, chansetting1))
        elif chantype == 9: # live
            self.getControl(222).setLabel(self.findItemInList(self.feedList, chansetting1))
        ###############

        self.log("fillInDetails return")


    def findItemInList(self, thelist, item):
        ### TV TIME ###
        #loitem = item.lower()
        item = item.decode('utf-8')
        loitem = item.lower()
        ###############
        
        for i in thelist:
            ### TV TIME ###
            #if loitem == i.lower():
            i = i.decode('utf-8')
            if loitem == i.lower():
            ###############
                return item
                
        if len(thelist) > 0:
            return thelist[0]
            
        return ''


    def getChanTypeLabel(self, chantype):
        if chantype == 0:
            return "Custom Playlist"
        elif chantype == 1:
            return "TV Network"
        elif chantype == 2:
            return "Movie Studio"
        elif chantype == 3:
            return "TV Genre"
        elif chantype == 4:
            return "Movie Genre"
        elif chantype == 5:
            return "Mixed Genre"
        elif chantype == 6:
            return "TV Show"
        ### TV TIME ###
        elif chantype == 7:
            return "Folder"
        elif chantype == 8:
            return "Music Genre"
        elif chantype == 9:
            return "Live"        
        ###############
        elif chantype == 9999:
            return "None"

        return ''

    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        ### TV TIME ###
        #self.dlg = xbmcgui.DialogProgress()
        #self.dlg.create("PseudoTV", "Preparing Configuration")
        #self.dlg.update(1)
        #chnlst = ChannelList()
        #chnlst.fillTVInfo()
        #self.dlg.update(40)
        #chnlst.fillMovieInfo()
        #self.dlg.update(80)
        #self.mixedGenreList = chnlst.makeMixedList(chnlst.showGenreList, chnlst.movieGenreList)
        #self.networkList = chnlst.networkList
        #self.studioList = chnlst.studioList
        #self.showGenreList = chnlst.showGenreList
        #self.movieGenreList = chnlst.movieGenreList
        self.dlg = xbmcgui.DialogProgress()
        self.dlg.create("TV Time", "Preparing Channel Wizard")
        self.dlg.update(0, "Preparing Channel Wizard")
        self.chnlst = ChannelList()
        self.dlg.update(10, "Preparing Channel Wizard", "Loading TV Settings")
        self.chnlst.fillTVInfo()
        self.networkList = self.chnlst.networkList
        self.studioList = self.chnlst.studioList
        self.showGenreList = self.chnlst.showGenreList
        self.dlg.update(20, "Preparing Channel Wizard", "Loading Movie Settings")
        self.chnlst.fillMovieInfo()
        self.movieGenreList = self.chnlst.movieGenreList
        self.dlg.update(40, "Preparing Channel Wizard", "Loading Music Settings")
        self.chnlst.fillMusicInfo()
        self.musicGenreList = self.chnlst.musicGenreList        
        self.dlg.update(60, "Preparing Channel Wizard", "Loading Live Feed Settings")
        self.chnlst.fillFeedInfo()
        self.feedList = self.chnlst.feedList
        self.dlg.update(80, "Preparing Channel Wizard", "Loading Mixed Genre Settings")
        self.mixedGenreList = self.chnlst.makeMixedList(self.showGenreList, self.movieGenreList)        
        ###############

        for i in range(len(self.chnlst.showList)):
            self.showList.append(self.chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())
        self.listcontrol = self.getControl(102)

        for i in range(200):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)

        ### TV TIME ###
        self.resolutionList = []
        self.resolutionList.append('All')
        self.resolutionList.append('SD Only')
        self.resolutionList.append('720p or Higher')
        self.resolutionList.append('1080p Only')

        self.showseqList = []
        self.showseqList.append('1 Show')
        self.showseqList.append('2 Shows')
        self.showseqList.append('3 Shows')
        self.showseqList.append('4 Shows')
        self.showseqList.append('5 Shows')
        self.showseqList.append('6 Shows')
        self.showseqList.append('7 Shows')
        self.showseqList.append('8 Shows')
        self.showseqList.append('9 Shows')
        self.showseqList.append('10 Shows')

        self.movieseqList = []
        self.movieseqList.append('1 Movie')
        self.movieseqList.append('2 Movies')
        self.movieseqList.append('3 Movies')
        self.movieseqList.append('4 Movies')
        self.movieseqList.append('5 Movies')
        self.movieseqList.append('6 Movies')
        self.movieseqList.append('7 Movies')
        self.movieseqList.append('8 Movies')
        self.movieseqList.append('9 Movies')
        self.movieseqList.append('10 Movies')

        # check if settings2.xml file exists
        # read in channel playlists in video, music and mixed folders
        """
        channelNum = 0
        for i in range(500):
            if os.path.exists(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')),"")
        ADDON_SETTINGS.writeSettings()
        """
        ###############

        ### TV TIME ###
        #self.dlg.update(90)
        self.dlg.update(90, "Preparing Channel Wizard", "Loading Channel List")
        ###############
        self.updateListing()
        self.dlg.close()
        self.getControl(105).setVisible(True)
        self.getControl(106).setVisible(False)
        self.setFocusId(102)
        self.log("prepareConfig return")


    def updateListing(self, channel = -1):
        self.log("updateListing")
        start = 0
        end = 200

        if channel > -1:
            start = channel - 1
            end = channel

        for i in range(start, end):
            theitem = self.listcontrol.getListItem(i)
            chantype = 9999
            chansetting1 = ''
            chansetting2 = ''
            ### TV TIME ###
            chansetting3 = ''
            ###############
            newlabel = ''

            try:
                chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_type"))
                chansetting1 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_1")
                chansetting2 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_2")
                ### TV TIME ###
                chansetting3 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_3")
                ###############
            except:
                pass

            if chantype == 0:
                newlabel = self.getSmartPlaylistName(chansetting1)
            ### TV TIME ###
            #elif chantype == 1 or chantype == 2 or chantype == 5 or chantype == 6:
            #    newlabel = chansetting1
            #elif chantype == 3:
            #    newlabel = chansetting1 + " TV"
            #elif chantype == 4:
            #    newlabel = chansetting1 + " Movies"
            elif (
                chantype == 1 or 
                chantype == 2 or 
                chantype == 3 or 
                chantype == 4 or 
                chantype == 5 or 
                chantype == 6 or
                chantype == 8
                ):
                newlabel = chansetting3
            elif chantype == 7 or chantype == 9:
                newlabel = self.chnlst.uncleanString(chansetting3)
            ###############
            theitem.setLabel2(newlabel)

        self.log("updateListing return")
Example #11
0
class APPS(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.log('__init__')
        self.chanlist = ChannelList()
        
        
    def log(self, msg, level = xbmc.LOGDEBUG):
        log('APPS: ' + msg, level)


    def onFocus(self, controlid):
        self.log('onFocus')
        
        
    def onInit(self):
        self.log('onInit')
        self.chanlist.PanelItems = self.getControl(500)
        self.chanlist.fillPlugins()
        self.setFocus(self.chanlist.PanelItems)
       
        
    def onClick(self, controlId):
        self.log('onClick ' + str(controlId))
        if controlId == 500:
            pos = self.chanlist.PanelItems.getSelectedPosition()
            playitem = self.chanlist.PanelItems.getListItem(pos)
            url = 'plugin://'+ playitem.getProperty('mediapath')
            self.chanlist.fillListItems(url)
            self.setFocus(self.chanlist.PanelItems)
            # xbmc.executebuiltin('Container.Refresh') 
            
            
    def onAction(self, act):
        self.log('onAction ' + str(act.getId()))
        action = act.getId()
        if action in ACTION_PREVIOUS_MENU:
            self.closeAPPS()  
        
        elif action == ACTION_TELETEXT_RED:
            self.log('ACTION_TELETEXT_RED')
            self.MyOverlayWindow.windowSwap('EPG')
        
        elif action == ACTION_TELETEXT_GREEN:
            self.log('ACTION_TELETEXT_GREEN')
            self.MyOverlayWindow.windowSwap('DVR')
        
        elif action == ACTION_TELETEXT_YELLOW:
            self.log('ACTION_TELETEXT_YELLOW')
            self.MyOverlayWindow.windowSwap('ONDEMAND')
                
        elif action == ACTION_TELETEXT_BLUE:
            self.log('ACTION_TELETEXT_BLUE')
            self.MyOverlayWindow.windowSwap('APPS')
            
        if action in ACTION_PREVIOUS_MENU:
            print 'ACTION_PREVIOUS_MENU'
        
        elif action in ACTION_MOVE_DOWN: 
            print 'ACTION_MOVE_DOWN'
                
        elif action in ACTION_MOVE_UP:
            print 'ACTION_MOVE_UP'

        elif action in ACTION_MOVE_LEFT: 
            print 'ACTION_MOVE_LEFT'
        
        elif action in ACTION_MOVE_RIGHT:
            print 'ACTION_MOVE_RIGHT'
            
        elif action in ACTION_PAGEDOWN: 
            print 'ACTION_PAGEDOWN'
                 
        elif action in ACTION_PAGEUP: 
            print 'ACTION_PAGEUP'
 
        elif action in ACTION_SELECT_ITEM:
            print 'ACTION_SELECT_ITEM'
                
                
    def closeAPPS(self):
        self.log('closeAPPS')
        self.close()
class ChannelListThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.myOverlay = None
        self.shouldExit = False
        sys.setcheckinterval(25)
        self.chanlist = ChannelList()
        self.chanlist.sleepTime = 0.1


    def log(self, msg, level = xbmc.LOGDEBUG):
        log('ChannelListThread: ' + msg, level)


    def run(self):
        self.log("Starting")
        self.shouldExit = False
        self.chanlist.exitThread = False

        if self.myOverlay == None:
            self.log("Overlay not defined. Exiting.")
            return

        ### TV TIME ### 
        prestageChannels = REAL_SETTINGS.getSetting('PrestageChannels') == "true"
        if prestageChannels:
            for i in range(self.myOverlay.maxChannels):
                if self.shouldExit == True:
                    self.log("Closing thread")
                    return

                self.log("Prestage Channel " + str(i + 1))
                self.chanlist.prestageChannel(i + 1)
        
        self.channelResetSetting = REAL_SETTINGS.getSetting('ChannelResetSetting')
        if self.channelResetSetting == "0":
        ###############
            for i in range(self.myOverlay.maxChannels):
                modified = True

                while modified == True and self.myOverlay.channels[i].isValid and self.myOverlay.channels[i].getTotalDuration() < PREP_CHANNEL_TIME:
                    modified = False

                    if self.shouldExit == True:
                        self.log("Closing thread")
                        return

                    time.sleep(2)
                    curtotal = self.myOverlay.channels[i].getTotalDuration()
                    self.chanlist.appendChannel(i + 1)

                    if self.shouldExit == True:
                        self.log("Closing thread")
                        return

                    time.sleep(2)
                    self.myOverlay.channels[i].setPlaylist(CHANNELS_LOC + "channel_" + str(i + 1) + ".m3u")

                    if self.myOverlay.channels[i].getTotalDuration() > curtotal:
                        modified = True
 
        self.log("All channels up to date.  Exiting thread.")
Example #13
0
    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        ### TV TIME ###
        #self.dlg = xbmcgui.DialogProgress()
        #self.dlg.create("PseudoTV", "Preparing Configuration")
        #self.dlg.update(1)
        #chnlst = ChannelList()
        #chnlst.fillTVInfo()
        #self.dlg.update(40)
        #chnlst.fillMovieInfo()
        #self.dlg.update(80)
        #self.mixedGenreList = chnlst.makeMixedList(chnlst.showGenreList, chnlst.movieGenreList)
        #self.networkList = chnlst.networkList
        #self.studioList = chnlst.studioList
        #self.showGenreList = chnlst.showGenreList
        #self.movieGenreList = chnlst.movieGenreList
        self.dlg = xbmcgui.DialogProgress()
        self.dlg.create("TV Time", "Preparing Channel Wizard")
        self.dlg.update(0, "Preparing Channel Wizard")
        self.chnlst = ChannelList()
        self.dlg.update(10, "Preparing Channel Wizard", "Loading TV Settings")
        self.chnlst.fillTVInfo()
        self.networkList = self.chnlst.networkList
        self.studioList = self.chnlst.studioList
        self.showGenreList = self.chnlst.showGenreList
        self.dlg.update(20, "Preparing Channel Wizard", "Loading Movie Settings")
        self.chnlst.fillMovieInfo()
        self.movieGenreList = self.chnlst.movieGenreList
        self.dlg.update(40, "Preparing Channel Wizard", "Loading Music Settings")
        self.chnlst.fillMusicInfo()
        self.musicGenreList = self.chnlst.musicGenreList        
        self.dlg.update(60, "Preparing Channel Wizard", "Loading Live Feed Settings")
        self.chnlst.fillFeedInfo()
        self.feedList = self.chnlst.feedList
        self.dlg.update(80, "Preparing Channel Wizard", "Loading Mixed Genre Settings")
        self.mixedGenreList = self.chnlst.makeMixedList(self.showGenreList, self.movieGenreList)        
        ###############

        for i in range(len(self.chnlst.showList)):
            self.showList.append(self.chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())
        self.listcontrol = self.getControl(102)

        for i in range(200):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)

        ### TV TIME ###
        self.resolutionList = []
        self.resolutionList.append('All')
        self.resolutionList.append('SD Only')
        self.resolutionList.append('720p or Higher')
        self.resolutionList.append('1080p Only')

        self.showseqList = []
        self.showseqList.append('1 Show')
        self.showseqList.append('2 Shows')
        self.showseqList.append('3 Shows')
        self.showseqList.append('4 Shows')
        self.showseqList.append('5 Shows')
        self.showseqList.append('6 Shows')
        self.showseqList.append('7 Shows')
        self.showseqList.append('8 Shows')
        self.showseqList.append('9 Shows')
        self.showseqList.append('10 Shows')

        self.movieseqList = []
        self.movieseqList.append('1 Movie')
        self.movieseqList.append('2 Movies')
        self.movieseqList.append('3 Movies')
        self.movieseqList.append('4 Movies')
        self.movieseqList.append('5 Movies')
        self.movieseqList.append('6 Movies')
        self.movieseqList.append('7 Movies')
        self.movieseqList.append('8 Movies')
        self.movieseqList.append('9 Movies')
        self.movieseqList.append('10 Movies')

        # check if settings2.xml file exists
        # read in channel playlists in video, music and mixed folders
        """
        channelNum = 0
        for i in range(500):
            if os.path.exists(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')),"")
        ADDON_SETTINGS.writeSettings()
        """
        ###############

        ### TV TIME ###
        #self.dlg.update(90)
        self.dlg.update(90, "Preparing Channel Wizard", "Loading Channel List")
        ###############
        self.updateListing()
        self.dlg.close()
        self.getControl(105).setVisible(True)
        self.getControl(106).setVisible(False)
        self.setFocusId(102)
        self.log("prepareConfig return")
class ChannelListThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.myOverlay = None
        sys.setcheckinterval(25)
        self.chanlist = ChannelList()
        self.paused = False
        self.fullUpdating = True
        
        
    def log(self, msg, level = xbmc.LOGDEBUG):
        log('ChannelListThread: ' + msg, level)


    def run(self):
        self.log("Starting")
        self.chanlist.exitThread = False
        self.chanlist.readConfig()
        self.chanlist.sleepTime = 0.1
        
        if self.myOverlay == None:
            self.log("Overlay not defined. Exiting.")
            return
            
        self.chanlist.myOverlay = self.myOverlay
        self.fullUpdating = (self.myOverlay.backgroundUpdating == 0)
        validchannels = 0

        for i in range(self.myOverlay.maxChannels):
            self.chanlist.channels.append(Channel())

            if self.myOverlay.channels[i].isValid:
                validchannels += 1
                
        # Don't load invalid channels if minimum threading mode is on
        if self.fullUpdating and self.myOverlay.isMaster:
            if validchannels < self.chanlist.enteredChannelCount:
                OptNotify("Background Loading...")
                setProperty("PTVL.BackgroundLoading","true")  

            for i in range(self.myOverlay.maxChannels):
                if self.myOverlay.channels[i].isValid == False:
                    while not KODI_MONITOR.abortRequested():
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return
                        time.sleep(1)
                        
                        if self.paused == False:
                            break

                    self.chanlist.channels[i].setAccessTime(self.myOverlay.channels[i].lastAccessTime)

                    try:
                        if self.chanlist.setupChannel(i + 1, True, True, False) == True:
                            while self.paused:
                                if self.myOverlay.isExiting:
                                    self.log("IsExiting")
                                    return
                                time.sleep(1)
                                
                            self.myOverlay.channels[i] = self.chanlist.channels[i]
                            if self.myOverlay.channels[i].isValid == True:
                                OptNotify("Channel " + str(i + 1) + " Added", icon=self.myOverlay.getChlogo(i + 1))  
                    except Exception,e:
                        self.log("Unknown Channel Creation Exception", xbmc.LOGERROR)
                        self.log(traceback.format_exc(), xbmc.LOGERROR)
                        return
                    time.sleep(2)
                
        self.chanlist.sleepTime = 0.3
        REAL_SETTINGS.setSetting('ForceChannelReset', 'false')
        self.myOverlay.postBackgroundLoading()
                 
        while not KODI_MONITOR.abortRequested():      
            OptNotify("Background Updating...")   
            setProperty("PTVL.BackgroundLoading","true")                   
            self.myOverlay.setCurrentChannel()
            for i in range(self.myOverlay.maxChannels):
                modified = True
                while modified == True and self.myOverlay.channels[i].getTotalDuration() < PREP_CHANNEL_TIME and self.myOverlay.channels[i].Playlist.size() < self.chanlist.Playlist_Limit:
                    # If minimum updating is on, don't attempt to load invalid channels
                    if self.fullUpdating == False and self.myOverlay.channels[i].isValid == False and self.myOverlay.isMaster:
                        break        
                    modified = False
                    
                    if self.myOverlay.isExiting:
                        self.log("Closing thread")
                        return 
                    time.sleep(2)

                    curtotal = self.myOverlay.channels[i].getTotalDuration()
                    chtype = self.myOverlay.getChtype(i + 1)
                    if self.myOverlay.isMaster:
                        if chtype != 9999:
                            if curtotal > 0 and chtype not in FORCE_MAKENEW:
                                # if curtotal > 0 and chtype not in FORCE_MAKENEW:
                                # When appending, many of the channel variables aren't set, so copy them over.
                                # This needs to be done before setup since a rule may use one of the values.
                                # It also needs to be done after since one of them may have changed while being setup.
                                self.chanlist.channels[i].playlistPosition =  xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
                                # self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                                self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                                self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                                self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                                self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                                self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                                
                                # set resume points
                                # self.chanlist.channels[i].setShowPosition(xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition())
                                self.chanlist.channels[i].setShowPosition(self.chanlist.channels[i].playlistPosition)
                                self.chanlist.channels[i].setAccessTime(time.time())
                                                
                                # Only allow appending valid channels, don't allow erasing them
                                try:
                                    self.chanlist.setupChannel(i + 1, True, False, True)
                                    DebugNotify("Channel " + str(i + 1) + " Append", icon=self.myOverlay.getChlogo(i + 1))      
                                except Exception,e:
                                    self.log("Unknown Channel Appending Exception", xbmc.LOGERROR)
                                    self.log(traceback.format_exc(), xbmc.LOGERROR)
                                    return

                                self.chanlist.channels[i].playlistPosition =  xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
                                # self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                                self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                                self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                                self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                                self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                                self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                            else:
                                try:
                                    self.chanlist.setupChannel(i + 1, True, True, False)
                                    DebugNotify("Channel " + str(i + 1) + " Updated", icon=self.myOverlay.getChlogo(i + 1))
                                except Exception,e:
                                    self.log("Unknown Channel Modification Exception", xbmc.LOGERROR)
                                    self.log(traceback.format_exc(), xbmc.LOGERROR)
                                    return
                            time.sleep(2)
                    else:
                        try:
                            # We're not master, so no modifications...just try and load the channel
                            self.chanlist.setupChannel(i + 1, True, False, False)
                            DebugNotify("Channel " + str(i + 1) + " Reloaded", icon=self.myOverlay.getChlogo(i + 1))   
                        except Exception,e:
                            self.log("Unknown Channel Loading Exception", xbmc.LOGERROR)
                            self.log(traceback.format_exc(), xbmc.LOGERROR)
                            return
                        time.sleep(2)
                        
                    self.myOverlay.channels[i] = self.chanlist.channels[i]
                    if self.myOverlay.isMaster:
                        ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(self.myOverlay.channels[i].totalTimePlayed))
                            
                    if self.myOverlay.channels[i].getTotalDuration() > curtotal and self.myOverlay.isMaster:
                        modified = True

                    # A do-while loop for the paused state
                    while not KODI_MONITOR.abortRequested():
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return
                        time.sleep(2)
                        
                        if self.paused == False:
                            break
Example #15
0
class APPS(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.log('__init__')
        self.chanlist = ChannelList()

    def onFocus(self, controlid):
        pass

    def log(self, msg, level=xbmc.LOGDEBUG):
        log('APPS: ' + msg, level)

    def onInit(self):
        self.log('onInit')
        self.chanlist.PanelItems = self.getControl(500)
        self.chanlist.fillPlugins()
        self.setFocus(self.chanlist.PanelItems)

    def onClick(self, controlId):
        self.log('onClick ' + str(controlId))
        if controlId == 500:
            pos = self.chanlist.PanelItems.getSelectedPosition()
            playitem = self.chanlist.PanelItems.getListItem(pos)
            url = playitem.getProperty('mediapath')
            self.chanlist.fillListItems('plugin://' + url)
            # xbmc.executebuiltin('Container.Refresh')

    def onAction(self, act):
        self.log('onAction ' + str(act.getId()))
        action = act.getId()
        if action in ACTION_PREVIOUS_MENU:
            self.closeAPPS()

        elif action == ACTION_TELETEXT_RED:
            self.log('ACTION_TELETEXT_RED')
            self.MyOverlayWindow.windowSwap('EPG')

        elif action == ACTION_TELETEXT_GREEN:
            self.log('ACTION_TELETEXT_GREEN')
            self.MyOverlayWindow.windowSwap('DVR')

        elif action == ACTION_TELETEXT_YELLOW:
            self.log('ACTION_TELETEXT_YELLOW')
            self.MyOverlayWindow.windowSwap('ONDEMAND')

        elif action == ACTION_TELETEXT_BLUE:
            self.log('ACTION_TELETEXT_BLUE')
            self.MyOverlayWindow.windowSwap('APPS')

        if action in ACTION_PREVIOUS_MENU:
            print 'ACTION_PREVIOUS_MENU'

        elif action in ACTION_MOVE_DOWN:
            print 'ACTION_MOVE_DOWN'

        elif action in ACTION_MOVE_UP:
            print 'ACTION_MOVE_UP'

        elif action in ACTION_MOVE_LEFT:
            print 'ACTION_MOVE_LEFT'

        elif action in ACTION_MOVE_RIGHT:
            print 'ACTION_MOVE_RIGHT'

        elif action in ACTION_PAGEDOWN:
            print 'ACTION_PAGEDOWN'

        elif action in ACTION_PAGEUP:
            print 'ACTION_PAGEUP'

        elif action in ACTION_SELECT_ITEM:
            print 'ACTION_SELECT_ITEM'

    def closeAPPS(self):
        self.log('closeAPPS')
        self.close()
class ChannelListThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.myOverlay = None
        sys.setcheckinterval(25)
        self.chanlist = ChannelList()
        self.paused = False
        self.fullUpdating = True

    def log(self, msg, level=xbmc.LOGDEBUG):
        log('ChannelListThread: ' + msg, level)

    def run(self):
        self.log("Starting")
        self.chanlist.exitThread = False
        self.chanlist.readConfig()
        self.chanlist.sleepTime = 1

        if self.myOverlay == None:
            self.log("Overlay not defined. Exiting.")
            return

        self.chanlist.myOverlay = self.myOverlay
        self.fullUpdating = (self.myOverlay.backgroundUpdating == 0)
        validchannels = 0

        for i in range(self.myOverlay.maxChannels):
            self.chanlist.channels.append(Channel())

            if self.myOverlay.channels[i].isValid:
                validchannels += 1

        # Don't load invalid channels if minimum threading mode is on
        if self.fullUpdating and self.myOverlay.isMaster:
            if validchannels < self.chanlist.enteredChannelCount:
                title = 'PseudoTV Lite, Background Loading...'
                xbmc.executebuiltin('XBMC.Notification(%s, %s, %s)' %
                                    (title, 4000, THUMB))

            for i in range(self.myOverlay.maxChannels):
                if self.myOverlay.channels[i].isValid == False:
                    while True:
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return

                        time.sleep(1)

                        if self.paused == False:
                            break

                    self.chanlist.channels[i].setAccessTime(
                        self.myOverlay.channels[i].lastAccessTime)

                    try:
                        if self.chanlist.setupChannel(i + 1, True, True,
                                                      False) == True:
                            while self.paused:
                                if self.myOverlay.isExiting:
                                    self.log("IsExiting")
                                    return

                                time.sleep(1)

                            self.myOverlay.channels[
                                i] = self.chanlist.channels[i]

                            if self.myOverlay.channels[i].isValid == True:
                                title = "PseudoTV Lite, Channel " + str(
                                    i + 1) + " Added"
                                xbmc.executebuiltin(
                                    'XBMC.Notification(%s, %s, %s)' %
                                    (title, 4000, THUMB))

                    except Exception, e:
                        self.log("Unknown Channel Creation Exception",
                                 xbmc.LOGERROR)
                        self.log(traceback.format_exc(), xbmc.LOGERROR)
                        return

        REAL_SETTINGS.setSetting('ForceChannelReset', 'false')
        self.chanlist.sleepTime = 3

        while True:
            for i in range(self.myOverlay.maxChannels):
                modified = True

                while modified == True and self.myOverlay.channels[
                        i].getTotalDuration(
                        ) < PREP_CHANNEL_TIME and self.myOverlay.channels[
                            i].Playlist.size() < 16288:
                    # If minimum updating is on, don't attempt to load invalid channels
                    if self.fullUpdating == False and self.myOverlay.channels[
                            i].isValid == False and self.myOverlay.isMaster:
                        break

                    modified = False

                    if self.myOverlay.isExiting:
                        self.log("Closing thread")
                        return

                    time.sleep(2)
                    curtotal = self.myOverlay.channels[i].getTotalDuration()

                    if self.myOverlay.isMaster:
                        if curtotal > 0:
                            # When appending, many of the channel variables aren't set, so copy them over.
                            # This needs to be done before setup since a rule may use one of the values.
                            # It also needs to be done after since one of them may have changed while being setup.
                            self.chanlist.channels[
                                i].playlistPosition = self.myOverlay.channels[
                                    i].playlistPosition
                            self.chanlist.channels[
                                i].showTimeOffset = self.myOverlay.channels[
                                    i].showTimeOffset
                            self.chanlist.channels[
                                i].lastAccessTime = self.myOverlay.channels[
                                    i].lastAccessTime
                            self.chanlist.channels[
                                i].totalTimePlayed = self.myOverlay.channels[
                                    i].totalTimePlayed
                            self.chanlist.channels[
                                i].isPaused = self.myOverlay.channels[
                                    i].isPaused
                            self.chanlist.channels[
                                i].mode = self.myOverlay.channels[i].mode
                            # Only allow appending valid channels, don't allow erasing them

                            try:
                                self.chanlist.setupChannel(
                                    i + 1, True, False, True)
                            except Exception, e:
                                self.log("Unknown Channel Appending Exception",
                                         xbmc.LOGERROR)
                                self.log(traceback.format_exc(), xbmc.LOGERROR)
                                return

                            self.chanlist.channels[
                                i].playlistPosition = self.myOverlay.channels[
                                    i].playlistPosition
                            self.chanlist.channels[
                                i].showTimeOffset = self.myOverlay.channels[
                                    i].showTimeOffset
                            self.chanlist.channels[
                                i].lastAccessTime = self.myOverlay.channels[
                                    i].lastAccessTime
                            self.chanlist.channels[
                                i].totalTimePlayed = self.myOverlay.channels[
                                    i].totalTimePlayed
                            self.chanlist.channels[
                                i].isPaused = self.myOverlay.channels[
                                    i].isPaused
                            self.chanlist.channels[
                                i].mode = self.myOverlay.channels[i].mode
                        else:
                            try:
                                self.chanlist.setupChannel(
                                    i + 1, True, True, False)
                            except Exception, e:
                                self.log(
                                    "Unknown Channel Modification Exception",
                                    xbmc.LOGERROR)
                                self.log(traceback.format_exc(), xbmc.LOGERROR)
                                return
                    else:
                        try:
                            # We're not master, so no modifications...just try and load the channel
                            self.chanlist.setupChannel(i + 1, True, False,
                                                       False)
                        except Exception, e:
                            self.log("Unknown Channel Loading Exception",
                                     xbmc.LOGERROR)
                            self.log(traceback.format_exc(), xbmc.LOGERROR)
                            return

                    self.myOverlay.channels[i] = self.chanlist.channels[i]

                    if self.myOverlay.isMaster:
                        ADDON_SETTINGS.setSetting(
                            'Channel_' + str(i + 1) + '_time',
                            str(self.myOverlay.channels[i].totalTimePlayed))

                    if self.myOverlay.channels[i].getTotalDuration(
                    ) > curtotal and self.myOverlay.isMaster:
                        modified = True

                    # A do-while loop for the paused state
                    while True:
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return

                        time.sleep(2)

                        if self.paused == False:
                            break
Example #17
0
 def __init__(self, *args, **kwargs):
     self.log('__init__')
     self.chanlist = ChannelList()
Example #18
0
    def onInit(self):
        self.log('onInit')
        migrate()
        self.channelLabelTimer = threading.Timer(5.0, self.hideChannelLabel)
        self.infoTimer = threading.Timer(5.0, self.hideInfo)
        self.background = self.getControl(101)
        self.getControl(102).setVisible(False)

        if not os.path.exists(GEN_CHAN_LOC):
            try:
                os.makedirs(GEN_CHAN_LOC)
            except:
                self.Error('Unable to create the cache directory')
                return

        self.myEPG = EPGWindow("script.pseudotv.EPG.xml", ADDON_INFO, "default")
        self.myEPG.MyOverlayWindow = self
        # Don't allow any actions during initialization
        self.actionSemaphore.acquire()

        ### TV TIME ###
        chn = ChannelList()
        # build meta files if first time loading
        if (
            REAL_SETTINGS.getSetting("bumpers") == "true" or 
            REAL_SETTINGS.getSetting("commercials") == "true" or  
            REAL_SETTINGS.getSetting("trailers") == "true"
            ):
            chn.buildMetaFiles() 

        chn.loadCustomPlaylists()

        if (REAL_SETTINGS.getSetting("autoFindMixGenres") == "true" or       
            REAL_SETTINGS.getSetting("autoFindMovieGenres") == "true" or        
            REAL_SETTINGS.getSetting("autoFindNetworks") == "true" or        
            REAL_SETTINGS.getSetting("autoFindStudios") == "true" or   
            REAL_SETTINGS.getSetting("autoFindTVGenres") == "true" or       
            REAL_SETTINGS.getSetting("autoFindTVShows") == "true" or
            REAL_SETTINGS.getSetting("autoFindMusicGenres") == "true" or
            REAL_SETTINGS.getSetting("autoFindLive") == "true"):
            chn.autoTune()
        ###############

        if self.readConfig() == False:
            return

        self.myEPG.channelLogos = self.channelLogos
        self.maxChannels = len(self.channels)

        ### TV TIME ###
        #if self.maxChannels == 0:
        #    self.Error('Unable to find any channels. Please configure the addon.')
        #    return
        if self.maxChannels == 0:
            dlg = xbmcgui.Dialog()
            
            autoTune = False
            if dlg.yesno("No Channels Configured", "Would you like TV Time to Auto Tune TV Network\nchannels the next time it loads?"):
                REAL_SETTINGS.setSetting("autoFindNetworks","true")
                autoTune = True

            if dlg.yesno("No Channels Configured", "Would you like TV Time to Auto Tune TV Genre\nchannels the next time it loads?"):
                REAL_SETTINGS.setSetting("autoFindTVGenres","true")
                autoTune = True

            if dlg.yesno("No Channels Configured", "Would you like TV Time to Auto Tune Movie Studio\nchannels the next time it loads?"):
                REAL_SETTINGS.setSetting("autoFindStudios","true")
                autoTune = True

            if dlg.yesno("No Channels Configured", "Would you like TV Time to Auto Tune Movie Genre\nchannels the next time it loads?"):
                REAL_SETTINGS.setSetting("autoFindMovieGenres","true")
                autoTune = True

            if dlg.yesno("No Channels Configured", "Would you like TV Time to Auto Tune Mix Genre\nchannels the next time it loads?"):
                REAL_SETTINGS.setSetting("autoFindMixGenres","true")
                autoTune = True

            if dlg.yesno("No Channels Configured", "Would you like TV Time to Auto Tune Music Genre\nchannels the next time it loads?"):
                REAL_SETTINGS.setSetting("autoFindMusicGenres","true")
                autoTune = True

            if dlg.yesno("No Channels Configured", "Would you like TV Time to Auto Tune Live\nchannels the next time it loads?"):
                REAL_SETTINGS.setSetting("autoFindLive","true")
                autoTune = True

            if autoTune:
                self.background.setVisible(True)
                self.end()
                return

            del dlg
        ###############
        
        found = False

        for i in range(self.maxChannels):
            if self.channels[i].isValid:
                found = True
                break

        ### TV TIME ###
        #if found == False:
        #    self.Error("No valid channel data found")
        #    return
        if found == False:
            self.Error('Unable to find any channels. \nPlease go to the Addon Settings to configure TV Time.')
            return
        ###############
        
        if self.sleepTimeValue > 0:
            self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

        try:
            if self.forceReset == False:
                self.currentChannel = self.fixChannel(int(ADDON_SETTINGS.getSetting("CurrentChannel")))
            else:
                ### TV TIME ###
                #self.currentChannel = self.fixChannel(1)
                if self.startupChannel == 0:
                    self.currentChannel = self.fixChannel(1)
                else:
                    if self.channels[self.startupChannel - 1].isValid:
                        self.currentChannel = self.fixChannel(self.startupChannel)
                    else:
                        self.currentChannel = self.fixChannel(1)
                ###############
        except:
            self.currentChannel = self.fixChannel(1)

        self.resetChannelTimes()
        self.setChannel(self.currentChannel)
        self.timeStarted = time.time()
        self.background.setVisible(False)
        ### TV TIME ###
        if int(ADDON_SETTINGS.getSetting("Channel_" + str(self.currentChannel) + "_type")) == 8:
            xbmc.executebuiltin("ActivateWindow(12006)")            
        ###############
        self.startSleepTimer()
        
        ### TV TIME ###
        #if self.channelResetSetting == "0":
        #    self.channelThread.start()
        self.channelThread.start()
        ###############
        
        self.actionSemaphore.release()
        self.log('onInit return')
Example #19
0
class APP(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.log('__init__')
        self.chanlist = ChannelList()
        
        
    def log(self, msg, level = xbmc.LOGDEBUG):
        log('APPS: ' + msg, level)


    def onFocus(self, controlid):
        self.log('onFocus')
        
        
    def onInit(self):
        self.log('onInit')
        self.PanelPlugins = self.getControl(500)
        self.PanelItems = self.getControl(501)
        self.fillPlugins()
        self.setFocus(self.PanelPlugins)
       
        
    def onClick(self, controlid):
        self.log('onClick ' + str(controlid))
        if controlid == 500:
            playitem = self.PanelPlugins.getListItem(self.PanelPlugins.getSelectedPosition())
            self.chanlist.fillListItems('plugin://'+ playitem.getProperty('mediapath'))
            self.setFocus(self.PanelItems)
            # xbmc.executebuiltin('Container.Refresh') 
        elif controlid in [6001,6002,6003,6004]:
            if controlid == 6001:
                self.log('ACTION_TELETEXT_RED')
                self.MyOverlayWindow.windowSwap('EPG')
            elif controlid == 6002:
                self.log('ACTION_TELETEXT_GREEN')
                self.MyOverlayWindow.windowSwap('DVR')
            elif controlid == 6003:
                self.log('ACTION_TELETEXT_YELLOW')
                self.MyOverlayWindow.windowSwap('ONDEMAND')
            elif controlid == 6004:
                self.log('ACTION_TELETEXT_BLUE') 
                self.MyOverlayWindow.windowSwap('APPS')

                
    def onAction(self, act):
        self.log('onAction ' + str(act.getId()))
        action = act.getId()
        if action in ACTION_PREVIOUS_MENU:
            self.closeAPPS()  
        
        elif action == ACTION_TELETEXT_RED:
            self.log('ACTION_TELETEXT_RED')
            self.MyOverlayWindow.windowSwap('EPG')
        
        elif action == ACTION_TELETEXT_GREEN:
            self.log('ACTION_TELETEXT_GREEN')
            self.MyOverlayWindow.windowSwap('DVR')
        
        elif action == ACTION_TELETEXT_YELLOW:
            self.log('ACTION_TELETEXT_YELLOW')
            self.MyOverlayWindow.windowSwap('ONDEMAND')
                
        elif action == ACTION_TELETEXT_BLUE:
            self.log('ACTION_TELETEXT_BLUE')
            self.MyOverlayWindow.windowSwap('APPS')
            
        if action in ACTION_PREVIOUS_MENU:
            print 'ACTION_PREVIOUS_MENU'
        
        elif action in ACTION_MOVE_DOWN: 
            print 'ACTION_MOVE_DOWN'
                
        elif action in ACTION_MOVE_UP:
            print 'ACTION_MOVE_UP'

        elif action in ACTION_MOVE_LEFT: 
            print 'ACTION_MOVE_LEFT'
        
        elif action in ACTION_MOVE_RIGHT:
            print 'ACTION_MOVE_RIGHT'
            
        elif action in ACTION_PAGEDOWN: 
            print 'ACTION_PAGEDOWN'
                 
        elif action in ACTION_PAGEUP: 
            print 'ACTION_PAGEUP'
 
        elif action in ACTION_SELECT_ITEM:
            print 'ACTION_SELECT_ITEM'
                
                
    def closeAPPS(self):
        self.log('closeAPPS')
        self.close()
        
        
    def fillPlugins(self, type='video'):
        self.log('fillPlugins, type = ' + type)
        json_query = ('{"jsonrpc":"2.0","method":"Addons.GetAddons","params":{"type":"xbmc.addon.%s","properties":["name","path","thumbnail","description","fanart","summary"]}, "id": 1 }'%type)
        json_detail = self.chanlist.sendJSON(json_query)
        detail = re.compile( "{(.*?)}", re.DOTALL ).findall(json_detail)
        for f in detail:
            names = re.search('"name" *: *"(.*?)",', f)
            paths = re.search('"addonid" *: *"(.*?)",', f)
            thumbnails = re.search('"thumbnail" *: *"(.*?)",', f)
            fanarts = re.search('"fanart" *: *"(.*?)",', f)
            descriptions = re.search('"description" *: *"(.*?)",', f)
            if not descriptions:
                descriptions = re.search('"summary" *: *"(.*?)",', f)
            if descriptions:
                description = self.chanlist.cleanLabels(descriptions.group(1))
            else:
                description = ''
            if names and paths:
                name = self.chanlist.cleanLabels(names.group(1))
                path = paths.group(1)
                if type == 'video' and path.startswith('plugin.video'):
                    thumbnail = removeNonAscii(thumbnails.group(1))
                    fanart = removeNonAscii(fanarts.group(1))
                    self.Items = xbmcgui.ListItem(label=name, thumbnailImage = thumbnail)
                    self.Items.setIconImage(thumbnail)
                    self.Items.setProperty("mediapath", path)
                    self.Items.setProperty("Fanart_Image", fanart)
                    
                    infoList = {}
                    infoList['mediatype']     = type
                    infoList['mpaa']          = 'Unknown'
                    infoList['tvshowtitle']   =  name
                    infoList['title']         =  name
                    infoList['originaltitle'] = 'originaltitle'
                    infoList['sorttitle']     = 'sorttitle'
                    infoList['studio']        = 'Studio'
                    infoList['genre']         = 'Genre'
                    infoList['plot']          = 'Plot'
                    infoList['plotoutline']   = 'plotoutline'
                    infoList['tagline']       = 'tagline'
                    infoList['dateadded']     = 'dateadded'
                    infoList['premiered']     = 'premiered'
                    infoList['aired']         = 'aired'
                    infoList['code']          = 'code'
                    infoList['lastplayed']    = 'lastplayed'
                    # infoList['album']         = 'album'
                    # infoList['artist']        = ['artist']
                    # infoList['votes']         = 'votes'
                    infoList['duration']      = 1
                    infoList['year']          = 1977
                    infoList['season']        = 3
                    infoList['episode']       = 4
                    infoList['playcount']     = 5
                    self.Items.setInfo('Video', infoList)    

                    infoArt = {}
                    infoArt['thumb']        = thumbnail
                    infoArt['poster']       = thumbnail
                    infoArt['banner']       = ''
                    infoArt['fanart']       = fanart
                    infoArt['clearart']     = ''
                    infoArt['clearlogo']    = ''
                    infoArt['landscape']    = fanart
                    infoList['icon']        = thumbnail
                    self.Items.setArt(infoArt) 
                    self.PanelPlugins.addItem(self.Items) 
    

    def fillListItems(self, url, type='video', file_type=False):
        self.log('fillListItems')
        self.Items = []
        if not file_type:
            detail = uni(self.chanlist.requestList(url, type))
        else:
            detail = uni(self.chanlist.requestItem(url, type))
        for f in detail:
            files = re.search('"file" *: *"(.*?)",', f)
            filetypes = re.search('"filetype" *: *"(.*?)",', f)
            labels = re.search('"label" *: *"(.*?)",', f)
            thumbnails = re.search('"thumbnail" *: *"(.*?)",', f)
            fanarts = re.search('"fanart" *: *"(.*?)",', f)
            descriptions = re.search('"description" *: *"(.*?)",', f)
            
            if filetypes and labels and files:
                filetype = filetypes.group(1)
                name = self.chanlist.cleanLabels(labels.group(1))
                file = (files.group(1).replace("\\\\", "\\"))
                
                if not descriptions:
                    description = ''
                else:
                    description = self.chanlist.cleanLabels(descriptions.group(1))
                
                if thumbnails != None and len(thumbnails.group(1)) > 0:
                    thumbnail = thumbnails.group(1)
                else:
                    thumbnail = THUMB
                    
                if fanarts != None and len(fanarts.group(1)) > 0:
                    fanart = fanarts.group(1)
                else:
                    fanart = FANART
                    
                self.Items = xbmcgui.ListItem(label=name, thumbnailImage = thumbnail)
                
                if filetype == 'file':
                    self.Items.setProperty('IsPlayable', 'true')
                else:
                    self.Items.setProperty('IsPlayable', 'false')
                    
                self.Items.setIconImage(thumbnail)
                self.Items.setProperty("mediapath", file)
                self.Items.setProperty("Fanart_Image", fanart)
                
                infoList = {}
                infoList['mediatype']     = type
                infoList['mpaa']          = 'Unknown'
                infoList['tvshowtitle']   =  name
                infoList['title']         =  name
                infoList['originaltitle'] = 'originaltitle'
                infoList['sorttitle']     = 'sorttitle'
                infoList['studio']        = 'Studio'
                infoList['genre']         = 'Genre'
                infoList['plot']          = 'Plot'
                infoList['plotoutline']   = 'plotoutline'
                infoList['tagline']       = 'tagline'
                infoList['dateadded']     = 'dateadded'
                infoList['premiered']     = 'premiered'
                infoList['aired']         = 'aired'
                infoList['code']          = 'code'
                infoList['lastplayed']    = 'lastplayed'
                # infoList['album']         = 'album'
                # infoList['artist']        = ['artist']
                # infoList['votes']         = 'votes'
                infoList['duration']      = 1
                infoList['year']          = 1977
                infoList['season']        = 3
                infoList['episode']       = 4
                infoList['playcount']     = 5
                self.Items.setInfo('Video', infoList)    

                infoArt = {}
                infoArt['thumb']        = thumbnail
                infoArt['poster']       = thumbnail
                infoArt['banner']       = ''
                infoArt['fanart']       = fanart
                infoArt['clearart']     = ''
                infoArt['clearlogo']    = ''
                infoArt['landscape']    = fanart
                infoList['icon']        = thumbnail
                self.Items.setArt(infoArt) 
                self.PanelItems.addItem(self.Items) 
Example #20
0
    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        self.dlg = xbmcgui.DialogProgress()
        self.dlg.create("TV Time", "Preparing Channel Wizard")
        self.dlg.update(0, "Preparing Channel Wizard")
        self.chnlst = ChannelList()
        self.dlg.update(10, "Preparing Channel Wizard", "Loading TV Settings")
        self.chnlst.fillTVInfo()
        self.networkList = self.chnlst.networkList
        self.studioList = self.chnlst.studioList
        self.showGenreList = self.chnlst.showGenreList
        self.dlg.update(20, "Preparing Channel Wizard", "Loading Movie Settings")
        self.chnlst.fillMovieInfo()
        self.movieGenreList = self.chnlst.movieGenreList
        self.dlg.update(40, "Preparing Channel Wizard", "Loading Music Settings")
        self.chnlst.fillMusicInfo()
        self.musicGenreList = self.chnlst.musicGenreList        
        self.dlg.update(60, "Preparing Channel Wizard", "Loading Live Feed Settings")
        self.chnlst.fillFeedInfo()
        self.feedList = self.chnlst.feedList
        self.dlg.update(80, "Preparing Channel Wizard", "Loading Mixed Genre Settings")
        self.mixedGenreList = self.chnlst.makeMixedList(self.showGenreList, self.movieGenreList)

        for i in range(len(self.chnlst.showList)):
            self.showList.append(self.chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())

        self.log("self.networkList " + str(self.networkList))
        self.log("self.studioList " + str(self.studioList))
        self.log("self.showGenreList " + str(self.showGenreList))
        self.log("self.movieGenreList " + str(self.movieGenreList))
        self.log("self.musicGenreList " + str(self.musicGenreList))
        self.log("self.mixedGenreList " + str(self.mixedGenreList))

        self.resolutionList = []
        self.resolutionList.append('All')
        self.resolutionList.append('SD Only')
        self.resolutionList.append('720p or Higher')
        self.resolutionList.append('1080p Only')

        self.showseqList = []
        self.showseqList.append('1 Show')
        self.showseqList.append('2 Shows')
        self.showseqList.append('3 Shows')
        self.showseqList.append('4 Shows')
        self.showseqList.append('5 Shows')
        self.showseqList.append('6 Shows')
        self.showseqList.append('7 Shows')
        self.showseqList.append('8 Shows')
        self.showseqList.append('9 Shows')
        self.showseqList.append('10 Shows')

        self.movieseqList = []
        self.movieseqList.append('1 Movie')
        self.movieseqList.append('2 Movies')
        self.movieseqList.append('3 Movies')
        self.movieseqList.append('4 Movies')
        self.movieseqList.append('5 Movies')
        self.movieseqList.append('6 Movies')
        self.movieseqList.append('7 Movies')
        self.movieseqList.append('8 Movies')
        self.movieseqList.append('9 Movies')
        self.movieseqList.append('10 Movies')

        # check if settings2.xml file exists
        # read in channel playlists in video, music and mixed folders
        channelNum = 0
        for i in range(500):
            if os.path.exists(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')),"")
        ADDON_SETTINGS.writeSettings()
                        
        """
        if not os.path.exists(xbmc.translatePath('special://profile/addon_data/' + ADDON_ID + '/settings2.xml')):
            # if not, load presets based on networklist and studiolist
            ChannelList().autoTune()
        else:
            if (REAL_SETTINGS.getSetting("autoFindNetworks") == "true" or 
                REAL_SETTINGS.getSetting("autoFindStudios") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMovieGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMixGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVShows") == "true" or
                REAL_SETTINGS.getSetting("autoFindMusicGenres") == "true"):
                self.log("autoTune")
                ChannelList().autoTune()
        """
        
        self.listcontrol = self.getControl(102)

        for i in range(200):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)


        self.dlg.update(90, "Preparing Channel Wizard", "Loading Channel List")
        self.updateListing()
        self.dlg.close()
        self.getControl(105).setVisible(True) # Channel List
        self.getControl(106).setVisible(False) # Channel Settings
        self.setFocusId(102)
        self.log("prepareConfig return")
Example #21
0
class ChannelConfig(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.log("__init__")
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        self.setCoordinateResolution(1)
        self.showingList = True
        self.channel = 0
        self.channel_type = 9999
        self.setting1 = ''
        self.setting2 = ''
        self.setting3 = ''
        self.setting4 = ''
        self.setting5 = ''
        self.setting6 = ''
        self.setting7 = ''
        self.setting8 = ''
        self.setting9 = ''
        self.doModal()
        self.log("__init__ return")


    def onInit(self):
        self.log("onInit")

        self.createDirectories()

        self.getControl(105).setVisible(False) # Channel Listing Control Group
        self.getControl(106).setVisible(False) # Channel Settings Control Group

        for i in range(NUMBER_CHANNEL_TYPES):
            self.getControl(120 + i).setVisible(False) # Channel Settings

        #migrate()
        self.prepareConfig()
        self.log("onInit return")


    def onFocus(self, controlId):
        pass


    def onAction(self, act):
        action = act.getId()

        if action == ACTION_PREVIOUS_MENU:
            if self.showingList == False:
                self.cancelChan()
                self.hideChanDetails()
            else:
                self.close()


    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        self.dlg = xbmcgui.DialogProgress()
        self.dlg.create("TV Time", "Preparing Channel Wizard")
        self.dlg.update(0, "Preparing Channel Wizard")
        self.chnlst = ChannelList()
        self.dlg.update(10, "Preparing Channel Wizard", "Loading TV Settings")
        self.chnlst.fillTVInfo()
        self.networkList = self.chnlst.networkList
        self.studioList = self.chnlst.studioList
        self.showGenreList = self.chnlst.showGenreList
        self.dlg.update(20, "Preparing Channel Wizard", "Loading Movie Settings")
        self.chnlst.fillMovieInfo()
        self.movieGenreList = self.chnlst.movieGenreList
        self.dlg.update(40, "Preparing Channel Wizard", "Loading Music Settings")
        self.chnlst.fillMusicInfo()
        self.musicGenreList = self.chnlst.musicGenreList        
        self.dlg.update(60, "Preparing Channel Wizard", "Loading Live Feed Settings")
        self.chnlst.fillFeedInfo()
        self.feedList = self.chnlst.feedList
        self.dlg.update(80, "Preparing Channel Wizard", "Loading Mixed Genre Settings")
        self.mixedGenreList = self.chnlst.makeMixedList(self.showGenreList, self.movieGenreList)

        for i in range(len(self.chnlst.showList)):
            self.showList.append(self.chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())

        self.log("self.networkList " + str(self.networkList))
        self.log("self.studioList " + str(self.studioList))
        self.log("self.showGenreList " + str(self.showGenreList))
        self.log("self.movieGenreList " + str(self.movieGenreList))
        self.log("self.musicGenreList " + str(self.musicGenreList))
        self.log("self.mixedGenreList " + str(self.mixedGenreList))

        self.resolutionList = []
        self.resolutionList.append('All')
        self.resolutionList.append('SD Only')
        self.resolutionList.append('720p or Higher')
        self.resolutionList.append('1080p Only')

        self.showseqList = []
        self.showseqList.append('1 Show')
        self.showseqList.append('2 Shows')
        self.showseqList.append('3 Shows')
        self.showseqList.append('4 Shows')
        self.showseqList.append('5 Shows')
        self.showseqList.append('6 Shows')
        self.showseqList.append('7 Shows')
        self.showseqList.append('8 Shows')
        self.showseqList.append('9 Shows')
        self.showseqList.append('10 Shows')

        self.movieseqList = []
        self.movieseqList.append('1 Movie')
        self.movieseqList.append('2 Movies')
        self.movieseqList.append('3 Movies')
        self.movieseqList.append('4 Movies')
        self.movieseqList.append('5 Movies')
        self.movieseqList.append('6 Movies')
        self.movieseqList.append('7 Movies')
        self.movieseqList.append('8 Movies')
        self.movieseqList.append('9 Movies')
        self.movieseqList.append('10 Movies')

        # check if settings2.xml file exists
        # read in channel playlists in video, music and mixed folders
        channelNum = 0
        for i in range(500):
            if os.path.exists(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/video/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/mixed/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp'):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", ChannelList().cleanString(ChannelList().getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_playlist", xbmc.translatePath('special://profile/playlists/music/') + 'Channel_' + str(i + 1) + '.xsp')
                #self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')),"")
        ADDON_SETTINGS.writeSettings()
                        
        """
        if not os.path.exists(xbmc.translatePath('special://profile/addon_data/' + ADDON_ID + '/settings2.xml')):
            # if not, load presets based on networklist and studiolist
            ChannelList().autoTune()
        else:
            if (REAL_SETTINGS.getSetting("autoFindNetworks") == "true" or 
                REAL_SETTINGS.getSetting("autoFindStudios") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMovieGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMixGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVShows") == "true" or
                REAL_SETTINGS.getSetting("autoFindMusicGenres") == "true"):
                self.log("autoTune")
                ChannelList().autoTune()
        """
        
        self.listcontrol = self.getControl(102)

        for i in range(200):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)


        self.dlg.update(90, "Preparing Channel Wizard", "Loading Channel List")
        self.updateListing()
        self.dlg.close()
        self.getControl(105).setVisible(True) # Channel List
        self.getControl(106).setVisible(False) # Channel Settings
        self.setFocusId(102)
        self.log("prepareConfig return")


    def saveSettings(self):
        chantype = 9999
        chan = str(self.channel)
        
        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + chan + "_type"))
        except:
            self.log("Unable to get channel type")

        setting1 = "Channel_" + chan + "_1"
        setting2 = "Channel_" + chan + "_2"
        setting3 = "Channel_" + chan + "_3"
        setting4 = "Channel_" + chan + "_4"
        setting5 = "Channel_" + chan + "_5"
        setting6 = "Channel_" + chan + "_6"
        setting7 = "Channel_" + chan + "_7"
        setting8 = "Channel_" + chan + "_8"
        setting9 = "Channel_" + chan + "_9"
        settingtime = "Channel_" + chan + "_time"
        playlist = "Channel_" + chan + "_playlist"
        totalDuration = "Channel_" + chan + "_totalDuration"
        
        if chantype == 0:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(130).getLabel2())
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(130).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(settingtime, 0)
        elif chantype == 1:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(142).getLabel()))
            if self.getControl(349).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(142).getLabel()))
            if self.getControl(346).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(347).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(343).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            if self.getControl(348).isSelected():
                ADDON_SETTINGS.setSetting(setting9, str(MODE_RANDOM_FILELISTS))
            else:
                ADDON_SETTINGS.setSetting(setting9, 0)
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        elif chantype == 2:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(152).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(152).getLabel()))
            if self.getControl(356).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, self.getControl(353).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        elif chantype == 3:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(162).getLabel()))
            if self.getControl(369).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(162).getLabel()) + ' TV')
            if self.getControl(366).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(367).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(363).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        elif chantype == 4:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(172).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(172).getLabel()) + ' Movies')
            if self.getControl(376).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            ADDON_SETTINGS.setSetting(setting5, self.getControl(373).getLabel())
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        elif chantype == 5:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(182).getLabel()))
            if self.getControl(389).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(182).getLabel()) + ' Mix')
            if self.getControl(386).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(387).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(383).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        elif chantype == 6:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(192).getLabel()))
            if self.getControl(194).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, '')                
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(192).getLabel()))
            if self.getControl(396).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(397).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(393).getLabel())
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        if chantype == 7: # folder
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(200).getLabel2()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(200).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        if chantype == 8: # music
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(212).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(212).getLabel()) + ' Music')
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        if chantype == 9: # live
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(222).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(222).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')
        elif chantype == 9999:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, '')
            ADDON_SETTINGS.setSetting(setting2, '')
            ADDON_SETTINGS.setSetting(setting3, '')
            ADDON_SETTINGS.setSetting(setting4, '')
            ADDON_SETTINGS.setSetting(setting5, '')
            ADDON_SETTINGS.setSetting(setting6, '')
            ADDON_SETTINGS.setSetting(setting7, '')
            ADDON_SETTINGS.setSetting(setting8, '')
            ADDON_SETTINGS.setSetting(setting9, '')
            ADDON_SETTINGS.setSetting(playlist, '')
            ADDON_SETTINGS.setSetting(totalDuration, '')

        # Check to see if the user changed anything
        set1 = ''
        set2 = ''
        set3 = ''
        set4 = ''
        set5 = ''
        set6 = ''
        set7 = ''
        set8 = ''
        set9 = ''

        try:
            set1 = ADDON_SETTINGS.getSetting(setting1)
            set2 = ADDON_SETTINGS.getSetting(setting2)
            set3 = ADDON_SETTINGS.getSetting(setting3)
            set4 = ADDON_SETTINGS.getSetting(setting4)
            set5 = ADDON_SETTINGS.getSetting(setting5)
            set6 = ADDON_SETTINGS.getSetting(setting6)
            set7 = ADDON_SETTINGS.getSetting(setting7)
            set8 = ADDON_SETTINGS.getSetting(setting8)
            set9 = ADDON_SETTINGS.getSetting(setting9)
        except:
            pass

        if chantype != self.channel_type or set1 != self.setting1 or set2 != self.setting2 or set3 != self.setting3 or set4 != self.setting4 or set5 != self.setting5 or set6 != self.setting6 or set7 != self.setting7 or set8 != self.setting8 or set9 != self.setting9:
            ADDON_SETTINGS.setSetting('Channel_' + chan + '_changed', 'true')

        ADDON_SETTINGS.writeSettings()
        # save total number of channels to settings.xml so we don't have to keep looping
        # through settings2.xml
        self.chnlst.setMaxChannels()
        
        self.log("saveSettings return")


    def cancelChan(self):
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_type", str(self.channel_type))
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_1", self.setting1)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_2", self.setting2)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_3", self.setting3)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_4", self.setting4)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_5", self.setting5)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_6", self.setting6)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_7", self.setting7)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_8", self.setting8)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_9", self.setting9)


    def hideChanDetails(self):
        self.getControl(106).setVisible(False)

        for i in range(NUMBER_CHANNEL_TYPES):
            self.getControl(120 + i).setVisible(False)

        self.setFocusId(102)
        self.getControl(105).setVisible(True)
        self.showingList = True
        self.updateListing(self.channel)
        self.listcontrol.selectItem(self.channel - 1)


    def onClick(self, controlId):
        self.log("onClick " + str(controlId))

        if controlId == 102:
            self.getControl(105).setVisible(False)
            self.getControl(106).setVisible(True)
            self.channel = self.listcontrol.getSelectedPosition() + 1
            self.changeChanType(self.channel, 0)
            
            self.setFocusId(110)
            self.showingList = False
        elif controlId == 110:
            self.changeChanType(self.channel, -1)
        elif controlId == 111:
            self.changeChanType(self.channel, 1)
        elif controlId == 112:
            self.saveSettings()
            self.hideChanDetails()
        elif controlId == 113:
            self.cancelChan()
            self.hideChanDetails()
        elif controlId == 130:
            dlg = xbmcgui.Dialog()
            retval = dlg.browse(1, "Channel " + str(self.channel) + " Playlist", "files", ".xsp", False, False, "special://videoplaylists/")

            if retval != "special://videoplaylists/":
                self.getControl(130).setLabel(self.chnlst.getSmartPlaylistName(retval), label2=retval)
        elif controlId == 140:
            self.changeListData(self.networkList, 142, -1)
        elif controlId == 141:
            self.changeListData(self.networkList, 142, 1)
        elif controlId == 150:
            self.changeListData(self.studioList, 152, -1)
        elif controlId == 151:
            self.changeListData(self.studioList, 152, 1)
        elif controlId == 160:
            self.changeListData(self.showGenreList, 162, -1)
        elif controlId == 161:
            self.changeListData(self.showGenreList, 162, 1)
        elif controlId == 170:
            self.changeListData(self.movieGenreList, 172, -1)
        elif controlId == 171:
            self.changeListData(self.movieGenreList, 172, 1)
        elif controlId == 180:
            self.changeListData(self.mixedGenreList, 182, -1)
        elif controlId == 181:
            self.changeListData(self.mixedGenreList, 182, 1)
        elif controlId == 190:
            self.changeListData(self.showList, 192, -1)
        elif controlId == 191:
            self.changeListData(self.showList, 192, 1)        
        elif controlId == 200: # Folder Channel
            dlg = xbmcgui.Dialog()
            # need to replace this with folder instead of file
            retval = dlg.browse(0, "Channel " + str(self.channel) + " Folder", "files", "*.*", False, False, "")
            if retval != "":
                # smb isn't supported at this time but it is here
                # as a placeholder if a solution can be found
                # for connecting to smb shares from python
                if retval.find("smb://") == -1:
                    ps = retval.split(os.sep)
                else:
                    ps = retval.split('/')
                chanName = ""
                for i in range(len(ps)-1):
                    chanName = ps[i]
                self.getControl(200).setLabel(chanName, label2=retval)        
        elif controlId == 210: # Music Based Channel
            self.changeListData(self.musicGenreList, 212, -1)
        elif controlId == 211:
            self.changeListData(self.musicGenreList, 212, 1)
        elif controlId == 220: # Live Channel
            self.changeListData(self.feedList, 222, -1)
        elif controlId == 221:
            self.changeListData(self.feedList, 222, 1)
        elif controlId == 344:
            self.changeListData(self.resolutionList, 343, -1)
        elif controlId == 345:
            self.changeListData(self.resolutionList, 343, 1)
        elif controlId == 354:
            self.changeListData(self.resolutionList, 353, -1)
        elif controlId == 355:
            self.changeListData(self.resolutionList, 353, 1)
        elif controlId == 364:
            self.changeListData(self.resolutionList, 363, -1)
        elif controlId == 365:
            self.changeListData(self.resolutionList, 363, 1)
        elif controlId == 374:
            self.changeListData(self.resolutionList, 373, -1)
        elif controlId == 375:
            self.changeListData(self.resolutionList, 373, 1)
        elif controlId == 384:
            self.changeListData(self.resolutionList, 383, -1)
        elif controlId == 385:
            self.changeListData(self.resolutionList, 383, 1)
        elif controlId == 394:
            self.changeListData(self.resolutionList, 393, -1)
        elif controlId == 395:
            self.changeListData(self.resolutionList, 393, 1)
        elif controlId == 489:
            self.changeListData(self.showseqList, 488, -1)
        elif controlId == 490:
            self.changeListData(self.showseqList, 488, 1)
        elif controlId == 492:
            self.changeListData(self.movieseqList, 491, -1)
        elif controlId == 493:
            self.changeListData(self.movieseqList, 491, 1)
            
        self.log("onClick return")



    def changeListData(self, thelist, controlid, val):
        self.log("changeListData " + str(controlid) + ", " + str(val))
        curval = self.getControl(controlid).getLabel()
        found = False
        index = 0

        if len(thelist) == 0:
            self.getControl(controlid).setLabel('')
            self.log("changeListData return Empty list")
            return

        for item in thelist:
            if item == curval:
                found = True
                break

            index += 1

        if found == True:
            index += val

        while index < 0:
            index += len(thelist)

        while index >= len(thelist):
            index -= len(thelist)

        self.getControl(controlid).setLabel(self.chnlst.uncleanString(thelist[index]))
        self.log("changeListData return")


    def changeChanType(self, channel, val):
        self.log("changeChanType " + str(channel) + ", " + str(val))
        chantype = 9999

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_type"))
        except:
            self.log("Unable to get channel type")

        if val != 0:
            chantype += val

            if chantype < 0:
                chantype = 9999
            elif chantype == 10000:
                chantype = 0
            elif chantype == 9998:
                chantype = NUMBER_CHANNEL_TYPES - 1
            elif chantype == NUMBER_CHANNEL_TYPES:
                chantype = 9999

            ADDON_SETTINGS.setSetting("Channel_" + str(channel) + "_type", str(chantype))
        else:
            self.channel_type = chantype
            self.setting1 = ''
            self.setting2 = ''
            self.setting3 = ''
            self.setting4 = ''
            self.setting5 = ''
            self.setting6 = ''
            self.setting7 = ''
            self.setting8 = ''
            self.setting9 = ''

            try:
                self.setting1 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_1")
                self.setting2 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_2")
                self.setting3 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_3")
                self.setting4 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_4")
                self.setting5 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_5")
                self.setting6 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_6")
                self.setting7 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_7")
                self.setting8 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_8")
                self.setting9 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_9")
            except:
                pass

        for i in range(NUMBER_CHANNEL_TYPES):
            if i == chantype:
                self.getControl(120 + i).setVisible(True) # show settings
                self.getControl(110).controlDown(self.getControl(120 + ((i + 1) * 10)))

                try:
                    self.getControl(111).controlDown(self.getControl(120 + ((i + 1) * 10 + 1)))
                except:
                    self.getControl(111).controlDown(self.getControl(120 + ((i + 1) * 10)))
            else:
                self.getControl(120 + i).setVisible(False) # hide settings

        self.fillInDetails(channel)
        self.log("changeChanType return")


    def fillInDetails(self, channel):
        self.getControl(104).setLabel("Channel " + str(channel))
        chantype = 9999
        chansetting1 = ''
        chansetting2 = ''
        chansetting3 = ''
        chansetting4 = ''
        chansetting5 = ''
        chansetting6 = ''
        chansetting7 = ''
        chansetting8 = ''

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_type"))
            chansetting1 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_1")
            chansetting2 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_2")
            chansetting3 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_3")
            chansetting4 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_4")
            chansetting5 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_5")
            chansetting6 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_6")
            chansetting7 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_7")
            chansetting8 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_8")
            chansetting9 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_9")
        except:
            self.log("Unable to get some setting")

        if chansetting2 == "": chansetting2 = 0
        if chansetting4 == "": chansetting4 = 0
        if chansetting5 == "": chansetting5 = 0
        if chansetting6 == "": chansetting6 = "All"
        #if chansetting7 == "": chansetting7 = 0
        #if chansetting8 == "": chansetting8 = 0
        if chansetting9 == "": chansetting9 = 0
        
        self.getControl(109).setLabel(self.getChanTypeLabel(chantype))

        if chantype == 0:
            plname = self.chnlst.getSmartPlaylistName(chansetting1)

            if len(plname) == 0:
                chansetting1 = ''

            self.getControl(130).setLabel(self.chnlst.getSmartPlaylistName(chansetting1), label2=chansetting1)
        elif chantype == 1:
            self.getControl(142).setLabel(self.findItemInList(self.networkList, chansetting1))
            self.getControl(343).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(349).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(346).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(347).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            if chansetting9 <> "":
                self.getControl(348).setSelected(int(chansetting9) == int(MODE_RANDOM_FILELISTS))
        elif chantype == 2:
            self.getControl(152).setLabel(self.findItemInList(self.studioList, chansetting1))
            self.getControl(353).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(356).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
        elif chantype == 3:
            self.getControl(162).setLabel(self.findItemInList(self.showGenreList, chansetting1))
            self.getControl(363).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(369).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(366).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(367).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
        elif chantype == 4:
            self.getControl(172).setLabel(self.findItemInList(self.movieGenreList, chansetting1))
            self.getControl(373).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(376).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
        elif chantype == 5:
            self.getControl(182).setLabel(self.findItemInList(self.mixedGenreList, chansetting1))
            self.getControl(383).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(389).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(386).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(387).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            self.getControl(488).setLabel(self.findItemInList(self.showseqList, chansetting7))
            self.getControl(491).setLabel(self.findItemInList(self.movieseqList, chansetting8))
        elif chantype == 6:
            self.getControl(192).setLabel(self.findItemInList(self.showList, chansetting1))
            self.getControl(393).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(396).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(397).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            self.getControl(194).setSelected(chansetting2 == str(MODE_SERIAL))
        elif chantype == 7: # folder
            fldname = chansetting3
            if len(fldname) == 0:
                chansetting1 = ''
            self.getControl(200).setLabel(fldname, label2=self.chnlst.uncleanString(chansetting1))
        elif chantype == 8: # music
            self.getControl(212).setLabel(self.findItemInList(self.musicGenreList, chansetting1))
        elif chantype == 9: # live
            self.getControl(222).setLabel(self.findItemInList(self.feedList, chansetting1))

        self.log("fillInDetails return")


    def findItemInList(self, thelist, item):
        loitem = item.lower()

        for i in thelist:
            if loitem == i.lower():
                return item
                
        if len(thelist) > 0:
            return thelist[0]
            
        return ''


    def getChanTypeLabel(self, chantype):
        if chantype == 0:
            return "Custom Playlist"
        elif chantype == 1:
            return "TV Network"
        elif chantype == 2:
            return "Movie Studio"
        elif chantype == 3:
            return "TV Genre"
        elif chantype == 4:
            return "Movie Genre"
        elif chantype == 5:
            return "Mixed Genre"
        elif chantype == 6:
            return "TV Show"
        elif chantype == 7:
            return "Folder"
        elif chantype == 8:
            return "Music Genre"
        elif chantype == 9:
            return "Live"
        elif chantype == 9999:
            return "None"

        return ''


    def updateListing(self, channel = -1):
        self.log("updateListing")
        start = 0
        end = 200

        if channel > -1:
            start = channel - 1
            end = channel

        for i in range(start, end):
            theitem = self.listcontrol.getListItem(i)
            chantype = 9999
            chansetting1 = ''
            chansetting2 = ''
            chansetting3 = ''
            newlabel = ''

            try:
                chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_type"))
                chansetting1 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_1")
                chansetting2 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_2")
                chansetting3 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_3")
            except:
                pass

            if chantype == 0:
                newlabel = self.chnlst.getSmartPlaylistName(chansetting1)
            elif chantype == 1 or chantype == 2 or chantype == 5 or chantype == 6:
                newlabel = chansetting3
            elif chantype == 3:
                newlabel = chansetting3
            elif chantype == 4:
                newlabel = chansetting3
            elif chantype == 7:
                newlabel = self.chnlst.uncleanString(chansetting3)
            elif chantype == 8:
                newlabel = chansetting3
            elif chantype == 9:
                newlabel = self.chnlst.uncleanString(chansetting3)

            theitem.setLabel2(newlabel)

        self.log("updateListing return")


#####################################################
#####################################################
#
# Utility Functions
#
#####################################################
#####################################################

    def log(self, msg, level = xbmc.LOGDEBUG):
        xbmc.log('TV Time-' + msg, level)


    def createDirectories(self):
        self.log("createDirectories")
        # setup directories
        self.createDirectory(CHANNELS_LOC)
        self.createDirectory(GEN_CHAN_LOC)
        self.createDirectory(PRESTAGE_LOC)
        self.createDirectory(TEMP_LOC)
        self.createDirectory(META_LOC)
        self.createDirectory(FEED_LOC)
        

    def createDirectory(self, directory):
        if not os.path.exists(directory):
            try:
                os.makedirs(directory)
            except:
                self.Error('Unable to create the directory - ' + str(directory))
                return
Example #22
0
    def readConfig(self):
        self.log('readConfig')
        ### TV TIME ###
        # Output all settings for debugging purposes
        self.log('#####################################################################################')
        self.log('General Settings:')
        self.log('  Auto off is - ' + str(REAL_SETTINGS.getSetting('AutoOff')))
        self.log('  Show info label on channel change is - ' + str(REAL_SETTINGS.getSetting('InfoOnChange') == "true")) 
        self.log('  Force Channel Reset is - ' + str(REAL_SETTINGS.getSetting('ForceChannelReset')))
        self.log('  Channel Reset Setting is - ' + str(REAL_SETTINGS.getSetting('ChannelResetSetting')))
        self.log('  Show Channel Bug is - ' + str(REAL_SETTINGS.getSetting('ShowChannelBug') == "true"))
        self.log('  Channel Logo Folder is - ' + str(REAL_SETTINGS.getSetting('ChannelLogoFolder')))   
        self.log('  Start Mode is - ' + str(REAL_SETTINGS.getSetting('StartMode')))   
        self.log('  Version is - ' + str(REAL_SETTINGS.getSetting('Version')))

        self.log('Channel Settings:')
        self.log('  Prestage Channels - ' + str(REAL_SETTINGS.getSetting('PrestageChannels')))
        self.log('  Startup Channel is - ' + str(REAL_SETTINGS.getSetting('startupChannel')))
        self.log('  Maximum Number of Music Genres to return - ' + str(REAL_SETTINGS.getSetting('maxMusicGenres')))
        self.log('  Maximum Number of Movie Genres to return  - ' + str(REAL_SETTINGS.getSetting('maxMovieGenres')))

        self.log('Auto Tune Settings:')
        self.log('  Auto Find TV Network Channels is - ' + str(REAL_SETTINGS.getSetting('autoFindNetworks')))
        self.log('  Auto Find Movie Studios Channels is - ' + str(REAL_SETTINGS.getSetting('autoFindStudios')))
        self.log('  Auto Find TV Genres Channels is - ' + str(REAL_SETTINGS.getSetting('autoFindTVGenres')))
        self.log('  Auto Find Movie Genres Channels is - ' + str(REAL_SETTINGS.getSetting('autoFindMovieGenres')))
        self.log('  Auto Find Mixed Genres Channels is - ' + str(REAL_SETTINGS.getSetting('autoFindMixGenres')))
        self.log('  Auto Find Music Genres Channels is - ' + str(REAL_SETTINGS.getSetting('autoFindMusicGenres')))
        self.log('  Auto Find Live Channels is - ' + str(REAL_SETTINGS.getSetting('autoFindLive')))
        self.log('  Channel Limit is - ' + str(REAL_SETTINGS.getSetting('limit')))
        
        self.log('Off Air Settings:')
        self.log('  Off Air Mode is - ' + str(REAL_SETTINGS.getSetting('offair') == "true" ))
        self.log('  Off Air File is - ' + str(REAL_SETTINGS.getSetting('offairfile')))

        self.log('Bumpers Settings:')
        self.log('  Bumpers Mode is - ' + str(REAL_SETTINGS.getSetting('bumpers') == "true" ))
        self.log('  Bumpers Folder is - ' + str(REAL_SETTINGS.getSetting('bumpersfolder')))
        self.log('  Number of Bumpers is - ' + str(REAL_SETTINGS.getSetting('numbumpers')))
        self.log('  Max Number of Bumpers is - ' + str(REAL_SETTINGS.getSetting('maxbumpers')))

        self.log('Commercials Settings:')
        self.log('  Commercials Mode is - ' + str(REAL_SETTINGS.getSetting('commercials') == "true" ))
        self.log('  Commercials Folder is - ' + str(REAL_SETTINGS.getSetting('commercialsfolder')))
        self.log('  Number of Commercials is - ' + str(REAL_SETTINGS.getSetting('numcommercials')))
        self.log('  Max Number of Commercials is - ' + str(REAL_SETTINGS.getSetting('maxcommercials')))

        self.log('Trailers Settings:')
        self.log('  Trailers Mode is - ' + str(REAL_SETTINGS.getSetting('trailers') == "true" ))
        self.log('  Trailers Folder is - ' + str(REAL_SETTINGS.getSetting('trailersfolder')))
        self.log('  Number of Trailers is - ' + str(REAL_SETTINGS.getSetting('numtrailers')))
        self.log('  Max Number of Trailers is - ' + str(REAL_SETTINGS.getSetting('maxtrailers')))

        self.log('Runtime Settings:')
        self.log('  Current Channel is - ' + str(REAL_SETTINGS.getSetting('CurrentChannel')))
        self.log('  Last Reset Time is - ' + str(REAL_SETTINGS.getSetting('LastResetTime')))
        self.log('#####################################################################################')        
        ###############
        
        # Sleep setting is in 30 minute incriments...so multiply by 30, and then 60 (min to sec)
        self.sleepTimeValue = int(REAL_SETTINGS.getSetting('AutoOff')) * 1800
        self.log('Auto off is ' + str(self.sleepTimeValue))
        self.infoOnChange = REAL_SETTINGS.getSetting("InfoOnChange") == "true"
        self.log('Show info label on channel change is ' + str(self.infoOnChange))
        self.showChannelBug = REAL_SETTINGS.getSetting("ShowChannelBug") == "true"
        self.log('Show channel bug - ' + str(self.showChannelBug))
        self.forceReset = REAL_SETTINGS.getSetting('ForceChannelReset') == "true"
        self.channelResetSetting = REAL_SETTINGS.getSetting('ChannelResetSetting')
        self.log("Channel reset setting - " + str(self.channelResetSetting))
        self.channelLogos = xbmc.translatePath(REAL_SETTINGS.getSetting('ChannelLogoFolder'))
        ### TV TIME ###
        self.startupChannel = int(REAL_SETTINGS.getSetting("startupChannel"))
        ###############

        if os.path.exists(self.channelLogos) == False:
            self.channelLogos = IMAGES_LOC

        self.log('Channel logo folder - ' + self.channelLogos)
        self.startupTime = time.time()
        chn = ChannelList()
        self.background.setVisible(True)
        self.channels = chn.setupList()

        if self.channels is None:
            self.log('readConfig No channel list returned')
            self.end()
            return False

        self.Player.stop()

        self.log('readConfig return')
        return True
Example #23
0
 def __init__(self, *args, **kwargs):
     self.log('__init__')
     self.chanlist = ChannelList()
Example #24
0
class Migrate:
    def __init__(self):
        self.chanlist = ChannelList()
        chkLowPower()
        
        
    def log(self, msg, level = xbmc.LOGDEBUG):
        log('Migrate: ' + msg, level)
          
   
    def onInit(self):
        self.log("onInit")
        
        
    def autoTune(self):
        self.log("autoTune")
        if REAL_SETTINGS.getSetting("Autotune") == "true" and REAL_SETTINGS.getSetting("Warning1") == "true":
            self.log('starting autoTune')
            Youtube = self.chanlist.youtube_player_ok()
            self.chanlist.background = True
            self.chanlist.makenewlists = True
            self.chanlist.forceReset = True
            self.myOverlay.setBackgroundStatus("Initializing: Autotuning",0,string2=" ")
            
            #Reserve channel check 
            channelNum = 1       
            if REAL_SETTINGS.getSetting("reserveChannels") == "true":
                self.log('autoTune, using reserve Channels')
                channelNum = 500
            baseNum = channelNum
            self.log('autoTune, Starting channelNum = ' + str(baseNum))
            
            # LiveTV - PVR
            if REAL_SETTINGS.getSetting("autoFindLivePVR") == "true":
                self.log("autoTune, adding Live PVR Channels")
                channelNum = baseNum
                PVRChannels = self.chanlist.getPVRChannels()
                for i in range(len(PVRChannels)):
                    try:
                        CHid = PVRChannels[i][0]
                        CHname = self.chanlist.cleanLabels(PVRChannels[i][1])
                        CHthmb = PVRChannels[i][2]
                        if REAL_SETTINGS.getSetting("respectChannels") == "true":
                            channelNum = self.chkChannelNum(int(CHid))
                        else:
                            channelNum = self.chkChannelNum(channelNum)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "8")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", CHid)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", self.chanlist.getPVRLink(i))
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", 'pvr')
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", CHname + ' PVR')
                        rulecnt = 1
                        if isLowPower() == True:
                            rulecnt = 2
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_id", "23")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_opt_1", 'No')
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "%s" %str(rulecnt))
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")  
                        self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding PVR channels",string2=CHname,progress=int(channelNum*100//CHANNEL_LIMIT))
                    except:
                        pass
            
            # LiveTV - HDHomeRun           
            if REAL_SETTINGS.getSetting("autoFindLiveHDHR")  == "true":
                self.log("autoTune, adding Live HDHomeRun Channels")
                channelNum = baseNum
                self.chanlist.cached_readXMLTV = []
                HDHRChannels = self.chanlist.getHDHRChannels(True)
                for i in range(len(HDHRChannels)):
                    try:
                        CHid = HDHRChannels[i][0]
                        CHname = self.chanlist.cleanLabels(HDHRChannels[i][1])
                        link = HDHRChannels[i][4]
                        if REAL_SETTINGS.getSetting("respectChannels") == "true":
                            channelNum = self.chkChannelNum(int(CHid))
                        else:
                            channelNum = self.chkChannelNum(channelNum)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "8")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", CHid)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", link)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", "hdhomerun")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", CHname + ' HDHR')
                        rulecnt = 1
                        if isLowPower() == True:
                            rulecnt = 2
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_id", "23")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_opt_1", 'No')
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "%s" %str(rulecnt))
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")     
                        self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding HDHomeRun channels",string2=CHname,progress=int(channelNum*100//CHANNEL_LIMIT))
                    except Exception,e:
                        self.log("autoFindLiveHD 2, Failed! " + str(e))
             
            # LiveTV - USTVnow
            if REAL_SETTINGS.getSetting("autoFindUSTVNOW") == "true" and isUSTVnow() != False:
                self.log("autoTune, adding USTVnow Channels")
                channelNum = baseNum
                USTVChannels = self.chanlist.getUSTVChannels()
                for i in range(len(USTVChannels)):
                    try:
                        CHname, path, thumb = USTVChannels[i]
                        channelNum = self.chkChannelNum(channelNum)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "8")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", CHname)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", path)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", "ustvnow")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", CHname + ' USTV')    
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_id", "13")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_opt_1", "2") 
                        rulecnt = 2
                        if isLowPower() == True:
                            rulecnt = 3
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_3_id", "23")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_3_opt_1", 'No')
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "%s" %str(rulecnt))
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")                 
                        self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding USTVnow channels",string2=CHname,progress=int(channelNum*100//CHANNEL_LIMIT))
                    except:
                        pass

            # Custom Playlists
            if REAL_SETTINGS.getSetting("autoFindCustom") == "true":
                self.log("autoTune, adding Custom SmartPlaylists")
                channelNum = baseNum
                Music_path = 'special://profile/playlists/music'
                Mixed_path = 'special://profile/playlists/mixed'
                Video_path = 'special://profile/playlists/video'
                xsp_path = [Music_path, Mixed_path, Video_path]
                i = 0
                for path in xsp_path:
                    xspLst = self.chanlist.walk(path,['.xsp'])
                    for xsp in xspLst:
                        if xsp.endswith('.xsp') and len(re.findall("channel_",xsp)) != 0:
                            i += 1
                            if REAL_SETTINGS.getSetting("respectChannels") == "true":
                                channelNum = self.chkChannelNum(int((re.findall("channel_(\d+)", xsp))[0]))
                            else:
                                channelNum = self.chkChannelNum(channelNum)
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", xbmc.translatePath(xsp))
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                            self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Custom SmartPlaylists",string2=uni(self.chanlist.getSmartPlaylistName(xsp)),progress=int(channelNum*100//CHANNEL_LIMIT))

            # Custom SuperFavs
            
            if REAL_SETTINGS.getSetting("autoFindSuperFav") == "true" :
                self.log("autoTune, adding Super Favourites")
                channelNum = baseNum
                plugin_details = self.chanlist.requestList('plugin://plugin.program.super.favourites')
                
                for i in plugin_details:
                    include = False
                    
                    try:
                        filetypes = re.search('"filetype" *: *"(.*?)"', i)
                        labels = re.search('"label" *: *"(.*?)"', i)
                        files = re.search('"file" *: *"(.*?)"', i)

                        #if core variables have info proceed
                        if filetypes and files and labels:
                            filetype = filetypes.group(1)
                            file = (files.group(1))
                            label = (labels.group(1))
                            
                            if label.lower() not in SF_FILTER:
                                if filetype == 'directory':
                                    if label.lower() in ['pseudotv']:
                                        plugin_details = self.chanlist.requestList(file)
                                        include = True
                                    
                                    elif label.lower().startswith('channel'):
                                        plugin_details = self.chanlist.requestList(file)
                                        include = True

                                    if include == True:
                                        channelNum = self.chkChannelNum(channelNum)         
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "15")
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", file)
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "")
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", str(MEDIA_LIMIT))
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", "0")
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "1")
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", label)
                                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                                        self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Super Favourites",string2=label,progress=int(channelNum*100//CHANNEL_LIMIT))
                    except:
                        pass
                      
            #TV - Networks/Genres
            
            if (REAL_SETTINGS.getSetting("autoFindNetworks") == "true" or REAL_SETTINGS.getSetting("autoFindTVGenres") == "true"):
                self.log("autoTune, Searching for TV Channels")
                self.chanlist.fillTVInfo()

            # need to add check for auto find network channels
            
            if REAL_SETTINGS.getSetting("autoFindNetworks") == "true":
                self.log("autoTune, adding TV Networks")
                channelNum = baseNum
                for i in range(len(self.chanlist.networkList)):
                    channelNum = self.chkChannelNum(channelNum)
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "1")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1",uni(self.chanlist.networkList[i]))
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "4")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                    self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding TV Networks",string2=uni(self.chanlist.networkList[i]),progress=int(channelNum*100//CHANNEL_LIMIT))
            
            
            if REAL_SETTINGS.getSetting("autoFindTVGenres") == "true":
                self.log("autoTune, adding TV Genres")
                channelNum = baseNum
                for i in range(len(self.chanlist.showGenreList)):
                    if self.chanlist.showGenreList[i] != '':
                        channelNum = self.chkChannelNum(channelNum)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "3")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", uni(self.chanlist.showGenreList[i]))
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "4")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                        self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding TV Genres",string2=uni(self.chanlist.showGenreList[i]),progress=int(channelNum*100//CHANNEL_LIMIT))
            
            
            if (REAL_SETTINGS.getSetting("autoFindStudios") == "true" or REAL_SETTINGS.getSetting("autoFindMovieGenres") == "true"):
                self.chanlist.fillMovieInfo()

            if REAL_SETTINGS.getSetting("autoFindStudios") == "true":
                self.log("autoTune, adding Movie Studios")
                channelNum = baseNum
                for i in range(len(self.chanlist.studioList)):
                    channelNum = self.chkChannelNum(channelNum)
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "2")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", uni(self.chanlist.studioList[i]))
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                    self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Movie Studios",string2=uni(self.chanlist.studioList[i]),progress=int(channelNum*100//CHANNEL_LIMIT))
                    
            
            if REAL_SETTINGS.getSetting("autoFindMovieGenres") == "true":
                self.log("autoTune, adding Movie Genres")
                channelNum = baseNum
                for i in range(len(self.chanlist.movieGenreList)):
                    if self.chanlist.movieGenreList[i] != '':
                        channelNum = self.chkChannelNum(channelNum)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "4")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", uni(self.chanlist.movieGenreList[i]))
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                        self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Movie Genres",string2=uni(self.chanlist.movieGenreList[i]),progress=int(channelNum*100//CHANNEL_LIMIT))
                     
            if REAL_SETTINGS.getSetting("autoFindMixGenres") == "true":
                self.chanlist.fillMixedGenreInfo()
            
            if REAL_SETTINGS.getSetting("autoFindMixGenres") == "true":
                self.log("autoTune, adding Mixed Genres")
                channelNum = baseNum
                for i in range(len(self.chanlist.mixedGenreList)):
                    if self.chanlist.mixedGenreList[i] != '':
                        channelNum = self.chkChannelNum(channelNum)
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "5")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", uni(self.chanlist.mixedGenreList[i]))
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "4")
                        ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                        self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Mixed Genres",string2=uni(self.chanlist.mixedGenreList[i]),progress=int(channelNum*100//CHANNEL_LIMIT))
            
            #recent movie/tv
             
            if REAL_SETTINGS.getSetting("autoFindRecent") == "true":
                self.log("autoTune, adding Recent TV/Movies")
                channelNum = baseNum
                channelNum = self.chkChannelNum(channelNum)
                TVflename = self.chanlist.createRecentlyAddedTV()
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", TVflename)
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "3")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", "Recent TV")  
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_id", "12")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_3_id", "13")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_3_opt_1", "4")  
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Recent TV",string2=' ')
                channelNum = self.chkChannelNum(channelNum)
                Movieflename = self.chanlist.createRecentlyAddedMovies()     
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", Movieflename)
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "2")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", "Recent Movies")  
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_id", "13")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_opt_1", "4")  
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Recent Movies",string2=' ')
               
            #3D movies
             
            if REAL_SETTINGS.getSetting("autoFind3DMovies") == "true":
                self.log("autoTune, adding 3D Movies")
                channelNum = baseNum
                if len(self.chanlist.movie3Dlist) >= MEDIA_LIMIT:
                    channelNum = self.chkChannelNum(channelNum)
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", "")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "0")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                    self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding 3D Movies",string2=' ')
                    
            #Music Genre
            if REAL_SETTINGS.getSetting("autoFindMusicGenres") == "true":
                self.log("autoTune, adding Music Genres")
                channelNum = baseNum
                self.chanlist.fillMusicInfo()
                for i in range(len(self.chanlist.musicGenreList)):
                    channelNum = self.chkChannelNum(channelNum)
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "12")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", uni(self.chanlist.musicGenreList[i]))
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "4")
                    ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                    self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Music Genres",string2=uni(self.chanlist.musicGenreList[i]),progress=int(channelNum*100//CHANNEL_LIMIT))
            
            #Local Directory
            if REAL_SETTINGS.getSetting("autoFindVideosLocal") != "":
                self.log("autoTune, adding Local Videos")
                channelNum = baseNum 
                channelNum = self.chkChannelNum(channelNum)
                LocalVideo = str(REAL_SETTINGS.getSetting('autoFindVideosLocal'))  
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "7")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", "" +LocalVideo+ "")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", str(MEDIA_LIMIT))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", "1")     
                self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Local Directory",string2=self.chanlist.getChannelName(7, channelNum, LocalVideo))

            #Youtube - PseudoNetwork
            if REAL_SETTINGS.getSetting("autoFindCommunity_PseudoNetworks") == "true" and isCompanionInstalled() == True:
                self.log("autoTune, adding PseudoNetworks")
                channelNum = baseNum
                detail = uni(self.chanlist.requestList('plugin://plugin.video.pseudo.companion/?mode=3000&name=PseudoNetworks&previous=getOnlineMedia&url'))
                show_busy_dialog()
                for i in detail:
                    files = re.search('"file" *: *"(.*?)",', i)
                    filetypes = re.search('"filetype" *: *"(.*?)",', i)
                    labels = re.search('"label" *: *"(.*?)",', i)
                    if filetypes and labels and files:
                        filetype = filetypes.group(1)
                        name = self.chanlist.cleanLabels(labels.group(1))
                        file = (files.group(1).replace("\\\\", "\\"))
                        if filetype == 'directory':
                            channelNum = self.chkChannelNum(channelNum)
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "15")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", file)
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", str(MEDIA_LIMIT))
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", "0")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "1")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", name)  
                            ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                            self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding PseudoNetworks",string2=name)
                    hide_busy_dialog()

            #Youtube - Seasonal
            
            if REAL_SETTINGS.getSetting("autoFindCommunity_Youtube_Seasonal") == "true":
                channelNum = baseNum
                today = datetime.datetime.now()
                month = today.strftime('%B')
                channelNum = self.chkChannelNum(channelNum)
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "10")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_1", month)
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", "31")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_3", str(MEDIA_LIMIT))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rulecount", "2")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_id", "1")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_1_opt_1", "Seasonal Channel")  
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_id", "13")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_rule_2_opt_1", "168")  
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_changed", "true")
                self.myOverlay.setBackgroundStatus("Initializing: Autotuning adding Seasonal Youtube",string2=" ")

            # #Reserve channel clear old            
            if REAL_SETTINGS.getSetting("reserveChannels") == "true":
                self.clearReserved(baseNum)
            
            # reset auto tune settings        
            REAL_SETTINGS.setSetting('Autotune', "false")
            REAL_SETTINGS.setSetting('Warning1', "false") 
            REAL_SETTINGS.setSetting("autoFindCustom","false")
            REAL_SETTINGS.setSetting("autoFindSuperFav","false") 
            REAL_SETTINGS.setSetting('autoFindLivePVR', "false")
            REAL_SETTINGS.setSetting('autoFindLiveHDHR', "0")
            REAL_SETTINGS.setSetting('autoFindUSTVNOW', "false")  
            REAL_SETTINGS.setSetting("autoFindNetworks","false")
            REAL_SETTINGS.setSetting("autoFindStudios","false")
            REAL_SETTINGS.setSetting("autoFindTVGenres","false")
            REAL_SETTINGS.setSetting("autoFindMovieGenres","false")
            REAL_SETTINGS.setSetting("autoFindMixGenres","false")
            REAL_SETTINGS.setSetting("autoFind3DMovies","false")    
            REAL_SETTINGS.setSetting("autoFindRecent","false")      
            REAL_SETTINGS.setSetting("autoFindMusicGenres","false")
            REAL_SETTINGS.setSetting("autoFindVideosLocal","")
            REAL_SETTINGS.setSetting("autoFindCommunity_PseudoNetworks","false")  
            REAL_SETTINGS.setSetting("ForceChannelReset","true")
            ADDON_SETTINGS.setSetting('LastExitTime', str(int(time.time())))
            ADDON_SETTINGS.writeSettings()
            self.log('autoTune, return')
            self.myOverlay.setBackgroundStatus("Initializing: Autotuning Complete",string2=' ')
            return True
class ChannelListThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.myOverlay = None
        sys.setcheckinterval(25)
        self.chanlist = ChannelList()
        self.paused = False
        self.fullUpdating = True


    def log(self, msg, level = xbmc.LOGDEBUG):
        log('ChannelListThread: ' + msg, level)


    def run(self):
        self.log("Starting")
        self.chanlist.exitThread = False
        self.chanlist.readConfig()
        self.chanlist.sleepTime = 0.1

        if self.myOverlay == None:
            self.log("Overlay not defined. Exiting.")
            return
            
        self.chanlist.myOverlay = self.myOverlay
        self.fullUpdating = (self.myOverlay.backgroundUpdating == 0)
        validchannels = 0

        for i in range(self.myOverlay.maxChannels):
            self.chanlist.channels.append(Channel())

            if self.myOverlay.channels[i].isValid:
                validchannels += 1

        # Don't load invalid channels if minimum threading mode is on
        if self.fullUpdating and self.myOverlay.isMaster:
            if validchannels < self.chanlist.enteredChannelCount:
                xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ( REAL_SETTINGS.getAddonInfo('name'), REAL_SETTINGS.getLocalizedString(30024), 4000, __icon__) )

            for i in range(self.myOverlay.maxChannels):
                if self.myOverlay.channels[i].isValid == False:
                    while True:
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return

                        time.sleep(1)

                        if self.paused == False:
                            break

                    self.chanlist.channels[i].setAccessTime(self.myOverlay.channels[i].lastAccessTime)

                    try:
                        if self.chanlist.setupChannel(i + 1, True, True, False) == True:
                            while self.paused:
                                if self.myOverlay.isExiting:
                                    self.log("IsExiting")
                                    return

                                time.sleep(1)

                            self.myOverlay.channels[i] = self.chanlist.channels[i]

                            if self.myOverlay.channels[i].isValid == True:
                                xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ( REAL_SETTINGS.getAddonInfo('name'), xbmc.getLocalizedString(19029) + ' ' + str(i + 1) + ' ' + REAL_SETTINGS.getLocalizedString(30025), 4000, __icon__) )
                    except:
                        self.log("Unknown Channel Creation Exception", xbmc.LOGERROR)
                        self.log(traceback.format_exc(), xbmc.LOGERROR)
                        return

        REAL_SETTINGS.setSetting('ForceChannelReset', 'false')
        self.chanlist.sleepTime = 0.3

        while True:
            for i in range(self.myOverlay.maxChannels):
                modified = True

                while modified == True and self.myOverlay.channels[i].getTotalDuration() < PREP_CHANNEL_TIME and self.myOverlay.channels[i].Playlist.size() < 16288:
                    # If minimum updating is on, don't attempt to load invalid channels
                    if self.fullUpdating == False and self.myOverlay.channels[i].isValid == False and self.myOverlay.isMaster:
                        break

                    modified = False

                    if self.myOverlay.isExiting:
                        self.log("Closing thread")
                        return

                    time.sleep(2)
                    curtotal = self.myOverlay.channels[i].getTotalDuration()

                    if self.myOverlay.isMaster:
                        if curtotal > 0:
                            # When appending, many of the channel variables aren't set, so copy them over.
                            # This needs to be done before setup since a rule may use one of the values.
                            # It also needs to be done after since one of them may have changed while being setup.
                            self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                            self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                            self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                            self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                            self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                            self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                            # Only allow appending valid channels, don't allow erasing them
                            
                            try:
                                self.chanlist.setupChannel(i + 1, True, False, True)
                            except:
                                self.log("Unknown Channel Appending Exception", xbmc.LOGERROR)
                                self.log(traceback.format_exc(), xbmc.LOGERROR)
                                return

                            self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                            self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                            self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                            self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                            self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                            self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                        else:
                            try:
                                self.chanlist.setupChannel(i + 1, True, True, False)
                            except:
                                self.log("Unknown Channel Modification Exception", xbmc.LOGERROR)
                                self.log(traceback.format_exc(), xbmc.LOGERROR)
                                return
                    else:
                        try:
                            # We're not master, so no modifications...just try and load the channel
                            self.chanlist.setupChannel(i + 1, True, False, False)
                        except:
                            self.log("Unknown Channel Loading Exception", xbmc.LOGERROR)
                            self.log(traceback.format_exc(), xbmc.LOGERROR)
                            return

                    self.myOverlay.channels[i] = self.chanlist.channels[i]

                    if self.myOverlay.isMaster:
                        ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(self.myOverlay.channels[i].totalTimePlayed))

                    if self.myOverlay.channels[i].getTotalDuration() > curtotal and self.myOverlay.isMaster:
                        modified = True

                    # A do-while loop for the paused state
                    while True:
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return

                        time.sleep(2)

                        if self.paused == False:
                            break

                timeslept = 0

            if self.fullUpdating == False and self.myOverlay.isMaster:
                return

            # If we're master, wait 30 minutes in between checks.  If not, wait 5 minutes.
            while (timeslept < 1800 and self.myOverlay.isMaster == True) or (timeslept < 300 and self.myOverlay.isMaster == False):
                if self.myOverlay.isExiting:
                    self.log("IsExiting")
                    return

                time.sleep(2)
                timeslept += 2

        self.log("All channels up to date.  Exiting thread.")


    def pause(self):
        self.paused = True
        self.chanlist.threadPaused = True


    def unpause(self):
        self.paused = False
        self.chanlist.threadPaused = False
Example #26
0
 def __init__(self):
     self.chanlist = ChannelList()
     chkLowPower()
Example #27
0
class APP(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.log('__init__')
        self.chanlist = ChannelList()

    def log(self, msg, level=xbmc.LOGDEBUG):
        log('APP: ' + msg, level)

    def onFocus(self, controlid):
        self.log('onFocus')

    def onInit(self):
        self.log('onInit')
        self.PanelPlugins = self.getControl(500)
        self.PanelItems = self.getControl(501)
        self.fillPlugins()
        self.setFocus(self.PanelPlugins)

    def onClick(self, controlid):
        self.log('onClick ' + str(controlid))
        if controlid == 500:
            playitem = self.PanelPlugins.getListItem(
                self.PanelPlugins.getSelectedPosition())
            self.chanlist.fillListItems('plugin://' +
                                        playitem.getProperty('mediapath'))
            self.setFocus(self.PanelItems)
            # xbmc.executebuiltin('Container.Refresh')
        elif controlid in [6001, 6002, 6003, 6004]:
            if controlid == 6001:
                self.log('ACTION_TELETEXT_RED')
                self.MyOverlayWindow.windowSwap('EPG')
            elif controlid == 6002:
                self.log('ACTION_TELETEXT_GREEN')
                self.MyOverlayWindow.windowSwap('DVR')
            elif controlid == 6003:
                self.log('ACTION_TELETEXT_YELLOW')
                self.MyOverlayWindow.windowSwap('VOD')
            elif controlid == 6004:
                self.log('ACTION_TELETEXT_BLUE')
                self.MyOverlayWindow.windowSwap('APP')

    def onAction(self, act):
        self.log('onAction ' + str(act.getId()))
        action = act.getId()
        if action in ACTION_PREVIOUS_MENU:
            self.closeAPP()

        elif action == ACTION_TELETEXT_RED:
            self.log('ACTION_TELETEXT_RED')
            self.MyOverlayWindow.windowSwap('EPG')

        elif action == ACTION_TELETEXT_GREEN:
            self.log('ACTION_TELETEXT_GREEN')
            self.MyOverlayWindow.windowSwap('DVR')

        elif action == ACTION_TELETEXT_YELLOW:
            self.log('ACTION_TELETEXT_YELLOW')
            self.MyOverlayWindow.windowSwap('VOD')

        elif action == ACTION_TELETEXT_BLUE:
            self.log('ACTION_TELETEXT_BLUE')
            self.MyOverlayWindow.windowSwap('APP')

        if action in ACTION_PREVIOUS_MENU:
            print 'ACTION_PREVIOUS_MENU'

        elif action in ACTION_MOVE_DOWN:
            print 'ACTION_MOVE_DOWN'

        elif action in ACTION_MOVE_UP:
            print 'ACTION_MOVE_UP'

        elif action in ACTION_MOVE_LEFT:
            print 'ACTION_MOVE_LEFT'

        elif action in ACTION_MOVE_RIGHT:
            print 'ACTION_MOVE_RIGHT'

        elif action in ACTION_PAGEDOWN:
            print 'ACTION_PAGEDOWN'

        elif action in ACTION_PAGEUP:
            print 'ACTION_PAGEUP'

        elif action in ACTION_SELECT_ITEM:
            print 'ACTION_SELECT_ITEM'

    def closeAPP(self):
        self.log('closeAPP')
        if self.MyOverlayWindow.channelThread.isAlive():
            self.MyOverlayWindow.channelThread.unpause()
        self.close()

    def fillPlugins(self, type='video'):
        self.log('fillPlugins, type = ' + type)
        json_query = (
            '{"jsonrpc":"2.0","method":"Addons.GetAddons","params":{"type":"xbmc.addon.%s","properties":["name","path","thumbnail","description","fanart","summary"]}, "id": 1 }'
            % type)
        json_detail = self.chanlist.sendJSON(json_query)
        detail = re.compile("{(.*?)}", re.DOTALL).findall(json_detail)
        for f in detail:
            names = re.search('"name" *: *"(.*?)",', f)
            paths = re.search('"addonid" *: *"(.*?)",', f)
            thumbnails = re.search('"thumbnail" *: *"(.*?)",', f)
            fanarts = re.search('"fanart" *: *"(.*?)",', f)
            descriptions = re.search('"description" *: *"(.*?)",', f)
            if not descriptions:
                descriptions = re.search('"summary" *: *"(.*?)",', f)
            if descriptions:
                description = self.chanlist.cleanLabels(descriptions.group(1))
            else:
                description = ''
            if names and paths:
                name = self.chanlist.cleanLabels(names.group(1))
                path = paths.group(1)
                if type == 'video' and path.startswith('plugin.video'):
                    thumbnail = removeNonAscii(thumbnails.group(1))
                    fanart = removeNonAscii(fanarts.group(1))
                    self.Items = xbmcgui.ListItem(label=name,
                                                  thumbnailImage=thumbnail)
                    self.Items.setIconImage(thumbnail)
                    self.Items.setProperty("mediapath", path)
                    self.Items.setProperty("Fanart_Image", fanart)

                    infoList = {}
                    infoList['mediatype'] = type
                    infoList['mpaa'] = 'Unknown'
                    infoList['tvshowtitle'] = name
                    infoList['title'] = name
                    infoList['originaltitle'] = 'originaltitle'
                    infoList['sorttitle'] = 'sorttitle'
                    infoList['studio'] = 'Studio'
                    infoList['genre'] = 'Genre'
                    infoList['plot'] = 'Plot'
                    infoList['plotoutline'] = 'plotoutline'
                    infoList['tagline'] = 'tagline'
                    infoList['dateadded'] = 'dateadded'
                    infoList['premiered'] = 'premiered'
                    infoList['aired'] = 'aired'
                    infoList['code'] = 'code'
                    infoList['lastplayed'] = 'lastplayed'
                    # infoList['album']         = 'album'
                    # infoList['artist']        = ['artist']
                    # infoList['votes']         = 'votes'
                    infoList['duration'] = 1
                    infoList['year'] = 1977
                    infoList['season'] = 3
                    infoList['episode'] = 4
                    infoList['playcount'] = 5
                    self.Items.setInfo('Video', infoList)

                    infoArt = {}
                    infoArt['thumb'] = thumbnail
                    infoArt['poster'] = thumbnail
                    infoArt['banner'] = ''
                    infoArt['fanart'] = fanart
                    infoArt['clearart'] = ''
                    infoArt['clearlogo'] = ''
                    infoArt['landscape'] = fanart
                    infoList['icon'] = thumbnail
                    self.Items.setArt(infoArt)
                    self.PanelPlugins.addItem(self.Items)

    def fillListItems(self, url, type='video', file_type=False):
        self.log('fillListItems')
        self.Items = []
        if not file_type:
            detail = uni(self.chanlist.requestList(url, type))
        else:
            detail = uni(self.chanlist.requestItem(url, type))
        for f in detail:
            files = re.search('"file" *: *"(.*?)",', f)
            filetypes = re.search('"filetype" *: *"(.*?)",', f)
            labels = re.search('"label" *: *"(.*?)",', f)
            thumbnails = re.search('"thumbnail" *: *"(.*?)",', f)
            fanarts = re.search('"fanart" *: *"(.*?)",', f)
            descriptions = re.search('"description" *: *"(.*?)",', f)

            if filetypes and labels and files:
                filetype = filetypes.group(1)
                name = self.chanlist.cleanLabels(labels.group(1))
                file = (files.group(1).replace("\\\\", "\\"))

                if not descriptions:
                    description = ''
                else:
                    description = self.chanlist.cleanLabels(
                        descriptions.group(1))

                if thumbnails != None and len(thumbnails.group(1)) > 0:
                    thumbnail = thumbnails.group(1)
                else:
                    thumbnail = THUMB

                if fanarts != None and len(fanarts.group(1)) > 0:
                    fanart = fanarts.group(1)
                else:
                    fanart = FANART

                self.Items = xbmcgui.ListItem(label=name,
                                              thumbnailImage=thumbnail)

                if filetype == 'file':
                    self.Items.setProperty('IsPlayable', 'true')
                else:
                    self.Items.setProperty('IsPlayable', 'false')

                self.Items.setIconImage(thumbnail)
                self.Items.setProperty("mediapath", file)
                self.Items.setProperty("Fanart_Image", fanart)

                infoList = {}
                infoList['mediatype'] = type
                infoList['mpaa'] = 'Unknown'
                infoList['tvshowtitle'] = name
                infoList['title'] = name
                infoList['originaltitle'] = 'originaltitle'
                infoList['sorttitle'] = 'sorttitle'
                infoList['studio'] = 'Studio'
                infoList['genre'] = 'Genre'
                infoList['plot'] = 'Plot'
                infoList['plotoutline'] = 'plotoutline'
                infoList['tagline'] = 'tagline'
                infoList['dateadded'] = 'dateadded'
                infoList['premiered'] = 'premiered'
                infoList['aired'] = 'aired'
                infoList['code'] = 'code'
                infoList['lastplayed'] = 'lastplayed'
                # infoList['album']         = 'album'
                # infoList['artist']        = ['artist']
                # infoList['votes']         = 'votes'
                infoList['duration'] = 1
                infoList['year'] = 1977
                infoList['season'] = 3
                infoList['episode'] = 4
                infoList['playcount'] = 5
                self.Items.setInfo('Video', infoList)

                infoArt = {}
                infoArt['thumb'] = thumbnail
                infoArt['poster'] = thumbnail
                infoArt['banner'] = ''
                infoArt['fanart'] = fanart
                infoArt['clearart'] = ''
                infoArt['clearlogo'] = ''
                infoArt['landscape'] = fanart
                infoList['icon'] = thumbnail
                self.Items.setArt(infoArt)
                self.PanelItems.addItem(self.Items)
Example #28
0
class TVOverlay(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        self.log('__init__')
        # initialize all variables
        self.channels = []
        self.Player = MyPlayer()
        self.Player.overlay = self
        self.inputChannel = -1
        self.channelLabel = []
        self.lastActionTime = 0
        self.actionSemaphore = threading.BoundedSemaphore()
        self.channelThread = ChannelListThread()
        self.channelThread.myOverlay = self

        if not USING_FRODO:
            self.setCoordinateResolution(1)

        self.timeStarted = 0
        self.infoOnChange = True
        self.infoOffset = 0
        self.invalidatedChannelCount = 0
        self.showingInfo = False
        self.showChannelBug = False
        self.notificationLastChannel = 0
        self.notificationLastShow = 0
        self.notificationShowedNotif = False
        self.isExiting = False
        self.maxChannels = 0
        self.notPlayingCount = 0
        self.ignoreInfoAction = False
        self.shortItemLength = 60
        self.runningActionChannel = 0
        self.channelDelay = 0

        for i in range(3):
            self.channelLabel.append(xbmcgui.ControlImage(50 + (50 * i), 50, 50, 50, IMAGES_LOC + 'solid.png', colorDiffuse='0xAA00ff00'))
            self.addControl(self.channelLabel[i])
            self.channelLabel[i].setVisible(False)

        self.doModal()
        self.log('__init__ return')


    def resetChannelTimes(self):
        for i in range(self.maxChannels):
            self.channels[i].setAccessTime(self.timeStarted - self.channels[i].totalTimePlayed)


    def onFocus(self, controlId):
        pass


    # override the doModal function so we can setup everything first
    def onInit(self):
        self.log('onInit')

        if FileAccess.exists(GEN_CHAN_LOC) == False:
            try:
                FileAccess.makedirs(GEN_CHAN_LOC)
            except:
                self.Error('Unable to create the cache directory')
                return

        if FileAccess.exists(MADE_CHAN_LOC) == False:
            try:
                FileAccess.makedirs(MADE_CHAN_LOC)
            except:
                self.Error('Unable to create the storage directory')
                return

        self.background = self.getControl(101)
        self.getControl(102).setVisible(False)
        self.background.setVisible(True)
        updateDialog = xbmcgui.DialogProgress()
        updateDialog.create("PseudoTV", "Initializing")
        self.backupFiles(updateDialog)
        ADDON_SETTINGS.loadSettings()
        
        if CHANNEL_SHARING:
            updateDialog.update(70, "Initializing", "Checking Other Instances")
            self.isMaster = GlobalFileLock.lockFile("MasterLock", False)
        else:
            self.isMaster = True

        updateDialog.update(95, "Initializing", "Migrating")

        if self.isMaster:
            migratemaster = Migrate()
            migratemaster.migrate()

        self.channelLabelTimer = threading.Timer(5.0, self.hideChannelLabel)
        self.playerTimer = threading.Timer(2.0, self.playerTimerAction)
        self.playerTimer.name = "PlayerTimer"
        self.infoTimer = threading.Timer(5.0, self.hideInfo)
        self.myEPG = EPGWindow("script.pseudotv.EPG.xml", ADDON_INFO, "default")
        self.myEPG.MyOverlayWindow = self
        # Don't allow any actions during initialization
        self.actionSemaphore.acquire()
        updateDialog.close()
        self.timeStarted = time.time()

        if self.readConfig() == False:
            return

        self.myEPG.channelLogos = self.channelLogos
        self.maxChannels = len(self.channels)

        if self.maxChannels == 0:
            self.Error('Unable to find any channels. Please configure the addon.')
            return

        found = False

        for i in range(self.maxChannels):
            if self.channels[i].isValid:
                found = True
                break

        if found == False:
            self.Error("Unable to populate channels. Please verify that you", "have scraped media in your library and that you have", "properly configured channels.")
            return

        if self.sleepTimeValue > 0:
            self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

        self.notificationTimer = threading.Timer(NOTIFICATION_CHECK_TIME, self.notificationAction)

        try:
            if self.forceReset == False:
                self.currentChannel = self.fixChannel(int(REAL_SETTINGS.getSetting("CurrentChannel")))
            else:
                self.currentChannel = self.fixChannel(1)
        except:
            self.currentChannel = self.fixChannel(1)

        self.resetChannelTimes()
        self.setChannel(self.currentChannel)
        self.background.setVisible(False)
        self.startSleepTimer()
        self.startNotificationTimer()
        self.playerTimer.start()

        if self.backgroundUpdating < 2 or self.isMaster == False:
            self.channelThread.name = "ChannelThread"
            self.channelThread.start()

        self.actionSemaphore.release()
        self.log('onInit return')


    # setup all basic configuration parameters, including creating the playlists that
    # will be used to actually run this thing
    def readConfig(self):
        self.log('readConfig')
        # Sleep setting is in 30 minute incriments...so multiply by 30, and then 60 (min to sec)
        self.sleepTimeValue = int(REAL_SETTINGS.getSetting('AutoOff')) * 1800
        self.log('Auto off is ' + str(self.sleepTimeValue))
        self.infoOnChange = REAL_SETTINGS.getSetting("InfoOnChange") == "true"
        self.log('Show info label on channel change is ' + str(self.infoOnChange))
        self.showChannelBug = REAL_SETTINGS.getSetting("ShowChannelBug") == "true"
        self.log('Show channel bug - ' + str(self.showChannelBug))
        self.forceReset = REAL_SETTINGS.getSetting('ForceChannelReset') == "true"
        self.channelResetSetting = REAL_SETTINGS.getSetting('ChannelResetSetting')
        self.log("Channel reset setting - " + str(self.channelResetSetting))
        self.channelLogos = xbmc.translatePath(REAL_SETTINGS.getSetting('ChannelLogoFolder'))
        self.backgroundUpdating = int(REAL_SETTINGS.getSetting("ThreadMode"))
        self.log("Background updating - " + str(self.backgroundUpdating))
        self.showNextItem = REAL_SETTINGS.getSetting("EnableComingUp") == "true"
        self.log("Show Next Item - " + str(self.showNextItem))
        self.hideShortItems = REAL_SETTINGS.getSetting("HideClips") == "true"
        self.log("Hide Short Items - " + str(self.hideShortItems))
        self.shortItemLength = SHORT_CLIP_ENUM[int(REAL_SETTINGS.getSetting("ClipLength"))]
        self.log("Short item length - " + str(self.shortItemLength))
        self.channelDelay = int(REAL_SETTINGS.getSetting("ChannelDelay")) * 250

        if FileAccess.exists(self.channelLogos) == False:
            self.channelLogos = IMAGES_LOC

        self.log('Channel logo folder - ' + self.channelLogos)
        self.channelList = ChannelList()
        self.channelList.myOverlay = self
        self.channels = self.channelList.setupList()

        if self.channels is None:
            self.log('readConfig No channel list returned')
            self.end()
            return False

        self.Player.stop()
        self.log('readConfig return')
        return True


    # handle fatal errors: log it, show the dialog, and exit
    def Error(self, line1, line2 = '', line3 = ''):
        self.log('FATAL ERROR: ' + line1 + " " + line2 + " " + line3, xbmc.LOGFATAL)
        dlg = xbmcgui.Dialog()
        dlg.ok('Error', line1, line2, line3)
        del dlg
        self.end()


    def channelDown(self):
        self.log('channelDown')

        if self.maxChannels == 1:
            return

        self.background.setVisible(True)
        channel = self.fixChannel(self.currentChannel - 1, False)
        self.setChannel(channel)
        self.background.setVisible(False)
        self.log('channelDown return')
        
        
    def backupFiles(self, updatedlg):
        self.log('backupFiles')

        if CHANNEL_SHARING == False:
            return

        updatedlg.update(1, "Initializing", "Copying Channels...")
        realloc = REAL_SETTINGS.getSetting('SettingsFolder')
        FileAccess.copy(realloc + '/settings2.xml', SETTINGS_LOC + '/settings2.xml')
        realloc = xbmc.translatePath(os.path.join(realloc, 'cache')) + '/'

        for i in range(999):
            FileAccess.copy(realloc + 'channel_' + str(i) + '.m3u', CHANNELS_LOC + 'channel_' + str(i) + '.m3u')
            updatedlg.update(int(i * .07) + 1, "Initializing", "Copying Channels...")


    def storeFiles(self):
        self.log('storeFiles')

        if CHANNEL_SHARING == False:
            return

        realloc = REAL_SETTINGS.getSetting('SettingsFolder')
        FileAccess.copy(SETTINGS_LOC + '/settings2.xml', realloc + '/settings2.xml')
        realloc = xbmc.translatePath(os.path.join(realloc, 'cache')) + '/'

        for i in range(self.maxChannels):
            if self.channels[i].isValid:
                FileAccess.copy(CHANNELS_LOC + 'channel_' + str(i) + '.m3u', realloc + 'channel_' + str(i) + '.m3u')


    def channelUp(self):
        self.log('channelUp')

        if self.maxChannels == 1:
            return

        self.background.setVisible(True)
        channel = self.fixChannel(self.currentChannel + 1)
        self.setChannel(channel)
        self.background.setVisible(False)
        self.log('channelUp return')


    def message(self, data):
        self.log('Dialog message: ' + data)
        dlg = xbmcgui.Dialog()
        dlg.ok('Info', data)
        del dlg


    def log(self, msg, level = xbmc.LOGDEBUG):
        log('TVOverlay: ' + msg, level)


    # set the channel, the proper show offset, and time offset
    def setChannel(self, channel):
        self.log('setChannel ' + str(channel))
        self.runActions(RULES_ACTION_OVERLAY_SET_CHANNEL, channel, self.channels[channel - 1])

        if self.Player.stopped:
            self.log('setChannel player already stopped', xbmc.LOGERROR);
            return

        if channel < 1 or channel > self.maxChannels:
            self.log('setChannel invalid channel ' + str(channel), xbmc.LOGERROR)
            return

        if self.channels[channel - 1].isValid == False:
            self.log('setChannel channel not valid ' + str(channel), xbmc.LOGERROR)
            return

        self.lastActionTime = 0
        timedif = 0
        self.getControl(102).setVisible(False)
        self.getControl(103).setImage('')
        self.showingInfo = False

        # first of all, save playing state, time, and playlist offset for
        # the currently playing channel
        if self.Player.isPlaying():
            if channel != self.currentChannel:
                self.channels[self.currentChannel - 1].setPaused(xbmc.getCondVisibility('Player.Paused'))

                # Automatically pause in serial mode
                if self.channels[self.currentChannel - 1].mode & MODE_ALWAYSPAUSE > 0:
                    self.channels[self.currentChannel - 1].setPaused(True)

                self.channels[self.currentChannel - 1].setShowTime(self.Player.getTime())
                self.channels[self.currentChannel - 1].setShowPosition(xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition())
                self.channels[self.currentChannel - 1].setAccessTime(time.time())

        self.currentChannel = channel
        # now load the proper channel playlist
        xbmc.PlayList(xbmc.PLAYLIST_MUSIC).clear()
        self.log("about to load");

        if xbmc.PlayList(xbmc.PLAYLIST_MUSIC).load(self.channels[channel - 1].fileName) == False:
            self.log("Error loading playlist", xbmc.LOGERROR)
            self.InvalidateChannel(channel)
            return

        # Disable auto playlist shuffling if it's on
        if xbmc.getInfoLabel('Playlist.Random').lower() == 'random':
            self.log('Random on.  Disabling.')
            xbmc.PlayList(xbmc.PLAYLIST_MUSIC).unshuffle()

        self.log("repeat all");
        xbmc.executebuiltin("PlayerControl(repeatall)")
        curtime = time.time()
        timedif = (curtime - self.channels[self.currentChannel - 1].lastAccessTime)

        if self.channels[self.currentChannel - 1].isPaused == False:
            # adjust the show and time offsets to properly position inside the playlist
            while self.channels[self.currentChannel - 1].showTimeOffset + timedif > self.channels[self.currentChannel - 1].getCurrentDuration():
                timedif -= self.channels[self.currentChannel - 1].getCurrentDuration() - self.channels[self.currentChannel - 1].showTimeOffset
                self.channels[self.currentChannel - 1].addShowPosition(1)
                self.channels[self.currentChannel - 1].setShowTime(0)

        # First, check to see if the video is a strm
        if self.channels[self.currentChannel - 1].getItemFilename(self.channels[self.currentChannel - 1].playlistPosition)[-4:].lower() == 'strm':
            self.log("Ignoring a stop because of a stream")
            self.Player.ignoreNextStop = True

        self.log("about to mute");
        # Mute the channel before changing
        xbmc.executebuiltin("Mute()");
        xbmc.sleep(self.channelDelay)
        # set the show offset
        self.Player.playselected(self.channels[self.currentChannel - 1].playlistPosition)
        self.log("playing selected file");
        # set the time offset
        self.channels[self.currentChannel - 1].setAccessTime(curtime)

        if self.channels[self.currentChannel - 1].isPaused:
            self.channels[self.currentChannel - 1].setPaused(False)

            try:
                self.Player.seekTime(self.channels[self.currentChannel - 1].showTimeOffset)

                if self.channels[self.currentChannel - 1].mode & MODE_ALWAYSPAUSE == 0:
                    self.Player.pause()

                    if self.waitForVideoPaused() == False:
                        xbmc.executebuiltin("Mute()");
                        return
            except:
                self.log('Exception during seek on paused channel', xbmc.LOGERROR)
        else:
            seektime = self.channels[self.currentChannel - 1].showTimeOffset + timedif + int((time.time() - curtime))

            try:
                self.log("Seeking");
                self.Player.seekTime(seektime)
            except:
                self.log("Unable to set proper seek time, trying different value")

                try:
                    seektime = self.channels[self.currentChannel - 1].showTimeOffset + timedif
                    self.Player.seekTime(seektime)
                except:
                    self.log('Exception during seek', xbmc.LOGERROR)

        # Unmute
        self.log("Finished, unmuting");
        xbmc.executebuiltin("Mute()");
        self.showChannelLabel(self.currentChannel)
        self.lastActionTime = time.time()
        self.runActions(RULES_ACTION_OVERLAY_SET_CHANNEL_END, channel, self.channels[channel - 1])
        self.log('setChannel return')


    def InvalidateChannel(self, channel):
        self.log("InvalidateChannel" + str(channel))

        if channel < 1 or channel > self.maxChannels:
            self.log("InvalidateChannel invalid channel " + str(channel))
            return

        self.channels[channel - 1].isValid = False
        self.invalidatedChannelCount += 1

        if self.invalidatedChannelCount > 3:
            self.Error("Exceeded 3 invalidated channels. Exiting.")
            return

        remaining = 0

        for i in range(self.maxChannels):
            if self.channels[i].isValid:
                remaining += 1

        if remaining == 0:
            self.Error("No channels available. Exiting.")
            return

        self.setChannel(self.fixChannel(channel))


    def waitForVideoPaused(self):
        self.log('waitForVideoPaused')
        sleeptime = 0

        while sleeptime < TIMEOUT:
            xbmc.sleep(100)

            if self.Player.isPlaying():
                if xbmc.getCondVisibility('Player.Paused'):
                    break

            sleeptime += 100
        else:
            self.log('Timeout waiting for pause', xbmc.LOGERROR)
            return False

        self.log('waitForVideoPaused return')
        return True


    def setShowInfo(self):
        self.log('setShowInfo')

        if self.infoOffset > 0:
            self.getControl(502).setLabel('COMING UP:')
        elif self.infoOffset < 0:
            self.getControl(502).setLabel('ALREADY SEEN:')
        elif self.infoOffset == 0:
            self.getControl(502).setLabel('NOW WATCHING:')

        if self.hideShortItems and self.infoOffset != 0:
            position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            curoffset = 0
            modifier = 1

            if self.infoOffset < 0:
                modifier = -1

            while curoffset != abs(self.infoOffset):
                position = self.channels[self.currentChannel - 1].fixPlaylistIndex(position + modifier)

                if self.channels[self.currentChannel - 1].getItemDuration(position) >= self.shortItemLength:
                    curoffset += 1
        else:
            position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition() + self.infoOffset

        self.getControl(503).setLabel(self.channels[self.currentChannel - 1].getItemTitle(position))
        self.getControl(504).setLabel(self.channels[self.currentChannel - 1].getItemEpisodeTitle(position))
        self.getControl(505).setLabel(self.channels[self.currentChannel - 1].getItemDescription(position))
        self.getControl(506).setImage(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '_c.png')
        self.log('setShowInfo return')


    # Display the current channel based on self.currentChannel.
    # Start the timer to hide it.
    def showChannelLabel(self, channel):
        self.log('showChannelLabel ' + str(channel))

        if self.channelLabelTimer.isAlive():
            self.channelLabelTimer.cancel()
            self.channelLabelTimer = threading.Timer(5.0, self.hideChannelLabel)

        tmp = self.inputChannel
        self.hideChannelLabel()
        self.inputChannel = tmp
        curlabel = 0

        if channel > 99:
            self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel // 100) + '.png')
            self.channelLabel[curlabel].setVisible(True)
            curlabel += 1

        if channel > 9:
            self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str((channel % 100) // 10) + '.png')
            self.channelLabel[curlabel].setVisible(True)
            curlabel += 1

        self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel % 10) + '.png')
        self.channelLabel[curlabel].setVisible(True)

        ##ADDED BY SRANSHAFT: USED TO SHOW NEW INFO WINDOW WHEN CHANGING CHANNELS
        if self.inputChannel == -1 and self.infoOnChange == True:
            self.infoOffset = 0
            self.showInfo(5.0)

        if self.showChannelBug == True:
            try:
                self.getControl(103).setImage(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png')
            except:
                pass
        else:
            try:
                self.getControl(103).setImage('')
            except:
                pass
        ##

        if xbmc.getCondVisibility('Player.ShowInfo'):
            if USING_FRODO:
                json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}'
                self.ignoreInfoAction = True
                self.channelList.sendJSON(json_query);
            else:
                xbmc.executehttpapi("SendKey(0xF049)")
                self.ignoreInfoAction = True

        self.channelLabelTimer.name = "ChannelLabel"
        self.channelLabelTimer.start()
        self.startNotificationTimer(10.0)
        self.log('showChannelLabel return')


    # Called from the timer to hide the channel label.
    def hideChannelLabel(self):
        self.log('hideChannelLabel')
        self.channelLabelTimer = threading.Timer(5.0, self.hideChannelLabel)

        for i in range(3):
            self.channelLabel[i].setVisible(False)

        self.inputChannel = -1
        self.log('hideChannelLabel return')


    def hideInfo(self):
        self.getControl(102).setVisible(False)
        self.infoOffset = 0
        self.showingInfo = False

        if self.infoTimer.isAlive():
            self.infoTimer.cancel()

        self.infoTimer = threading.Timer(5.0, self.hideInfo)


    def showInfo(self, timer):
        if self.hideShortItems:
            position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition() + self.infoOffset

            if self.channels[self.currentChannel - 1].getItemDuration(xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()) < self.shortItemLength:
                return

        self.getControl(102).setVisible(True)
        self.showingInfo = True
        self.setShowInfo()

        if self.infoTimer.isAlive():
            self.infoTimer.cancel()

        self.infoTimer = threading.Timer(timer, self.hideInfo)
        self.infoTimer.name = "InfoTimer"

        if xbmc.getCondVisibility('Player.ShowInfo'):
            if USING_FRODO:
                json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}'
                self.ignoreInfoAction = True
                self.channelList.sendJSON(json_query);
            else:
                xbmc.executehttpapi("SendKey(0xF049)")
                self.ignoreInfoAction = True

        self.infoTimer.start()


    # return a valid channel in the proper range
    def fixChannel(self, channel, increasing = True):
        while channel < 1 or channel > self.maxChannels:
            if channel < 1: channel = self.maxChannels + channel
            if channel > self.maxChannels: channel -= self.maxChannels

        if increasing:
            direction = 1
        else:
            direction = -1

        if self.channels[channel - 1].isValid == False:
            return self.fixChannel(channel + direction, increasing)

        return channel


    # Handle all input while videos are playing
    def onAction(self, act):
        action = act.getId()
        self.log('onAction ' + str(action))

        if self.Player.stopped:
            return

        # Since onAction isnt always called from the same thread (weird),
        # ignore all actions if we're in the middle of processing one
        if self.actionSemaphore.acquire(False) == False:
            self.log('Unable to get semaphore')
            return

        lastaction = time.time() - self.lastActionTime

        # during certain times we just want to discard all input
        if lastaction < 2:
            self.log('Not allowing actions')
            action = ACTION_INVALID

        self.startSleepTimer()

        if action == ACTION_SELECT_ITEM:
            # If we're manually typing the channel, set it now
            if self.inputChannel > 0:
                if self.inputChannel != self.currentChannel:
                    self.setChannel(self.inputChannel)

                self.inputChannel = -1
            else:
                # Otherwise, show the EPG
                if self.channelThread.isAlive():
                    self.channelThread.pause()

                if self.notificationTimer.isAlive():
                    self.notificationTimer.cancel()
                    self.notificationTimer = threading.Timer(NOTIFICATION_CHECK_TIME, self.notificationAction)

                if self.sleepTimeValue > 0:
                    if self.sleepTimer.isAlive():
                        self.sleepTimer.cancel()
                        self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

                self.hideInfo()
                self.newChannel = 0
                self.myEPG.doModal()

                if self.channelThread.isAlive():
                    self.channelThread.unpause()

                self.startNotificationTimer()

                if self.newChannel != 0:
                    self.background.setVisible(True)
                    self.setChannel(self.newChannel)
                    self.background.setVisible(False)
        elif action == ACTION_MOVE_UP or action == ACTION_PAGEUP:
            self.channelUp()
        elif action == ACTION_MOVE_DOWN or action == ACTION_PAGEDOWN:
            self.channelDown()
        elif action == ACTION_MOVE_LEFT:
            if self.showingInfo:
                self.infoOffset -= 1
                self.showInfo(10.0)
            else:
                xbmc.executebuiltin("PlayerControl(SmallSkipBackward)")
        elif action == ACTION_MOVE_RIGHT:
            if self.showingInfo:
                self.infoOffset += 1
                self.showInfo(10.0)
            else:
                xbmc.executebuiltin("PlayerControl(SmallSkipForward)")
        elif action in ACTION_PREVIOUS_MENU:
            if self.showingInfo:
                self.hideInfo()
            else:
                dlg = xbmcgui.Dialog()

                if self.sleepTimeValue > 0:
                    if self.sleepTimer.isAlive():
                        self.sleepTimer.cancel()
                        self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

                if dlg.yesno("Beenden?", "Sicher, du willst PseudoTV beenden?"):
                    self.end()
                    return  # Don't release the semaphore
                else:
                    self.startSleepTimer()

                del dlg
        elif action == ACTION_SHOW_INFO:
            if self.ignoreInfoAction:
                self.ignoreInfoAction = False
            else:
                if self.showingInfo:
                    self.hideInfo()

                    if xbmc.getCondVisibility('Player.ShowInfo'):
                        if USING_FRODO:
                            json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}'
                            self.ignoreInfoAction = True
                            self.channelList.sendJSON(json_query);
                        else:
                            xbmc.executehttpapi("SendKey(0xF049)")
                            self.ignoreInfoAction = True
                else:
                    self.showInfo(10.0)
        elif action >= ACTION_NUMBER_0 and action <= ACTION_NUMBER_9:
            if self.inputChannel < 0:
                self.inputChannel = action - ACTION_NUMBER_0
            else:
                if self.inputChannel < 100:
                    self.inputChannel = self.inputChannel * 10 + action - ACTION_NUMBER_0

            self.showChannelLabel(self.inputChannel)
        elif action == ACTION_OSD:
            xbmc.executebuiltin("ActivateWindow(12901)")

        self.actionSemaphore.release()
        self.log('onAction return')


    # Reset the sleep timer
    def startSleepTimer(self):
        if self.sleepTimeValue == 0:
            return

        # Cancel the timer if it is still running
        if self.sleepTimer.isAlive():
            self.sleepTimer.cancel()
            self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

        if self.Player.stopped == False:
            self.sleepTimer.name = "SleepTimer"
            self.sleepTimer.start()


    def startNotificationTimer(self, timertime = NOTIFICATION_CHECK_TIME):
        self.log("startNotificationTimer")

        if self.notificationTimer.isAlive():
            self.notificationTimer.cancel()

        self.notificationTimer = threading.Timer(timertime, self.notificationAction)

        if self.Player.stopped == False:
            self.notificationTimer.name = "NotificationTimer"
            self.notificationTimer.start()


    # This is called when the sleep timer expires
    def sleepAction(self):
        self.log("sleepAction")
        self.actionSemaphore.acquire()
#        self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)
        # TODO: show some dialog, allow the user to cancel the sleep
        # perhaps modify the sleep time based on the current show
        self.end()


    # Run rules for a channel
    def runActions(self, action, channel, parameter):
        self.log("runActions " + str(action) + " on channel " + str(channel))

        if channel < 1:
            return

        self.runningActionChannel = channel
        index = 0

        for rule in self.channels[channel - 1].ruleList:
            if rule.actions & action > 0:
                self.runningActionId = index
                parameter = rule.runAction(action, self, parameter)

            index += 1

        self.runningActionChannel = 0
        self.runningActionId = 0
        return parameter


    def notificationAction(self):
        self.log("notificationAction")
        docheck = False

        if self.showNextItem == False:
            return

        if self.Player.isPlaying():
            if self.notificationLastChannel != self.currentChannel:
                docheck = True
            else:
                if self.notificationLastShow != xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition():
                    docheck = True
                else:
                    if self.notificationShowedNotif == False:
                        docheck = True

            if docheck == True:
                self.notificationLastChannel = self.currentChannel
                self.notificationLastShow = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
                self.notificationShowedNotif = False

                if self.hideShortItems:
                    # Don't show any notification if the current show is < 60 seconds
                    if self.channels[self.currentChannel - 1].getItemDuration(self.notificationLastShow) < self.shortItemLength:
                        self.notificationShowedNotif = True

                timedif = self.channels[self.currentChannel - 1].getItemDuration(self.notificationLastShow) - self.Player.getTime()

                if self.notificationShowedNotif == False and timedif < NOTIFICATION_TIME_BEFORE_END and timedif > NOTIFICATION_DISPLAY_TIME:
                    nextshow = self.channels[self.currentChannel - 1].fixPlaylistIndex(self.notificationLastShow + 1)

                    if self.hideShortItems:
                        # Find the next show that is >= 60 seconds long
                        while nextshow != self.notificationLastShow:
                            if self.channels[self.currentChannel - 1].getItemDuration(nextshow) >= self.shortItemLength:
                                break

                            nextshow = self.channels[self.currentChannel - 1].fixPlaylistIndex(nextshow + 1)

                    xbmc.executebuiltin("Notification(Coming Up Next, " + self.channels[self.currentChannel - 1].getItemTitle(nextshow).replace(',', '') + ", " + str(NOTIFICATION_DISPLAY_TIME * 1000) + ")")
                    self.notificationShowedNotif = True

        self.startNotificationTimer()


    def playerTimerAction(self):
        self.playerTimer = threading.Timer(2.0, self.playerTimerAction)

        if self.Player.isPlaying():
            self.lastPlayTime = int(self.Player.getTime())
            self.lastPlaylistPosition = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            self.notPlayingCount = 0
        else:
            self.notPlayingCount += 1
            self.log("Adding to notPlayingCount")

        if self.channels[self.currentChannel - 1].getCurrentFilename()[-4:].lower() != 'strm':
            if self.notPlayingCount >= 3:
                self.end()
                return

        if self.Player.stopped == False:
            self.playerTimer.name = "PlayerTimer"
            self.playerTimer.start()


    # cleanup and end
    def end(self):
        self.log('end')
        # Prevent the player from setting the sleep timer
        self.Player.stopped = True
        self.background.setVisible(True)
        curtime = time.time()
        xbmc.executebuiltin("PlayerControl(repeatoff)")
        self.isExiting = True
        updateDialog = xbmcgui.DialogProgress()
        updateDialog.create("PseudoTV", "Exiting")
        
        if CHANNEL_SHARING and self.isMaster:
            updateDialog.update(0, "Exiting", "Removing File Locks")
            GlobalFileLock.unlockFile('MasterLock')
        
        GlobalFileLock.close()

        if self.playerTimer.isAlive():
            self.playerTimer.cancel()
            self.playerTimer.join()

        if self.Player.isPlaying():
            self.lastPlayTime = self.Player.getTime()
            self.lastPlaylistPosition = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            self.Player.stop()

        updateDialog.update(1, "Exiting", "Stopping Threads")

        try:
            if self.channelLabelTimer.isAlive():
                self.channelLabelTimer.cancel()
                self.channelLabelTimer.join()
        except:
            pass

        updateDialog.update(2)

        try:
            if self.notificationTimer.isAlive():
                self.notificationTimer.cancel()
                self.notificationTimer.join()
        except:
            pass

        updateDialog.update(3)

        try:
            if self.infoTimer.isAlive():
                self.infoTimer.cancel()
                self.infoTimer.join()
        except:
            pass

        updateDialog.update(4)

        try:
            if self.sleepTimeValue > 0:
                if self.sleepTimer.isAlive():
                    self.sleepTimer.cancel()
        except:
            pass

        updateDialog.update(5)

        if self.channelThread.isAlive():
            for i in range(30):
                try:
                    self.channelThread.join(1.0)
                except:
                    pass

                if self.channelThread.isAlive() == False:
                    break

                updateDialog.update(6 + i, "Exiting", "Stopping Threads")

            if self.channelThread.isAlive():
                self.log("Problem joining channel thread", xbmc.LOGERROR)

        if self.isMaster:
            try:
                REAL_SETTINGS.setSetting('CurrentChannel', str(self.currentChannel))
            except:
                pass

            ADDON_SETTINGS.setSetting('LastExitTime', str(int(curtime)))

        if self.timeStarted > 0 and self.isMaster:
            updateDialog.update(35, "Exiting", "Saving Settings")
            validcount = 0

            for i in range(self.maxChannels):
                if self.channels[i].isValid:
                    validcount += 1
            
            if validcount > 0:
                incval = 65.0 / float(validcount)

                for i in range(self.maxChannels):
                    updateDialog.update(35 + int((incval * i)))

                    if self.channels[i].isValid:
                        if self.channels[i].mode & MODE_RESUME == 0:
                            ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(int(curtime - self.timeStarted + self.channels[i].totalTimePlayed)))
                        else:
                            if i == self.currentChannel - 1:
                                # Determine pltime...the time it at the current playlist position
                                pltime = 0
                                self.log("position for current playlist is " + str(self.lastPlaylistPosition))

                                for pos in range(self.lastPlaylistPosition):
                                    pltime += self.channels[i].getItemDuration(pos)

                                ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(pltime + self.lastPlayTime))
                            else:
                                tottime = 0

                                for j in range(self.channels[i].playlistPosition):
                                    tottime += self.channels[i].getItemDuration(j)

                                tottime += self.channels[i].showTimeOffset
                                ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(int(tottime)))
                                
                self.storeFiles()

        updateDialog.close()
        self.background.setVisible(False)
        self.close()
class ChannelListThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.myOverlay = None
        sys.setcheckinterval(25)
        self.chanlist = ChannelList()
        self.paused = False
        self.fullUpdating = True

        
    def log(self, msg, level = xbmc.LOGDEBUG):
        log('ChannelListThread: ' + msg, level)


    def run(self):
        self.log("Starting")
        self.chanlist.exitThread = False
        self.chanlist.readConfig()
        self.chanlist.sleepTime = 1

        if self.myOverlay == None:
            self.log("Overlay not defined. Exiting.")
            return
            
        self.chanlist.myOverlay = self.myOverlay
        self.fullUpdating = (self.myOverlay.backgroundUpdating == 0)
        validchannels = 0

        for i in range(self.myOverlay.maxChannels):
            self.chanlist.channels.append(Channel())

            if self.myOverlay.channels[i].isValid:
                validchannels += 1
                
        # Don't load invalid channels if minimum threading mode is on
        if self.fullUpdating and self.myOverlay.isMaster:
            if validchannels < self.chanlist.enteredChannelCount:
                title = 'PseudoTV Live, Background Loading...'
                xbmc.executebuiltin('XBMC.Notification(%s, %s, %s)' % (title, 4000 , THUMB))

            for i in range(self.myOverlay.maxChannels):
                if self.myOverlay.channels[i].isValid == False:
                    while True:
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return

                        time.sleep(1)

                        if self.paused == False:
                            break

                    self.chanlist.channels[i].setAccessTime(self.myOverlay.channels[i].lastAccessTime)

                    try:
                        if self.chanlist.setupChannel(i + 1, True, True, False) == True:
                            while self.paused:
                                if self.myOverlay.isExiting:
                                    self.log("IsExiting")
                                    return

                                time.sleep(1)

                            self.myOverlay.channels[i] = self.chanlist.channels[i]

                            if self.myOverlay.channels[i].isValid == True:
                                title = "PseudoTV Live, Channel " + str(i + 1) + " Added"
                                xbmc.executebuiltin('XBMC.Notification(%s, %s, %s)' % (title, 4000, THUMB))
                                
                    except Exception,e:
                        self.log("Unknown Channel Creation Exception", xbmc.LOGERROR)
                        self.log(traceback.format_exc(), xbmc.LOGERROR)
                        return

        REAL_SETTINGS.setSetting('ForceChannelReset', 'false')
        self.chanlist.sleepTime = 3
        InfoTimer = INFOBAR_TIMER[int(REAL_SETTINGS.getSetting('InfoTimer'))]
        self.myOverlay.ArtServiceThread = threading.Timer(float(InfoTimer), self.myOverlay.ArtService)
        self.myOverlay.ArtServiceThread.name = "ArtServiceThread"
        self.myOverlay.ArtServiceThread.start()

        if REAL_SETTINGS.getSetting("EnableSettop") == "true":
            self.log('onInit, Settop Enabled')
            self.myOverlay.channelThread_Timer = threading.Timer(float(SETTOP_REFRESH), self.myOverlay.Settop)
            self.myOverlay.channelThread_Timer.name = "channelThread_Timer"
            self.myOverlay.channelThread_Timer.start() 
            
        while True:
            for i in range(self.myOverlay.maxChannels):
                modified = True

                while modified == True and self.myOverlay.channels[i].getTotalDuration() < PREP_CHANNEL_TIME and self.myOverlay.channels[i].Playlist.size() < 16288:
                    # If minimum updating is on, don't attempt to load invalid channels
                    if self.fullUpdating == False and self.myOverlay.channels[i].isValid == False and self.myOverlay.isMaster:
                        break

                    modified = False

                    if self.myOverlay.isExiting:
                        self.log("Closing thread")
                        return

                    time.sleep(2)
                    try:
                        curtotal = self.myOverlay.channels[i].getTotalDuration()
                        if self.myOverlay.isMaster:
                            if curtotal > 0:
                                # When appending, many of the channel variables aren't set, so copy them over.
                                # This needs to be done before setup since a rule may use one of the values.
                                # It also needs to be done after since one of them may have changed while being setup.
                                self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                                self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                                self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                                self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                                self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                                self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                                # Only allow appending valid channels, don't allow erasing them
                                
                                try:
                                    self.chanlist.setupChannel(i + 1, True, False, True)
                                except Exception,e:
                                    self.log("Unknown Channel Appending Exception", xbmc.LOGERROR)
                                    self.log(traceback.format_exc(), xbmc.LOGERROR)
                                    return

                                self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                                self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                                self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                                self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                                self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                                self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                            else:
                                try:
                                    self.chanlist.setupChannel(i + 1, True, True, False)
                                except Exception,e:
                                    self.log("Unknown Channel Modification Exception", xbmc.LOGERROR)
                                    self.log(traceback.format_exc(), xbmc.LOGERROR)
                                    return
                        else:
                            try:
                                # We're not master, so no modifications...just try and load the channel
                                self.chanlist.setupChannel(i + 1, True, False, False)
                            except Exception,e:
                                self.log("Unknown Channel Loading Exception", xbmc.LOGERROR)
                                self.log(traceback.format_exc(), xbmc.LOGERROR)
                                return

                        self.myOverlay.channels[i] = self.chanlist.channels[i]

                        if self.myOverlay.isMaster:
                            ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(self.myOverlay.channels[i].totalTimePlayed))

                        if self.myOverlay.channels[i].getTotalDuration() > curtotal and self.myOverlay.isMaster:
                            modified = True

                        # A do-while loop for the paused state
                        while True:
                            if self.myOverlay.isExiting:
                                self.log("Closing thread")
                                return

                            time.sleep(2)

                            if self.paused == False:
                                break
                    except:
class ChannelListThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.myOverlay = None
        sys.setcheckinterval(25)
        self.chanlist = ChannelList()
        self.paused = False
        self.fullUpdating = True


    def log(self, msg, level = xbmc.LOGDEBUG):
        log('ChannelListThread: ' + msg, level)


    def run(self):
        self.log("Starting")
        self.chanlist.exitThread = False
        self.chanlist.readConfig()
        self.chanlist.sleepTime = 0.1

        if self.myOverlay == None:
            self.log("Overlay not defined. Exiting.")
            return

        self.chanlist.myOverlay = self.myOverlay
        self.fullUpdating = (self.myOverlay.backgroundUpdating == 0)
        validchannels = 0

        for i in range(self.myOverlay.maxChannels):
            self.chanlist.channels.append(Channel())

            if self.myOverlay.channels[i].isValid:
                validchannels += 1

        # Don't load invalid channels if minimum threading mode is on
        if self.fullUpdating and self.myOverlay.isMaster:
            if validchannels < self.chanlist.enteredChannelCount:
                xbmc.executebuiltin("Notification(%s, %s, %d, %s)" % (ADDON_NAME, LANGUAGE(30024), 4000, ICON))

            for i in range(self.myOverlay.maxChannels):
                if self.myOverlay.channels[i].isValid == False:
                    while True:
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return

                        xbmc.sleep(1000)

                        if self.paused == False:
                            break

                    self.chanlist.channels[i].setAccessTime(self.myOverlay.channels[i].lastAccessTime)

                    try:
                        if self.chanlist.setupChannel(i + 1, True, True, False) == True:
                            while self.paused:
                                if self.myOverlay.isExiting:
                                    self.log("IsExiting")
                                    return

                                xbmc.sleep(1000)

                            self.myOverlay.channels[i] = self.chanlist.channels[i]

                            if self.myOverlay.channels[i].isValid == True:
                                xbmc.executebuiltin("Notification(%s, %s, %d, %s)" % (ADDON_NAME, xbmc.getLocalizedString(19029) + ' ' + str(i + 1) + ' ' + LANGUAGE(30025), 4000, ICON))
                    except:
                        self.log("Unknown Channel Creation Exception", xbmc.LOGERROR)
                        self.log(traceback.format_exc(), xbmc.LOGERROR)
                        return

        ADDON.setSetting('ForceChannelReset', 'false')
        self.chanlist.sleepTime = 0.3

        while True:
            for i in range(self.myOverlay.maxChannels):
                modified = True

                while modified == True and self.myOverlay.channels[i].getTotalDuration() < PREP_CHANNEL_TIME and self.myOverlay.channels[i].Playlist.size() < 16288:
                    # If minimum updating is on, don't attempt to load invalid channels
                    if self.fullUpdating == False and self.myOverlay.channels[i].isValid == False and self.myOverlay.isMaster:
                        break

                    modified = False

                    if self.myOverlay.isExiting:
                        self.log("Closing thread")
                        return

                    xbmc.sleep(2000)
                    curtotal = self.myOverlay.channels[i].getTotalDuration()

                    if self.myOverlay.isMaster:
                        if curtotal > 0:
                            # When appending, many of the channel variables aren't set, so copy them over.
                            # This needs to be done before setup since a rule may use one of the values.
                            # It also needs to be done after since one of them may have changed while being setup.
                            self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                            self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                            self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                            self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                            self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                            self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                            # Only allow appending valid channels, don't allow erasing them

                            try:
                                self.chanlist.setupChannel(i + 1, True, False, True)
                            except:
                                self.log("Unknown Channel Appending Exception", xbmc.LOGERROR)
                                self.log(traceback.format_exc(), xbmc.LOGERROR)
                                return

                            self.chanlist.channels[i].playlistPosition = self.myOverlay.channels[i].playlistPosition
                            self.chanlist.channels[i].showTimeOffset = self.myOverlay.channels[i].showTimeOffset
                            self.chanlist.channels[i].lastAccessTime = self.myOverlay.channels[i].lastAccessTime
                            self.chanlist.channels[i].totalTimePlayed = self.myOverlay.channels[i].totalTimePlayed
                            self.chanlist.channels[i].isPaused = self.myOverlay.channels[i].isPaused
                            self.chanlist.channels[i].mode = self.myOverlay.channels[i].mode
                        else:
                            try:
                                self.chanlist.setupChannel(i + 1, True, True, False)
                            except:
                                self.log("Unknown Channel Modification Exception", xbmc.LOGERROR)
                                self.log(traceback.format_exc(), xbmc.LOGERROR)
                                return
                    else:
                        try:
                            # We're not master, so no modifications...just try and load the channel
                            self.chanlist.setupChannel(i + 1, True, False, False)
                        except:
                            self.log("Unknown Channel Loading Exception", xbmc.LOGERROR)
                            self.log(traceback.format_exc(), xbmc.LOGERROR)
                            return

                    self.myOverlay.channels[i] = self.chanlist.channels[i]

                    if self.myOverlay.isMaster:
                        ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(self.myOverlay.channels[i].totalTimePlayed))

                    if self.myOverlay.channels[i].getTotalDuration() > curtotal and self.myOverlay.isMaster:
                        modified = True

                    # A do-while loop for the paused state
                    while True:
                        if self.myOverlay.isExiting:
                            self.log("Closing thread")
                            return

                        xbmc.sleep(2000)

                        if self.paused == False:
                            break

                timeslept = 0

            if self.fullUpdating == False and self.myOverlay.isMaster:
                return

            # If we're master, wait 30 minutes in between checks.  If not, wait 5 minutes.
            while (timeslept < 1800 and self.myOverlay.isMaster == True) or (timeslept < 300 and self.myOverlay.isMaster == False):
                if self.myOverlay.isExiting:
                    self.log("IsExiting")
                    return

                xbmc.sleep(2000)
                timeslept += 2

        self.log("All channels up to date.  Exiting thread.")


    def pause(self):
        self.paused = True
        self.chanlist.threadPaused = True


    def unpause(self):
        self.paused = False
        self.chanlist.threadPaused = False
Example #31
0
    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        self.dlg = xbmcgui.DialogProgress()
        self.dlg.create("TV Time", "Preparing Channel Wizard")
        self.dlg.update(0, "Preparing Channel Wizard")
        self.chnlst = ChannelList()
        self.dlg.update(10, "Preparing Channel Wizard", "Loading TV Settings")
        self.chnlst.fillTVInfo()
        self.networkList = self.chnlst.networkList
        self.studioList = self.chnlst.studioList
        self.showGenreList = self.chnlst.showGenreList
        self.dlg.update(20, "Preparing Channel Wizard", "Loading Movie Settings")
        self.chnlst.fillMovieInfo()
        self.movieGenreList = self.chnlst.movieGenreList
        self.dlg.update(40, "Preparing Channel Wizard", "Loading Music Settings")
        self.chnlst.fillMusicInfo()
        self.musicGenreList = self.chnlst.musicGenreList
        self.dlg.update(60, "Preparing Channel Wizard", "Loading Live Feed Settings")
        self.chnlst.fillFeedInfo()
        self.feedList = self.chnlst.feedList
        self.dlg.update(80, "Preparing Channel Wizard", "Loading Mixed Genre Settings")
        self.mixedGenreList = self.chnlst.makeMixedList(self.showGenreList, self.movieGenreList)

        for i in range(len(self.chnlst.showList)):
            self.showList.append(self.chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())

        self.log("self.networkList " + str(self.networkList))
        self.log("self.studioList " + str(self.studioList))
        self.log("self.showGenreList " + str(self.showGenreList))
        self.log("self.movieGenreList " + str(self.movieGenreList))
        self.log("self.musicGenreList " + str(self.musicGenreList))
        self.log("self.mixedGenreList " + str(self.mixedGenreList))

        self.resolutionList = []
        self.resolutionList.append("All")
        self.resolutionList.append("SD Only")
        self.resolutionList.append("720p or Higher")
        self.resolutionList.append("1080p Only")

        self.showseqList = []
        self.showseqList.append("1 Show")
        self.showseqList.append("2 Shows")
        self.showseqList.append("3 Shows")
        self.showseqList.append("4 Shows")
        self.showseqList.append("5 Shows")
        self.showseqList.append("6 Shows")
        self.showseqList.append("7 Shows")
        self.showseqList.append("8 Shows")
        self.showseqList.append("9 Shows")
        self.showseqList.append("10 Shows")

        self.movieseqList = []
        self.movieseqList.append("1 Movie")
        self.movieseqList.append("2 Movies")
        self.movieseqList.append("3 Movies")
        self.movieseqList.append("4 Movies")
        self.movieseqList.append("5 Movies")
        self.movieseqList.append("6 Movies")
        self.movieseqList.append("7 Movies")
        self.movieseqList.append("8 Movies")
        self.movieseqList.append("9 Movies")
        self.movieseqList.append("10 Movies")

        # check if settings2.xml file exists
        # read in channel playlists in video, music and mixed folders
        channelNum = 0
        for i in range(500):
            if os.path.exists(
                xbmc.translatePath("special://profile/playlists/video") + "/Channel_" + str(i + 1) + ".xsp"
            ):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_1",
                    xbmc.translatePath("special://profile/playlists/video/") + "Channel_" + str(i + 1) + ".xsp",
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_3",
                    ChannelList().cleanString(
                        ChannelList().getSmartPlaylistName(
                            xbmc.translatePath("special://profile/playlists/video") + "/Channel_" + str(i + 1) + ".xsp"
                        )
                    ),
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_playlist",
                    xbmc.translatePath("special://profile/playlists/video/") + "Channel_" + str(i + 1) + ".xsp",
                )
                # self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(
                xbmc.translatePath("special://profile/playlists/mixed") + "/Channel_" + str(i + 1) + ".xsp"
            ):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_1",
                    xbmc.translatePath("special://profile/playlists/mixed/") + "Channel_" + str(i + 1) + ".xsp",
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_3",
                    ChannelList().cleanString(
                        ChannelList().getSmartPlaylistName(
                            xbmc.translatePath("special://profile/playlists/mixed") + "/Channel_" + str(i + 1) + ".xsp"
                        )
                    ),
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_playlist",
                    xbmc.translatePath("special://profile/playlists/mixed/") + "Channel_" + str(i + 1) + ".xsp",
                )
                # self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(
                xbmc.translatePath("special://profile/playlists/music") + "/Channel_" + str(i + 1) + ".xsp"
            ):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_1",
                    xbmc.translatePath("special://profile/playlists/music/") + "Channel_" + str(i + 1) + ".xsp",
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_3",
                    ChannelList().cleanString(
                        ChannelList().getSmartPlaylistName(
                            xbmc.translatePath("special://profile/playlists/music") + "/Channel_" + str(i + 1) + ".xsp"
                        )
                    ),
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_playlist",
                    xbmc.translatePath("special://profile/playlists/music/") + "Channel_" + str(i + 1) + ".xsp",
                )
                # self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')),"")
        ADDON_SETTINGS.writeSettings()

        """
        if not os.path.exists(xbmc.translatePath('special://profile/addon_data/' + ADDON_ID + '/settings2.xml')):
            # if not, load presets based on networklist and studiolist
            ChannelList().autoTune()
        else:
            if (REAL_SETTINGS.getSetting("autoFindNetworks") == "true" or 
                REAL_SETTINGS.getSetting("autoFindStudios") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMovieGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMixGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVShows") == "true" or
                REAL_SETTINGS.getSetting("autoFindMusicGenres") == "true"):
                self.log("autoTune")
                ChannelList().autoTune()
        """

        self.listcontrol = self.getControl(102)

        for i in range(200):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)

        self.dlg.update(90, "Preparing Channel Wizard", "Loading Channel List")
        self.updateListing()
        self.dlg.close()
        self.getControl(105).setVisible(True)  # Channel List
        self.getControl(106).setVisible(False)  # Channel Settings
        self.setFocusId(102)
        self.log("prepareConfig return")
class ChannelListThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.myOverlay = None
        self.shouldExit = False
        sys.setcheckinterval(25)
        self.chanlist = ChannelList()
        self.chanlist.sleepTime = 0.1
        self.paused = False


    def log(self, msg, level = xbmc.LOGDEBUG):
        log('ChannelListThread: ' + msg, level)


    def run(self):
        self.log("Starting")
        self.shouldExit = False
        self.chanlist.exitThread = False

        if self.myOverlay == None:
            self.log("Overlay not defined. Exiting.")
            return

        for i in range(self.myOverlay.maxChannels):
            modified = True

            while modified == True and self.myOverlay.channels[i].isValid and self.myOverlay.channels[i].getTotalDuration() < PREP_CHANNEL_TIME:
                modified = False

                if self.shouldExit == True:
                    self.log("Closing thread")
                    return

                time.sleep(2)
                curtotal = self.myOverlay.channels[i].getTotalDuration()
                self.chanlist.appendChannel(i + 1)

                # A do-while loop for the paused state
                while True:
                    if self.shouldExit == True:
                        self.log("Closing thread")
                        return

                    time.sleep(2)

                    if self.paused == False:
                        break

                self.myOverlay.channels[i].setPlaylist(CHANNELS_LOC + "channel_" + str(i + 1) + ".m3u")

                if self.myOverlay.channels[i].getTotalDuration() > curtotal:
                    modified = True

        self.log("All channels up to date.  Exiting thread.")


    def pause(self):
        self.paused = True


    def unpause(self):
        self.paused = False
Example #33
0
class TVOverlay(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        self.log('__init__')
        # initialize all variables
        self.channels = []
        self.Player = MyPlayer()
        self.Player.overlay = self
        self.inputChannel = -1
        self.channelLabel = []
        self.lastActionTime = 0
        self.actionSemaphore = threading.BoundedSemaphore()
        self.channelThread = ChannelListThread()
        self.channelThread.myOverlay = self
        self.timeStarted = 0
        self.infoOnChange = False
        self.infoDuration = 10
        self.infoOffset = 0
        self.invalidatedChannelCount = 0
        self.showingInfo = False
        self.showChannelBug = False
        self.channelBugPosition = 0
        self.notificationLastChannel = 0
        self.notificationLastShow = 0
        self.notificationShowedNotif = False
        self.isExiting = False
        self.maxChannels = 0
        self.notPlayingCount = 0
        self.ignoreInfoAction = False
        self.shortItemLength = 120
        self.seekForward = 30
        self.seekBackward = -30
        self.runningActionChannel = 0
        self.channelDelay = 500
        self.numberColor = '0xFF00FF00'

        for i in range(3):
            self.numberColor = NUM_COLOUR[int(ADDON.getSetting("NumberColour"))]
            self.channelLabel.append(xbmcgui.ControlImage(90 + (35 * i), 90, 50, 50, IMAGES_LOC, colorDiffuse=self.numberColor))
            self.addControl(self.channelLabel[i])
            self.channelLabel[i].setVisible(False)

        self.doModal()
        self.log('__init__ return')


    def resetChannelTimes(self):
        for i in range(self.maxChannels):
            self.channels[i].setAccessTime(self.timeStarted - self.channels[i].totalTimePlayed)


    def onFocus(self, controlId):
        pass


    # override the doModal function so we can setup everything first
    def onInit(self):
        self.log('onInit')

        if FileAccess.exists(GEN_CHAN_LOC) == False:
            try:
                FileAccess.makedirs(GEN_CHAN_LOC)
            except:
                self.Error(LANGUAGE(30035))
                return

        if FileAccess.exists(MADE_CHAN_LOC) == False:
            try:
                FileAccess.makedirs(MADE_CHAN_LOC)
            except:
                self.Error(LANGUAGE(30036))
                return

        if FileAccess.exists(CHANNELBUG_LOC) == False:
                try:
                    FileAccess.makedirs(CHANNELBUG_LOC)
                except:
                    self.Error(LANGUAGE(30036))
                    return

        self.getControl(102).setVisible(False)
        self.backupFiles()
        ADDON_SETTINGS.loadSettings()

        if CHANNEL_SHARING:
            updateDialog = xbmcgui.DialogProgressBG()
            updateDialog.create(ADDON_NAME, '')
            updateDialog.update(1, message='Initializing Channel Sharing')
            FileAccess.makedirs(LOCK_LOC)
            updateDialog.update(50, message='Initializing Channel Sharing')
            self.isMaster = GlobalFileLock.lockFile("MasterLock", False)
            updateDialog.update(100, message='Initializing Channel Sharing')
            xbmc.sleep(200)
            updateDialog.close()
        else:
            self.isMaster = True

        if self.isMaster:
            migratemaster = Migrate()
            migratemaster.migrate()

        self.channelLabelTimer = threading.Timer(3.0, self.hideChannelLabel)
        self.playerTimer = threading.Timer(2.0, self.playerTimerAction)
        self.playerTimer.name = "PlayerTimer"
        self.infoTimer = threading.Timer(5.0, self.hideInfo)
        self.myEPG = EPGWindow("script.pseudotv.EPG.xml", CWD, "default")
        self.myEPG.MyOverlayWindow = self
        # Don't allow any actions during initialization
        self.actionSemaphore.acquire()
        self.timeStarted = time.time()

        if self.readConfig() == False:
            return

        self.myEPG.channelLogos = self.channelLogos
        self.maxChannels = len(self.channels)

        if self.maxChannels == 0:
            self.Error(LANGUAGE(30037))
            return

        found = False

        for i in range(self.maxChannels):
            if self.channels[i].isValid:
                found = True
                break

        if found == False:
            self.Error(LANGUAGE(30038))
            return

        if self.sleepTimeValue > 0:
            self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

        self.notificationTimer = threading.Timer(NOTIFICATION_CHECK_TIME, self.notificationAction)

        try:
            if self.forceReset == False:
                self.currentChannel = self.fixChannel(int(ADDON.getSetting("CurrentChannel")))
            else:
                self.currentChannel = self.fixChannel(1)
        except:
            self.currentChannel = self.fixChannel(1)

        self.resetChannelTimes()
        self.setChannel(self.currentChannel)
        self.startSleepTimer()
        self.startNotificationTimer()
        self.playerTimer.start()

        if self.backgroundUpdating < 2 or self.isMaster == False:
            self.channelThread.name = "ChannelThread"
            self.channelThread.start()

        self.actionSemaphore.release()
        self.log('onInit return')


    # setup all basic configuration parameters, including creating the playlists that
    # will be used to actually run this thing
    def readConfig(self):
        self.log('readConfig')
        # Sleep setting is in 30 minute incriments...so multiply by 30, and then 60 (min to sec)
        self.sleepTimeValue = int(ADDON.getSetting('AutoOff')) * 1800
        self.log('Auto off is ' + str(self.sleepTimeValue))
        self.infoOnChange = ADDON.getSetting("InfoOnChange") == "true"
        self.infoDuration = INFO_DUR[int(ADDON.getSetting("InfoLength"))]
        self.log('Show info label on channel change is ' + str(self.infoOnChange))
        self.showChannelBug = ADDON.getSetting("ShowChannelBug") == "true"
        self.channelBugPosition = CHANNELBUG_POS[int(ADDON.getSetting("ChannelBugPosition"))]
        self.log('Show channel bug - ' + str(self.showChannelBug))
        self.forceReset = ADDON.getSetting('ForceChannelReset') == "true"
        self.channelResetSetting = ADDON.getSetting('ChannelResetSetting')
        self.log("Channel reset setting - " + str(self.channelResetSetting))
        self.channelLogos = xbmc.translatePath(ADDON.getSetting('ChannelLogoFolder'))
        self.backgroundUpdating = int(ADDON.getSetting("ThreadMode"))
        self.log("Background updating - " + str(self.backgroundUpdating))
        self.showNextItem = ADDON.getSetting("EnableComingUp") == "true"
        self.log("Show Next Item - " + str(self.showNextItem))
        self.hideShortItems = ADDON.getSetting("HideClips") == "true"
        self.log("Hide Short Items - " + str(self.hideShortItems))
        self.shortItemLength = SHORT_CLIP_ENUM[int(ADDON.getSetting("ClipLength"))]
        self.seekForward = SEEK_FORWARD[int(ADDON.getSetting("SeekForward"))]
        self.seekBackward = SEEK_BACKWARD[int(ADDON.getSetting("SeekBackward"))]
        self.log("Short item length - " + str(self.shortItemLength))

        if FileAccess.exists(self.channelLogos) == False:
            self.channelLogos = LOGOS_LOC

        self.log('Channel logo folder - ' + self.channelLogos)
        self.channelList = ChannelList()
        self.channelList.myOverlay = self
        self.channels = self.channelList.setupList()

        if self.channels is None:
            self.log('readConfig No channel list returned')
            self.end()
            return False

        self.Player.stop()
        self.log('readConfig return')
        return True


    # handle fatal errors: log it, show the dialog, and exit
    def Error(self, line1, line2 = '', line3 = ''):
        self.log('FATAL ERROR: ' + line1 + " " + line2 + " " + line3, xbmc.LOGFATAL)
        dlg = xbmcgui.Dialog()
        dlg.ok(xbmc.getLocalizedString(257), line1, line2, line3)
        del dlg
        self.end()


    def channelDown(self):
        self.log('channelDown')

        if self.maxChannels == 1:
            return

        channel = self.fixChannel(self.currentChannel - 1, False)
        self.setChannel(channel)
        self.log('channelDown return')


    def backupFiles(self):
        self.log('backupFiles')

        if CHANNEL_SHARING == False:
            return

        realloc = ADDON.getSetting('SettingsFolder')
        FileAccess.copy(realloc + '/settings2.xml', SETTINGS_LOC + '/settings2.xml')
        realloc = xbmc.translatePath(os.path.join(realloc, 'cache')) + '/'

        for i in range(1000):
            FileAccess.copy(realloc + 'channel_' + str(i) + '.m3u', CHANNELS_LOC + 'channel_' + str(i) + '.m3u')


    def storeFiles(self):
        self.log('storeFiles')

        if CHANNEL_SHARING == False:
            return

        realloc = ADDON.getSetting('SettingsFolder')
        FileAccess.copy(SETTINGS_LOC + '/settings2.xml', realloc + '/settings2.xml')
        realloc = xbmc.translatePath(os.path.join(realloc, 'cache')) + '/'

        for i in range(self.maxChannels + 1):
            FileAccess.copy(CHANNELS_LOC + 'channel_' + str(i) + '.m3u', realloc + 'channel_' + str(i) + '.m3u')


    def channelUp(self):
        self.log('channelUp')

        if self.maxChannels == 1:
            return

        channel = self.fixChannel(self.currentChannel + 1)
        self.setChannel(channel)
        self.log('channelUp return')


    def message(self, data):
        self.log('Dialog message: ' + data)
        dlg = xbmcgui.Dialog()
        dlg.ok(xbmc.getLocalizedString(19033), data)
        del dlg


    def log(self, msg, level = xbmc.LOGDEBUG):
        log('TVOverlay: ' + msg, level)


    # set the channel, the proper show offset, and time offset
    def setChannel(self, channel):
        self.log('setChannel ' + str(channel))
        self.runActions(RULES_ACTION_OVERLAY_SET_CHANNEL, channel, self.channels[channel - 1])

        if self.Player.stopped:
            self.log('setChannel player already stopped', xbmc.LOGERROR);
            return

        if channel < 1 or channel > self.maxChannels:
            self.log('setChannel invalid channel ' + str(channel), xbmc.LOGERROR)
            return

        if self.channels[channel - 1].isValid == False:
            self.log('setChannel channel not valid ' + str(channel), xbmc.LOGERROR)
            return

        self.lastActionTime = 0
        timedif = 0
        self.getControl(102).setVisible(False)
        self.getControl(103).setImage('')
        self.showingInfo = False

        # first of all, save playing state, time, and playlist offset for
        # the currently playing channel
        if self.Player.isPlaying():
            if channel != self.currentChannel:
                self.channels[self.currentChannel - 1].setPaused(xbmc.getCondVisibility('Player.Paused'))

                # Automatically pause in serial mode
                if self.channels[self.currentChannel - 1].mode & MODE_ALWAYSPAUSE > 0:
                    self.channels[self.currentChannel - 1].setPaused(True)

                self.channels[self.currentChannel - 1].setShowTime(self.Player.getTime())
                self.channels[self.currentChannel - 1].setShowPosition(xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition())
                self.channels[self.currentChannel - 1].setAccessTime(time.time())

        self.currentChannel = channel
        # now load the proper channel playlist
        xbmc.PlayList(xbmc.PLAYLIST_MUSIC).clear()
        self.log("about to load");

        if xbmc.PlayList(xbmc.PLAYLIST_MUSIC).load(self.channels[channel - 1].fileName) == False:
            self.log("Error loading playlist", xbmc.LOGERROR)
            self.InvalidateChannel(channel)
            return

        # Disable auto playlist shuffling if it's on
        if xbmc.getInfoLabel('Playlist.Random').lower() == 'random':
            self.log('Random on.  Disabling.')
            xbmc.PlayList(xbmc.PLAYLIST_MUSIC).unshuffle()

        self.log("repeat all");
        xbmc.executebuiltin("PlayerControl(RepeatAll)")
        curtime = time.time()
        timedif = (curtime - self.channels[self.currentChannel - 1].lastAccessTime)

        if self.channels[self.currentChannel - 1].isPaused == False:
            # adjust the show and time offsets to properly position inside the playlist
            while self.channels[self.currentChannel - 1].showTimeOffset + timedif > self.channels[self.currentChannel - 1].getCurrentDuration():
                timedif -= self.channels[self.currentChannel - 1].getCurrentDuration() - self.channels[self.currentChannel - 1].showTimeOffset
                self.channels[self.currentChannel - 1].addShowPosition(1)
                self.channels[self.currentChannel - 1].setShowTime(0)

        xbmc.sleep(self.channelDelay)
        # set the show offset
        self.Player.playselected(self.channels[self.currentChannel - 1].playlistPosition)
        self.log("playing selected file");
        # set the time offset
        self.channels[self.currentChannel - 1].setAccessTime(curtime)

        if self.channels[self.currentChannel - 1].isPaused:
            self.channels[self.currentChannel - 1].setPaused(False)

            try:
                self.Player.seekTime(self.channels[self.currentChannel - 1].showTimeOffset)

                if self.channels[self.currentChannel - 1].mode & MODE_ALWAYSPAUSE == 0:
                    self.Player.pause()

                    if self.waitForVideoPaused() == False:
                        return
            except:
                self.log('Exception during seek on paused channel', xbmc.LOGERROR)
        else:
            seektime = self.channels[self.currentChannel - 1].showTimeOffset + timedif + int((time.time() - curtime))

            try:
                self.log("Seeking");
                self.Player.seekTime(seektime)
            except:
                self.log("Unable to set proper seek time, trying different value")

                try:
                    seektime = self.channels[self.currentChannel - 1].showTimeOffset + timedif
                    self.Player.seekTime(seektime)
                except:
                    self.log('Exception during seek', xbmc.LOGERROR)

        self.showChannelLabel(self.currentChannel)
        self.lastActionTime = time.time()
        self.runActions(RULES_ACTION_OVERLAY_SET_CHANNEL_END, channel, self.channels[channel - 1])
        self.log('setChannel return')


    def InvalidateChannel(self, channel):
        self.log("InvalidateChannel" + str(channel))

        if channel < 1 or channel > self.maxChannels:
            self.log("InvalidateChannel invalid channel " + str(channel))
            return

        self.channels[channel - 1].isValid = False
        self.invalidatedChannelCount += 1

        if self.invalidatedChannelCount > 3:
            self.Error(LANGUAGE(30039))
            return

        remaining = 0

        for i in range(self.maxChannels):
            if self.channels[i].isValid:
                remaining += 1

        if remaining == 0:
            self.Error(LANGUAGE(30040))
            return

        self.setChannel(self.fixChannel(channel))


    def waitForVideoPaused(self):
        self.log('waitForVideoPaused')
        sleeptime = 0

        while sleeptime < TIMEOUT:
            xbmc.sleep(100)

            if self.Player.isPlaying():
                if xbmc.getCondVisibility('Player.Paused'):
                    break

            sleeptime += 100
        else:
            self.log('Timeout waiting for pause', xbmc.LOGERROR)
            return False

        self.log('waitForVideoPaused return')
        return True


    def setShowInfo(self):
        self.log('setShowInfo')

        if self.infoOffset > 0:
            self.getControl(502).setLabel(LANGUAGE(30041))
        elif self.infoOffset < 0:
            self.getControl(502).setLabel(LANGUAGE(30042))
        elif self.infoOffset == 0:
            self.getControl(502).setLabel(LANGUAGE(30043))

        if self.hideShortItems and self.infoOffset != 0:
            position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            curoffset = 0
            modifier = 1

            if self.infoOffset < 0:
                modifier = -1

            while curoffset != abs(self.infoOffset):
                position = self.channels[self.currentChannel - 1].fixPlaylistIndex(position + modifier)

                if self.channels[self.currentChannel - 1].getItemDuration(position) >= self.shortItemLength:
                    curoffset += 1
        else:
            position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition() + self.infoOffset

        self.getControl(503).setLabel(self.channels[self.currentChannel - 1].getItemTitle(position))
        self.getControl(504).setLabel(self.channels[self.currentChannel - 1].getItemEpisodeTitle(position))
        self.getControl(505).setText(self.channels[self.currentChannel - 1].getItemDescription(position))
        self.getControl(506).setImage(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png')
        if not FileAccess.exists(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png'):
            self.getControl(506).setImage(IMAGES_LOC + 'Default.png')

        self.log('setShowInfo return')


    # Display the current channel based on self.currentChannel.
    # Start the timer to hide it.
    def showChannelLabel(self, channel):
        self.log('showChannelLabel ' + str(channel))

        if self.channelLabelTimer.isAlive():
            self.channelLabelTimer.cancel()
            self.channelLabelTimer = threading.Timer(3.0, self.hideChannelLabel)

        tmp = self.inputChannel
        self.hideChannelLabel()
        self.inputChannel = tmp
        curlabel = 0

        if channel > 99:
            self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel // 100) + '.png')
            self.channelLabel[curlabel].setVisible(True)
            curlabel += 1

        if channel > 9:
            self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str((channel % 100) // 10) + '.png')
            self.channelLabel[curlabel].setVisible(True)
            curlabel += 1

        self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel % 10) + '.png')
        self.channelLabel[curlabel].setVisible(True)

        if self.inputChannel == -1 and self.infoOnChange == True:
            self.infoOffset = 0
            xbmc.sleep(self.channelDelay)
            self.showInfo(self.infoDuration)

        self.setChannelBug()

        if xbmc.getCondVisibility('Player.ShowInfo'):
            json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}'
            self.ignoreInfoAction = True
            self.channelList.sendJSON(json_query);
        self.channelLabelTimer.name = "ChannelLabel"
        self.channelLabelTimer.start()
        self.startNotificationTimer()
        self.log('showChannelLabel return')

    def setChannelBug(self):
        posx = self.channelBugPosition[0]
        posy = self.channelBugPosition[1]
        if self.showChannelBug:
            try:
                if not FileAccess.exists(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png'):
                    self.getControl(103).setImage(IMAGES_LOC + 'Default2.png')
                    self.getControl(103).setPosition(posx, posy)
                original = Image.open(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png')
                converted_img = original.convert('LA')
                img_bright = ImageEnhance.Brightness(converted_img)
                converted_img = img_bright.enhance(2.0)
                if not FileAccess.exists(CHANNELBUG_LOC + ascii(self.channels[self.currentChannel - 1].name) + '.png'):
                    converted_img.save(CHANNELBUG_LOC + ascii(self.channels[self.currentChannel - 1].name) + '.png')
                self.getControl(103).setImage(CHANNELBUG_LOC + ascii(self.channels[self.currentChannel - 1].name) + '.png')
                self.getControl(103).setPosition(posx, posy)

            except:
                self.getControl(103).setImage(IMAGES_LOC + 'Default2.png')
                self.getControl(103).setPosition(posx, posy)
        else:
            self.getControl(103).setImage('')

    # Called from the timer to hide the channel label.
    def hideChannelLabel(self):
        self.log('hideChannelLabel')
        self.channelLabelTimer = threading.Timer(3.0, self.hideChannelLabel)

        for i in range(3):
            self.channelLabel[i].setVisible(False)

        self.inputChannel = -1
        self.log('hideChannelLabel return')


    def hideInfo(self):
        self.getControl(102).setVisible(False)
        self.getControl(103).setVisible(True)
        self.infoOffset = 0
        self.showingInfo = False

        if self.infoTimer.isAlive():
            self.infoTimer.cancel()

        self.infoTimer = threading.Timer(5.0, self.hideInfo)


    def showInfo(self, timer):
        if self.hideShortItems:
            position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition() + self.infoOffset

            if self.channels[self.currentChannel - 1].getItemDuration(xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()) < self.shortItemLength:
                return

        self.getControl(103).setVisible(False)
        self.getControl(102).setVisible(True)
        self.showingInfo = True
        self.setShowInfo()

        if self.infoTimer.isAlive():
            self.infoTimer.cancel()

        self.infoTimer = threading.Timer(timer, self.hideInfo)
        self.infoTimer.name = "InfoTimer"

        if xbmc.getCondVisibility('Player.ShowInfo'):
            json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}'
            self.ignoreInfoAction = True
            self.channelList.sendJSON(json_query);

        self.infoTimer.start()


    # return a valid channel in the proper range
    def fixChannel(self, channel, increasing = True):
        while channel < 1 or channel > self.maxChannels:
            if channel < 1: channel = self.maxChannels + channel
            if channel > self.maxChannels: channel -= self.maxChannels

        if increasing:
            direction = 1
        else:
            direction = -1

        if self.channels[channel - 1].isValid == False:
            return self.fixChannel(channel + direction, increasing)

        return channel


    # Handle all input while videos are playing
    def onAction(self, act):
        action = act.getId()
        self.log('onAction ' + str(action))

        if self.Player.stopped:
            return

        # Since onAction isnt always called from the same thread (weird),
        # ignore all actions if we're in the middle of processing one
        if self.actionSemaphore.acquire(False) == False:
            self.log('Unable to get semaphore')
            return

        lastaction = time.time() - self.lastActionTime

        # during certain times we just want to discard all input
        if lastaction < 2:
            self.log('Not allowing actions')
            action = ACTION_INVALID

        self.startSleepTimer()

        if action == ACTION_SELECT_ITEM:
            # If we're manually typing the channel, set it now
            if self.inputChannel > 0:
                if self.inputChannel != self.currentChannel and self.inputChannel <= self.maxChannels:
                    self.setChannel(self.inputChannel)
                    if self.infoOnChange == True:
                        self.infoOffset = 0
                        xbmc.sleep(self.channelDelay)
                        self.showInfo(self.infoDuration)
                self.inputChannel = -1
            else:
                # Otherwise, show the EPG
                if self.channelThread.isAlive():
                    self.channelThread.pause()

                if self.notificationTimer.isAlive():
                    self.notificationTimer.cancel()
                    self.notificationTimer = threading.Timer(NOTIFICATION_CHECK_TIME, self.notificationAction)

                if self.sleepTimeValue > 0:
                    if self.sleepTimer.isAlive():
                        self.sleepTimer.cancel()
                        self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

                self.hideInfo()
                self.getControl(103).setVisible(False)
                self.newChannel = 0
                self.myEPG.doModal()
                self.getControl(103).setVisible(True)

                if self.channelThread.isAlive():
                    self.channelThread.unpause()

                self.startNotificationTimer()

                if self.newChannel != 0:
                    self.setChannel(self.newChannel)

        elif action == ACTION_MOVE_UP or action == ACTION_PAGEUP:
            self.channelUp()
        elif action == ACTION_MOVE_DOWN or action == ACTION_PAGEDOWN:
            self.channelDown()
        elif action == ACTION_MOVE_LEFT:
            if self.showingInfo:
                self.infoOffset -= 1
                self.showInfo(10)
            else:
                xbmc.executebuiltin("Seek("+str(self.seekBackward)+")")

        elif action == ACTION_MOVE_RIGHT:
            if self.showingInfo:
                self.infoOffset += 1
                self.showInfo(10)
            else:
                xbmc.executebuiltin("Seek("+str(self.seekForward)+")")

        elif action in ACTION_PREVIOUS_MENU:
            if self.showingInfo:
                self.hideInfo()
            else:
                dlg = xbmcgui.Dialog()

                if self.sleepTimeValue > 0:
                    if self.sleepTimer.isAlive():
                        self.sleepTimer.cancel()
                        self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

                if dlg.yesno(xbmc.getLocalizedString(13012), LANGUAGE(30031)):
                    self.end()
                    return  # Don't release the semaphore
                else:
                    self.startSleepTimer()

        elif action == ACTION_SHOW_INFO:
            if self.ignoreInfoAction:
                self.ignoreInfoAction = False
            else:
                if self.showingInfo:
                    self.hideInfo()

                    if xbmc.getCondVisibility('Player.ShowInfo'):
                        json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}'
                        self.ignoreInfoAction = True
                        self.channelList.sendJSON(json_query);

                else:
                    self.showInfo(10)
        elif action >= ACTION_NUMBER_0 and action <= ACTION_NUMBER_9:
            if self.inputChannel < 0:
                self.inputChannel = action - ACTION_NUMBER_0
            else:
                if self.inputChannel < 100:
                    self.inputChannel = self.inputChannel * 10 + action - ACTION_NUMBER_0

            self.showChannelLabel(self.inputChannel)
        elif action == ACTION_OSD:
            xbmc.executebuiltin("ActivateWindow(videoosd)")

        self.actionSemaphore.release()
        self.log('onAction return')


    # Reset the sleep timer
    def startSleepTimer(self):
        if self.sleepTimeValue == 0:
            return

        # Cancel the timer if it is still running
        if self.sleepTimer.isAlive():
            self.sleepTimer.cancel()
            self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

        if self.Player.stopped == False:
            self.sleepTimer.name = "SleepTimer"
            self.sleepTimer.start()


    def startNotificationTimer(self, timertime = NOTIFICATION_CHECK_TIME):
        self.log("startNotificationTimer")

        if self.notificationTimer.isAlive():
            self.notificationTimer.cancel()

        self.notificationTimer = threading.Timer(timertime, self.notificationAction)

        if self.Player.stopped == False:
            self.notificationTimer.name = "NotificationTimer"
            self.notificationTimer.start()


    # This is called when the sleep timer expires
    def sleepAction(self):
        self.log("sleepAction")
        self.actionSemaphore.acquire()
        self.end()


    # Run rules for a channel
    def runActions(self, action, channel, parameter):
        self.log("runActions " + str(action) + " on channel " + str(channel))

        if channel < 1:
            return

        self.runningActionChannel = channel
        index = 0

        for rule in self.channels[channel - 1].ruleList:
            if rule.actions & action > 0:
                self.runningActionId = index
                parameter = rule.runAction(action, self, parameter)

            index += 1

        self.runningActionChannel = 0
        self.runningActionId = 0
        return parameter


    def notificationAction(self):
        self.log("notificationAction")
        docheck = False

        if self.showNextItem == False:
            return

        if self.Player.isPlaying():
            if self.notificationLastChannel != self.currentChannel:
                docheck = True
            else:
                if self.notificationLastShow != xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition():
                    docheck = True
                else:
                    if self.notificationShowedNotif == False:
                        docheck = True

            if docheck == True:
                self.notificationLastChannel = self.currentChannel
                self.notificationLastShow = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
                self.notificationShowedNotif = False

                if self.hideShortItems:
                    # Don't show any notification if the current show is < 60 seconds
                    if self.channels[self.currentChannel - 1].getItemDuration(self.notificationLastShow) < self.shortItemLength:
                        self.notificationShowedNotif = True

                timedif = self.channels[self.currentChannel - 1].getItemDuration(self.notificationLastShow) - self.Player.getTime()

                if self.notificationShowedNotif == False and timedif < NOTIFICATION_TIME_BEFORE_END and timedif > NOTIFICATION_DISPLAY_TIME:
                    nextshow = self.channels[self.currentChannel - 1].fixPlaylistIndex(self.notificationLastShow + 1)

                    if self.hideShortItems:
                        # Find the next show that is >= 60 seconds long
                        while nextshow != self.notificationLastShow:
                            if self.channels[self.currentChannel - 1].getItemDuration(nextshow) >= self.shortItemLength:
                                break

                            nextshow = self.channels[self.currentChannel - 1].fixPlaylistIndex(nextshow + 1)

                    xbmc.executebuiltin('Notification(%s, %s, %d, %s)' % (LANGUAGE(30005), self.channels[self.currentChannel - 1].getItemTitle(nextshow).replace(',', ''), NOTIFICATION_DISPLAY_TIME * 1000, ICON))
                    self.notificationShowedNotif = True

        self.startNotificationTimer()


    def playerTimerAction(self):
        self.playerTimer = threading.Timer(2.0, self.playerTimerAction)

        if self.Player.isPlaying():
            self.lastPlayTime = int(self.Player.getTime())
            self.lastPlaylistPosition = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            self.notPlayingCount = 0
        else:
            self.notPlayingCount += 1
            self.log("Adding to notPlayingCount")

        if self.notPlayingCount >= 3:
            self.end()
            return

        if self.Player.stopped == False:
            self.playerTimer.name = "PlayerTimer"
            self.playerTimer.start()


    # cleanup and end
    def end(self):
        self.log('end')
        # Prevent the player from setting the sleep timer
        self.Player.stopped = True
        curtime = time.time()
        xbmc.executebuiltin("PlayerControl(RepeatOff)")
        self.isExiting = True
        updateDialog = xbmcgui.DialogProgressBG()
        updateDialog.create(ADDON_NAME, '')

        if self.isMaster and CHANNEL_SHARING == True:
            updateDialog.update(1, message='Exiting - Removing File Locks')
            GlobalFileLock.unlockFile('MasterLock')

        GlobalFileLock.close()

        if self.playerTimer.isAlive():
            self.playerTimer.cancel()
            self.playerTimer.join()

        if self.Player.isPlaying():
            self.lastPlayTime = self.Player.getTime()
            self.lastPlaylistPosition = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            self.Player.stop()

        updateDialog.update(2, message='Exiting - Stopping Threads')

        try:
            if self.channelLabelTimer.isAlive():
                self.channelLabelTimer.cancel()
                self.channelLabelTimer.join()
        except:
            pass

        updateDialog.update(3, message='Exiting - Stopping Threads')

        try:
            if self.notificationTimer.isAlive():
                self.notificationTimer.cancel()
                self.notificationTimer.join()
        except:
            pass

        updateDialog.update(4, message='Exiting - Stopping Threads')

        try:
            if self.infoTimer.isAlive():
                self.infoTimer.cancel()
                self.infoTimer.join()
        except:
            pass

        updateDialog.update(5, message='Exiting - Stopping Threads')

        try:
            if self.sleepTimeValue > 0:
                if self.sleepTimer.isAlive():
                    self.sleepTimer.cancel()
        except:
            pass

        updateDialog.update(6, message='Exiting - Stopping Threads')

        if self.channelThread.isAlive():
            for i in range(30):
                try:
                    self.channelThread.join(1.0)
                except:
                    pass

                if self.channelThread.isAlive() == False:
                    break

                updateDialog.update(6 + i, message='Exiting - Stopping Threads')

            if self.channelThread.isAlive():
                self.log("Problem joining channel thread", xbmc.LOGERROR)

        if self.isMaster:
            try:
                ADDON.setSetting('CurrentChannel', str(self.currentChannel))
            except:
                pass

            ADDON_SETTINGS.setSetting('LastExitTime', str(int(curtime)))

        if ADDON.getSettingBool("ResetWatched"):
            updateDialog.update(33, message='Exiting - Resetting Watched Status')
            Reset = ResetWatched()
            Reset.Resetter()
            
        if self.timeStarted > 0 and self.isMaster:
            updateDialog.update(35, message='Exiting - Saving Settings')
            validcount = 0

            for i in range(self.maxChannels):
                if self.channels[i].isValid:
                    validcount += 1

            if validcount > 0:
                incval = 65.0 / float(validcount)

                for i in range(self.maxChannels):
                    updateDialog.update(35 + int((incval * i)))

                    if self.channels[i].isValid:
                        if self.channels[i].mode & MODE_RESUME == 0:
                            ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(int(curtime - self.timeStarted + self.channels[i].totalTimePlayed)))
                        else:
                            if i == self.currentChannel - 1:
                                # Determine pltime...the time it at the current playlist position
                                pltime = 0
                                self.log("position for current playlist is " + str(self.lastPlaylistPosition))

                                for pos in range(self.lastPlaylistPosition):
                                    pltime += self.channels[i].getItemDuration(pos)

                                ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(pltime + self.lastPlayTime))
                            else:
                                tottime = 0

                                for j in range(self.channels[i].playlistPosition):
                                    tottime += self.channels[i].getItemDuration(j)

                                tottime += self.channels[i].showTimeOffset
                                ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(int(tottime)))

                self.storeFiles()
                xbmc.PlayList(xbmc.PLAYLIST_MUSIC).clear()

        updateDialog.close()
        self.close()
Example #34
0
class ChannelConfig(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        self.log("__init__")
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        self.setCoordinateResolution(1)
        self.showingList = True
        self.channel = 0
        self.channel_type = 9999
        self.setting1 = ""
        self.setting2 = ""
        self.setting3 = ""
        self.setting4 = ""
        self.setting5 = ""
        self.setting6 = ""
        self.setting7 = ""
        self.setting8 = ""
        self.setting9 = ""
        self.doModal()
        self.log("__init__ return")

    def onInit(self):
        self.log("onInit")

        self.createDirectories()

        self.getControl(105).setVisible(False)  # Channel Listing Control Group
        self.getControl(106).setVisible(False)  # Channel Settings Control Group

        for i in range(NUMBER_CHANNEL_TYPES):
            self.getControl(120 + i).setVisible(False)  # Channel Settings

        # migrate()
        self.prepareConfig()
        self.log("onInit return")

    def onFocus(self, controlId):
        pass

    def onAction(self, act):
        action = act.getId()

        if action == ACTION_PREVIOUS_MENU:
            if self.showingList == False:
                self.cancelChan()
                self.hideChanDetails()
            else:
                self.close()

    def prepareConfig(self):
        self.log("prepareConfig")
        self.showList = []
        self.getControl(105).setVisible(False)
        self.getControl(106).setVisible(False)
        self.dlg = xbmcgui.DialogProgress()
        self.dlg.create("TV Time", "Preparing Channel Wizard")
        self.dlg.update(0, "Preparing Channel Wizard")
        self.chnlst = ChannelList()
        self.dlg.update(10, "Preparing Channel Wizard", "Loading TV Settings")
        self.chnlst.fillTVInfo()
        self.networkList = self.chnlst.networkList
        self.studioList = self.chnlst.studioList
        self.showGenreList = self.chnlst.showGenreList
        self.dlg.update(20, "Preparing Channel Wizard", "Loading Movie Settings")
        self.chnlst.fillMovieInfo()
        self.movieGenreList = self.chnlst.movieGenreList
        self.dlg.update(40, "Preparing Channel Wizard", "Loading Music Settings")
        self.chnlst.fillMusicInfo()
        self.musicGenreList = self.chnlst.musicGenreList
        self.dlg.update(60, "Preparing Channel Wizard", "Loading Live Feed Settings")
        self.chnlst.fillFeedInfo()
        self.feedList = self.chnlst.feedList
        self.dlg.update(80, "Preparing Channel Wizard", "Loading Mixed Genre Settings")
        self.mixedGenreList = self.chnlst.makeMixedList(self.showGenreList, self.movieGenreList)

        for i in range(len(self.chnlst.showList)):
            self.showList.append(self.chnlst.showList[i][0])

        self.mixedGenreList.sort(key=lambda x: x.lower())

        self.log("self.networkList " + str(self.networkList))
        self.log("self.studioList " + str(self.studioList))
        self.log("self.showGenreList " + str(self.showGenreList))
        self.log("self.movieGenreList " + str(self.movieGenreList))
        self.log("self.musicGenreList " + str(self.musicGenreList))
        self.log("self.mixedGenreList " + str(self.mixedGenreList))

        self.resolutionList = []
        self.resolutionList.append("All")
        self.resolutionList.append("SD Only")
        self.resolutionList.append("720p or Higher")
        self.resolutionList.append("1080p Only")

        self.showseqList = []
        self.showseqList.append("1 Show")
        self.showseqList.append("2 Shows")
        self.showseqList.append("3 Shows")
        self.showseqList.append("4 Shows")
        self.showseqList.append("5 Shows")
        self.showseqList.append("6 Shows")
        self.showseqList.append("7 Shows")
        self.showseqList.append("8 Shows")
        self.showseqList.append("9 Shows")
        self.showseqList.append("10 Shows")

        self.movieseqList = []
        self.movieseqList.append("1 Movie")
        self.movieseqList.append("2 Movies")
        self.movieseqList.append("3 Movies")
        self.movieseqList.append("4 Movies")
        self.movieseqList.append("5 Movies")
        self.movieseqList.append("6 Movies")
        self.movieseqList.append("7 Movies")
        self.movieseqList.append("8 Movies")
        self.movieseqList.append("9 Movies")
        self.movieseqList.append("10 Movies")

        # check if settings2.xml file exists
        # read in channel playlists in video, music and mixed folders
        channelNum = 0
        for i in range(500):
            if os.path.exists(
                xbmc.translatePath("special://profile/playlists/video") + "/Channel_" + str(i + 1) + ".xsp"
            ):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_1",
                    xbmc.translatePath("special://profile/playlists/video/") + "Channel_" + str(i + 1) + ".xsp",
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_3",
                    ChannelList().cleanString(
                        ChannelList().getSmartPlaylistName(
                            xbmc.translatePath("special://profile/playlists/video") + "/Channel_" + str(i + 1) + ".xsp"
                        )
                    ),
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_playlist",
                    xbmc.translatePath("special://profile/playlists/video/") + "Channel_" + str(i + 1) + ".xsp",
                )
                # self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/video') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(
                xbmc.translatePath("special://profile/playlists/mixed") + "/Channel_" + str(i + 1) + ".xsp"
            ):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_1",
                    xbmc.translatePath("special://profile/playlists/mixed/") + "Channel_" + str(i + 1) + ".xsp",
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_3",
                    ChannelList().cleanString(
                        ChannelList().getSmartPlaylistName(
                            xbmc.translatePath("special://profile/playlists/mixed") + "/Channel_" + str(i + 1) + ".xsp"
                        )
                    ),
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_playlist",
                    xbmc.translatePath("special://profile/playlists/mixed/") + "Channel_" + str(i + 1) + ".xsp",
                )
                # self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/mixed') + '/Channel_' + str(i + 1) + '.xsp')),"")
            elif os.path.exists(
                xbmc.translatePath("special://profile/playlists/music") + "/Channel_" + str(i + 1) + ".xsp"
            ):
                channelNum = channelNum + 1
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_type", "0")
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_time", "0")
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_1",
                    xbmc.translatePath("special://profile/playlists/music/") + "Channel_" + str(i + 1) + ".xsp",
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_2", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_3",
                    ChannelList().cleanString(
                        ChannelList().getSmartPlaylistName(
                            xbmc.translatePath("special://profile/playlists/music") + "/Channel_" + str(i + 1) + ".xsp"
                        )
                    ),
                )
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_4", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_5", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_6", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_7", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_8", str(""))
                ADDON_SETTINGS.setSetting("Channel_" + str(channelNum) + "_9", str(""))
                ADDON_SETTINGS.setSetting(
                    "Channel_" + str(channelNum) + "_playlist",
                    xbmc.translatePath("special://profile/playlists/music/") + "Channel_" + str(i + 1) + ".xsp",
                )
                # self.updateDialog(progressIndicator,"Auto Tune","Found " + str(self.channelList.getSmartPlaylistName(xbmc.translatePath('special://profile/playlists/music') + '/Channel_' + str(i + 1) + '.xsp')),"")
        ADDON_SETTINGS.writeSettings()

        """
        if not os.path.exists(xbmc.translatePath('special://profile/addon_data/' + ADDON_ID + '/settings2.xml')):
            # if not, load presets based on networklist and studiolist
            ChannelList().autoTune()
        else:
            if (REAL_SETTINGS.getSetting("autoFindNetworks") == "true" or 
                REAL_SETTINGS.getSetting("autoFindStudios") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMovieGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindMixGenres") == "true" or 
                REAL_SETTINGS.getSetting("autoFindTVShows") == "true" or
                REAL_SETTINGS.getSetting("autoFindMusicGenres") == "true"):
                self.log("autoTune")
                ChannelList().autoTune()
        """

        self.listcontrol = self.getControl(102)

        for i in range(200):
            theitem = xbmcgui.ListItem()
            theitem.setLabel(str(i + 1))
            self.listcontrol.addItem(theitem)

        self.dlg.update(90, "Preparing Channel Wizard", "Loading Channel List")
        self.updateListing()
        self.dlg.close()
        self.getControl(105).setVisible(True)  # Channel List
        self.getControl(106).setVisible(False)  # Channel Settings
        self.setFocusId(102)
        self.log("prepareConfig return")

    def saveSettings(self):
        chantype = 9999
        chan = str(self.channel)

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + chan + "_type"))
        except:
            self.log("Unable to get channel type")

        setting1 = "Channel_" + chan + "_1"
        setting2 = "Channel_" + chan + "_2"
        setting3 = "Channel_" + chan + "_3"
        setting4 = "Channel_" + chan + "_4"
        setting5 = "Channel_" + chan + "_5"
        setting6 = "Channel_" + chan + "_6"
        setting7 = "Channel_" + chan + "_7"
        setting8 = "Channel_" + chan + "_8"
        setting9 = "Channel_" + chan + "_9"
        settingtime = "Channel_" + chan + "_time"
        playlist = "Channel_" + chan + "_playlist"
        totalDuration = "Channel_" + chan + "_totalDuration"

        if chantype == 0:
            ADDON_SETTINGS.setSetting(setting1, self.getControl(130).getLabel2())
            ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(130).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, "")
            ADDON_SETTINGS.setSetting(setting5, "")
            ADDON_SETTINGS.setSetting(setting6, "")
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(settingtime, 0)
        elif chantype == 1:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(142).getLabel()))
            if self.getControl(349).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(142).getLabel()))
            if self.getControl(346).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(347).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(343).getLabel())
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            if self.getControl(348).isSelected():
                ADDON_SETTINGS.setSetting(setting9, str(MODE_RANDOM_FILELISTS))
            else:
                ADDON_SETTINGS.setSetting(setting9, 0)
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        elif chantype == 2:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(152).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(152).getLabel()))
            if self.getControl(356).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            ADDON_SETTINGS.setSetting(setting5, "")
            ADDON_SETTINGS.setSetting(setting6, self.getControl(353).getLabel())
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        elif chantype == 3:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(162).getLabel()))
            if self.getControl(369).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(162).getLabel()) + " TV")
            if self.getControl(366).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(367).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(363).getLabel())
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        elif chantype == 4:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(172).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(172).getLabel()) + " Movies")
            if self.getControl(376).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            ADDON_SETTINGS.setSetting(setting5, self.getControl(373).getLabel())
            ADDON_SETTINGS.setSetting(setting6, "")
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        elif chantype == 5:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(182).getLabel()))
            if self.getControl(389).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(182).getLabel()) + " Mix")
            if self.getControl(386).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(387).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(383).getLabel())
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        elif chantype == 6:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(192).getLabel()))
            if self.getControl(194).isSelected():
                ADDON_SETTINGS.setSetting(setting2, str(MODE_SERIAL))
            else:
                ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(192).getLabel()))
            if self.getControl(396).isSelected():
                ADDON_SETTINGS.setSetting(setting4, str(MODE_UNWATCHED))
            else:
                ADDON_SETTINGS.setSetting(setting4, 0)
            if self.getControl(397).isSelected():
                ADDON_SETTINGS.setSetting(setting5, str(MODE_NOSPECIALS))
            else:
                ADDON_SETTINGS.setSetting(setting5, 0)
            ADDON_SETTINGS.setSetting(setting6, self.getControl(393).getLabel())
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        if chantype == 7:  # folder
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(200).getLabel2()))
            ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(200).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, "")
            ADDON_SETTINGS.setSetting(setting5, "")
            ADDON_SETTINGS.setSetting(setting6, "")
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        if chantype == 8:  # music
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(212).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(212).getLabel()) + " Music")
            ADDON_SETTINGS.setSetting(setting4, "")
            ADDON_SETTINGS.setSetting(setting5, "")
            ADDON_SETTINGS.setSetting(setting6, "")
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        if chantype == 9:  # live
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, self.chnlst.cleanString(self.getControl(222).getLabel()))
            ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, self.chnlst.cleanString(self.getControl(222).getLabel()))
            ADDON_SETTINGS.setSetting(setting4, "")
            ADDON_SETTINGS.setSetting(setting5, "")
            ADDON_SETTINGS.setSetting(setting6, "")
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")
        elif chantype == 9999:
            ADDON_SETTINGS.setSetting(settingtime, 0)
            ADDON_SETTINGS.setSetting(setting1, "")
            ADDON_SETTINGS.setSetting(setting2, "")
            ADDON_SETTINGS.setSetting(setting3, "")
            ADDON_SETTINGS.setSetting(setting4, "")
            ADDON_SETTINGS.setSetting(setting5, "")
            ADDON_SETTINGS.setSetting(setting6, "")
            ADDON_SETTINGS.setSetting(setting7, "")
            ADDON_SETTINGS.setSetting(setting8, "")
            ADDON_SETTINGS.setSetting(setting9, "")
            ADDON_SETTINGS.setSetting(playlist, "")
            ADDON_SETTINGS.setSetting(totalDuration, "")

        # Check to see if the user changed anything
        set1 = ""
        set2 = ""
        set3 = ""
        set4 = ""
        set5 = ""
        set6 = ""
        set7 = ""
        set8 = ""
        set9 = ""

        try:
            set1 = ADDON_SETTINGS.getSetting(setting1)
            set2 = ADDON_SETTINGS.getSetting(setting2)
            set3 = ADDON_SETTINGS.getSetting(setting3)
            set4 = ADDON_SETTINGS.getSetting(setting4)
            set5 = ADDON_SETTINGS.getSetting(setting5)
            set6 = ADDON_SETTINGS.getSetting(setting6)
            set7 = ADDON_SETTINGS.getSetting(setting7)
            set8 = ADDON_SETTINGS.getSetting(setting8)
            set9 = ADDON_SETTINGS.getSetting(setting9)
        except:
            pass

        if (
            chantype != self.channel_type
            or set1 != self.setting1
            or set2 != self.setting2
            or set3 != self.setting3
            or set4 != self.setting4
            or set5 != self.setting5
            or set6 != self.setting6
            or set7 != self.setting7
            or set8 != self.setting8
            or set9 != self.setting9
        ):
            ADDON_SETTINGS.setSetting("Channel_" + chan + "_changed", "true")

        ADDON_SETTINGS.writeSettings()
        # save total number of channels to settings.xml so we don't have to keep looping
        # through settings2.xml
        self.chnlst.setMaxChannels()

        self.log("saveSettings return")

    def cancelChan(self):
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_type", str(self.channel_type))
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_1", self.setting1)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_2", self.setting2)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_3", self.setting3)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_4", self.setting4)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_5", self.setting5)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_6", self.setting6)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_7", self.setting7)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_8", self.setting8)
        ADDON_SETTINGS.setSetting("Channel_" + str(self.channel) + "_9", self.setting9)

    def hideChanDetails(self):
        self.getControl(106).setVisible(False)

        for i in range(NUMBER_CHANNEL_TYPES):
            self.getControl(120 + i).setVisible(False)

        self.setFocusId(102)
        self.getControl(105).setVisible(True)
        self.showingList = True
        self.updateListing(self.channel)
        self.listcontrol.selectItem(self.channel - 1)

    def onClick(self, controlId):
        self.log("onClick " + str(controlId))

        if controlId == 102:
            self.getControl(105).setVisible(False)
            self.getControl(106).setVisible(True)
            self.channel = self.listcontrol.getSelectedPosition() + 1
            self.changeChanType(self.channel, 0)

            self.setFocusId(110)
            self.showingList = False
        elif controlId == 110:
            self.changeChanType(self.channel, -1)
        elif controlId == 111:
            self.changeChanType(self.channel, 1)
        elif controlId == 112:
            self.saveSettings()
            self.hideChanDetails()
        elif controlId == 113:
            self.cancelChan()
            self.hideChanDetails()
        elif controlId == 130:
            dlg = xbmcgui.Dialog()
            retval = dlg.browse(
                1,
                "Channel " + str(self.channel) + " Playlist",
                "files",
                ".xsp",
                False,
                False,
                "special://videoplaylists/",
            )

            if retval != "special://videoplaylists/":
                self.getControl(130).setLabel(self.chnlst.getSmartPlaylistName(retval), label2=retval)
        elif controlId == 140:
            self.changeListData(self.networkList, 142, -1)
        elif controlId == 141:
            self.changeListData(self.networkList, 142, 1)
        elif controlId == 150:
            self.changeListData(self.studioList, 152, -1)
        elif controlId == 151:
            self.changeListData(self.studioList, 152, 1)
        elif controlId == 160:
            self.changeListData(self.showGenreList, 162, -1)
        elif controlId == 161:
            self.changeListData(self.showGenreList, 162, 1)
        elif controlId == 170:
            self.changeListData(self.movieGenreList, 172, -1)
        elif controlId == 171:
            self.changeListData(self.movieGenreList, 172, 1)
        elif controlId == 180:
            self.changeListData(self.mixedGenreList, 182, -1)
        elif controlId == 181:
            self.changeListData(self.mixedGenreList, 182, 1)
        elif controlId == 190:
            self.changeListData(self.showList, 192, -1)
        elif controlId == 191:
            self.changeListData(self.showList, 192, 1)
        elif controlId == 200:  # Folder Channel
            dlg = xbmcgui.Dialog()
            # need to replace this with folder instead of file
            retval = dlg.browse(0, "Channel " + str(self.channel) + " Folder", "files", "*.*", False, False, "")
            if retval != "":
                # smb isn't supported at this time but it is here
                # as a placeholder if a solution can be found
                # for connecting to smb shares from python
                if retval.find("smb://") == -1:
                    ps = retval.split(os.sep)
                else:
                    ps = retval.split("/")
                chanName = ""
                for i in range(len(ps) - 1):
                    chanName = ps[i]
                self.getControl(200).setLabel(chanName, label2=retval)
        elif controlId == 210:  # Music Based Channel
            self.changeListData(self.musicGenreList, 212, -1)
        elif controlId == 211:
            self.changeListData(self.musicGenreList, 212, 1)
        elif controlId == 220:  # Live Channel
            self.changeListData(self.feedList, 222, -1)
        elif controlId == 221:
            self.changeListData(self.feedList, 222, 1)
        elif controlId == 344:
            self.changeListData(self.resolutionList, 343, -1)
        elif controlId == 345:
            self.changeListData(self.resolutionList, 343, 1)
        elif controlId == 354:
            self.changeListData(self.resolutionList, 353, -1)
        elif controlId == 355:
            self.changeListData(self.resolutionList, 353, 1)
        elif controlId == 364:
            self.changeListData(self.resolutionList, 363, -1)
        elif controlId == 365:
            self.changeListData(self.resolutionList, 363, 1)
        elif controlId == 374:
            self.changeListData(self.resolutionList, 373, -1)
        elif controlId == 375:
            self.changeListData(self.resolutionList, 373, 1)
        elif controlId == 384:
            self.changeListData(self.resolutionList, 383, -1)
        elif controlId == 385:
            self.changeListData(self.resolutionList, 383, 1)
        elif controlId == 394:
            self.changeListData(self.resolutionList, 393, -1)
        elif controlId == 395:
            self.changeListData(self.resolutionList, 393, 1)
        elif controlId == 489:
            self.changeListData(self.showseqList, 488, -1)
        elif controlId == 490:
            self.changeListData(self.showseqList, 488, 1)
        elif controlId == 492:
            self.changeListData(self.movieseqList, 491, -1)
        elif controlId == 493:
            self.changeListData(self.movieseqList, 491, 1)

        self.log("onClick return")

    def changeListData(self, thelist, controlid, val):
        self.log("changeListData " + str(controlid) + ", " + str(val))
        curval = self.getControl(controlid).getLabel()
        found = False
        index = 0

        if len(thelist) == 0:
            self.getControl(controlid).setLabel("")
            self.log("changeListData return Empty list")
            return

        for item in thelist:
            if item == curval:
                found = True
                break

            index += 1

        if found == True:
            index += val

        while index < 0:
            index += len(thelist)

        while index >= len(thelist):
            index -= len(thelist)

        self.getControl(controlid).setLabel(self.chnlst.uncleanString(thelist[index]))
        self.log("changeListData return")

    def changeChanType(self, channel, val):
        self.log("changeChanType " + str(channel) + ", " + str(val))
        chantype = 9999

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_type"))
        except:
            self.log("Unable to get channel type")

        if val != 0:
            chantype += val

            if chantype < 0:
                chantype = 9999
            elif chantype == 10000:
                chantype = 0
            elif chantype == 9998:
                chantype = NUMBER_CHANNEL_TYPES - 1
            elif chantype == NUMBER_CHANNEL_TYPES:
                chantype = 9999

            ADDON_SETTINGS.setSetting("Channel_" + str(channel) + "_type", str(chantype))
        else:
            self.channel_type = chantype
            self.setting1 = ""
            self.setting2 = ""
            self.setting3 = ""
            self.setting4 = ""
            self.setting5 = ""
            self.setting6 = ""
            self.setting7 = ""
            self.setting8 = ""
            self.setting9 = ""

            try:
                self.setting1 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_1")
                self.setting2 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_2")
                self.setting3 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_3")
                self.setting4 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_4")
                self.setting5 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_5")
                self.setting6 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_6")
                self.setting7 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_7")
                self.setting8 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_8")
                self.setting9 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_9")
            except:
                pass

        for i in range(NUMBER_CHANNEL_TYPES):
            if i == chantype:
                self.getControl(120 + i).setVisible(True)  # show settings
                self.getControl(110).controlDown(self.getControl(120 + ((i + 1) * 10)))

                try:
                    self.getControl(111).controlDown(self.getControl(120 + ((i + 1) * 10 + 1)))
                except:
                    self.getControl(111).controlDown(self.getControl(120 + ((i + 1) * 10)))
            else:
                self.getControl(120 + i).setVisible(False)  # hide settings

        self.fillInDetails(channel)
        self.log("changeChanType return")

    def fillInDetails(self, channel):
        self.getControl(104).setLabel("Channel " + str(channel))
        chantype = 9999
        chansetting1 = ""
        chansetting2 = ""
        chansetting3 = ""
        chansetting4 = ""
        chansetting5 = ""
        chansetting6 = ""
        chansetting7 = ""
        chansetting8 = ""

        try:
            chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_type"))
            chansetting1 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_1")
            chansetting2 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_2")
            chansetting3 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_3")
            chansetting4 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_4")
            chansetting5 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_5")
            chansetting6 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_6")
            chansetting7 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_7")
            chansetting8 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_8")
            chansetting9 = ADDON_SETTINGS.getSetting("Channel_" + str(channel) + "_9")
        except:
            self.log("Unable to get some setting")

        if chansetting2 == "":
            chansetting2 = 0
        if chansetting4 == "":
            chansetting4 = 0
        if chansetting5 == "":
            chansetting5 = 0
        if chansetting6 == "":
            chansetting6 = "All"
        # if chansetting7 == "": chansetting7 = 0
        # if chansetting8 == "": chansetting8 = 0
        if chansetting9 == "":
            chansetting9 = 0

        self.getControl(109).setLabel(self.getChanTypeLabel(chantype))

        if chantype == 0:
            plname = self.chnlst.getSmartPlaylistName(chansetting1)

            if len(plname) == 0:
                chansetting1 = ""

            self.getControl(130).setLabel(self.chnlst.getSmartPlaylistName(chansetting1), label2=chansetting1)
        elif chantype == 1:
            self.getControl(142).setLabel(self.findItemInList(self.networkList, chansetting1))
            self.getControl(343).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(349).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(346).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(347).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            if chansetting9 <> "":
                self.getControl(348).setSelected(int(chansetting9) == int(MODE_RANDOM_FILELISTS))
        elif chantype == 2:
            self.getControl(152).setLabel(self.findItemInList(self.studioList, chansetting1))
            self.getControl(353).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(356).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
        elif chantype == 3:
            self.getControl(162).setLabel(self.findItemInList(self.showGenreList, chansetting1))
            self.getControl(363).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(369).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(366).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(367).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
        elif chantype == 4:
            self.getControl(172).setLabel(self.findItemInList(self.movieGenreList, chansetting1))
            self.getControl(373).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(376).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
        elif chantype == 5:
            self.getControl(182).setLabel(self.findItemInList(self.mixedGenreList, chansetting1))
            self.getControl(383).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting2 <> "":
                self.getControl(389).setSelected(int(chansetting2) == int(MODE_SERIAL))
            if chansetting4 <> "":
                self.getControl(386).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(387).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            self.getControl(488).setLabel(self.findItemInList(self.showseqList, chansetting7))
            self.getControl(491).setLabel(self.findItemInList(self.movieseqList, chansetting8))
        elif chantype == 6:
            self.getControl(192).setLabel(self.findItemInList(self.showList, chansetting1))
            self.getControl(393).setLabel(self.findItemInList(self.resolutionList, chansetting6))
            if chansetting4 <> "":
                self.getControl(396).setSelected(int(chansetting4) == int(MODE_UNWATCHED))
            if chansetting5 <> "":
                self.getControl(397).setSelected(int(chansetting5) == int(MODE_NOSPECIALS))
            self.getControl(194).setSelected(chansetting2 == str(MODE_SERIAL))
        elif chantype == 7:  # folder
            fldname = chansetting3
            if len(fldname) == 0:
                chansetting1 = ""
            self.getControl(200).setLabel(fldname, label2=self.chnlst.uncleanString(chansetting1))
        elif chantype == 8:  # music
            self.getControl(212).setLabel(self.findItemInList(self.musicGenreList, chansetting1))
        elif chantype == 9:  # live
            self.getControl(222).setLabel(self.findItemInList(self.feedList, chansetting1))

        self.log("fillInDetails return")

    def findItemInList(self, thelist, item):
        loitem = item.lower()

        for i in thelist:
            if loitem == i.lower():
                return item

        if len(thelist) > 0:
            return thelist[0]

        return ""

    def getChanTypeLabel(self, chantype):
        if chantype == 0:
            return "Custom Playlist"
        elif chantype == 1:
            return "TV Network"
        elif chantype == 2:
            return "Movie Studio"
        elif chantype == 3:
            return "TV Genre"
        elif chantype == 4:
            return "Movie Genre"
        elif chantype == 5:
            return "Mixed Genre"
        elif chantype == 6:
            return "TV Show"
        elif chantype == 7:
            return "Folder"
        elif chantype == 8:
            return "Music Genre"
        elif chantype == 9:
            return "Live"
        elif chantype == 9999:
            return "None"

        return ""

    def updateListing(self, channel=-1):
        self.log("updateListing")
        start = 0
        end = 200

        if channel > -1:
            start = channel - 1
            end = channel

        for i in range(start, end):
            theitem = self.listcontrol.getListItem(i)
            chantype = 9999
            chansetting1 = ""
            chansetting2 = ""
            chansetting3 = ""
            newlabel = ""

            try:
                chantype = int(ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_type"))
                chansetting1 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_1")
                chansetting2 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_2")
                chansetting3 = ADDON_SETTINGS.getSetting("Channel_" + str(i + 1) + "_3")
            except:
                pass

            if chantype == 0:
                newlabel = self.chnlst.getSmartPlaylistName(chansetting1)
            elif chantype == 1 or chantype == 2 or chantype == 5 or chantype == 6:
                newlabel = chansetting3
            elif chantype == 3:
                newlabel = chansetting3
            elif chantype == 4:
                newlabel = chansetting3
            elif chantype == 7:
                newlabel = self.chnlst.uncleanString(chansetting3)
            elif chantype == 8:
                newlabel = chansetting3
            elif chantype == 9:
                newlabel = self.chnlst.uncleanString(chansetting3)

            theitem.setLabel2(newlabel)

        self.log("updateListing return")

    #####################################################
    #####################################################
    #
    # Utility Functions
    #
    #####################################################
    #####################################################

    def log(self, msg, level=xbmc.LOGDEBUG):
        xbmc.log("TV Time-" + msg, level)

    def createDirectories(self):
        self.log("createDirectories")
        # setup directories
        self.createDirectory(CHANNELS_LOC)
        self.createDirectory(GEN_CHAN_LOC)
        self.createDirectory(PRESTAGE_LOC)
        self.createDirectory(TEMP_LOC)
        self.createDirectory(META_LOC)
        self.createDirectory(FEED_LOC)

    def createDirectory(self, directory):
        if not os.path.exists(directory):
            try:
                os.makedirs(directory)
            except:
                self.Error("Unable to create the directory - " + str(directory))
                return