8e9a8a27a3a0476af68991a7f16115327e85d9b8
[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 self.neededTag in prerequisites["tag"]:
153                                         return True
154                         return False
155                 if prerequisites.has_key("bcastsystem"):
156                         for bcastsystem in prerequisites["bcastsystem"]:
157                                 if nimmanager.hasNimType(bcastsystem):
158                                         return True
159                         return False
160                 if prerequisites.has_key("hardware"):
161                         for hardware in prerequisites["hardware"]:
162                                 # TODO: hardware detection
163                                 met = True
164                 return True
165         
166         def installPackages(self, indexes):
167                 print "installing packages", indexes
168                 if len(indexes) == 0:
169                         self.setStatus(self.STATUS_DONE)
170                         return
171                 self.installIndexes = indexes
172                 print "+++++++++++++++++++++++bla"
173                 self.currentlyInstallingMetaIndex = 0
174                 self.installPackage(self.installIndexes[self.currentlyInstallingMetaIndex])
175
176         def installPackage(self, index):
177                 print "installing package with index", index, "and name", self.packageslist[index][0]["attributes"]["name"]
178                 
179                 attributes = self.packageslist[index][0]["attributes"]
180                 self.installingAttributes = attributes
181                 self.attributeNames = ["skin", "config", "favourites", "package", "services"]
182                 self.currentAttributeIndex = 0
183                 self.currentIndex = -1
184                 self.installNext()
185                 
186         def setStatus(self, status):
187                 self.status = status
188                 self.statusCallback(self.status, None)
189                                                 
190         def installNext(self, *args, **kwargs):
191                 self.currentIndex += 1
192                 attributes = self.installingAttributes
193                 #print "attributes:", attributes
194                 
195                 if self.currentAttributeIndex >= len(self.attributeNames): # end of package reached
196                         if self.currentlyInstallingMetaIndex is None or self.currentlyInstallingMetaIndex >= len(self.installIndexes) - 1:
197                                 self.setStatus(self.STATUS_DONE)
198                                 return
199                         else:
200                                 self.currentlyInstallingMetaIndex += 1
201                                 self.installPackage(self.installIndexes[self.currentlyInstallingMetaIndex])
202                 
203                 self.setStatus(self.STATUS_WORKING)             
204                 
205                 currentAttribute = self.attributeNames[self.currentAttributeIndex]
206                 
207                 print "installing", currentAttribute, "with index", self.currentIndex
208                 
209                 if attributes.has_key(currentAttribute):
210                         if self.currentIndex >= len(attributes[currentAttribute]): # all jobs done for current attribute
211                                 self.currentIndex = -1
212                                 self.currentAttributeIndex += 1
213                                 self.installNext()
214                                 return
215                 else: # nothing to install here
216                         self.currentIndex = -1
217                         self.currentAttributeIndex += 1
218                         self.installNext()
219                         return
220                         
221                 if currentAttribute == "skin":
222                         skin = attributes["skin"][self.currentIndex]
223                         self.installSkin(skin["directory"], skin["name"])
224                 elif currentAttribute == "config":
225                         if self.currentIndex == 0:
226                                 from Components.config import configfile
227                                 configfile.save()
228                         config = attributes["config"][self.currentIndex]
229                         self.mergeConfig(config["directory"], config["name"])
230                 elif currentAttribute == "favourites":
231                         favourite = attributes["favourites"][self.currentIndex]
232                         self.installFavourites(favourite["directory"], favourite["name"])
233                 elif currentAttribute == "package":
234                         package = attributes["package"][self.currentIndex]
235                         self.installIPK(package["directory"], package["name"])
236                 elif currentAttribute == "services":
237                         service = attributes["services"][self.currentIndex]
238                         self.mergeServices(service["directory"], service["name"])
239                                 
240         def readfile(self, filename):
241                 if not os.path.isfile(filename):
242                         return []
243                 fd = open(filename)
244                 lines = fd.readlines()
245                 fd.close()
246                 return lines
247                         
248         def mergeConfig(self, directory, name, merge = True):
249                 print "merging config:", directory, " - ", name
250                 if os.path.isfile(directory + name):
251                         config.loadFromFile(directory + name)
252                         configfile.save()
253                 self.installNext()
254                 
255         def installIPK(self, directory, name):
256                 if self.blocking:
257                         os.system("ipkg install " + directory + name)
258                         self.installNext()
259                 else:
260                         self.ipkg = IpkgComponent()
261                         self.ipkg.addCallback(self.ipkgCallback)
262                         self.ipkg.startCmd(IpkgComponent.CMD_INSTALL, {'package': directory + name})
263                 
264         def ipkgCallback(self, event, param):
265                 print "ipkgCallback"
266                 if event == IpkgComponent.EVENT_DONE:
267                         self.installNext()
268                 elif event == IpkgComponent.EVENT_ERROR:
269                         self.installNext()
270         
271         def installSkin(self, directory, name):
272                 print "installing skin:", directory, " - ", name
273                 print "cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN))
274                 if self.blocking:
275                         os.system("cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN)))
276                         self.installNext()
277                 else:
278                         if self.console.execute("cp -a %s %s" % (directory, resolveFilename(SCOPE_SKIN))):
279                                 print "execute failed"
280                                 self.installNext()
281
282         def mergeServices(self, directory, name, merge = False):
283                 print "merging services:", directory, " - ", name
284                 if os.path.isfile(directory + name):
285                         db = eDVBDB.getInstance()
286                         db.reloadServicelist()
287                         db.loadServicelist(directory + name)
288                         db.saveServicelist()
289                 self.installNext()
290
291         def installFavourites(self, directory, name):
292                 print "installing favourites:", directory, " - ", name
293
294                 if self.blocking:
295                         os.system("cp %s %s" % ((directory + name), resolveFilename(SCOPE_CONFIG)))
296                         self.installNext()
297                 else:
298                         if self.console.execute("cp %s %s" % ((directory + name), resolveFilename(SCOPE_CONFIG))):
299                                 print "execute failed"
300                                 self.installNext()