always load the local configuration file
authorChristian Weiske <cweiske@cweiske.de>
Thu, 29 Aug 2013 19:38:59 +0000 (21:38 +0200)
committerChristian Weiske <cweiske@cweiske.de>
Thu, 29 Aug 2013 19:38:59 +0000 (21:38 +0200)
README.rst
src/AtomFeed.py
src/CurlyTx.py
src/CurlyTxSettings.py
src/config.py

index ee22bcd041637dc79947fc61ed31d7adad730c55..0726c32ff2196172dcfee29e605cb7a23c5c01a9 100644 (file)
@@ -56,6 +56,9 @@ up/down buttons and press "OK" - the page edit window will open.
 Press the green button and the settings will be saved.
 You're back on the main window now and the URL you just configured will be loaded.
 
 Press the green button and the settings will be saved.
 You're back on the main window now and the URL you just configured will be loaded.
 
+Note that with version 1.1, CurlyTx supports opening local files.
+Prepend them with ``file://``, e.g. ``file:///tmp/test.txt``.
+
 
 Adding many pages
 =================
 
 Adding many pages
 =================
@@ -92,6 +95,14 @@ Start CurlyTx, go to the settings and write the feed URL in the
 Then press "OK" and the feed's pages will be loaded into the settings window.
 
 
 Then press "OK" and the feed's pages will be loaded into the settings window.
 
 
+Local configuration file
+========================
+CurlyTx looks for a local page feed file on the harddisk on every run,
+at ``/etc/enigma2/curlytx-pagefeed.xml``.
+If this file exists, it gets loaded unconditionally and overwrites
+the current page configuration.
+
+
 =================
 Modifying CurlyTx
 =================
 =================
 Modifying CurlyTx
 =================
index 9e76e9ff4deedc50511fc812559a7b9e66829555..51da7f8249cd352fec76aba95b91b69e620c7758 100644 (file)
@@ -4,21 +4,39 @@
 # License: GPLv3 or later
 
 from twisted.web.client import getPage
 # License: GPLv3 or later
 
 from twisted.web.client import getPage
-from xml.etree.cElementTree import fromstring
+from xml.etree.cElementTree import fromstring, ParseError
+
+import os
 
 class AtomFeed:
     """ Simple XML parser that extracts pages from a atom feed """
     ns = "{http://www.w3.org/2005/Atom}"
 
 class AtomFeed:
     """ Simple XML parser that extracts pages from a atom feed """
     ns = "{http://www.w3.org/2005/Atom}"
+    errorCallback = None
+
     def __init__(self, url, callback, errorCallback):
         """ Fetches the URL
 
         Parsed pages are sent back to callback by parse()
         """
     def __init__(self, url, callback, errorCallback):
         """ Fetches the URL
 
         Parsed pages are sent back to callback by parse()
         """
-        getPage(url).addCallback(self.parse, callback).addErrback(errorCallback)
+        self.errorCallback = errorCallback
+        if (url.startswith('file://')):
+            file = url[7:]
+            if not os.path.exists(file):
+                errorCallback('Settings atom feed file does not exist: ' + file)
+                return
+
+            with open(file, 'r') as f:
+                self.parse(f.read(), callback)
+        else:
+            getPage(url).addCallback(self.parse, callback).addErrback(self.onError)
 
     def parse(self, data, callback):
         """ Parse atom feed data into pages list and run callback """
 
     def parse(self, data, callback):
         """ Parse atom feed data into pages list and run callback """
-        xml = fromstring(data)
+        try:
+            xml = fromstring(data)
+        except ParseError:
+            return self.errorCallback("Invalid XML")
+
         pages = []
         for entry in xml.findall("{0}entry".format(self.ns)):
             titleE = entry.find("{0}title".format(self.ns))
         pages = []
         for entry in xml.findall("{0}entry".format(self.ns)):
             titleE = entry.find("{0}title".format(self.ns))
@@ -54,3 +72,7 @@ class AtomFeed:
         elif type == "":
             return 2
         return 1
         elif type == "":
             return 2
         return 1
+
+    def onError(self, error):
+        """ Pass the error message only """
+        self.errorCallback(error.getErrorMessage())
index 8e18c0f6eb946092fe17cfa580e1fa71c78c55be..3572601ffdf9e546021224852f1ca8beee7a9c4d 100644 (file)
@@ -7,21 +7,22 @@ from . import _
 
 from Screens.Screen import Screen
 from Screens.HelpMenu import HelpableScreen
 
 from Screens.Screen import Screen
 from Screens.HelpMenu import HelpableScreen
-from Screens.MessageBox import MessageBox
 from Components.Label import Label
 from Components.ScrollLabel import ScrollLabel
 from Components.ActionMap import ActionMap
 from Components.Sources.StaticText import StaticText
 from Components.Label import Label
 from Components.ScrollLabel import ScrollLabel
 from Components.ActionMap import ActionMap
 from Components.Sources.StaticText import StaticText
+from Tools import Directories
 from twisted.web import client
 from twisted.web.client import _makeGetterFactory, HTTPClientFactory
 from enigma import gFont
 
 from . import config
 from twisted.web import client
 from twisted.web.client import _makeGetterFactory, HTTPClientFactory
 from enigma import gFont
 
 from . import config
+from config import createPage, loadDefaultPageOptions, feedPagesToConfig, savePageConfig
 from Components.config import config
 
 import os
 
 from Components.config import config
 
 import os
 
-class CurlyTx(Screen,HelpableScreen):
+class CurlyTx(Screen, HelpableScreen):
     skin = """
         <screen name="CurlyTx" position="center,center" size="560,430" title="CurlyTx" >
          <ePixmap position="0,0" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
     skin = """
         <screen name="CurlyTx" position="center,center" size="560,430" title="CurlyTx" >
          <ePixmap position="0,0" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
@@ -40,6 +41,7 @@ class CurlyTx(Screen,HelpableScreen):
     currentFontSize = 20
     httpGetterFactory = None
     showingHeaders = False
     currentFontSize = 20
     httpGetterFactory = None
     showingHeaders = False
+    staticPageFeedFile = 'curlytx-pagefeed.xml'
 
     def __init__(self, session, args = None):
         #self.skin = CurlyTx.skin
 
     def __init__(self, session, args = None):
         #self.skin = CurlyTx.skin
@@ -72,10 +74,11 @@ class CurlyTx(Screen,HelpableScreen):
 
         self.loadHelp()
         self.loadButtons()
 
         self.loadHelp()
         self.loadButtons()
-        self.onLayoutFinish.append(self.afterLayout)
+        self.onFirstExecBegin.append(self.afterLayout)
 
     def afterLayout(self):
         self.setTextFont
 
     def afterLayout(self):
         self.setTextFont
+        self.loadStaticConfig()
         self.loadUrl(config.plugins.CurlyTx.defaultPage.value)
 
     def loadHelp(self):
         self.loadUrl(config.plugins.CurlyTx.defaultPage.value)
 
     def loadHelp(self):
@@ -262,3 +265,31 @@ class CurlyTx(Screen,HelpableScreen):
             contextFactory=contextFactory,
             *args, **kwargs)
         return self.httpGetterFactory.deferred
             contextFactory=contextFactory,
             *args, **kwargs)
         return self.httpGetterFactory.deferred
+
+    def loadStaticConfig(self):
+        """
+        Always try to load the static config file from
+        /etc/enigma2/curlytx-pagefeed.xml
+        """
+        staticFeedPath = Directories.resolveFilename(Directories.SCOPE_CONFIG, self.staticPageFeedFile)
+        if not os.path.exists(staticFeedPath):
+            return
+
+        from AtomFeed import AtomFeed
+        AtomFeed(
+            'file://' + staticFeedPath,
+            self.saveStaticConfig, self.loadStaticConfigFail
+            )
+
+    def loadStaticConfigFail(self, errorMessage):
+        """ Loading the page url feed failed somehow """
+        from Screens.MessageBox import MessageBox
+        self.session.open(
+            MessageBox,
+            _("Error loading page feed:") + "\n\n" + str(errorMessage),
+            type = MessageBox.TYPE_ERROR
+            )
+
+    def saveStaticConfig(self, pages):
+        feedPagesToConfig(pages)
+        savePageConfig()
index c04acb2091b0685ef69fa30ca5b080494e686578..ba2281c4280b5e46ba8681782b002298e71443e6 100644 (file)
@@ -12,7 +12,7 @@ from Components.Sources.StaticText import StaticText
 from Screens.MessageBox import MessageBox
 
 from . import config
 from Screens.MessageBox import MessageBox
 
 from . import config
-from config import createPage, loadDefaultPageOptions
+from config import createPage, loadDefaultPageOptions, feedPagesToConfig, savePageConfig
 from Components.config import config, getConfigListEntry, ConfigSelection
 from Components.ConfigList import ConfigList, ConfigListScreen
 
 from Components.config import config, getConfigListEntry, ConfigSelection
 from Components.ConfigList import ConfigList, ConfigListScreen
 
@@ -153,32 +153,19 @@ class CurlyTxSettings(ConfigListScreen, HelpableScreen, Screen):
         self["config"].setList(self.getConfigList())
 
     def feedPagesReceived(self, pages):
         self["config"].setList(self.getConfigList())
 
     def feedPagesReceived(self, pages):
-        if len(pages) == 0:
-            return
-
-        del config.plugins.CurlyTx.pages[:]
-
-        for pageData in pages:
-            page = createPage()
-            config.plugins.CurlyTx.pages.append(page)
-            page.title.setValue(pageData["title"])
-            page.uri.setValue(pageData["url"])
-
+        feedPagesToConfig(pages)
         self["config"].setList(self.getConfigList())
 
         self["config"].setList(self.getConfigList())
 
-    def feedPagesFail(self, failure):
+    def feedPagesFail(self, errorMessage):
         """ Downloading the page url feed failed somehow """
         self.session.open(
             MessageBox,
         """ Downloading the page url feed failed somehow """
         self.session.open(
             MessageBox,
-            _("Error loading page feed:") + "\n\n" + str(failure.getErrorMessage()),
+            _("Error loading page feed:") + "\n\n" + str(errorMessage),
             MessageBox.TYPE_ERROR
             )
 
     def keySave(self):
             MessageBox.TYPE_ERROR
             )
 
     def keySave(self):
-        for i in range(0, len(config.plugins.CurlyTx.pages)):
-            config.plugins.CurlyTx.pages[i].save()
-
-        config.plugins.CurlyTx.pages.save()
+        savePageConfig()
         ConfigListScreen.keySave(self)
 
     def cancelConfirm(self, result):
         ConfigListScreen.keySave(self)
 
     def cancelConfirm(self, result):
index e32e27b5cae17c14e2347eb4bfe02057d7152493..7b1114271eacf3e6f7bac05aaa5f991b019ccc0f 100644 (file)
@@ -25,6 +25,26 @@ def loadDefaultPageOptions():
     else:
         config.plugins.CurlyTx.defaultPage = ConfigSelection(defaults, "0")
 
     else:
         config.plugins.CurlyTx.defaultPage = ConfigSelection(defaults, "0")
 
+def feedPagesToConfig(pages):
+    """ save pages from atom feed into config. """
+    if len(pages) == 0:
+        return
+
+    del config.plugins.CurlyTx.pages[:]
+
+    for pageData in pages:
+        page = createPage()
+        config.plugins.CurlyTx.pages.append(page)
+        page.title.setValue(pageData["title"])
+        page.uri.setValue(pageData["url"])
+
+def savePageConfig():
+    for i in range(0, len(config.plugins.CurlyTx.pages)):
+        config.plugins.CurlyTx.pages[i].save()
+
+    config.plugins.CurlyTx.pages.save()
+
+
 #configuration setup
 config.plugins.CurlyTx = ConfigSubsection()
 config.plugins.CurlyTx.menuMain = ConfigYesNo(default = True)
 #configuration setup
 config.plugins.CurlyTx = ConfigSubsection()
 config.plugins.CurlyTx.menuMain = ConfigYesNo(default = True)