Пример #1
0
    def saveConfig(self):
        self.saveRequired(False)  # Reset save button state

        # Disable quit button
        self.ui.btnQuit.setEnabled(False)

        # Save button icon & text
        s_btnIcon = self.ui.btnSave.icon()
        s_btnText = self.ui.btnSave.text()
        self.ui.btnSave.setText(u"Saving...")
        self.ui.btnSave.setIcon(QIcon())
        self.repaint()
        qApp.processEvents()

        tools.msgDebug(u"Saving configuration...", __name__)

        config = Config()

        # Save Data
        config.setShows(self.myShows)
        config.setColors(self.myColors)

        if self.ui.radioDispFixedLines.isChecked():
            value = "Fixed"
        else:
            value = "Automatic"
        config.set("display", "type", value)

        config.set("display", "past_days",
                   str(self.ui.spinNumPastDays.value()))
        config.set("display", "lines_fixed",
                   str(self.ui.spinFixedDispLines.value()))
        config.set("display", "lines_min",
                   str(self.ui.spinMinDispLines.value()))
        config.set("display", "lines_max",
                   str(self.ui.spinMaxDispLines.value()))
        config.set("display", "format", str(self.ui.leditFormat.text()))
        sep = self.ui.leditDateSeparator.text()
        list = self.ui.comboDateFormat.itemData(
            self.ui.comboDateFormat.currentIndex()).toStringList()
        dateFormat = list.join(sep)
        config.set("display", "date_separator", str(sep))
        config.set("display", "date_format", str(dateFormat))

        config.set("misc", "cache_expiration",
                   str(self.ui.spinCacheExpiration.value()))
        config.set("misc", "browser", str(self.ui.leditBrowser.text()))
        config.set("misc", "theme", str(self.ui.comboTheme.currentText()))

        # Set this so that the widget knows something changed
        config.set("main", "config_changed", "True")

        tools.msgDebug(u"Saving done!", __name__)

        config.close()  # Destroy Config()

        # Restore buttons
        self.ui.btnSave.setIcon(s_btnIcon)
        self.ui.btnSave.setText(s_btnText)
        self.ui.btnQuit.setEnabled(True)
Пример #2
0
def copyThemeFilesToConfigDir(widget):
    # Copy files
    for file in Globals().nsCGuiFiles:
        source = karamba.readThemeFile(widget, file)
        dest = open(os.path.join(Globals().nsCGuiBaseDir, file), "w")
        tools.msgDebug("Copying file: %s" % file, __name__)
        print >> dest, source
        dest.close()
Пример #3
0
def copyThemeFilesToConfigDir(widget):
    # Copy files
    for file in Globals().nsCGuiFiles:
        source = karamba.readThemeFile( widget, file )
        dest   = open( os.path.join( Globals().nsCGuiBaseDir, file ), "w" )
        tools.msgDebug("Copying file: %s" % file, __name__)
        print >> dest, source
        dest.close()
Пример #4
0
 def on_btnSelectColor_clicked(self):
     selColor = QColorDialog.getColor(QColor(self.lastColorUsed), self)
     if not selColor.isValid():
         tools.msgDebug(u"Canceled by user!", __name__)
         return
     tools.msgDebug( u"Selected color: #%02X%02X%02X" % ( selColor.red(), selColor.green(), selColor.blue() ), __name__ )
     self.ui.lblSelectColor.setPixmap( self.drawPreviewColor( selColor, 36, 36 ) )
     self.lastColorUsed = str( selColor.name() )
Пример #5
0
 def on_btnSetDefaultColor_clicked(self):
     selColor = QColorDialog.getColor(QColor(self.myColors['default']), self)
     if not selColor.isValid():
         tools.msgDebug(u"Canceled by user!", __name__)
         return
     tools.msgDebug( u"Selected color: #%02X%02X%02X" % ( selColor.red(), selColor.green(), selColor.blue() ), __name__ )
     self.ui.lblDefaultColor.setPixmap( self.drawPreviewColor( selColor, 36, 36 ) )
     self.myColors['default'] = str( selColor.name() )
     # Need to save
     self.saveRequired()
Пример #6
0
    def search(self, keywords):
        # Clear Search Results
        self.searchResults = []

        # Sanitize keywords and build the URL
        url = self.urlSearch % urllib.quote_plus(keywords)
        tools.msgDebug("Requesting %s" % url, __name__)
        # do the request
        content = self.request(url)  # request() from Http()
        if not content:
            return False  # In case something went wrong during fetching
        # ...and parse the results
        try:
            tools.msgDebug("Parsing feed content...", __name__)
            doc = ETree.fromstring(content)
        except:
            tools.msgDebug("Unexpected error while parsing the XML feed...",
                           __name__)
            return False

        # If the search returns nothing...
        if doc.text == "0":
            tools.msgDebug("Search returned 0 results", __name__)
            return self.searchResults

        # Extract infos from the returned results
        for show in doc.getiterator('show'):
            showInfos = {}
            for child in show.getchildren():
                if child.tag == "showid":
                    showInfos["id"] = int(child.text)
                    showInfos["url"] = self.urlShowTemplate % showInfos["id"]
                elif child.tag == "name":
                    showInfos["name"] = u'' + child.text
                elif child.tag == "started":
                    showInfos["year_begin"] = child.text
                elif child.tag == "ended":
                    # This hack is necessary to retain compatibility with
                    # previous versions' config. files
                    if child.text == "0":
                        showInfos["year_end"] = "????"
                    else:
                        showInfos["year_end"] = child.text
                elif child.tag == "country":
                    showInfos["flag"] = child.text.lower()

            tools.msgDebug(
                "ShowName: %s, Flag: %s, Years: %s-%s, id: %d, url: %s" %
                (showInfos["name"], showInfos["flag"], showInfos["year_begin"],
                 showInfos["year_end"], showInfos["id"], showInfos["url"]),
                __name__)

            self.searchResults.append(showInfos)

        return self.searchResults
Пример #7
0
 def on_btnSelectColor_clicked(self):
     selColor = QColorDialog.getColor(QColor(self.lastColorUsed), self)
     if not selColor.isValid():
         tools.msgDebug(u"Canceled by user!", __name__)
         return
     tools.msgDebug(
         u"Selected color: #%02X%02X%02X" %
         (selColor.red(), selColor.green(), selColor.blue()), __name__)
     self.ui.lblSelectColor.setPixmap(
         self.drawPreviewColor(selColor, 36, 36))
     self.lastColorUsed = str(selColor.name())
Пример #8
0
    def saveConfig(self):
        self.saveRequired( False )  # Reset save button state

        # Disable quit button
        self.ui.btnQuit.setEnabled( False )

        # Save button icon & text
        s_btnIcon = self.ui.btnSave.icon()
        s_btnText = self.ui.btnSave.text()
        self.ui.btnSave.setText(u"Saving...")
        self.ui.btnSave.setIcon(QIcon())
        self.repaint()
        qApp.processEvents()

        tools.msgDebug(u"Saving configuration...", __name__)

        config = Config()

        # Save Data
        config.setShows( self.myShows )
        config.setColors( self.myColors )

        if self.ui.radioDispFixedLines.isChecked():
            value = "Fixed"
        else:
            value = "Automatic"
        config.set( "display", "type", value )

        config.set( "display", "past_days",     str( self.ui.spinNumPastDays.value()     ) )
        config.set( "display", "lines_fixed",   str( self.ui.spinFixedDispLines.value()  ) )
        config.set( "display", "lines_min",     str( self.ui.spinMinDispLines.value()    ) )
        config.set( "display", "lines_max",     str( self.ui.spinMaxDispLines.value()    ) )
        config.set( "display", "format",        str( self.ui.leditFormat.text()          ) )
        sep  = self.ui.leditDateSeparator.text()
        list = self.ui.comboDateFormat.itemData( self.ui.comboDateFormat.currentIndex() ).toStringList()
        dateFormat = list.join(sep)
        config.set( "display", "date_separator",str( sep                                 ) )
        config.set( "display", "date_format",   str( dateFormat                          ) )

        config.set( "misc", "cache_expiration", str( self.ui.spinCacheExpiration.value() ) )
        config.set( "misc", "browser",          str( self.ui.leditBrowser.text()         ) )
        config.set( "misc", "theme",            str( self.ui.comboTheme.currentText()    ) )

        # Set this so that the widget knows something changed
        config.set( "main", "config_changed", "True" )

        tools.msgDebug(u"Saving done!", __name__)

        config.close()  # Destroy Config()

        # Restore buttons
        self.ui.btnSave.setIcon( s_btnIcon )
        self.ui.btnSave.setText( s_btnText )
        self.ui.btnQuit.setEnabled( True )
Пример #9
0
    def getCachedEpisodeList(self, id):
        # Cache filename
        cacheFileName = Globals().nsCacheFilePrefix + str( id )
        
        # Get data
        tools.msgDebug("Getting data from cache %s..." % cacheFileName, __name__)
        fp = open( cacheFileName, "rb" )
        data = cPickle.load( fp )
        fp.close()

        # Return episode list
        return data['episode_list']
Пример #10
0
def widgetUpdated(widget):
    global g_configGuiPid, g_dateCheck, g_nextCacheRefresh, g_showList, g_showIds, g_pastDays, g_linesMin, g_linesMax

    tools.msgDebug("Widget update triggered...", __name__)

    # Block widget updates when GUI is running...
    if g_configGuiPid:
        tools.msgDebug("Widget updates suspended, GUI's running...", __name__)
        return

    # If date changed since the widget was launched, refresh view
    if date.today() != g_dateCheck:
        tools.msgDebug("Day changed, refreshing view...", __name__)
        episodeList  = data.getEpisodeList( g_showIds, g_pastDays, g_linesMax )
        applet.episodeList = episodeList
        numReturnedEpisode = len( episodeList )
        if numReturnedEpisode < g_linesMin:
            themeLines = g_linesMin
        elif numReturnedEpisode > g_linesMax:
            themeLines = g_linesMax
        else:
            themeLines = numReturnedEpisode
        applet.themeLines = themeLines
        applet.drawBackground()
        applet.printEpisodeList()

        # Reset date check
        g_dateCheck = date.today()


    # Check chether cache needs refresh or no
    ncrTS = g_nextCacheRefresh
    nowTS = int( datetime.utcnow().strftime("%s") )
    if ncrTS == -1:
        # Cache is empty...
        return
    if ncrTS < nowTS:
        tools.msgDebug("Cache needs refresh...", __name__)
        # If nextCacheRefresh is past, we need to refresh cache
        # First, cleanup cache
        cache.deleteOldCacheFiles()
        # Refresh cache
        staledList = cache.getStaledCacheFiles()
        for id in staledList:
            for show in g_showList:
                if show['id'] == id:
                    showName = show['name']
            tools.msgDebug("Refreshing cache: '%s'...", __name__)
            cache.cacheEpisodeList( id )

        # Reset nextCacheRefresh value
        g_nextCacheRefresh = cache.getNextRefreshTS()
Пример #11
0
def menuOptionChanged(widget, key, value):
    global g_configGuiPid

    karamba.setMenuConfigOption(widget, "config_gui", 0)

    if key == "config_gui":
        if g_configGuiPid == None:
            # Launch config GUI
            gui=os.path.join( Globals().nsCGuiBaseDir, "launchGUI" )
            cmd = ["python", gui]
            g_configGuiPid=karamba.executeInteractive(widget, cmd)
        else:
            tools.msgDebug("GUI already running", __name__)
Пример #12
0
def menuOptionChanged(widget, key, value):
    global g_configGuiPid

    karamba.setMenuConfigOption(widget, "config_gui", 0)

    if key == "config_gui":
        if g_configGuiPid == None:
            # Launch config GUI
            gui = os.path.join(Globals().nsCGuiBaseDir, "launchGUI")
            cmd = ["python", gui]
            g_configGuiPid = karamba.executeInteractive(widget, cmd)
        else:
            tools.msgDebug("GUI already running", __name__)
Пример #13
0
def widgetUpdated(widget):
    global g_configGuiPid, g_dateCheck, g_nextCacheRefresh, g_showList, g_showIds, g_pastDays, g_linesMin, g_linesMax

    tools.msgDebug("Widget update triggered...", __name__)

    # Block widget updates when GUI is running...
    if g_configGuiPid:
        tools.msgDebug("Widget updates suspended, GUI's running...", __name__)
        return

    # If date changed since the widget was launched, refresh view
    if date.today() != g_dateCheck:
        tools.msgDebug("Day changed, refreshing view...", __name__)
        episodeList = data.getEpisodeList(g_showIds, g_pastDays, g_linesMax)
        applet.episodeList = episodeList
        numReturnedEpisode = len(episodeList)
        if numReturnedEpisode < g_linesMin:
            themeLines = g_linesMin
        elif numReturnedEpisode > g_linesMax:
            themeLines = g_linesMax
        else:
            themeLines = numReturnedEpisode
        applet.themeLines = themeLines
        applet.drawBackground()
        applet.printEpisodeList()

        # Reset date check
        g_dateCheck = date.today()

    # Check chether cache needs refresh or no
    ncrTS = g_nextCacheRefresh
    nowTS = int(datetime.utcnow().strftime("%s"))
    if ncrTS == -1:
        # Cache is empty...
        return
    if ncrTS < nowTS:
        tools.msgDebug("Cache needs refresh...", __name__)
        # If nextCacheRefresh is past, we need to refresh cache
        # First, cleanup cache
        cache.deleteOldCacheFiles()
        # Refresh cache
        staledList = cache.getStaledCacheFiles()
        for id in staledList:
            for show in g_showList:
                if show['id'] == id:
                    showName = show['name']
            tools.msgDebug("Refreshing cache: '%s'...", __name__)
            cache.cacheEpisodeList(id)

        # Reset nextCacheRefresh value
        g_nextCacheRefresh = cache.getNextRefreshTS()
Пример #14
0
    def search(self, keywords):
        # Clear Search Results
        self.searchResults = []

        # Sanitize keywords and build the URL
        url = self.urlSearch % urllib.quote_plus(keywords)
        tools.msgDebug("Requesting %s" % url, __name__)
        # do the request
        content = self.request(url)     # request() from Http()
        if not content:
            return False    # In case something went wrong during fetching
        # ...and parse the results
        try:
            tools.msgDebug("Parsing feed content...", __name__)
            doc = ETree.fromstring(content)
        except:
            tools.msgDebug("Unexpected error while parsing the XML feed...", __name__)
            return False

        # If the search returns nothing...
        if doc.text == "0":
            tools.msgDebug("Search returned 0 results", __name__)
            return self.searchResults

        # Extract infos from the returned results
        for show in doc.getiterator('show'):
            showInfos = {}
            for child in show.getchildren():
                if   child.tag == "showid":
                    showInfos["id"]   = int( child.text )
                    showInfos["url"]  = self.urlShowTemplate % showInfos["id"]
                elif child.tag == "name":
                    showInfos["name"] = u''+child.text
                elif child.tag == "started":
                    showInfos["year_begin"] = child.text
                elif child.tag == "ended":
                    # This hack is necessary to retain compatibility with
                    # previous versions' config. files
                    if child.text == "0":
                        showInfos["year_end"] = "????"
                    else:
                        showInfos["year_end"] = child.text
                elif child.tag == "country":
                    showInfos["flag"] = child.text.lower()

            tools.msgDebug("ShowName: %s, Flag: %s, Years: %s-%s, id: %d, url: %s" % ( showInfos["name"], showInfos["flag"], showInfos["year_begin"], showInfos["year_end"], showInfos["id"], showInfos["url"] ), __name__ )

            self.searchResults.append(showInfos)

        return self.searchResults
Пример #15
0
    def addToMyShows(self, index):
        # Restore the cursor in case we're dropping an item and a messagebox appears
        QApplication.changeOverrideCursor(Qt.ArrowCursor)

        selectedShow = self.dispSearchResults[index]

        # Make sure the requested show isn't already tracked
        # For that, check the id (which is unique)
        checkShow = [
            item['id'] for item in self.myShows
            if item['id'] == selectedShow['id']
        ]
        if selectedShow['id'] in checkShow:
            tools.msgDebug(u"""Show already in "My Shows". Can't add!""",
                           __name__)
            QMessageBox().information(
                self, "Information",
                'Cannot add "%s".\n' % selectedShow['name'] +
                'This show is already tracked.', QMessageBox.Ok)
            return

        # Tell the user if the show is terminated
        if selectedShow['year_end'] != "????":
            yesno = QMessageBox().question(
                self, "Attention",
                '"%s" seem to be terminated.\n' % selectedShow['name'] +
                "Adding it to your list would be pointless.\n\n" +
                "Are you sure you still want to continue?", QMessageBox.Yes,
                QMessageBox.No)
            if yesno == QMessageBox().No:
                return

        # Add the show to our list
        self.myShows.append(selectedShow)

        # Sort the shows by names
        self.myShows = tools.sortShowsByName(self.myShows)

        # Need to save...
        self.saveRequired()

        #################################################
        ## REMOVEME
        #################################################
        #wct = TestConf( self.myShows )
        #wct.start()
        #################################################

        # Refresh list
        self.displayMyShows()
Пример #16
0
 def on_btnSetDefaultColor_clicked(self):
     selColor = QColorDialog.getColor(QColor(self.myColors['default']),
                                      self)
     if not selColor.isValid():
         tools.msgDebug(u"Canceled by user!", __name__)
         return
     tools.msgDebug(
         u"Selected color: #%02X%02X%02X" %
         (selColor.red(), selColor.green(), selColor.blue()), __name__)
     self.ui.lblDefaultColor.setPixmap(
         self.drawPreviewColor(selColor, 36, 36))
     self.myColors['default'] = str(selColor.name())
     # Need to save
     self.saveRequired()
Пример #17
0
def createConfigDirs():
    # Create dirs
    mode = Globals().nsDirMode
    dirs = [ Globals().superKarambaDir,
             Globals().nsConfDir,
             Globals().nsCacheDir,
             Globals().nsCGuiBaseDir ]
    for dir in Globals().nsCGuiDirs:
        dirs.append( os.path.join( Globals().nsCGuiBaseDir, dir ) )
    for dir in dirs:
        try:
            os.mkdir( dir, mode )
            tools.msgDebug("Created dir: %s" % dir, __name__)
        except OSError:
            pass
Пример #18
0
    def addToMyShows(self, index):
        # Restore the cursor in case we're dropping an item and a messagebox appears
        QApplication.changeOverrideCursor( Qt.ArrowCursor )

        selectedShow = self.dispSearchResults[index]

        # Make sure the requested show isn't already tracked
        # For that, check the id (which is unique)
        checkShow = [ item['id'] for item in self.myShows if item['id'] == selectedShow['id']]
        if selectedShow['id'] in checkShow:
            tools.msgDebug(u"""Show already in "My Shows". Can't add!""", __name__)
            QMessageBox().information(self,
                                      "Information",
                                      'Cannot add "%s".\n' % selectedShow['name'] +
                                      'This show is already tracked.',
                                      QMessageBox.Ok)
            return

        # Tell the user if the show is terminated
        if selectedShow['year_end'] != "????":
            yesno = QMessageBox().question(self,
                                           "Attention",
                                           '"%s" seem to be terminated.\n' % selectedShow['name'] +
                                           "Adding it to your list would be pointless.\n\n" +
                                           "Are you sure you still want to continue?",
                                           QMessageBox.Yes, QMessageBox.No)
            if yesno == QMessageBox().No:
                return

        # Add the show to our list
        self.myShows.append( selectedShow )

        # Sort the shows by names
        self.myShows = tools.sortShowsByName( self.myShows )

        # Need to save...
        self.saveRequired()


        #################################################
        ## REMOVEME
        #################################################
        #wct = TestConf( self.myShows )
        #wct.start()
        #################################################

        # Refresh list
        self.displayMyShows()
Пример #19
0
def createConfigDirs():
    # Create dirs
    mode = Globals().nsDirMode
    dirs = [
        Globals().superKarambaDir,
        Globals().nsConfDir,
        Globals().nsCacheDir,
        Globals().nsCGuiBaseDir
    ]
    for dir in Globals().nsCGuiDirs:
        dirs.append(os.path.join(Globals().nsCGuiBaseDir, dir))
    for dir in dirs:
        try:
            os.mkdir(dir, mode)
            tools.msgDebug("Created dir: %s" % dir, __name__)
        except OSError:
            pass
Пример #20
0
    def closeEvent(self, event):
        if self.modifFlag:
            yesno = QMessageBox().question(self,
                                           "Attention",
                                           "Changes were made!\n" +
                                           "Are you sure you want to quit without saving?",
                                           QMessageBox.Yes, QMessageBox.No)
            if yesno == QMessageBox().No:
                event.ignore()
                return

        # User wants to quit
        # Make sure Config() isn't opened
        self.hide()
        self.uiHelpDialog.hide()
        while Config.LOCK:
            tools.msgDebug(u"Waiting for config to be written before exiting...", __name__)
            time.sleep(0.2)

        tools.msgDebug(u"Exiting...", __name__)
Пример #21
0
    def closeEvent(self, event):
        if self.modifFlag:
            yesno = QMessageBox().question(
                self, "Attention", "Changes were made!\n" +
                "Are you sure you want to quit without saving?",
                QMessageBox.Yes, QMessageBox.No)
            if yesno == QMessageBox().No:
                event.ignore()
                return

        # User wants to quit
        # Make sure Config() isn't opened
        self.hide()
        self.uiHelpDialog.hide()
        while Config.LOCK:
            tools.msgDebug(
                u"Waiting for config to be written before exiting...",
                __name__)
            time.sleep(0.2)

        tools.msgDebug(u"Exiting...", __name__)
Пример #22
0
    def cacheEpisodeList(self, id):
        # Cache filename
        cacheFileName = Globals().nsCacheFilePrefix + str( id )

        # Get the data
        parser = TvRage()
        epList = parser.getEpisodeList( id )

        if not epList:
            return False    # In case something went wrong during parsing...

        showEpList = {}
        showEpList['fetch_time']   = int( datetime.utcnow().strftime("%s") ) # Timestamp (UTC)
        showEpList['episode_list'] = epList

        # Open the file for writing
        tools.msgDebug("Writing cache file %s..." % cacheFileName, __name__)
        fp = open( cacheFileName, "wb" )
        cPickle.dump( showEpList, fp, cPickle.HIGHEST_PROTOCOL )
        fp.close()

        # At this point we suppose everything hopefully went well
        return True
Пример #23
0
    def _createDefaultConfFile(self):
        self.writeFlag = True  # Must save the config

        tools.msgDebug(
            "Creating default config file %s" % Globals().nsConfFile, __name__)

        #----------------------------------------------------------------------
        # Create necessary sections
        #sections = ( 'main', 'gui', 'display', 'colors', 'shows', 'misc' )
        sections = ('main', 'display', 'colors', 'shows', 'misc')
        for section in sections:
            self.add_section(section)
        # Main
        self.set("main", "version", "0")
        self.set("main", "debug", str(self.debug))
        # Gui
        #self.set( "gui",     "filter",      str(self.filter)      )
        # Display
        self.set("display", "past_days", str(self.numPastDays))
        self.set("display", "lines_fixed", str(self.linesFixed))
        self.set("display", "lines_min", str(self.linesMin))
        self.set("display", "lines_max", str(self.linesMax))
        self.set("display", "type", str(self.linesType))
        self.set("display", "format", str(self.format))
        self.set("display", "date_format", str(self.dateFormat))
        self.set("display", "date_separator", str(self.dateSeparator))
        # Misc
        self.set("misc", "cache_expiration", str(self.cacheExpiration))
        self.set("misc", "browser", str(self.browser))
        self.set("misc", "when_format", str(self.whenFormat))
        self.set("misc", "theme", str(self.theme))
        #----------------------------------------------------------------------

        # Set shows
        self.setShows(self.myShows)
        # Set color
        self.setColors(self.myColors)
Пример #24
0
    def _createDefaultConfFile(self):
        self.writeFlag = True   # Must save the config

        tools.msgDebug("Creating default config file %s" % Globals().nsConfFile, __name__)

        #----------------------------------------------------------------------
        # Create necessary sections
        #sections = ( 'main', 'gui', 'display', 'colors', 'shows', 'misc' )
        sections = ( 'main', 'display', 'colors', 'shows', 'misc' )
        for section in sections:
            self.add_section( section )
        # Main
        self.set( "main",    "version",     "0"                   )
        self.set( "main",    "debug",       str(self.debug)       )
        # Gui
        #self.set( "gui",     "filter",      str(self.filter)      )
        # Display
        self.set( "display", "past_days",   str(self.numPastDays) )
        self.set( "display", "lines_fixed", str(self.linesFixed)  )
        self.set( "display", "lines_min",   str(self.linesMin)    )
        self.set( "display", "lines_max",   str(self.linesMax)    )
        self.set( "display", "type",        str(self.linesType)   )
        self.set( "display", "format",      str(self.format)      )
        self.set( "display", "date_format", str(self.dateFormat)  )
        self.set( "display", "date_separator", str(self.dateSeparator)  )
        # Misc
        self.set( "misc",    "cache_expiration", str(self.cacheExpiration ) )
        self.set( "misc",    "browser",     str(self.browser)     )
        self.set( "misc",    "when_format", str(self.whenFormat)  )
        self.set( "misc",    "theme",       str(self.theme)       )
        #----------------------------------------------------------------------

        # Set shows
        self.setShows ( self.myShows )
        # Set color
        self.setColors ( self.myColors )
Пример #25
0
 def _releaseLock(self):
     if self.writeFlag:
         tools.msgDebug( "Saving config...", __name__ )
         # Write back to config file
         fp = open( Globals().nsConfFile, "w" )
         self.write( fp )
         fp.close()
         tools.msgDebug( "Config saved to %s" % Globals().nsConfFile, __name__ )
     # Release LOCK
     Config.LOCK = False
     tools.msgDebug( "Config LOCK released", __name__ )
Пример #26
0
 def _acquireLock(self):
     # If a LOCK already exist, wait until it is released
     while Config.LOCK:
         tools.msgDebug("Config file LOCKed! Waiting for lock to be released...", __name__)
         randomize = float( random.randint( 0, 1000) ) / 1000
         time.sleep( randomize )
     # Acquire LOCK
     Config.LOCK = True
     tools.msgDebug("Config LOCK acquired", __name__)
     # Read config
     self.read( Globals().nsConfFile )
     tools.msgDebug("Config read", __name__)
Пример #27
0
 def _releaseLock(self):
     if self.writeFlag:
         tools.msgDebug("Saving config...", __name__)
         # Write back to config file
         fp = open(Globals().nsConfFile, "w")
         self.write(fp)
         fp.close()
         tools.msgDebug("Config saved to %s" % Globals().nsConfFile,
                        __name__)
     # Release LOCK
     Config.LOCK = False
     tools.msgDebug("Config LOCK released", __name__)
Пример #28
0
 def _acquireLock(self):
     # If a LOCK already exist, wait until it is released
     while Config.LOCK:
         tools.msgDebug(
             "Config file LOCKed! Waiting for lock to be released...",
             __name__)
         randomize = float(random.randint(0, 1000)) / 1000
         time.sleep(randomize)
     # Acquire LOCK
     Config.LOCK = True
     tools.msgDebug("Config LOCK acquired", __name__)
     # Read config
     self.read(Globals().nsConfFile)
     tools.msgDebug("Config read", __name__)
Пример #29
0
    def deleteOldCacheFiles(self):
        tools.msgDebug("Purging cache dir...", __name__)
        cacheDirContents = os.listdir( Globals().nsCacheDir )
        cacheFilePrefix = os.path.basename( Globals().nsCacheFilePrefix )

        for id in self.showIds:
            fileName = cacheFilePrefix + str( id )
            if fileName in cacheDirContents:
                index = cacheDirContents.index( fileName )
                cacheDirContents.pop( index )

        # Remove unwanted files
        exitFlag = True
        for file in cacheDirContents:
            fileName = os.path.join( Globals().nsCacheDir, file )
            try:
                os.remove( fileName )
                tools.msgDebug("Deleted %s..." % fileName, __name__)
            except:
                exitFlag = False
                tools.msgDebug("Error raised while trying to delete %s..." % fileName, __name__)

        return exitFlag
Пример #30
0
    def _readThemeInfos(self, theme):
        self.themeName = theme
        self.themePath = os.path.join("themes", self.themeName)
        themeInfo = os.path.join( self.themePath, "theme.info" )
        themeInfoContent = karamba.readThemeFile( Applet.widget, themeInfo )

        if themeInfoContent == "":
            tools.msgDebug("Error finding/reading %s..." % themeInfo, __name__)
            # Try to fallback to the default theme
            self.themeName = Globals().defaultThemeName
            self.themePath = os.path.join("themes", self.themeName)
            themeInfo = os.path.join( self.themePath, "theme.info" )
            themeInfoContent = karamba.readThemeFile( Applet.widget, themeInfo )
            if themeInfoContent == "":
                tools.msgDebug("Error finding/reading %s..." % themeInfo, __name__)
                return False

        #######################################################################
        # FIXME: Unfortunately, it is not possible to directly feed ConfigParser
        # with a str()....
        # Yep! That's another ugly hack!
        #######################################################################
        tempName = os.tempnam()
        fp = open( tempName, "w" )
        fp.write( themeInfoContent )
        fp.close()
        fp = open( tempName, "r" )
        scp = SafeConfigParser()
        scp.readfp( fp )
        fp.close()
        os.unlink( tempName )
        #######################################################################

        self.themeHeaderImg = os.path.join( self.themePath, scp.get( "images", "header" ) )
        self.themeHeaderTxtTitle = scp.get( "header", "title_text" )
        X = scp.getint( "header", "title_pos_x" )
        Y = scp.getint( "header", "title_pos_y" )
        self.themeHeaderTxtTitleXY = ( X, Y )
        W = scp.getint( "header", "title_width" )
        H = 0
        self.themeHeaderTxtTitleWH = ( W, H )
        self.themeHeaderTxtWhen = scp.get( "header", "when_text" )
        X = scp.getint( "header", "when_pos_x" )
        Y = scp.getint( "header", "when_pos_y" )
        self.themeHeaderTxtWhenXY = ( X, Y )
        W = scp.getint( "header", "when_width" )
        H = 0
        self.themeHeaderTxtWhenWH = ( W, H )
        self.themeBodyImg   = os.path.join( self.themePath, scp.get( "images", "body"   ) )
        X = scp.getint( "body", "title_pos_x" )
        Y = scp.getint( "body", "title_pos_y" )
        self.themeBodyTitleXY = ( X, Y )
        W = scp.getint( "body", "title_width" )
        H = scp.getint( "body", "title_height" )
        self.themeBodyTitleWH = ( W, H )
        X = scp.getint( "body", "when_pos_x" )
        Y = scp.getint( "body", "when_pos_y" )
        self.themeBodyWhenXY = ( X, Y )
        W = scp.getint( "body", "when_width" )
        H = scp.getint( "body", "when_height" )
        self.themeBodyWhenWH = ( W, H )
        self.themeFooterImg = os.path.join( self.themePath, scp.get( "images", "footer" ) )
Пример #31
0
    def _readThemeInfos(self, theme):
        self.themeName = theme
        self.themePath = os.path.join("themes", self.themeName)
        themeInfo = os.path.join(self.themePath, "theme.info")
        themeInfoContent = karamba.readThemeFile(Applet.widget, themeInfo)

        if themeInfoContent == "":
            tools.msgDebug("Error finding/reading %s..." % themeInfo, __name__)
            # Try to fallback to the default theme
            self.themeName = Globals().defaultThemeName
            self.themePath = os.path.join("themes", self.themeName)
            themeInfo = os.path.join(self.themePath, "theme.info")
            themeInfoContent = karamba.readThemeFile(Applet.widget, themeInfo)
            if themeInfoContent == "":
                tools.msgDebug("Error finding/reading %s..." % themeInfo,
                               __name__)
                return False

        #######################################################################
        # FIXME: Unfortunately, it is not possible to directly feed ConfigParser
        # with a str()....
        # Yep! That's another ugly hack!
        #######################################################################
        tempName = os.tempnam()
        fp = open(tempName, "w")
        fp.write(themeInfoContent)
        fp.close()
        fp = open(tempName, "r")
        scp = SafeConfigParser()
        scp.readfp(fp)
        fp.close()
        os.unlink(tempName)
        #######################################################################

        self.themeHeaderImg = os.path.join(self.themePath,
                                           scp.get("images", "header"))
        self.themeHeaderTxtTitle = scp.get("header", "title_text")
        X = scp.getint("header", "title_pos_x")
        Y = scp.getint("header", "title_pos_y")
        self.themeHeaderTxtTitleXY = (X, Y)
        W = scp.getint("header", "title_width")
        H = 0
        self.themeHeaderTxtTitleWH = (W, H)
        self.themeHeaderTxtWhen = scp.get("header", "when_text")
        X = scp.getint("header", "when_pos_x")
        Y = scp.getint("header", "when_pos_y")
        self.themeHeaderTxtWhenXY = (X, Y)
        W = scp.getint("header", "when_width")
        H = 0
        self.themeHeaderTxtWhenWH = (W, H)
        self.themeBodyImg = os.path.join(self.themePath,
                                         scp.get("images", "body"))
        X = scp.getint("body", "title_pos_x")
        Y = scp.getint("body", "title_pos_y")
        self.themeBodyTitleXY = (X, Y)
        W = scp.getint("body", "title_width")
        H = scp.getint("body", "title_height")
        self.themeBodyTitleWH = (W, H)
        X = scp.getint("body", "when_pos_x")
        Y = scp.getint("body", "when_pos_y")
        self.themeBodyWhenXY = (X, Y)
        W = scp.getint("body", "when_width")
        H = scp.getint("body", "when_height")
        self.themeBodyWhenWH = (W, H)
        self.themeFooterImg = os.path.join(self.themePath,
                                           scp.get("images", "footer"))
Пример #32
0
def initWidget(widget):
    global g_nextCacheRefresh, g_showList, g_showIds, g_cacheExpiration, g_pastDays, g_linesMin, g_linesMax

    # Pass the widget reference
    Applet.widget = widget

    # Init splash
    splash = Applet().Splash()
    splash.show()

    # Create dir structure
    splash.setText("Checking config dirs...")
    createConfigDirs()

    # Read config
    splash.setText("Reading config...")
    config = Config()

    # Check whether we want DEBUG messages enabled or not
    if config.getboolean("main", "debug") == False:
        tools.msgDebug("Disabling debug messages !", __name__)
        Globals.DEBUG = False

    # Copy GUI files (if necessary)
    if Globals().versions['nextShows'] != config.get("main", "version") \
    or not "launchGUI" in os.listdir( Globals().nsCGuiBaseDir ):
        # Init dir structures and copy files
        splash.setText("Setup GUI...")
        copyThemeFilesToConfigDir(widget)
        config.set("main", "version", Globals().versions['nextShows'])

    # Get other useful infos from config
    splash.setText("Reading config...")
    displayType = config.get("display", "type")
    if displayType == "Fixed":
        g_linesMax = config.getint("display", "lines_fixed")
        g_linesMin = g_linesMax
    else:
        g_linesMin = config.getint("display", "lines_min")
        g_linesMax = config.getint("display", "lines_max")
    g_cacheExpiration          = config.getint("misc",    "cache_expiration")
    g_pastDays                 = config.getint("display", "past_days")
    applet.colorList           = config.getColors()
    applet.episodeFormatString = config.get(   "display", "format")
    applet.browser             = config.get(   "misc",    "browser")
    applet.dateFormat          = config.get(   "display", "date_format")
    applet.whenFormat          = config.getint("misc",    "when_format")

    # Getting the show list
    splash.setText("Getting show list....")
    g_showList = config.getShows()

    # Extract IDs
    g_showIds = [ show['id'] for show in g_showList ]

    # Init cache
    cache.setExpiration( g_cacheExpiration )
    cache.showIds = g_showIds

    # Refresh cache if necessary
    staledList = cache.getStaledCacheFiles()
    for id in staledList:
        for show in g_showList:
            if show['id'] == id:
                showName = show['name']
        splash.setText("Updating cache: '%s'..." % showName)
        cache.cacheEpisodeList( id )

    # Fetch data to display
    splash.setText("Filtering episodes...")
    data = Data()
    episodeList  = data.getEpisodeList( g_showIds, g_pastDays, g_linesMax )
    applet.episodeList = episodeList

    # Close the splash
    splash.setText("Done!")
    splash.hide()

    # Init widget
    # Fallback (for compatibility reasons)
    # "[display] theme=" was moved to "[misc] theme="
    try:
        applet.themeName = config.get("misc", "theme")
    except:
        applet.themeName = Globals().defaultThemeName
    numReturnedEpisode = len( episodeList )
    if numReturnedEpisode < g_linesMin:
        themeLines = g_linesMin
    elif numReturnedEpisode > g_linesMax:
        themeLines = g_linesMax
    else:
        themeLines = numReturnedEpisode
    applet.themeLines = themeLines
    applet.drawBackground()
    applet.printEpisodeList()

    # Store next cache refresh
    g_nextCacheRefresh = cache.getNextRefreshTS()

    # Setup menu entry for config GUI
    karamba.addMenuConfigOption(widget, "config_gui", "Configure...")
    karamba.setMenuConfigOption(widget, "config_gui", 0)
Пример #33
0
    def initForm(self):
        # 1st tab labels
        self.ui.lblResultsDisplayed.setText( u"Displayed results: 0/0" )
        self.ui.lblTrackedShows.setText( u"Tracked shows: 0" )

        # Format Sample
        fmtSample = u"<u><b>Sample:</b></u> <b>show:</b> %s, <b>title:</b> %s, <b>season</b>: %d, <b>episode</b>: %d" % (
                      Globals().sampleEpisode['show'],
                      Globals().sampleEpisode['title'],
                      Globals().sampleEpisode['season'],
                      Globals().sampleEpisode['episode'] )
        self.ui.lblFormatSample.setText( fmtSample )

        #### Versions
        version = Globals().versions
        # nextShows Footer Release
        labelContent=str(self.ui.lblFooterRelease.text())
        self.ui.lblFooterRelease.setText(labelContent % version['nextShows'])
        # nextShows Release (About tab)
        labelContent=str(self.ui.lblNextShowsVersion.text())
        self.ui.lblNextShowsVersion.setText(labelContent % version['nextShows'])
        # Libs releases (About tab)
        # Python version
        a,b,c,d,e = sys.version_info
        pythonVersion = "%d.%d.%d" % (a, b, c)
        #
        labelContent=str(self.ui.lblLibsVersion.text())
        self.ui.lblLibsVersion.setText(labelContent % (
            pythonVersion,
            QT_VERSION_STR,
            PYQT_VERSION_STR,
            version["KDE"]) )


        #### Default values
        self.ui.spinNumPastDays.setMinimum(0)
        self.ui.spinNumPastDays.setMaximum(99)
        #self.ui.spinNumPastDays.setValue(1)
        self.ui.spinFixedDispLines.setMinimum(1)
        self.ui.spinFixedDispLines.setMaximum(50)
        #self.ui.spinFixedDispLines.setValue(10)
        self.ui.spinMinDispLines.setMinimum(1)
        self.ui.spinMinDispLines.setMaximum(49)
        #self.ui.spinMinDispLines.setValue(1)
        self.ui.spinMaxDispLines.setMinimum(2)
        self.ui.spinMaxDispLines.setMaximum(50)
        #self.ui.spinMaxDispLines.setValue(10)
        #
        self.ui.spinColorsSingleDay.setMinimum(-99)
        self.ui.spinColorsSingleDay.setMaximum(99)
        self.ui.spinColorsSingleDay.setValue(0)
        self.ui.spinColorsFrom.setMinimum(-99)
        self.ui.spinColorsFrom.setMaximum(98)
        self.ui.spinColorsFrom.setValue(0)
        self.ui.spinColorsTo.setMinimum(-98)
        self.ui.spinColorsTo.setMaximum(99)
        self.ui.spinColorsTo.setValue(10)

        # default color for "Select color"
        self.ui.lblSelectColor.setPixmap( self.drawPreviewColor( self.lastColorUsed, 36, 36 ) )

        # Theme combo
        self.ui.comboTheme.addItems( Globals().availableThemes )


        ####
        #### Read config
        ####
        tools.msgDebug(u"Reading config...", __name__)
        config = Config()

        # Enable/Disable DEBUG
        if config.getboolean("main", "debug") == False:
            tools.msgDebug("Disabling debug messages !", __name__)
            Globals.DEBUG = False

        # Get Data
        self.myShows  = config.getShows()
        self.displayMyShows()
        self.myColors = config.getColors()
        self.ui.lblDefaultColor.setPixmap( self.drawPreviewColor( self.myColors['default'], 36, 36 ) )
        self.displayMyColors()

        if config.get("display", "type") == "Fixed":
            self.ui.radioDispFixedLines.setChecked( True )
        else:
            self.ui.radioDispAutoResize.setChecked( True )

        self.ui.spinNumPastDays.setValue(    int( config.get( "display", "past_days"   ) ) )
        self.ui.spinFixedDispLines.setValue( int( config.get( "display", "lines_fixed" ) ) )
        self.ui.spinMinDispLines.setValue(   int( config.get( "display", "lines_min"   ) ) )
        self.ui.spinMaxDispLines.setValue(   int( config.get( "display", "lines_max"   ) ) )
        self.ui.leditFormat.setText( config.get( "display", "format" ) )
        self.refreshFormatPreview( str(self.ui.leditFormat.text()) )

        self.ui.spinCacheExpiration.setValue( int( config.get( "misc", "cache_expiration" ) ) )
        self.ui.leditBrowser.setText( config.get( "misc", "browser" ) )

        # Fallback code since the "theme" key was located in the [display] section
        # in versions < 2.1.0
        try:
            idx = int( Globals().availableThemes.index( config.get( "misc", "theme" ) ) )
        except:
            idx = 0
        self.ui.comboTheme.setCurrentIndex( idx )

        # Date Separator
        # Fallback code since the "date_separator" key doesn't exist in version < 2.1.0
        try:
            sep = config.get( "display", "date_separator" )
        except:
            sep = "/"
        self.ui.leditDateSeparator.setText( sep )

        # Date Format
        dateFormat = config.get( "display", "date_format" )
        data       = [ "%"+a for a in dateFormat.split( sep ) ]
        idx        = self.ui.comboDateFormat.findData( QVariant( data ) )
        if idx==-1: idx = 0
        self.ui.comboDateFormat.setCurrentIndex( idx )

        config.close()

        # Reset "Save" button state
        self.saveRequired(False)

        tools.msgDebug(u"Done!", __name__)
Пример #34
0
    def initForm(self):
        # 1st tab labels
        self.ui.lblResultsDisplayed.setText(u"Displayed results: 0/0")
        self.ui.lblTrackedShows.setText(u"Tracked shows: 0")

        # Format Sample
        fmtSample = u"<u><b>Sample:</b></u> <b>show:</b> %s, <b>title:</b> %s, <b>season</b>: %d, <b>episode</b>: %d" % (
            Globals().sampleEpisode['show'], Globals().sampleEpisode['title'],
            Globals().sampleEpisode['season'],
            Globals().sampleEpisode['episode'])
        self.ui.lblFormatSample.setText(fmtSample)

        #### Versions
        version = Globals().versions
        # nextShows Footer Release
        labelContent = str(self.ui.lblFooterRelease.text())
        self.ui.lblFooterRelease.setText(labelContent % version['nextShows'])
        # nextShows Release (About tab)
        labelContent = str(self.ui.lblNextShowsVersion.text())
        self.ui.lblNextShowsVersion.setText(labelContent %
                                            version['nextShows'])
        # Libs releases (About tab)
        # Python version
        a, b, c, d, e = sys.version_info
        pythonVersion = "%d.%d.%d" % (a, b, c)
        #
        labelContent = str(self.ui.lblLibsVersion.text())
        self.ui.lblLibsVersion.setText(
            labelContent %
            (pythonVersion, QT_VERSION_STR, PYQT_VERSION_STR, version["KDE"]))

        #### Default values
        self.ui.spinNumPastDays.setMinimum(0)
        self.ui.spinNumPastDays.setMaximum(99)
        #self.ui.spinNumPastDays.setValue(1)
        self.ui.spinFixedDispLines.setMinimum(1)
        self.ui.spinFixedDispLines.setMaximum(50)
        #self.ui.spinFixedDispLines.setValue(10)
        self.ui.spinMinDispLines.setMinimum(1)
        self.ui.spinMinDispLines.setMaximum(49)
        #self.ui.spinMinDispLines.setValue(1)
        self.ui.spinMaxDispLines.setMinimum(2)
        self.ui.spinMaxDispLines.setMaximum(50)
        #self.ui.spinMaxDispLines.setValue(10)
        #
        self.ui.spinColorsSingleDay.setMinimum(-99)
        self.ui.spinColorsSingleDay.setMaximum(99)
        self.ui.spinColorsSingleDay.setValue(0)
        self.ui.spinColorsFrom.setMinimum(-99)
        self.ui.spinColorsFrom.setMaximum(98)
        self.ui.spinColorsFrom.setValue(0)
        self.ui.spinColorsTo.setMinimum(-98)
        self.ui.spinColorsTo.setMaximum(99)
        self.ui.spinColorsTo.setValue(10)

        # default color for "Select color"
        self.ui.lblSelectColor.setPixmap(
            self.drawPreviewColor(self.lastColorUsed, 36, 36))

        # Theme combo
        self.ui.comboTheme.addItems(Globals().availableThemes)

        ####
        #### Read config
        ####
        tools.msgDebug(u"Reading config...", __name__)
        config = Config()

        # Enable/Disable DEBUG
        if config.getboolean("main", "debug") == False:
            tools.msgDebug("Disabling debug messages !", __name__)
            Globals.DEBUG = False

        # Get Data
        self.myShows = config.getShows()
        self.displayMyShows()
        self.myColors = config.getColors()
        self.ui.lblDefaultColor.setPixmap(
            self.drawPreviewColor(self.myColors['default'], 36, 36))
        self.displayMyColors()

        if config.get("display", "type") == "Fixed":
            self.ui.radioDispFixedLines.setChecked(True)
        else:
            self.ui.radioDispAutoResize.setChecked(True)

        self.ui.spinNumPastDays.setValue(
            int(config.get("display", "past_days")))
        self.ui.spinFixedDispLines.setValue(
            int(config.get("display", "lines_fixed")))
        self.ui.spinMinDispLines.setValue(
            int(config.get("display", "lines_min")))
        self.ui.spinMaxDispLines.setValue(
            int(config.get("display", "lines_max")))
        self.ui.leditFormat.setText(config.get("display", "format"))
        self.refreshFormatPreview(str(self.ui.leditFormat.text()))

        self.ui.spinCacheExpiration.setValue(
            int(config.get("misc", "cache_expiration")))
        self.ui.leditBrowser.setText(config.get("misc", "browser"))

        # Fallback code since the "theme" key was located in the [display] section
        # in versions < 2.1.0
        try:
            idx = int(Globals().availableThemes.index(
                config.get("misc", "theme")))
        except:
            idx = 0
        self.ui.comboTheme.setCurrentIndex(idx)

        # Date Separator
        # Fallback code since the "date_separator" key doesn't exist in version < 2.1.0
        try:
            sep = config.get("display", "date_separator")
        except:
            sep = "/"
        self.ui.leditDateSeparator.setText(sep)

        # Date Format
        dateFormat = config.get("display", "date_format")
        data = ["%" + a for a in dateFormat.split(sep)]
        idx = self.ui.comboDateFormat.findData(QVariant(data))
        if idx == -1: idx = 0
        self.ui.comboDateFormat.setCurrentIndex(idx)

        config.close()

        # Reset "Save" button state
        self.saveRequired(False)

        tools.msgDebug(u"Done!", __name__)
Пример #35
0
    def getEpisodeList(self, id):
        # Clear episodeList
        self.episodeList = []

        # Sanitize keywords and build the URL
        url = self.urlEpisodeList % id
        tools.msgDebug("Requesting %s" % url, __name__)
        # do the request...
        content = self.request(url)  # request() from Http()
        if not content:
            return False  # In case something went wrong during fetching
        # ...and parse the results
        try:
            tools.msgDebug("Parsing feed content...", __name__)
            doc = ETree.fromstring(content)
        except:
            tools.msgDebug("Unexpected error while parsing the XML feed...",
                           __name__)
            return False

        showName = u'' + doc.find('name').text

        # No Episode List ?
        if not doc.find('Episodelist'):
            return self.episodeList

        # Get Episode list...
        for season in doc.find('Episodelist').getchildren():
            if season.tag == "Season":
                for ep in season.findall('episode'):
                    episode = {}
                    episode['show'] = showName
                    episode['season'] = int(season.attrib["no"])
                    episode['episode'] = 0
                    episode['title'] = ""
                    episode['url'] = ""
                    episode['airdate'] = (0, 0, 0)
                    for child in ep.getchildren():
                        if child.tag == "seasonnum":
                            episode['episode'] = int(child.text)
                        elif child.tag == "title":
                            episode['title'] = u'' + child.text
                        elif child.tag == "link":
                            episode['url'] = u'' + child.text
                        elif child.tag == "airdate":
                            matchEAD = self.reEpisodeAirDate.match(child.text)
                            if matchEAD:
                                year, month, day = matchEAD.group(
                                    1), matchEAD.group(2), matchEAD.group(3)
                                episode['airdate'] = (int(year), int(month),
                                                      int(day))

                    # Only append episode if we got all the data we need
                    if not episode['show']:
                        continue
                    elif episode['season'] <= 0:
                        continue
                    elif episode['episode'] <= 0:
                        continue
                    elif not episode['title']:
                        continue
                    elif not episode['url']:
                        continue
                    #elif episode['airdate'][0] <= 0:
                    #    continue
                    #elif episode['airdate'][1] < 1 or episode['airdate'][1] > 12:
                    #    continue
                    #elif episode['airdate'][2] < 1 or episode['airdate'][2] > 31:
                    #    continue

                    tools.msgDebug(
                        "Found: %s-S%02dE%02d-%s (%04d-%02d-%02d)" %
                        (episode['show'], episode['season'],
                         episode['episode'], episode['title'],
                         episode['airdate'][0], episode['airdate'][1],
                         episode['airdate'][2]), __name__)
                    self.episodeList.append(episode)

        return self.episodeList
Пример #36
0
    def getEpisodeList(self, id):
        # Clear episodeList
        self.episodeList = []

        # Sanitize keywords and build the URL
        url = self.urlEpisodeList % id
        tools.msgDebug("Requesting %s" % url, __name__)
        # do the request...
        content = self.request(url)     # request() from Http()
        if not content:
            return False    # In case something went wrong during fetching
        # ...and parse the results
        try:
            tools.msgDebug("Parsing feed content...", __name__)
            doc = ETree.fromstring(content)
        except:
            tools.msgDebug("Unexpected error while parsing the XML feed...", __name__)
            return False

        showName = u''+doc.find('name').text

        # No Episode List ?
        if not doc.find('Episodelist'):
            return self.episodeList

        # Get Episode list...
        for season in doc.find('Episodelist').getchildren():
            if season.tag == "Season":
                for ep in season.findall('episode'):
                    episode = {}
                    episode['show']    = showName
                    episode['season']  = int( season.attrib["no"] )
                    episode['episode'] = 0
                    episode['title']   = ""
                    episode['url']     = ""
                    episode['airdate'] = ( 0, 0, 0 )
                    for child in ep.getchildren():
                        if   child.tag == "seasonnum":
                            episode['episode'] = int( child.text )
                        elif child.tag == "title":
                            episode['title'] = u''+child.text
                        elif child.tag == "link":
                            episode['url'] = u''+child.text
                        elif child.tag == "airdate":
                            matchEAD = self.reEpisodeAirDate.match( child.text )
                            if matchEAD:
                                year, month, day = matchEAD.group(1), matchEAD.group(2), matchEAD.group(3)
                                episode['airdate'] = ( int(year), int(month), int(day) )

                    # Only append episode if we got all the data we need
                    if   not episode['show']:
                        continue
                    elif episode['season'] <= 0:
                        continue
                    elif episode['episode'] <= 0:
                        continue
                    elif not episode['title']:
                        continue
                    elif not episode['url']:
                        continue
                    #elif episode['airdate'][0] <= 0:
                    #    continue
                    #elif episode['airdate'][1] < 1 or episode['airdate'][1] > 12:
                    #    continue
                    #elif episode['airdate'][2] < 1 or episode['airdate'][2] > 31:
                    #    continue

                    tools.msgDebug( "Found: %s-S%02dE%02d-%s (%04d-%02d-%02d)" %
                        ( episode['show'], episode['season'], episode['episode'], episode['title'],
                        episode['airdate'][0], episode['airdate'][1], episode['airdate'][2] ),
                        __name__ )
                    self.episodeList.append( episode )

        return self.episodeList
Пример #37
0
def initWidget(widget):
    global g_nextCacheRefresh, g_showList, g_showIds, g_cacheExpiration, g_pastDays, g_linesMin, g_linesMax

    # Pass the widget reference
    Applet.widget = widget

    # Init splash
    splash = Applet().Splash()
    splash.show()

    # Create dir structure
    splash.setText("Checking config dirs...")
    createConfigDirs()

    # Read config
    splash.setText("Reading config...")
    config = Config()

    # Check whether we want DEBUG messages enabled or not
    if config.getboolean("main", "debug") == False:
        tools.msgDebug("Disabling debug messages !", __name__)
        Globals.DEBUG = False

    # Copy GUI files (if necessary)
    if Globals().versions['nextShows'] != config.get("main", "version") \
    or not "launchGUI" in os.listdir( Globals().nsCGuiBaseDir ):
        # Init dir structures and copy files
        splash.setText("Setup GUI...")
        copyThemeFilesToConfigDir(widget)
        config.set("main", "version", Globals().versions['nextShows'])

    # Get other useful infos from config
    splash.setText("Reading config...")
    displayType = config.get("display", "type")
    if displayType == "Fixed":
        g_linesMax = config.getint("display", "lines_fixed")
        g_linesMin = g_linesMax
    else:
        g_linesMin = config.getint("display", "lines_min")
        g_linesMax = config.getint("display", "lines_max")
    g_cacheExpiration = config.getint("misc", "cache_expiration")
    g_pastDays = config.getint("display", "past_days")
    applet.colorList = config.getColors()
    applet.episodeFormatString = config.get("display", "format")
    applet.browser = config.get("misc", "browser")
    applet.dateFormat = config.get("display", "date_format")
    applet.whenFormat = config.getint("misc", "when_format")

    # Getting the show list
    splash.setText("Getting show list....")
    g_showList = config.getShows()

    # Extract IDs
    g_showIds = [show['id'] for show in g_showList]

    # Init cache
    cache.setExpiration(g_cacheExpiration)
    cache.showIds = g_showIds

    # Refresh cache if necessary
    staledList = cache.getStaledCacheFiles()
    for id in staledList:
        for show in g_showList:
            if show['id'] == id:
                showName = show['name']
        splash.setText("Updating cache: '%s'..." % showName)
        cache.cacheEpisodeList(id)

    # Fetch data to display
    splash.setText("Filtering episodes...")
    data = Data()
    episodeList = data.getEpisodeList(g_showIds, g_pastDays, g_linesMax)
    applet.episodeList = episodeList

    # Close the splash
    splash.setText("Done!")
    splash.hide()

    # Init widget
    # Fallback (for compatibility reasons)
    # "[display] theme=" was moved to "[misc] theme="
    try:
        applet.themeName = config.get("misc", "theme")
    except:
        applet.themeName = Globals().defaultThemeName
    numReturnedEpisode = len(episodeList)
    if numReturnedEpisode < g_linesMin:
        themeLines = g_linesMin
    elif numReturnedEpisode > g_linesMax:
        themeLines = g_linesMax
    else:
        themeLines = numReturnedEpisode
    applet.themeLines = themeLines
    applet.drawBackground()
    applet.printEpisodeList()

    # Store next cache refresh
    g_nextCacheRefresh = cache.getNextRefreshTS()

    # Setup menu entry for config GUI
    karamba.addMenuConfigOption(widget, "config_gui", "Configure...")
    karamba.setMenuConfigOption(widget, "config_gui", 0)