cc07160703721ce71575acf92a3248cbb849e581
[enigma2.git] / lib / python / Components / DreamInfoHandler.py
1 import xml.sax
2 from Tools.Directories import crawlDirectory, resolveFilename, SCOPE_CONFIG, SCOPE_SKIN
3 from Components.NimManager import nimmanager
4 from Components.Ipkg import IpkgComponent
5 from Components.config import config, configfile
6 from enigma import eConsoleAppContainer, eDVBDB
7 import os
8
9 class InfoHandlerParseError(Exception):
10         def __init__(self, value):
11                 self.value = value
12         def __str__(self):
13                 return repr(self.value)
14
15 class InfoHandler(xml.sax.ContentHandler):
16         def __init__(self, prerequisiteMet, directory):
17                 self.attributes = {}
18                 self.directory = directory
19                 self.list = []
20                 self.globalprerequisites = {}
21                 self.prerequisites = {}
22                 self.elements = []
23                 self.validFileTypes = ["skin", "config", "services", "favourites", "package"]
24                 self.prerequisitesMet = prerequisiteMet
25         
26                                 
27         def printError(self, error):
28                 print "Error in defaults xml files:", error
29                 raise InfoHandlerParseError, error
30     
31         def startElement(self, name, attrs):
32                 print name, ":", attrs.items()
33                 self.elements.append(name)
34                 if name in ["hardware", "bcastsystem", "satellite"]:
35                         if not attrs.has_key("type"):
36                                         self.printError(str(name) + " tag with no type attribute")
37                         if self.elements[-3] == "default":
38                                 prerequisites = self.globalprerequisites
39                         else:
40                                 prerequisites = self.prerequisites
41                         if not prerequisites.has_key(name):
42                                 prerequisites[name] = []
43                         prerequisites[name].append(str(attrs["type"]))
44                 if name == "files":
45                         if attrs.has_key("type"):
46                                 if attrs["type"] == "directories":
47                                         self.attributes["filestype"] = "directories"
48                                 # TODO add a compressed archive type
49                 if name == "file":
50                         self.prerequisites = {}
51                         if not attrs.has_key("type"):
52                                 self.printError("file tag with no type attribute")
53                         else:
54                                 if not attrs.has_key("name"):
55                                         self.printError("file tag with no name attribute")
56                                 else:   
57                                         if not attrs.has_key("directory"):
58                                                 directory = self.directory
59                                         type = attrs["type"]
60                                         if not type in self.validFileTypes:
61                                                 self.printError("file tag with invalid type attribute")
62                                         else:
63                                                 self.filetype = type
64                                                 self.fileattrs = attrs
65         def endElement(self, name):
66                 print "end", name
67                 print "self.elements:", self.elements
68                 self.elements.pop()
69                 if name == "file":
70                         print "prerequisites:", self.prerequisites
71                         if len(self.prerequisites) == 0 or self.prerequisitesMet(self.prerequisites):
72                                 if not self.attributes.has_key(self.filetype):
73                                         self.attributes[self.filetype] = []
74                                 if self.fileattrs.has_key("directory"):
75                                         directory = str(self.fileattrs["directory"])
76                                         if len(directory) < 1 or directory[0] != "/":
77                                                 directory = self.directory + directory
78                                 else:
79                                         directory = self.directory
80                                 self.attributes[self.filetype].append({ "name": str(self.fileattrs["name"]), "directory": directory })
81     
82                 if name == "default":
83                         self.list.append({"attributes": self.attributes, 'prerequisites': self.globalprerequisites})
84                         self.attributes = {}
85                         self.globalprerequisites = {}
86     
87         def characters(self, data):
88                 if self.elements[-1] == "author":
89                         self.attributes["author"] = str(data)
90                 if self.elements[-1] == "name":
91                         self.attributes["name"] = str(data)
92                 print "characters", data
93                 
94 class DreamInfoHandler:
95         STATUS_WORKING = 0
96         STATUS_DONE = 1
97         STATUS_ERROR = 2
98         STATUS_INIT = 4
99         
100         def __init__(self, statusCallback):
101                 self.directory = "/"
102                 
103                 self.console = eConsoleAppContainer()
104                 self.console.appClosed.get().append(self.installNext)
105                 
106                 self.statusCallback = statusCallback
107                 self.setStatus(self.STATUS_INIT)
108                                 
109                 self.packageslist = []
110         
111         def readInfo(self, directory, file):
112                 print "Reading .info file", file
113                 handler = InfoHandler(self.prerequisiteMet, directory)
114                 try:
115                         xml.sax.parse(file, handler)
116                         for entry in handler.list:
117                                 self.packageslist.append((entry,file)) 
118                 except InfoHandlerParseError:
119                         print "file", file, "ignored due to errors in the file"
120                 print handler.list
121         
122         # prerequisites = True: give only packages matching the prerequisites
123         def fillPackagesList(self, prerequisites = True):
124                 self.packageslist = []
125                 packages = crawlDirectory(self.directory, ".*\.info$")
126                 for package in packages:
127                         self.readInfo(package[0] + "/", package[0] + "/" + package[1])
128                         
129                 if prerequisites:
130                         for package in self.packageslist[:]:
131                                 if not self.prerequisiteMet(package[0]["prerequisites"]):
132                                         self.packageslist.remove(package)
133                 return packages
134                         
135         def prerequisiteMet(self, prerequisites):
136                 # TODO: we need to implement a hardware detection here...
137                 print "prerequisites:", prerequisites
138                 met = True
139                 if prerequisites.has_key("bcastsystem"):
140                         for bcastsystem in prerequisites["bcastsystem"]:
141                                 if nimmanager.hasNimType(bcastsystem):
142                                         return True
143                         return False
144                 if prerequisites.has_key("hardware"):
145                         for hardware in prerequisites["hardware"]:
146                                 # TODO: hardware detection
147                                 met = True
148                 return True
149                         
150         def installPackage(self, index):
151                 print "installing package with index", index, "and name", self.packageslist[index][0]["attributes"]["name"]
152                 
153                 attributes = self.packageslist[index][0]["attributes"]
154                 self.installingAttributes = attributes
155                 self.attributeNames = ["skin", "config", "favourites", "package", "services"]
156                 self.currentAttributeIndex = 0
157                 self.currentIndex = -1
158                 self.installNext()
159                 
160         def setStatus(self, status):
161                 self.status = status
162                 self.statusCallback(self.status, None)
163                                                 
164         def installNext(self, *args, **kwargs):
165                 self.currentIndex += 1
166                 attributes = self.installingAttributes
167                 
168                 if self.currentAttributeIndex >= len(self.attributeNames): # end reached
169                         self.setStatus(self.STATUS_DONE)
170                         return
171                 
172                 self.setStatus(self.STATUS_WORKING)             
173                 
174                 currentAttribute = self.attributeNames[self.currentAttributeIndex]
175                 
176                 print "installing", currentAttribute, "with index", self.currentIndex
177                 
178                 if attributes.has_key(currentAttribute):
179                         if self.currentIndex >= len(attributes[currentAttribute]): # all jobs done for current attribute
180                                 self.currentIndex = -1
181                                 self.currentAttributeIndex += 1
182                                 self.installNext()
183                                 return
184                 else: # nothing to install here
185                         self.currentAttributeIndex += 1
186                         self.installNext()
187                         return
188                         
189                 if currentAttribute == "skin":
190                         skin = attributes["skin"][self.currentIndex]
191                         self.installSkin(skin["directory"], skin["name"])
192                 elif currentAttribute == "config":
193                         if self.currentIndex == 0:
194                                 from Components.config import configfile
195                                 configfile.save()
196                         config = attributes["config"][self.currentIndex]
197                         self.mergeConfig(config["directory"], config["name"])
198                 elif currentAttribute == "favourites":
199                         favourite = attributes["favourites"][self.currentIndex]
200                         self.installFavourites(favourite["directory"], favourite["name"])
201                 elif currentAttribute == "package":
202                         package = attributes["package"][self.currentIndex]
203                         self.installIPK(package["directory"], package["name"])
204                 elif currentAttribute == "services":
205                         service = attributes["services"][self.currentIndex]
206                         self.mergeServices(service["directory"], service["name"])
207                                 
208         def readfile(self, filename):
209                 if not os.path.isfile(filename):
210                         return []
211                 fd = open(filename)
212                 lines = fd.readlines()
213                 fd.close()
214                 return lines
215                         
216         def mergeConfig(self, directory, name, merge = True):
217                 print "merging config:", directory, " - ", name
218                 if os.path.isfile(directory + name):
219                         config.loadFromFile(directory + name)
220                         configfile.save()
221                 self.installNext()
222                 
223         def installIPK(self, directory, name):
224                 self.ipkg = IpkgComponent()
225                 self.ipkg.addCallback(self.ipkgCallback)
226                 self.ipkg.startCmd(IpkgComponent.CMD_INSTALL, {'package': directory + name})
227                 
228         def ipkgCallback(self, event, param):
229                 print "ipkgCallback"
230                 if event == IpkgComponent.EVENT_DONE:
231                         self.installNext()
232                 elif event == IpkgComponent.EVENT_ERROR:
233                         self.installNext()
234         
235         def installSkin(self, directory, name):
236                 print "installing skin:", directory, " - ", name
237                 print "cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN))
238                 if self.console.execute("cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN))):
239                         print "execute failed"
240                         self.installNext()
241
242         def mergeServices(self, directory, name, merge = False):
243                 print "merging services:", directory, " - ", name
244                 
245                 db = eDVBDB.getInstance()
246                 db.reloadServicelist()
247                 db.loadServicelist(directory + name)
248                 db.saveServicelist()
249                 self.installNext()
250
251         def installFavourites(self, directory, name):
252                 print "installing favourites:", directory, " - ", name
253
254                 if self.console.execute("cp %s %s" % ((directory + name), resolveFilename(SCOPE_CONFIG))):
255                         print "execute failed"
256                         self.installNext()