properly handle tags combined with other prerequisites
[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", "tag"]:
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, blocking = False, neededTag = None):
101                 self.directory = "/"
102                 
103                 self.neededTag = neededTag
104                 
105                 # caution: blocking should only be used, if further execution in enigma2 depends on the outcome of
106                 # the installer!
107                 self.blocking = blocking
108                 
109                 self.currentlyInstallingMetaIndex = None
110                 
111                 self.console = eConsoleAppContainer()
112                 self.console.appClosed.get().append(self.installNext)
113                 
114                 self.statusCallback = statusCallback
115                 self.setStatus(self.STATUS_INIT)
116                                 
117                 self.packageslist = []
118                         
119         def readInfo(self, directory, file):
120                 print "Reading .info file", file
121                 handler = InfoHandler(self.prerequisiteMet, directory)
122                 try:
123                         xml.sax.parse(file, handler)
124                         for entry in handler.list:
125                                 self.packageslist.append((entry,file)) 
126                 except InfoHandlerParseError:
127                         print "file", file, "ignored due to errors in the file"
128                 print handler.list
129         
130         # prerequisites = True: give only packages matching the prerequisites
131         def fillPackagesList(self, prerequisites = True):
132                 self.packageslist = []
133                 packages = crawlDirectory(self.directory, ".*\.info$")
134                 for package in packages:
135                         self.readInfo(package[0] + "/", package[0] + "/" + package[1])
136                         
137                 if prerequisites:
138                         for package in self.packageslist[:]:
139                                 if not self.prerequisiteMet(package[0]["prerequisites"]):
140                                         self.packageslist.remove(package)
141                 return packages
142                         
143         def prerequisiteMet(self, prerequisites):
144                 # TODO: we need to implement a hardware detection here...
145                 print "prerequisites:", prerequisites
146                 met = True
147                 if self.neededTag is None:
148                         if prerequisites.has_key("tag"):
149                                 return False
150                 else:
151                         if prerequisites.has_key("tag"):
152                                 if not self.neededTag in prerequisites["tag"]:
153                                         return False
154                                 
155                 if prerequisites.has_key("satellite"):
156                         for sat in prerequisites["satellite"]:
157                                 if int(sat) not in nimmanager.getConfiguredSats():
158                                         return False                            
159                 if prerequisites.has_key("bcastsystem"):
160                         for bcastsystem in prerequisites["bcastsystem"]:
161                                 if nimmanager.hasNimType(bcastsystem):
162                                         return True
163                         return False
164                 if prerequisites.has_key("hardware"):
165                         for hardware in prerequisites["hardware"]:
166                                 # TODO: hardware detection
167                                 met = True
168                 return True
169         
170         def installPackages(self, indexes):
171                 print "installing packages", indexes
172                 if len(indexes) == 0:
173                         self.setStatus(self.STATUS_DONE)
174                         return
175                 self.installIndexes = indexes
176                 print "+++++++++++++++++++++++bla"
177                 self.currentlyInstallingMetaIndex = 0
178                 self.installPackage(self.installIndexes[self.currentlyInstallingMetaIndex])
179
180         def installPackage(self, index):
181                 print "installing package with index", index, "and name", self.packageslist[index][0]["attributes"]["name"]
182                 
183                 attributes = self.packageslist[index][0]["attributes"]
184                 self.installingAttributes = attributes
185                 self.attributeNames = ["skin", "config", "favourites", "package", "services"]
186                 self.currentAttributeIndex = 0
187                 self.currentIndex = -1
188                 self.installNext()
189                 
190         def setStatus(self, status):
191                 self.status = status
192                 self.statusCallback(self.status, None)
193                                                 
194         def installNext(self, *args, **kwargs):
195                 self.currentIndex += 1
196                 attributes = self.installingAttributes
197                 #print "attributes:", attributes
198                 
199                 if self.currentAttributeIndex >= len(self.attributeNames): # end of package reached
200                         print "end of package reached"
201                         if self.currentlyInstallingMetaIndex is None or self.currentlyInstallingMetaIndex >= len(self.installIndexes) - 1:
202                                 print "set status to DONE"
203                                 self.setStatus(self.STATUS_DONE)
204                                 return
205                         else:
206                                 print "increment meta index to install next package"
207                                 self.currentlyInstallingMetaIndex += 1
208                                 self.installPackage(self.installIndexes[self.currentlyInstallingMetaIndex])
209                 
210                 self.setStatus(self.STATUS_WORKING)             
211                 
212                 currentAttribute = self.attributeNames[self.currentAttributeIndex]
213                 
214                 print "installing", currentAttribute, "with index", self.currentIndex
215                 
216                 if attributes.has_key(currentAttribute):
217                         if self.currentIndex >= len(attributes[currentAttribute]): # all jobs done for current attribute
218                                 self.currentIndex = -1
219                                 self.currentAttributeIndex += 1
220                                 self.installNext()
221                                 return
222                 else: # nothing to install here
223                         self.currentIndex = -1
224                         self.currentAttributeIndex += 1
225                         self.installNext()
226                         return
227                         
228                 if currentAttribute == "skin":
229                         skin = attributes["skin"][self.currentIndex]
230                         self.installSkin(skin["directory"], skin["name"])
231                 elif currentAttribute == "config":
232                         if self.currentIndex == 0:
233                                 from Components.config import configfile
234                                 configfile.save()
235                         config = attributes["config"][self.currentIndex]
236                         self.mergeConfig(config["directory"], config["name"])
237                 elif currentAttribute == "favourites":
238                         favourite = attributes["favourites"][self.currentIndex]
239                         self.installFavourites(favourite["directory"], favourite["name"])
240                 elif currentAttribute == "package":
241                         package = attributes["package"][self.currentIndex]
242                         self.installIPK(package["directory"], package["name"])
243                 elif currentAttribute == "services":
244                         service = attributes["services"][self.currentIndex]
245                         self.mergeServices(service["directory"], service["name"])
246                                 
247         def readfile(self, filename):
248                 if not os.path.isfile(filename):
249                         return []
250                 fd = open(filename)
251                 lines = fd.readlines()
252                 fd.close()
253                 return lines
254                         
255         def mergeConfig(self, directory, name, merge = True):
256                 print "merging config:", directory, " - ", name
257                 if os.path.isfile(directory + name):
258                         config.loadFromFile(directory + name)
259                         configfile.save()
260                 self.installNext()
261                 
262         def installIPK(self, directory, name):
263                 if self.blocking:
264                         os.system("ipkg install " + directory + name)
265                         self.installNext()
266                 else:
267                         self.ipkg = IpkgComponent()
268                         self.ipkg.addCallback(self.ipkgCallback)
269                         self.ipkg.startCmd(IpkgComponent.CMD_INSTALL, {'package': directory + name})
270                 
271         def ipkgCallback(self, event, param):
272                 print "ipkgCallback"
273                 if event == IpkgComponent.EVENT_DONE:
274                         self.installNext()
275                 elif event == IpkgComponent.EVENT_ERROR:
276                         self.installNext()
277         
278         def installSkin(self, directory, name):
279                 print "installing skin:", directory, " - ", name
280                 print "cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN))
281                 if self.blocking:
282                         os.system("cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN)))
283                         self.installNext()
284                 else:
285                         if self.console.execute("cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN))):
286                                 print "execute failed"
287                                 self.installNext()
288
289         def mergeServices(self, directory, name, merge = False):
290                 print "merging services:", directory, " - ", name
291                 if os.path.isfile(directory + name):
292                         db = eDVBDB.getInstance()
293                         db.reloadServicelist()
294                         db.loadServicelist(directory + name)
295                         db.saveServicelist()
296                 self.installNext()
297
298         def installFavourites(self, directory, name):
299                 print "installing favourites:", directory, " - ", name
300
301                 if self.blocking:
302                         os.system("cp %s %s" % ((directory + name), resolveFilename(SCOPE_CONFIG)))
303                         self.installNext()
304                 else:
305                         if self.console.execute("cp %s %s" % ((directory + name), resolveFilename(SCOPE_CONFIG))):
306                                 print "execute failed"
307                                 self.installNext()