Merge pull request #156 from Dima73/pull1
[openblackhole/openblackhole-enigma2.git] / lib / python / Plugins / SystemPlugins / CommonInterfaceAssignment / plugin.py
1 from Screens.Screen import Screen
2 from Screens.ChannelSelection import *
3 from Components.ActionMap import HelpableActionMap, ActionMap, NumberActionMap
4 from Components.Sources.List import List
5 from Components.Sources.StaticText import StaticText
6 from Components.config import ConfigNothing
7 from Components.ConfigList import ConfigList
8 from Components.Label import Label
9 from Components.SelectionList import SelectionList
10 from Components.MenuList import MenuList
11 from ServiceReference import ServiceReference
12 from Plugins.Plugin import PluginDescriptor
13 from xml.etree.cElementTree import parse as ci_parse
14 from Tools.XMLTools import elementsWithTag, mergeText, stringToXML
15 from enigma import eDVBCI_UI, eDVBCIInterfaces, eEnv
16 from Screens.ChoiceBox import ChoiceBox
17 from Tools.BoundFunction import boundFunction
18 from Tools.XMLTools import stringToXML
19
20 import os
21
22 class CIselectMainMenu(Screen):
23         skin = """
24                 <screen name="CIselectMainMenu" position="center,center" size="500,250" title="CI assignment" >
25                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
26                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
27                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
28                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
29                         <widget name="CiList" position="5,50" size="490,200" scrollbarMode="showOnDemand" />
30                 </screen>"""
31
32         def __init__(self, session, args = 0):
33
34                 Screen.__init__(self, session)
35
36                 self["key_red"] = StaticText(_("Close"))
37                 self["key_green"] = StaticText(_("Edit"))
38
39                 self["actions"] = ActionMap(["ColorActions","SetupActions"],
40                         {
41                                 "green": self.greenPressed,
42                                 "red": self.close,
43                                 "ok": self.greenPressed,
44                                 "cancel": self.close
45                         }, -1)
46
47                 NUM_CI = eDVBCIInterfaces.getInstance() and eDVBCIInterfaces.getInstance().getNumOfSlots()
48
49                 print "[CI_Wizzard] FOUND %d CI Slots " % NUM_CI
50
51                 self.dlg = None
52                 self.state = { }
53                 self.list = [ ]
54                 if  NUM_CI and NUM_CI > 0:
55                         for slot in range(NUM_CI):
56                                 state = eDVBCI_UI.getInstance().getState(slot)
57                                 if state != -1:
58                                         appname = _("Slot %d") %(slot+1) + " - " + _("unknown error")
59                                         if state == 0:
60                                                 appname = _("Slot %d") %(slot+1) + " - " + _("no module found")
61                                         elif state == 1:
62                                                 appname = _("Slot %d") %(slot+1) + " - " + _("init modules")
63                                         elif state == 2:
64                                                 appname = _("Slot %d") %(slot+1) + " - " + eDVBCI_UI.getInstance().getAppName(slot)
65                                         self.list.append( (appname, ConfigNothing(), 0, slot) )
66                 else:
67                         self.list.append( (_("no CI slots found") , ConfigNothing(), 1, -1) )
68
69                 menuList = ConfigList(self.list)
70                 menuList.list = self.list
71                 menuList.l.setList(self.list)
72                 self["CiList"] = menuList
73                 self.onShown.append(self.setWindowTitle)
74
75         def setWindowTitle(self):
76                 self.setTitle(_("CI assignment"))
77
78         def greenPressed(self):
79                 cur = self["CiList"].getCurrent()
80                 if cur and len(cur) > 2:
81                         action = cur[2]
82                         slot = cur[3]
83                         if action == 1:
84                                 print "[CI_Wizzard] there is no CI Slot in your receiver"
85                         else:
86                                 print "[CI_Wizzard] selected CI Slot : %d" % slot
87                                 if config.usage.setup_level.index > 1: # advanced
88                                         self.session.open(CIconfigMenu, slot)
89                                 else:
90                                         self.session.open(easyCIconfigMenu, slot)
91
92         """def yellowPressed(self): # unused
93                 NUM_CI=eDVBCIInterfaces.getInstance().getNumOfSlots()
94                 print "[CI_Check] FOUND %d CI Slots " % NUM_CI
95                 if NUM_CI > 0:
96                         for ci in range(NUM_CI):
97                                 print eDVBCIInterfaces.getInstance().getDescrambleRules(ci)"""
98
99 class CIconfigMenu(Screen):
100         skin = """
101                 <screen name="CIconfigMenu" position="center,center" size="560,440" title="CI assignment" >
102                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
103                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
104                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
105                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
106                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
107                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
108                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
109                         <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
110                         <widget source="CAidList_desc" render="Label" position="5,50" size="550,22" font="Regular;20"  backgroundColor="#25062748" transparent="1" />
111                         <widget source="CAidList" render="Label" position="5,80" size="550,45" font="Regular;20"  backgroundColor="#25062748" transparent="1" />
112                         <ePixmap pixmap="skin_default/div-h.png" position="0,125" zPosition="1" size="560,2" />
113                         <widget source="ServiceList_desc" render="Label" position="5,130" size="550,22" font="Regular;20" backgroundColor="#25062748" transparent="1"  />
114                         <widget name="ServiceList" position="5,160" size="550,250" zPosition="1" scrollbarMode="showOnDemand" />
115                         <widget source="ServiceList_info" render="Label" position="5,160" size="550,250" zPosition="2" font="Regular;20" backgroundColor="#25062748" transparent="1"  />
116                 </screen>"""
117
118         def __init__(self, session, ci_slot="9"):
119
120                 Screen.__init__(self, session)
121                 self.ci_slot = ci_slot
122                 self.filename = eEnv.resolve("${sysconfdir}/enigma2/ci") + str(self.ci_slot) + ".xml"
123
124                 self["key_red"] = StaticText(_("Delete"))
125                 self["key_green"] = StaticText(_("Add service"))
126                 self["key_yellow"] = StaticText(_("Add provider"))
127                 self["key_blue"] = StaticText(_("Select CAId"))
128                 self["CAidList_desc"] = StaticText(_("Assigned CAIds:"))
129                 self["CAidList"] = StaticText()
130                 self["ServiceList_desc"] = StaticText(_("Assigned services/provider:"))
131                 self["ServiceList_info"] = StaticText()
132
133                 self["actions"] = ActionMap(["ColorActions","SetupActions"],
134                         {
135                                 "green": self.greenPressed,
136                                 "red": self.redPressed,
137                                 "yellow": self.yellowPressed,
138                                 "blue": self.bluePressed,
139                                 "cancel": self.cancel
140                         }, -1)
141
142                 print "[CI_Wizzard_Config] Configuring CI Slots : %d  " % self.ci_slot
143
144                 i = 0
145                 self.caidlist  =[]
146                 print eDVBCIInterfaces.getInstance().readCICaIds(self.ci_slot)
147                 for caid in eDVBCIInterfaces.getInstance().readCICaIds(self.ci_slot):
148                         i += 1
149                         self.caidlist.append((str(hex(int(caid))),str(caid),i))
150
151                 print "[CI_Wizzard_Config_CI%d] read following CAIds from CI: %s" %(self.ci_slot, self.caidlist)
152
153                 self.selectedcaid = []
154                 self.servicelist = []
155                 self.caids = ""
156
157                 serviceList = ConfigList(self.servicelist)
158                 serviceList.list = self.servicelist
159                 serviceList.l.setList(self.servicelist)
160                 self["ServiceList"] = serviceList
161
162                 self.loadXML()
163                 # if config mode !=advanced autoselect any caid
164                 if config.usage.setup_level.index <= 1: # advanced
165                         self.selectedcaid=self.caidlist
166                         self.finishedCAidSelection(self.selectedcaid)
167                 self.onShown.append(self.setWindowTitle)
168
169         def setWindowTitle(self):
170                 self.setTitle(_("CI assignment"))
171
172         def redPressed(self):
173                 self.delete()
174
175         def greenPressed(self):
176                 self.session.openWithCallback( self.finishedChannelSelection, myChannelSelection, None)
177
178         def yellowPressed(self):
179                 self.session.openWithCallback( self.finishedProviderSelection, myProviderSelection, None)
180
181         def bluePressed(self):
182                 self.session.openWithCallback(self.finishedCAidSelection, CAidSelect, self.caidlist, self.selectedcaid)
183
184         def cancel(self):
185                 self.saveXML()
186                 activate_all(self, editcallback=True)
187                 self.close()
188
189         def setServiceListInfo(self):
190                 if len(self.servicelist):
191                         self["ServiceList_info"].setText("")
192                 else:
193                         self["ServiceList_info"].setText(_("No services/providers selected"))
194
195         def delete(self):
196                 cur = self["ServiceList"].getCurrent()
197                 if cur and len(cur) > 2:
198                         self.servicelist.remove(cur)
199                 self["ServiceList"].l.setList(self.servicelist)
200                 self.setServiceListInfo()
201
202         def finishedChannelSelection(self, *args):
203                 if len(args):
204                         ref = args[0]
205                         service_ref = ServiceReference(ref)
206                         service_name = service_ref.getServiceName()
207                         if find_in_list(self.servicelist, service_name, 0) == False:
208                                 split_ref = service_ref.ref.toString().split(":")
209                                 if split_ref[0] == "1":#== dvb service und nicht muell von None
210                                         self.servicelist.append((service_name, ConfigNothing(), 0, service_ref.ref.toString()))
211                                         self["ServiceList"].l.setList(self.servicelist)
212                                         self.setServiceListInfo()
213
214         def finishedProviderSelection(self, *args):
215                 item = len(args)
216                 if item > 1: # bei nix selected kommt nur 1 arg zurueck (==None)
217                         if item > 2 and args[2] is True:
218                                 for ref in args[0]:
219                                         service_ref = ServiceReference(ref)
220                                         service_name = service_ref.getServiceName()
221                                         if len(service_name) and find_in_list(self.servicelist, service_name, 0) == False:
222                                                 split_ref = service_ref.ref.toString().split(":")
223                                                 if split_ref[0] == "1":
224                                                         self.servicelist.append((service_name, ConfigNothing(), 0, service_ref.ref.toString()))
225                                 self["ServiceList"].l.setList(self.servicelist)
226                                 self.setServiceListInfo()
227                         else:
228                                 name = args[0]
229                                 dvbnamespace = args[1]
230                                 if find_in_list(self.servicelist, name, 0) == False:
231                                         self.servicelist.append((name, ConfigNothing(), 1, dvbnamespace))
232                                         self["ServiceList"].l.setList(self.servicelist)
233                                         self.setServiceListInfo()
234
235         def finishedCAidSelection(self, *args):
236                 if len(args):
237                         self.selectedcaid = args[0]
238                         self.caids=""
239                         if len(self.selectedcaid):
240                                 for item in self.selectedcaid:
241                                         if len(self.caids):
242                                                 self.caids += ", " + item[0]
243                                         else:
244                                                 self.caids = item[0]
245                         else:
246                                 self.selectedcaid = []
247                                 self.caids = _("no CAId selected")
248                 else:
249                         self.selectedcaid = []
250                         self.caids = _("no CAId selected")
251                 self["CAidList"].setText(self.caids)
252
253         def saveXML(self):
254                 try:
255                         fp = file(self.filename, 'w')
256                         fp.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n")
257                         fp.write("<ci>\n")
258                         fp.write("\t<slot>\n")
259                         fp.write("\t\t<id>%s</id>\n" % self.ci_slot)
260                         for item in self.selectedcaid:
261                                 if len(self.selectedcaid):
262                                         fp.write("\t\t<caid id=\"%s\" />\n" % item[0])
263                         for item in self.servicelist:
264                                 if len(self.servicelist):
265                                         if item[2]==1:
266                                                 fp.write("\t\t<provider name=\"%s\" dvbnamespace=\"%s\" />\n" % (stringToXML(item[0]), item[3]))
267                                         else:
268                                                 fp.write("\t\t<service name=\"%s\" ref=\"%s\" />\n"  % (stringToXML(item[0]), item[3]))
269                         fp.write("\t</slot>\n")
270                         fp.write("</ci>\n")
271                         fp.close()
272                 except:
273                         print "[CI_Config_CI%d] xml not written" % self.ci_slot
274                         os.unlink(self.filename)
275
276         def loadXML(self):
277                 if not os.path.exists(self.filename):
278                         self.setServiceListInfo()
279                         return
280
281                 def getValue(definitions, default):
282                         ret = ""
283                         Len = len(definitions)
284                         return Len > 0 and definitions[Len-1].text or default
285                 self.read_services = []
286                 self.read_providers = []
287                 self.usingcaid = []
288                 self.ci_config = []
289                 try:
290                         tree = ci_parse(self.filename).getroot()
291                         for slot in tree.findall("slot"):
292                                 read_slot = getValue(slot.findall("id"), False).encode("UTF-8")
293                                 print "ci " + read_slot
294                                 i=0
295                                 for caid in slot.findall("caid"):
296                                         read_caid = caid.get("id").encode("UTF-8")
297                                         self.selectedcaid.append((str(read_caid),str(read_caid),i))
298                                         self.usingcaid.append(long(read_caid,16))
299                                         i+=1
300
301                                 for service in  slot.findall("service"):
302                                         read_service_name = service.get("name").encode("UTF-8")
303                                         read_service_ref = service.get("ref").encode("UTF-8")
304                                         self.read_services.append (read_service_ref)
305
306                                 for provider in  slot.findall("provider"):
307                                         read_provider_name = provider.get("name").encode("UTF-8")
308                                         read_provider_dvbname = provider.get("dvbnamespace").encode("UTF-8")
309                                         self.read_providers.append((read_provider_name,read_provider_dvbname))
310
311                                 self.ci_config.append((int(read_slot), (self.read_services, self.read_providers, self.usingcaid)))
312                 except:
313                         print "[CI_Config_CI%d] error parsing xml..." % self.ci_slot
314                         try:
315                                 os.remove(self.filename)
316                         except:
317                                 print "[CI_Activate_Config_CI%d] error remove damaged xml..." % self.ci_slot
318
319                 for item in self.read_services:
320                         if len(item):
321                                 self.finishedChannelSelection(item)
322
323                 for item in self.read_providers:
324                         if len(item):
325                                 self.finishedProviderSelection(item[0],item[1])
326
327                 print self.ci_config
328                 self.finishedCAidSelection(self.selectedcaid)
329                 self["ServiceList"].l.setList(self.servicelist)
330                 self.setServiceListInfo()
331
332 class easyCIconfigMenu(CIconfigMenu):
333         skin = """
334                 <screen name="easyCIconfigMenu" position="center,center" size="560,440" title="CI assignment" >
335                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
336                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
337                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
338                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
339                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
340                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
341                         <widget source="ServiceList_desc" render="Label" position="5,50" size="550,22" font="Regular;20" backgroundColor="#25062748" transparent="1"  />
342                         <widget name="ServiceList" position="5,80" size="550,300" zPosition="1" scrollbarMode="showOnDemand" />
343                         <widget source="ServiceList_info" render="Label" position="5,80" size="550,300" zPosition="2" font="Regular;20" backgroundColor="#25062748" transparent="1"  />
344                 </screen>"""
345
346         def __init__(self, session, ci_slot="9"):
347
348                 ci=ci_slot
349                 CIconfigMenu.__init__(self, session, ci_slot)
350
351                 self["actions"] = ActionMap(["ColorActions","SetupActions"],
352                 {
353                         "green": self.greenPressed,
354                         "red": self.redPressed,
355                         "yellow": self.yellowPressed,
356                         "cancel": self.cancel
357                 })
358
359 class CAidSelect(Screen):
360         skin = """
361                 <screen name="CAidSelect" position="center,center" size="450,440" title="select CAId's" >
362                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
363                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
364                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
365                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
366                         <widget name="list" position="5,50" size="440,330" scrollbarMode="showOnDemand" />
367                         <ePixmap pixmap="skin_default/div-h.png" position="0,390" zPosition="1" size="450,2" />
368                         <widget source="introduction" render="Label" position="0,400" size="450,40" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
369                 </screen>"""
370
371         def __init__(self, session, list, selected_caids):
372
373                 Screen.__init__(self, session)
374
375                 self.list = SelectionList()
376                 self["list"] = self.list
377
378                 for listindex in range(len(list)):
379                         if find_in_list(selected_caids,list[listindex][0],0):
380                                 self.list.addSelection(list[listindex][0], list[listindex][1], listindex, True)
381                         else:
382                                 self.list.addSelection(list[listindex][0], list[listindex][1], listindex, False)
383
384                 self["key_red"] = StaticText(_("Cancel"))
385                 self["key_green"] = StaticText(_("Save"))
386                 self["introduction"] = StaticText(_("Press OK to select/deselect a CAId."))
387
388                 self["actions"] = ActionMap(["ColorActions","SetupActions"],
389                 {
390                         "ok": self.list.toggleSelection,
391                         "cancel": self.cancel,
392                         "green": self.greenPressed,
393                         "red": self.cancel
394                 }, -1)
395                 self.onShown.append(self.setWindowTitle)
396
397         def setWindowTitle(self):
398                 self.setTitle(_("select CAId's"))
399
400         def greenPressed(self):
401                 list = self.list.getSelectionsList()
402                 print list
403                 self.close(list)
404
405         def cancel(self):
406                 self.close()
407
408 class myProviderSelection(ChannelSelectionBase):
409         skin = """
410                 <screen name="myProviderSelection" position="center,center" size="560,440" title="Select provider to add...">
411                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
412                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
413                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
414                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
415                         <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
416                         <widget name="list" position="5,50" size="550,330" scrollbarMode="showOnDemand" />
417                         <ePixmap pixmap="skin_default/div-h.png" position="0,390" zPosition="1" size="560,2" />
418                         <widget source="introduction" render="Label" position="0,400" size="560,40" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
419                 </screen>"""
420
421         def __init__(self, session, title):
422                 ChannelSelectionBase.__init__(self, session)
423                 self.onShown.append(self.__onExecCallback)
424                 self.bouquet_mark_edit = EDIT_BOUQUET
425
426                 self["actions"] = ActionMap(["OkCancelActions", "ChannelSelectBaseActions"],
427                         {
428                                 "showFavourites": self.showFavourites,
429                                 "showAllServices": self.showAllServices,
430                                 "showProviders": self.showProviders,
431                                 "showSatellites": boundFunction(self.showSatellites, changeMode=True),
432                                 "cancel": self.cancel,
433                                 "ok": self.channelSelected
434                         })
435                 self["key_red"] = StaticText(_("Close"))
436                 self["key_green"] = StaticText()
437                 self["key_yellow"] = StaticText()
438                 self["key_blue"] = StaticText()
439                 self["introduction"] = StaticText(_("Press OK to select a provider."))
440
441
442         def showProviders(self):
443                 pass
444
445         def showAllServices(self):
446                 self.close(None)
447
448         def showFavourites(self):
449                 pass
450
451         def __onExecCallback(self):
452                 self.showSatellites()
453                 self.setTitle(_("Select provider to add..."))
454
455         def channelSelected(self): # just return selected service
456                 ref = self.getCurrentSelection()
457                 if ref is None: return
458                 if not (ref.flags & 64):
459                         splited_ref = ref.toString().split(":")
460                         if ref.flags == 7 and splited_ref[6] != "0":
461                                 self.dvbnamespace = splited_ref[6]
462                                 self.enterPath(ref)
463                         elif (ref.flags & 7) == 7 and 'provider' in ref.toString():
464                                 menu = [(_("Provider"), "provider"),(_("All services provider"), "providerlist")]
465                                 def addAction(choice):
466                                         if choice is not None:
467                                                 if choice[1] == "provider":
468                                                         self.close(ref.getName(), self.dvbnamespace)
469                                                 elif choice[1] == "providerlist":
470                                                         serviceHandler = eServiceCenter.getInstance()
471                                                         servicelist = serviceHandler.list(ref)
472                                                         if not servicelist is None:
473                                                                 providerlist = []
474                                                                 while True:
475                                                                         service = servicelist.getNext()
476                                                                         if not service.valid():
477                                                                                 break
478                                                                         providerlist.append((service))
479                                                                 if providerlist:
480                                                                         self.close(providerlist, self.dvbnamespace, True)
481                                                                 else:
482                                                                         self.close(None)
483                                 self.session.openWithCallback(addAction, ChoiceBox, title = _("Select action"), list=menu)
484
485         def showSatellites(self, changeMode=False):
486                 if changeMode:
487                         return
488                 if not self.pathChangeDisabled:
489                         refstr = '%s FROM SATELLITES ORDER BY satellitePosition'%(self.service_types)
490                         if not self.preEnterPath(refstr):
491                                 ref = eServiceReference(refstr)
492                                 justSet=False
493                                 prev = None
494
495                                 if self.isBasePathEqual(ref):
496                                         if self.isPrevPathEqual(ref):
497                                                 justSet=True
498                                         prev = self.pathUp(justSet)
499                                 else:
500                                         currentRoot = self.getRoot()
501                                         if currentRoot is None or currentRoot != ref:
502                                                 justSet=True
503                                                 self.clearPath()
504                                                 self.enterPath(ref, True)
505                                 if justSet:
506                                         serviceHandler = eServiceCenter.getInstance()
507                                         servicelist = serviceHandler.list(ref)
508                                         if not servicelist is None:
509                                                 while True:
510                                                         service = servicelist.getNext()
511                                                         if not service.valid(): #check if end of list
512                                                                 break
513                                                         unsigned_orbpos = service.getUnsignedData(4) >> 16
514                                                         orbpos = service.getData(4) >> 16
515                                                         if orbpos < 0:
516                                                                 orbpos += 3600
517                                                         if service.getPath().find("FROM PROVIDER") != -1:
518                                                                 service_type = _("Providers")
519                                                                 try:
520                                                                         # why we need this cast?
521                                                                         service_name = str(nimmanager.getSatDescription(orbpos))
522                                                                 except:
523                                                                         if unsigned_orbpos == 0xFFFF: #Cable
524                                                                                 service_name = _("Cable")
525                                                                         elif unsigned_orbpos == 0xEEEE: #Terrestrial
526                                                                                 service_name = _("Terrestrial")
527                                                                         else:
528                                                                                 if orbpos > 1800: # west
529                                                                                         orbpos = 3600 - orbpos
530                                                                                         h = _("W")
531                                                                                 else:
532                                                                                         h = _("E")
533                                                                                 service_name = ("%d.%d" + h) % (orbpos / 10, orbpos % 10)
534                                                                 service.setName("%s - %s" % (service_name, service_type))
535                                                                 self.servicelist.addService(service)
536                                                 self.servicelist.finishFill()
537                                                 if prev is not None:
538                                                         self.setCurrentSelection(prev)
539
540         def cancel(self):
541                 self.close(None)
542
543 class myChannelSelection(ChannelSelectionBase):
544         skin = """
545                 <screen name="myChannelSelection" position="center,center" size="560,440" title="Select service to add...">
546                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
547                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
548                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
549                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
550                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
551                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
552                         <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
553                         <widget name="list" position="5,50" size="550,330" scrollbarMode="showOnDemand" />
554                         <ePixmap pixmap="skin_default/div-h.png" position="0,390" zPosition="1" size="560,2" />
555                         <widget source="introduction" render="Label" position="0,400" size="560,40" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
556                 </screen>"""
557
558         def __init__(self, session, title):
559                 ChannelSelectionBase.__init__(self, session)
560                 self.onShown.append(self.__onExecCallback)
561                 self.bouquet_mark_edit = OFF
562
563                 self["actions"] = ActionMap(["OkCancelActions", "TvRadioActions", "ChannelSelectBaseActions"],
564                         {
565                                 "showProviders": self.showProviders,
566                                 "showSatellites": boundFunction(self.showSatellites, changeMode=True),
567                                 "showAllServices": self.showAllServices,
568                                 "cancel": self.cancel,
569                                 "ok": self.channelSelected,
570                                 "keyRadio": self.setModeRadio,
571                                 "keyTV": self.setModeTv
572                         })
573
574                 self["key_red"] = StaticText(_("All"))
575                 self["key_green"] = StaticText(_("Close"))
576                 self["key_yellow"] = StaticText()
577                 self["key_blue"] = StaticText(_("Favourites"))
578                 self["introduction"] = StaticText(_("Press OK to select a provider."))
579
580         def __onExecCallback(self):
581                 self.setModeTv()
582                 self.setTitle(_("Select service to add..."))
583
584         def showProviders(self):
585                 pass
586
587         def showSatellites(self, changeMode=False):
588                 if changeMode:
589                         self.close(None)
590
591         def channelSelected(self): # just return selected service
592                 ref = self.getCurrentSelection()
593                 if (ref.flags & 7) == 7:
594                         self.enterPath(ref)
595                 elif not (ref.flags & eServiceReference.isMarker):
596                         ref = self.getCurrentSelection()
597                         self.close(ref)
598
599         def setModeTv(self):
600                 self.setTvMode()
601                 self.showFavourites()
602
603         def setModeRadio(self):
604                 self.setRadioMode()
605                 self.showFavourites()
606
607         def cancel(self):
608                 self.close(None)
609
610 def activate_all(session, editcallback=False):
611         NUM_CI = eDVBCIInterfaces.getInstance().getNumOfSlots()
612         print "[CI_Activate] FOUND %d CI Slots " % NUM_CI
613         if NUM_CI and NUM_CI > 0:
614                 def getValue(definitions, default):
615                         # How many definitions are present
616                         Len = len(definitions)
617                         return Len > 0 and definitions[Len-1].text or default
618
619                 for ci in range(NUM_CI):
620                         filename = eEnv.resolve("${sysconfdir}/enigma2/ci") + str(ci) + ".xml"
621
622                         if not os.path.exists(filename):
623                                 print "[CI_Activate_Config_CI%d] no config file found" %ci
624                                 continue
625
626                         try:
627                                 tree = ci_parse(filename).getroot()
628                                 read_services=[]
629                                 read_providers=[]
630                                 usingcaid=[]
631                                 for slot in tree.findall("slot"):
632                                         read_slot = getValue(slot.findall("id"), False).encode("UTF-8")
633
634                                         for caid in slot.findall("caid"):
635                                                 read_caid = caid.get("id").encode("UTF-8")
636                                                 usingcaid.append(long(read_caid,16))
637
638                                         for service in slot.findall("service"):
639                                                 read_service_ref = service.get("ref").encode("UTF-8")
640                                                 read_services.append (read_service_ref)
641
642                                         for provider in slot.findall("provider"):
643                                                 read_provider_name = provider.get("name").encode("UTF-8")
644                                                 read_provider_dvbname = provider.get("dvbnamespace").encode("UTF-8")
645                                                 read_providers.append((read_provider_name,long(read_provider_dvbname,16)))
646
647                                         if editcallback or (read_slot is not False and (read_services or read_providers or usingcaid)):
648                                                 print "[CI_Activate] activate CI%d with following settings:" % int(read_slot)
649                                                 print read_services, read_providers, usingcaid
650                                                 try:
651                                                         eDVBCIInterfaces.getInstance().setDescrambleRules(int(read_slot), (read_services, read_providers, usingcaid))
652                                                 except:
653                                                         print "[CI_Activate_Config_CI%d] error setting DescrambleRules..." % int(read_slot)
654                         except:
655                                 print "[CI_Activate_Config_CI%d] error parsing xml..." % ci
656                                 try:
657                                         os.remove(filename)
658                                 except:
659                                         print "[CI_Activate_Config_CI%d] error remove damaged xml..." % ci
660
661 def find_in_list(list, search, listpos=0):
662         for item in list:
663                 if item[listpos] == search:
664                         return True
665         return False
666
667 global_session = None
668
669 def sessionstart(reason, session):
670         global global_session
671         global_session = session
672
673 def autostart(reason, **kwargs):
674         global global_session
675         if reason == 0:
676                 print "[CI_Assignment] activating ci configs:"
677                 activate_all(global_session)
678         elif reason == 1:
679                 global_session = None
680
681 def main(session, **kwargs):
682         session.open(CIselectMainMenu)
683
684 def isModule():
685         NUM_CI = eDVBCIInterfaces.getInstance() and eDVBCIInterfaces.getInstance().getNumOfSlots()
686         if NUM_CI and NUM_CI > 0:
687                 for slot in range(NUM_CI):
688                         state = eDVBCI_UI.getInstance().getState(slot)
689                         if state > 0:
690                                 return True
691         return False
692
693 def menu(menuid, **kwargs):
694         if menuid == "cam" and isModule():
695                 return [(_("Common Interface assignment"), main, "ci_assign", 11)]
696         return []
697
698 def Plugins(**kwargs):
699         description = _("a gui to assign services/providers to common interface modules")
700         if config.usage.setup_level.index > 1:
701                 description = _("a gui to assign services/providers/caids to common interface modules")
702         return [PluginDescriptor(where = PluginDescriptor.WHERE_SESSIONSTART, needsRestart = False, fnc = sessionstart),
703                         PluginDescriptor(where = PluginDescriptor.WHERE_AUTOSTART, needsRestart = False, fnc = autostart),
704                         PluginDescriptor(name = _("Common Interface assignment"), description = description, where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc = menu)]