from Components.ActionMap import HelpableActionMap
from Plugins.Plugin import PluginDescriptor
from Screens.PluginBrowser import *
from Screens.SleepTimerEdit import *
from Screens.Ipkg import Ipkg
from Components.Ipkg import IpkgComponent
from Components.SelectionList import SelectionList
from Screens.NetworkSetup import *
from enigma import *
from Screens.Standby import *
from Screens.MessageBox import MessageBox
from Screens.Console import Console
from Components.ActionMap import ActionMap, NumberActionMap
from Screens.Screen import Screen
from Components.MenuList import MenuList
from Components.Label import Label
from Components.ScrollLabel import ScrollLabel
from Components.Pixmap import Pixmap
from Components.config import config, ConfigSubsection, ConfigText, ConfigSubList, getConfigListEntry, ConfigSelection,  ConfigIP, ConfigYesNo, ConfigSequence, ConfigNumber, ConfigInteger
from Components.ConfigList import ConfigListScreen
from Components.MenuList import MenuList
from Screens.Screen import Screen
from Screens.ChoiceBox import ChoiceBox
from Components.Sources.StaticText import StaticText
from Components.Sources.Progress import Progress
from Components.Label import Label
from Components.FileList import FileList
from Components.MultiContent import MultiContentEntryText
from Tools.Directories import fileExists
from Tools.Directories import pathExists
from Screens.Console import Console
from os import system, remove, path, walk, makedirs, listdir
from Screens.VirtualKeyBoard import VirtualKeyBoard

import re
import urllib
import os
import base64
from subprocess import Popen,PIPE
import ServiceReference

from twisted.cred import checkers
from twisted.web import client
from twisted.internet import reactor, defer
from twisted.python import failure

global serverurl
global activenam
global activesource
global version
global checkok
global menu
global PreviewPath

# for local compile in the box
#
# import py_compile
# py_compile.compile("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/downloader.py")

version = "3.04"
serverurl = ""
activenam = ""
activesource = ""
readyflag = 0
checkok = True
usblist = ""

RestoreYesNo = [('y',_("yes")),('n',_("no"))]
RestoreNoYes = [('n',_("no")),('y',_("yes"))]

font = "Regular;16"
os.system("mkdir -p /tmp/aaf")
#os.system("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/url_check.sh")

activesource = "http://kati910.aaf-board.info/dbase"
#activesource = "http://97.74.32.10/dbase/ufs-e2"
activenam = "Addons-Server"
serverurl = activesource + "/E2/"
PreviewPath = "http://97.74.32.10/svn/preview"

# Boytyp lesen
file = open("/proc/stb/info/model", "r")
box = file.readline().strip()
file.close()

# dm8000 is a vu-box
#box = "dm8000"
if box == "dm8000":
  serverurl = activesource + "/vuplus/"

config.AddonManager = ConfigSubsection()
config.AddonManager.which_server = ConfigInteger(2, limits=(1, 2))
config.AddonManager.preview_timeout = ConfigInteger(default=600,limits=(50, 2000))
config.AddonManager.preview_on = ConfigInteger(1, limits=(0, 1))
config.AddonManager.marker_on = ConfigInteger(1, limits=(0, 1))
config.AddonManager.marker_off = ConfigInteger(1, limits=(0, 1))
config.AddonManager.mark_color = ConfigInteger(1, limits=(0, 2))
config.AddonManager.ungenau = ConfigInteger(1, limits=(0, 1))
config.AddonManager.Schriftart = ConfigInteger(16, limits=(10, 22))

config.AddonManager2 = ConfigSubsection()
config.AddonManager2.sett_on = ConfigSelection(RestoreYesNo)
config.AddonManager2.camconfig_on = ConfigSelection(RestoreYesNo)
config.AddonManager2.plug_on = ConfigSelection(RestoreNoYes)
config.AddonManager2.binarys_on = ConfigSelection(RestoreNoYes)
config.AddonManager2.network_on = ConfigSelection(RestoreYesNo)
config.AddonManager2.samba_on = ConfigSelection(RestoreYesNo)
config.AddonManager2.bilder_on = ConfigSelection(RestoreYesNo)
config.AddonManager2.sonstige_on = ConfigSelection(RestoreYesNo)
config.AddonManager2.am_on = ConfigSelection(RestoreNoYes)
config.AddonManager2.backup_on = ConfigSelection(RestoreYesNo)


RESTORE_CONFIG_SKIN = """<screen position="center,center" size="620,360" title="Backup Restore Setup" >
  <widget name="config" position="20,2" size="570,253" scrollbarMode="showOnDemand" />
	<widget name="label1" position="10,265" size="610,50" font="Regular;18" zPosition="1" backgroundColor="#251e1f20" transparent="1" />
	<eLabel backgroundColor="white" position="10,265" size="610,1" zPosition="5"/>
	<eLabel backgroundColor="red" position="37,330" size="150,3" zPosition="5"/>
	<eLabel backgroundColor="green" position="224,330" size="150,3" zPosition="5"/>
	<eLabel backgroundColor="yellow" position="411,330" size="150,3" zPosition="5"/>
	<widget name="key_red" position="37,296" zPosition="1" size="150,40" font="Regular;20" halign="center" valign="center" transparent="1" />
	<widget name="key_green" position="224,296" zPosition="1" size="150,40" font="Regular;20" halign="center" valign="center" transparent="1" />
	<widget name="key_yellow" position="411,296" zPosition="1" size="150,40" font="Regular;20" halign="center" valign="center" transparent="1" />
</screen>"""

SELECTRESTORE_SKIN = """
		<screen position="center,center" size="520,376" title="Auswahlmenue fuer Restore" >
			<ePixmap position="445,0" size="70,53" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/picon_default.png" transparent="1" alphatest="on" />
			<ePixmap position="90,350" size="36,20" pixmap="skin_default/buttons/key_red.png" transparent="1" alphatest="on" />
			<ePixmap position="270,350" size="36,20" pixmap="skin_default/buttons/key_green.png" transparent="1" alphatest="on" />
			<eLabel text="RESTORE - Auswahl" position="70,12" size="480,35" font="Regular;30" foregroundColor="#ffa323" transparent="1" />
			<eLabel text="Delete" position="130,350" size="240,25" font="Regular;20" transparent="1" />
			<eLabel text="Restore" position="310,350" size="240,25" font="Regular;20" transparent="1" />
			<widget name="filelist" position="10,110" size="520,232" scrollbarMode="showOnDemand" />
		</screen>"""


def applySkinVars(skin,dict):
		for key in dict.keys():
				try:
						skin = skin.replace('{'+key+'}',dict[key])
				except Exception,e:
						print e,"@key=",key
		return skin

def command(comandline):
  print "[Addon-Manager] command=", comandline
  comandline = comandline + " >/tmp/command.txt"
  os.system(comandline)
  text = ""
  file = open("/tmp/command.txt", "r")
  for line in file:
  	text = text + line.strip() + '\n'
  file.close
  # if one or last line then remove linefeed
  if text[-1:] == '\n': text = text[:-1]
  comandline = text
  os.system("rm /tmp/command.txt")
  return comandline

def restore():
		ffile = open("/var/etc/restore.cfg", "w")
		ffile.write('settings=' + config.AddonManager2.sett_on.value[0] + '\n' )
		ffile.write('binarys=' + config.AddonManager2.camconfig_on.value[0] + '\n')
		ffile.write('camconfig=' + config.AddonManager2.plug_on.value[0] + '\n')
		ffile.write('plugins=' + config.AddonManager2.network_on.value[0] + '\n')
		ffile.write('network=' + config.AddonManager2.samba_on.value[0] + '\n')
		ffile.write('samba=' + config.AddonManager2.bilder_on.value[0] + '\n')
		ffile.write('sonstige=' + config.AddonManager2.sonstige_on.value[0] + '\n')
		ffile.write('addonmanager=' + config.AddonManager2.am_on.value[0] + '\n')
		ffile.close()

restore()

#----- Class Cancel -------------------------------------------------------
class UserRequestedCancel(Exception):
	pass

#----- Progressdownloader -------------------------------------------------
class HTTPProgressDownloader(client.HTTPDownloader):
	def __init__(self, url, outfile, headers=None):
		#client.HTTPDownloader.__init__(self, url, outfile, headers={"Authorization":authHeader}, agent="AAF Download Plugin")
		client.HTTPDownloader.__init__(self, url, outfile, agent="AAF Download Plugin")
		self.status = None
		self.progress_callback = None
		self.deferred = defer.Deferred()

	def noPage(self, reason):
		if self.status == "304":
			print reason.getErrorMessage()
			client.HTTPDownloader.page(self, "")
		else:
			client.HTTPDownloader.noPage(self, reason)

	def gotHeaders(self, headers):
		if self.status == "200":
			if headers.has_key("content-length"):
				self.totalbytes = int(headers["content-length"][0])
			else:
				self.totalbytes = 0
			self.currentbytes = 0.0
		return client.HTTPDownloader.gotHeaders(self, headers)

	def pagePart(self, packet):
		if self.status == "200":
			self.currentbytes += len(packet)
		if self.totalbytes and self.progress_callback:
			self.progress_callback(self.currentbytes, self.totalbytes)
		return client.HTTPDownloader.pagePart(self, packet)

	def pageEnd(self):
		return client.HTTPDownloader.pageEnd(self)

class downloadWithProgress:
	def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs):
		scheme, host, port, path = client._parse(url)
		self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs)
		self.connection = reactor.connectTCP(host, port, self.factory)

	def start(self):
		return self.factory.deferred

	def stop(self):
		print "[Addon-Manager] [stop]"
		self.connection.disconnect()
		#self.factory.deferred.errback(failure.Failure(UserRequestedCancel))

	def addProgress(self, progress_callback):
		print "[Addon-Manager] [addProgress]"
		self.factory.progress_callback = progress_callback

class Feedlist(MenuList):
	def __init__(self, list=[], enableWrapAround = False):
		MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)

		Schriftart = config.AddonManager.Schriftart.value
		self.l.setFont(0, gFont("Regular", Schriftart))
		self.l.setItemHeight(22)

	def clear(self):
		del self.list[:]
		self.l.setList(self.list)

	def getPLUGINname(self):
		l = self.l.getCurrentSelection()
		return l and l[0][0]

	def getPLUGINurl(self):
		l = self.l.getCurrentSelection()
		return l and l[0][1]

	def getLISTname(self):
		l = self.l.getCurrentSelection()
		return l and l[0][0][:-2]+"txt"

	def getLISTurl(self):
		l = self.l.getCurrentSelection()
		return l and l[0][1][:-2]+"txt"

	def isValid(self):
		l = self.l.getCurrentSelection()
		if l[0] == 0:
			return False
		else:
			return True

	def moveSelection(self,idx=0):
		if self.instance is not None:
			self.instance.moveSelectionTo(idx)

class PLUGINDownload(Screen):
	LIST_SOURCE = 1
	LIST_DEST = 2
	Skin = """
		<screen name="PLUGINDownload" position="{screen.pos}" size="{screen.size}" title="{version.text}">
			<ePixmap pixmap="skin_default/buttons/red.png" position="{red.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="{green.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/yellow.png" position="{yellow.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/blue.png" position="{blue.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/pressed.png" position="{red2.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/pressed.png" position="{green2.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/pressed.png" position="{yellow2.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/pressed.png" position="{blue2.pos}" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<widget source="key_red" render="Label" position="{red.pos}" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#9f1313" transparent="1" />
			<widget source="key_green" render="Label" position="{green.pos}" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
			<widget source="key_yellow" render="Label" position="{yellow.pos}" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#a08500" transparent="1" />
			<widget source="key_blue" render="Label" position="{blue.pos}" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#18188b" transparent="1" />
			<widget source="key_1" render="Label" position="{red2.pos}" zPosition="1" size="140,40" font="Regular;16" valign="center" halign="center" backgroundColor="#9f1313" transparent="1" />
			<widget source="key_2" render="Label" position="{green2.pos}" zPosition="1" size="140,40" font="Regular;16" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
			<widget source="key_3" render="Label" position="{yellow2.pos}" zPosition="1" size="140,40" font="Regular;16" valign="center" halign="center" backgroundColor="#a08500" transparent="1" />
			<widget source="key_4" render="Label" position="{blue2.pos}" zPosition="1" size="140,40" font="Regular;16" valign="center" halign="center" backgroundColor="#18188b" transparent="1" />
			<widget source="label_top" render="Label" position="10,94" size="340,20" foregroundColor="#3366ff" font="Regular;16" />
			<widget name="feedlist" position="10,116" size="{feed.size}" scrollbarMode="showOnDemand" />
			<widget name="destlist" position="0,116" size="{dest.size}" scrollbarMode="showOnDemand" />
			<widget source="label_bottom" render="Label" position="10,352" size="240,18" foregroundColor="#3366ff" font="Regular;16"/>
			<widget source="infolabel" render="Label" position="{infolabel.pos}" size="{infolabel.size}" font="Regular;16" />
			<widget name="Preview" position="{prev.pos}" size="{prev.size}" alphatest="on"/>
			<widget source="job_progressbar1" render="Progress" position="10,390" size="{progr.size}" borderWidth="1" backgroundColor="#9f1313" />
			<widget source="job_progresslabel1" render="Label" position="130,394" zPosition="2" font="Regular;18" halign="center" transparent="1" size="{proglabel.size}" foregroundColor="#000000" />
			<widget source="job_progressbar" render="Progress" position="10,390" size="{progr.size}" borderWidth="1" backgroundColor="#254f7497" />
			<widget source="job_progresslabel" render="Label" position="130,394" zPosition="2" font="Regular;18" halign="center" transparent="1" size="{proglabel.size}" foregroundColor="#000000" />
			<widget source="statusbar" render="Label" position="10,420" size="{status.size}" font="Regular;16" foregroundColor="#cccccc" />
		</screen>"""

# 			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/aaf.png" position="{logo.pos}" zPosition="0" size="160,140" transparent="1" alphatest="on" />

	def __init__(self, session, destdir="/tmp/aaf/"):
		#switch automatic to current skin
		current_w = getDesktop(0).size().width()
		current_h = getDesktop(0).size().height()
		print "[Addon-Manager] DESKTOPsize is",current_w,current_h

		# define the start koordinates and size
		if current_w == 1280:
				size_w = 720
				size_h = 442
		else:
				size_w = 560
				size_h = 442

		# calculate Skin koordinates
		font = "Regular;18"
		vers = "AAF Addon-Manager V " + version
		pos_w = (current_w - size_w)/2
		pos_h = (current_h - size_h)/2
		list_w = size_w - 20
		list_pos = (size_w - list_w)/2
		red_pos = size_w/2 - 280
		green_pos = size_w/2 - 140
		yellow_pos = size_w/2
		blue_pos = size_w/2 + 140
		feed_size = size_w/2 - 30
		dest_size = feed_size + 10
		prev_size = size_w/2 - 15
		prev_pos = size_w/2
		proglabel_size = size_w/2 + 20
		infolabel_pos = size_w/2 - 10
		infolabel_size = size_w/2 - 15
		logo_pos = size_w -100

		# set Skinvariables
		self.dict = {
				'font': font,
				'version.text': vers,
				'list.size': "%i,232"%(list_w),
				'feed.size': "%i,222"%(feed_size),
				'dest.size': "%i,222"%(dest_size),
				'prev.size': "%i,284"%(prev_size),
				'progr.size': "%i,26"%(list_w),
				'proglabel.size': "%i,22"%(proglabel_size),
				'status.size': "%i,16"%(list_w),

				'list.pos': "%i,110"%(list_pos),
				'prev.pos': "%i,120"%(prev_pos),
				'screen.size': "%i,%i"%(size_w,size_h),
				'screen.pos': "%i,%i"%(pos_w,pos_h),
				'red.pos': "%i,0"%(red_pos),
				'green.pos': "%i,0"%(green_pos),
				'yellow.pos': "%i,0"%(yellow_pos),
				'blue.pos': "%i,0"%(blue_pos),
				'red2.pos': "%i,40"%(red_pos),
				'green2.pos': "%i,40"%(green_pos),
				'yellow2.pos': "%i,40"%(yellow_pos),
				'blue2.pos': "%i,40"%(blue_pos),

				'infolabel.size': "%i,284"%(infolabel_size),
				'infolabel.pos': "%i,94"%(infolabel_pos),
				'logo.pos': "%i,336"%(logo_pos),
				}
		self.skin = applySkinVars(PLUGINDownload.Skin,self.dict)

		Screen.__init__(self, session)
		
		self["job_progressbar"] = Progress()
		self["job_progresslabel"] = StaticText()
		self["job_progressbar1"] = Progress()
		self["job_progresslabel1"] = StaticText()
		self["infolabel"] = StaticText()
		self["statusbar"] = StaticText()
		self["label_top"] = StaticText()
		self["label_bottom"] = StaticText()
		self["path_bottom"] = StaticText()
		self["key_green"] = StaticText()
		self["key_yellow"] = StaticText()
		self["key_blue"] = StaticText()
		self["key_red"] = StaticText()
		self["key_1"] = StaticText()
		self["key_2"] = StaticText()
		self["key_3"] = StaticText()
		self["key_4"] = StaticText()

		self["feedlist"] = Feedlist([0,(eListboxPythonMultiContent.TYPE_TEXT, 0, 0,250, 30, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, "feed not available")])

		self.currDir = "/mnt/usb"
		self["destlist"] = FileList(self.currDir, showDirectories = True, isTop = True)
		self["destlist"].hide()
		self["Preview"] = Pixmap()
		self["Preview"].hide()

		self.download_container = eConsoleAppContainer()
		self.LIST = ""
		self.LISTfile = ""
		self.feedhtml = ""
		self.focus = None
		self.download = None
		self.plug = "all"
		self.farbe = 1
		self.ListTyp = "pic"

		self.feed_base = serverurl + "%s/" % self.plug
		self.plugin_filter = ""
		#self.showpreview = "on"

		self.showpreview = config.AddonManager.preview_on.value
		self.previewtimeout = config.AddonManager.preview_timeout.value
		self.marker_on = config.AddonManager.marker_on.value
		self.marker_off = config.AddonManager.marker_off.value

		self.ThumbTimer = eTimer()
		self.ThumbTimer.callback.append(self.list_download)

		self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "EPGSelectActions", "MenuActions", "InfobarTeletextActions", "NumberActions", "MovieSelectionActions", "InfobarActions"],
			{
				"cancel": self.closeCB,
				"red": self.red_download,
				"green": self.green_download,
				"yellow": self.yellow_download,
				"blue": self.blue_download,

				"1": self.eins_download,
				"2": self.FavMenu,
				"3": self.drei_download,
				"4": self.vier_download,
				"5": self.fuenf_download,
				"6": self.BackupRestore,
				"9": self.sh_preview,
				"0": self.update,

				"prevBouquet": self.switchList,
				"nextBouquet": self.switchList,
				"ok": self.check_download,
				"left": self.left,
				"right": self.right,
				"up": self.up,
				"upRepeated": self.up,
				"downRepeated": self.down,
				"menu": self.settings_menu,
				"startTeletext": self.switch_ListTyp,
				"showEventInfo": self.info,
				"showTv": self.FavMenu,
				"down": self.down
			}, -1)

		aafpointer = 0
		#/etc/imageinfo AAF Enigma2
		fd=open("/etc/imageinfo","r")
		for line in fd:
			if line.find("AAF Enigma2") > -1:
				aafpointer = aafpointer +1
		fd.close

		# /etc/motd wElc0me to AAF
		fd=open("/etc/motd","r")
		for line in fd:
			if line.find("wElc0me to") > -1:
				aafpointer = aafpointer +1
		fd.close

		# Url Check
		os.system("cat /var/etc/ipkg/official-feed.conf | cut -d '/' -f4 > /tmp/onlineupdate")
		fd=open("/tmp/onlineupdate","r")
		url=fd.readline().strip()
		fd.close()

		if url.find("97.74.32.10") > -1:
			aafpointer = aafpointer +1
		if url.find("addons.aaf-board.net") > -1:
			aafpointer = aafpointer +1

		if str(aafpointer) <= "0":
		#if str(aafpointer) <= "2":
			print "Permission denied ", str(aafpointer)
			self["statusbar"].text = _("Sorry, Permission denied")
			self.close()
		else:
			self.focus = self.LIST_SOURCE
			self.read_Boxtyp()

			self.plug = "ipk"

			if fileExists("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/startservice.cfg"):
				file = open("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/startservice.cfg","r")
				self.plugin_filter = str(file.readline().strip())
				file.close()
			else:
				self.plugin_filter = "-"  # show all ipk

			if box <> "dm8000":
				evfd.getInstance().vfd_write_string("load PlugList")
			if os.path.exists("/var/etc/ipkg/official-feed.conf") is True:
				file = open("/var/etc/ipkg/official-feed.conf", "r")
				self.feed_base = file.readline().strip()
				self.feed_base = self.feed_base.replace(u"src/gz cross ","")
				self.feed_base = str(self.feed_base) + "/"
			elif os.path.exists("/etc/ipkg/official-feed.conf") is True:
				file = open("/etc/ipkg/official-feed.conf", "r")
				self.feed_base = file.readline().strip()
				self.feed_base = self.feed_base.replace(u"src/gz cross ","")
				self.feed_base = str(self.feed_base) + "/"
			self.feed_download()

	def FavMenu(self):
		Filter = "-"
		self.session.openWithCallback(self.MenuCallback, FilterPanel,Filter)

	def MenuCallback(self):
		global menu
		print "FavMenu Callback", menu
		if menu == "stop":
				menu = "-"
		self.plugin_filter = menu
		self.feed_finished(self.feedhtml)


	def BackupRestoreVU(self):
		self.session.open(RestoreConfigScreenVU)

	def BackupRestore(self):
			self.session.open(RestoreConfigScreenVU)

	def downloading(self, state=True):
		if state is True:	
			self["key_red"].text = _("Cancel")
			self["key_green"].text = ""
			self["key_yellow"].text = ""
			self["key_blue"].text = ""
		else:
			self.download = None
			self["key_red"].text = _("System")
			self["key_green"].text = (_("Skins"))
			self["key_yellow"].text = (_("Players"))
			self["key_blue"].text = (_("Emus"))
			self["key_1"].text = _("(1) Bootbilder")
			self["key_2"].text = (_("(2) Select"))
			self["key_3"].text = (_("(3) SWAP all"))
			self["key_4"].text = (_("(4) IPK all"))

	def switchList(self,to_where=None):
		if self.download or not self["feedlist"].isValid():
			return

		self["job_progressbar"].value = 0
		self["job_progresslabel"].text = ""

		if self.focus is  self.LIST_DEST:
			self["statusbar"].text = _("Please select a target device")
			self["label_top"].text = _("choose destination directory")+":"
			self["feedlist"].hide()
			self["destlist"].show()

		if self.focus is self.LIST_SOURCE:
			self["statusbar"].text = _("Please choose file from AAF Server to download")
			self["label_top"].text = _("...select file (FAV = Filter)")
			self["feedlist"].show()
			self["destlist"].hide()
			self["label_bottom"].text = _("attached to: ")+ activenam


#----- load Menutext or Picture -------------------------------------------------------
	def switch_ListTyp(self):
		if self.ListTyp == "txt":
			self.ListTyp = "pic"
			self["Preview"].show()
			LISTurl = self["feedlist"].getLISTurl()
			LISTurl = LISTurl+".png"
			print "[Addon-Manager] downloading " + LISTurl
			self.download = self.list_download
			self.downloading(True)
			#client.getPage(LISTurl, headers={"Authorization":authHeader}).addCallback(self.pic_finished).addErrback(self.pic_failed)
			client.getPage(LISTurl).addCallback(self.pic_finished).addErrback(self.pic_failed)

		if self.ListTyp == "pic":
			self.ListTyp = "txt"
			self["statusbar"].text = ""
			self.LISTfilename = ""
			self.LIST = ""
			self["Preview"].hide()
			LISTurl = self["feedlist"].getLISTurl()
			#client.getPage(LISTurl, headers={"Authorization":authHeader}).addCallback(self.list_finished).addErrback(self.list_failed)
			client.getPage(LISTurl).addCallback(self.list_finished).addErrback(self.list_failed)
			self["statusbar"].text = _("Downloading file description...")
			self.downloading(False)

#----- Menu Keys are pressed -------------------------------------------------------
	def up(self):
		if self.download:
			return
		if self.focus is self.LIST_SOURCE:
			self["feedlist"].up()
			self.ThumbTimer.start(self.previewtimeout, True)
		if self.focus is self.LIST_DEST:
			self["destlist"].up()

	def down(self):
		if self.download:
			return
		if self.focus is self.LIST_SOURCE:
			self["feedlist"].down()
			self.ThumbTimer.start(self.previewtimeout, True)
		if self.focus is self.LIST_DEST:
			self["destlist"].down()

	def left(self):
		if self.download:
			return
		if self.focus is self.LIST_SOURCE:
			self["feedlist"].pageUp()
			self.ThumbTimer.start(self.previewtimeout, True)
		if self.focus is self.LIST_DEST:
			self["destlist"].pageUp()

	def right(self):
		if self.download:
			return
		if self.focus is self.LIST_SOURCE:
			self["feedlist"].pageDown()
			self.ThumbTimer.start(self.previewtimeout, True)
		if self.focus is self.LIST_DEST:
			self["destlist"].pageDown()

	def ok(self):
		if self.download:
			return
		if self.focus is self.LIST_DEST:
			if self["destlist"].canDescent():
				self["destlist"].descent()

	def settings_menu(self):
		self.session.open(AddonConfigScreen)

	def info(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("Version V " + version)
		message = "%s %s\n\n%s" % (_("AAF Addon-Manager\n\n     Version "), version, _("       AAF-Team\n\n@Bauernbub 2009"))
		self.session.openWithCallback(self.update_now, MessageBox, message, MessageBox.TYPE_INFO)

#----- AM Update -------------------------------------------------------
	def update(self):
		versurl = activesource + "/version_e2.txt"
		h = urllib.urlretrieve(versurl, "/tmp/version_e2.txt")
		dummy = open("/tmp/version_e2.txt").read()
		version_server = dummy[0:len(dummy) -2]
		if version_server == version:
			print "[Addon-Manager] gleich"
			message = "%s %s\n%s %s\n\n%s" % (_("Version am Server:"), version_server, _("Version in der Box:"), version, _("Ein Update ist nicht erforderlich!"))
			if box <> "dm8000":
				evfd.getInstance().vfd_write_string("No Update")
			self.session.open( MessageBox, message, MessageBox.TYPE_INFO)
		else:
			if version_server > version:
				message = "%s %s\n%s %s\n\n%s" % (_("Version am Server:"), version_server, _("Version in der Box:"), version, _("Ein Update ist empfehlenswert!"))
				if box <> "dm8000":
					evfd.getInstance().vfd_write_string("UPDATE is here")
				self.session.openWithCallback(self.update_now, MessageBox, message, MessageBox.TYPE_YESNO)
			else:
				message = "%s %s\n%s %s\n\n%s" % (_("\nKlingt wie ein Scherz, aber die Version am Server ist aelter als die auf ihrer Box!\n\nVersion am Server:"), version_server, _("Version in der Box:"), version, _("NICHT UPDATEN, sie besitzen vermutlich eine fortgeschrittene Betaversion!"))
				if box <> "dm8000":
					evfd.getInstance().vfd_write_string("Update is older")
				self.session.openWithCallback(self.update_now, MessageBox, message, MessageBox.TYPE_YESNO)

	def update_now(self, answer):
		self.downloading(False)
		if answer == True:

			if box <> "dm8000":
				versurl = activesource + "/addon-man_e2.tar.gz"
			else:
				versurl = activesource + "/addon-man_vu_e2.tar.gz"

			h = urllib.urlretrieve(versurl, "/tmp/aaf/addon-man_e2.tar.gz")

			os.system("cd /tmp/aaf; tar -xzf addon-man_e2.tar.gz")
			if os.path.exists("/tmp/aaf/addon-man_e2.tar.gz") is True:
				os.system("cp -RP /tmp/aaf/* / ; sync")
				os.system("rm -r /tmp/aaf")
				os.system("cd / ; rm *tar.gz")
				os.system("mkdir /tmp/aaf")
				if box <> "dm8000":
					evfd.getInstance().vfd_write_string("rebooting ....")
				message = "%s" % (_("Der Addon-Manager hat einen Neustart angefordert!\nDie Box wird nun neu gestartet!"))
				self.session.openWithCallback(self.update_now, MessageBox, message, MessageBox.TYPE_YESNO)
				#self.session.open( MessageBox, message, MessageBox.TYPE_INFO)
				#TryQuitMainloop(self.session,2)
				os.system("killall -9 enigma2")

#----- Feed Download Procedures -------------------------------------------------------
	def feed_download(self):
		self.downloading(True)
		self.download = self.feed_download
		print "[feed-download]" +  self.feed_base + "index.txt"

		if os.path.exists("/tmp/aaf") is False:
				os.system("mkdir /tmp/aaf")

		ipkurl = command('cat /var/etc/ipkg/official-feed.conf | cut -d "/" -f4')
		os.system("cd /usr/lib/enigma2/python/Plugins/Extensions/AddonManager/; ./ipkdownload")
		if os.path.exists("/tmp/aaf/index.txt") is True:
				self.feedhtml = open("/tmp/aaf/index.txt").read()
				self.feed_finished(self.feedhtml)


	def feed_failed(self, failure_instance):
		print "[Addon-Manager] [feed_failed] " + str(failure_instance)
		self["infolabel"].text = _("Could not connect to AAF-Plugin Server:") + "\n" + failure_instance.getErrorMessage() + "\n\n" + _("Please check your network settings!")
		self.downloading(False)

	def feed_finished(self, feedhtml):
		#print "[Addon-Manager] [feed_finished] " + str(feedhtml)
		self.downloading(False)

		fileresultmask = re.compile("(?P<name>.*?)\#\#(?P<url>.*?_sh4.ipk)", re.DOTALL)
		if box == "dm8000":
				fileresultmask = re.compile("(?P<name>.*?)\#\#(?P<url>.*?.ipk)", re.DOTALL)

		if os.path.exists("/var/etc/uninst") is False:
			os.system("mkdir -p /var/etc/uninst")

		os.system("ls /var/etc/uninst >/tmp/uninst.txt")
		os.system("ls /usr/lib/ipkg/info/*.postrm >>/tmp/uninst.txt")

		fd=open("/tmp/uninst.txt")
		inhalt=fd.read() # Lese die gesamte Datei
		fd.close()
		inhalt = inhalt.lower()
		inhalt = inhalt.replace("\n","")
		inhalt = inhalt.replace("\r","")
		searchresults = fileresultmask.finditer(feedhtml)

		ausblenden = 0
		#self.ungenau = config.AddonManager.ungenau.value
		self.farbe = config.AddonManager.mark_color.value

		if self.farbe == 0:
				farbwahl = 16711680
		elif self.farbe == 1:
				farbwahl = 65280
		elif self.farbe == 2:
				farbwahl = 49151
		fileresultlist = []
		if searchresults:
			for x in searchresults:
				url = x.group("url")

				# filtering the Filename string
				if url.find(self.plugin_filter) > -1:
					#print "url=", url
					ausblenden = 0
				else:
					ausblenden = 1

				if url[0:7] != "http://":
					url = self.feed_base + x.group("url")
				name = x.group("name")
				name_lo = name.lower()
				name_lo = name_lo.replace("\n","")
				name_lo = name_lo.replace("\r","")
				font_s = 0
				name_lo = name_lo.split("_")[0]
				#print "name_lo = ", str(name_lo)

				if self.marker_on == True:
					if inhalt.find(name_lo) > -1 and ausblenden == 0:
						font_s = 1
						if self.marker_off != True:
							ausblenden = 1
						else:
							ausblenden = 0

				if ausblenden == 0:
						if font_s == 1:
							entry = [[name, url],(eListboxPythonMultiContent.TYPE_TEXT, 0, 0,300, 30, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, name, farbwahl)]
						else:
							entry = [[name, url],(eListboxPythonMultiContent.TYPE_TEXT, 0, 0,300, 30, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, name)]
						fileresultlist.append(entry)
				else:
						ausblenden = 0

			self["feedlist"].l.setList(fileresultlist)
			self["feedlist"].moveSelection(0)
		if len(fileresultlist) > 0:
			self.switchList(self.LIST_SOURCE)
			self.list_download()
		else:
			self["infolabel"].text = _("Cannot parse feed directory")

		if box <> "dm8000":
				evfd.getInstance().vfd_write_string("AddonManager")


#----- List Download Procedures -------------------------------------------------------
	def list_download(self):
		global PreviewPath
		global LISTurlText
		if self.showpreview == True:
			#print "[Addon-Manager] [check_for_LIST]"
			if self["feedlist"].isValid():
				#print "[Addon-Manager] PLUGINname: " + self["feedlist"].getPLUGINname()
				self["job_progressbar"].value = 0
				self["job_progresslabel"].text = ""
				if self["feedlist"].getPLUGINurl() is None:
					self["key_green"].text = ""
					return
				self["key_green"].text = _("Download")
				LISTurl = self["feedlist"].getLISTurl()
				LISTurl1 = LISTurl.split("_")[0]
				UrlLink = LISTurl.split("enigma2-plugin-")[0]
				LISTName = LISTurl1.split("enigma2-plugin-")[1].split("-")[1]
				
				if LISTName.find(".") > -1:
					LISTName = LISTName.split(".")[0]

				LISTurl = PreviewPath + "/enigma2-pluginpreview-" + LISTName+".png"
				LISTurlText = PreviewPath + "/enigma2-pluginpreview-" + LISTName+".txt"

				#print "[Addon-Manager] downloading " + LISTurl
				self.download = self.list_download
				self.downloading(True)
				#client.getPage(LISTurl, headers={"Authorization":authHeader}).addCallback(self.pic_finished).addErrback(self.pic_failed)
				client.getPage(LISTurl).addCallback(self.pic_finished).addErrback(self.pic_failed)

				self["statusbar"].text = _("Downloading file description...")

	def list_failed(self, failure_instance):
		print "[Addon-Manager] [list_failed] " + str(failure_instance)
		self["infolabel"].text = _("No details for this file") + "\n" + self["feedlist"].getPLUGINname()
		self["statusbar"].text = ""
		self.LISTfilename = ""
		self.LIST = ""
		self.downloading(False)

	def list_finished(self,LISTdata=""):
		#print "[Addon-Manager] [list_finished] " + str(LISTdata)
		self.downloading(False)
		self.LIST = LISTdata
		self.ListTyp = "txt"

		if self.LIST != "":
			self.LISTfilename = self["feedlist"].getLISTname()
			self["infolabel"].text = self.LIST
		else:
			self.LISTfilename = ""
			self["infolabel"].text = _("No details for this file")
		self["statusbar"].text = ""

#----- Pic Download Procedures -------------------------------------------------------
	def pic_failed(self, failure_instance):
		print "[Addon-Manager] [list_failed] " + str(failure_instance)
		self["infolabel"].text = _("No details for this file") + "\n" + self["feedlist"].getPLUGINname()
		self["statusbar"].text = ""
		self.LISTfilename = ""
		self.LIST = ""
		self["Preview"].hide()

		# no pic-file, now look for txt
		self["statusbar"].text = _("Downloading file description...")
		#LISTurl = self["feedlist"].getLISTurl()
		#client.getPage(LISTurl, headers={"Authorization":authHeader}).addCallback(self.list_finished).addErrback(self.list_failed)
		global LISTurlText
		client.getPage(LISTurlText).addCallback(self.list_finished).addErrback(self.list_failed)

		self.downloading(False)

	def pic_finished(self,LISTdata=""):
		print "[Addon-Manager] [list_finished] " + str(LISTdata)
		self.downloading(False)
		self.LIST = LISTdata
		self.ListTyp = "pic"

		if self.LIST != "":
			self.LISTfilename = self["feedlist"].getLISTname()
			self["infolabel"].text = ""
			# write skin-preview to file
			ffile = open("/tmp/skin.png", "w")
			ffile.write(self.LIST)
			ffile.close()
			pngpath = "/tmp/skin.png"
			self.previewPath = pngpath
			self["Preview"].show()
			self["Preview"].instance.setPixmapFromFile(self.previewPath)
		else:
			self.LISTfilename = ""
			self["infolabel"].text = _("No details for this file")
		self["statusbar"].text = ""
#-----------------------------------------------------------------

	def sh_preview(self):
		if self.showpreview == 1:
			self.showpreview = 0
			self.LISTfilename = self["feedlist"].getLISTname()
			self["infolabel"].text = _("Preview = off: (press Key 9) ")
			pngpath = "/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/no_preview.png"
			self.previewPath = pngpath
			self["Preview"].show()
			self["Preview"].instance.setPixmapFromFile(self.previewPath)
		else:
			self.showpreview = 1
			self.LISTfilename = self["feedlist"].getLISTname()
			self["infolabel"].text = _("Preview = on: ")
			self["Preview"].hide()

	def read_Boxtyp(self):
			file = open("/proc/stb/info/model", "r")
			self.box = file.readline().strip()
			file.close()

	def red_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("Plugins")
		self.plugin_filter = "system-" 
		self.feed_finished(self.feedhtml)

	def green_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("Settings")
		self.plugin_filter = "skins-"
		self.feed_finished(self.feedhtml)

	def yellow_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("EmusConfig")
		self.plugin_filter = "players-"
		self.feed_finished(self.feedhtml)

	def blue_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("Emus")
		self.plugin_filter = "emus-"
		self.feed_finished(self.feedhtml)


# ----- Numbers --------
	def eins_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("Bootbilder")
		self.plugin_filter = "bootlogos-"
		self.feed_finished(self.feedhtml)

	def zwei_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("Radiobilder")
		self.plugin_filter = "radiologos-"
		self.feed_finished(self.feedhtml)

	def drei_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("SWAP all")
		self.plugin_filter = "swap"
		self.feed_finished(self.feedhtml)

	def vier_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("IPK all")
		self.plugin_filter = "-"
		self.feed_finished(self.feedhtml)

	def fuenf_download(self):
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("IPK all")
		self.plugin_filter = "-" 
		self.feed_finished(self.feedhtml)



#----- plugin download ------------------------------------------------------------
	def check_download(self):
 			self.plugin_download()

	def plugin_download(self):
		print "[Addon-Manager] Plugin-Download"
		if self["feedlist"].isValid():
			url = self["feedlist"].getPLUGINurl()
			print url
			self.foundipk = re.search('sh4', str(url))
			self.urlname = url
			self.error_counter = "0"
			if len(str(self.foundipk)) == 4:
				self.PLUGINlocal = '/tmp/aaf/downfile.tar.gz'
				if box <> "dm8000":
					evfd.getInstance().vfd_write_string("load Tarfile")
			else:
				self.PLUGINlocal = '/tmp/aaf/downfile.sh4.ipk'
				if box <> "dm8000":
					evfd.getInstance().vfd_write_string("load IPK")

			#self.box = "dm8000"
			if box == "dm8000":
				self.PLUGINlocal = '/tmp/aaf/downfile.sh4.ipk'
				if box <> "dm8000":
					evfd.getInstance().vfd_write_string("load IPK")

			self.PluginPath = "E2/image"

			if self.error_counter == "0":
				self["job_progressbar"].value = 0
				self["job_progresslabel"].text = ""
				print "[Addon-Manager] downloading " + url
				self.download = self.plugin_download
				self.downloading(True)
				print "[Addon-Manager] [plugin_download] downloading %s to %s" % (url, self.PLUGINlocal)
				self.download = downloadWithProgress(url,self.PLUGINlocal)
				self.download.addProgress(self.plugin_progress)
				self["job_progressbar"].range = 1000

				self.download.start().addCallback(self.plugin_finished)
				self.downloading(True)

	def plugin_progress(self, recvbytes, totalbytes):
		#print "[Addon-Manager] [update_progress] recvbytes=%d, totalbytes=%d" % (recvbytes, totalbytes)
		self["job_progressbar"].value = int(1000*recvbytes/float(totalbytes))
		self["job_progresslabel"].text = "%d of %d kBytes (%.2f%%)" % (recvbytes/1024, totalbytes/1024, 100*recvbytes/float(totalbytes))

	def plugin_failed(self, failure_instance=None, error_message=""):
    # here is an problem, an error was produced! Help me!
		if error_message == "" and failure_instance is not None:
			error_message = failure_instance.getErrorMessage()
		print "[Addon-Manager] [plugin_failed] " + error_message
		if fileExists(self.PLUGINlocal):
			message = "%s %s\n%s" % (_("File Download failed:"), error_message, _("Remove the incomplete file?"))
			self.session.openWithCallback(self.plugin_remove, MessageBox, message, MessageBox.TYPE_YESNO)
		else:
			message = "%s %s" % (_(".PLUGIN Download failed:"),error_message)
			self.session.open(MessageBox, message, MessageBox.TYPE_ERROR)
			self.downloading(False)

#------------ plugin finished ----------------------------------------------

	def plugin_finished(self, string=""):
		ffile = open("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/inst.log", "w")
		ffile.write("gedrueckte Kategorie:" + self.plug)
		ffile.write("\n")
		ffile.close()

		if len(str(self.foundipk)) == 4:
				ffile = open("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/inst.log","a")
				ffile.write("es ist ein Tarfile ")
				ffile.write("\n")
				ffile.close()

		else:
				ffile = open("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/inst.log","a")
				ffile.write("IPK wird entpackt!")
				ffile.write("\n")
				ffile.close()

				self["statusbar"].text = _("Decompressing IPK-File...")
				os.system("cd /tmp/aaf ; ipkg update")

				if config.AddonManager.ungenau.value == 1:
					self.CpString = "cd /tmp/aaf ; ipkg install /tmp/aaf/downfile.sh4.ipk"
					self.session.open(Console, title = _("IPK Installer"), cmdlist = ["%s" % self.CpString], closeOnSuccess = False)
				else:
					os.system("cd /tmp/aaf ; ipkg install /tmp/aaf/downfile.sh4.ipk")

				##os.system("rm -r /tmp/aaf")

		os.system("mkdir /tmp/aaf")
		self["statusbar"].text = _("Installation OK!")
		self.downloading(False)
		#if self.plug == "skins":
		#	self.session.open(SkinSelector)

	def restartGUI(self, answer):
		if answer is True:
			os.system("killall -9 enigma2")

	def errorstop(self, error_message):
		print "[Addon-Manager] An error has occurred: %s" % str(error_message)
		message = ("%s" % error_message)
		#self.session.open(MessageBox, message, MessageBox.TYPE_ERROR)
		self.downloading(False)
		self.close()

	def errorHandler(self, error_message):
		print "[Addon-Manager] An error has occurred: %s" % str(error_message)
		message = "%s %s" % (_(".PLUGIN Download failed:"),error_message)
		self.session.open(MessageBox, message, MessageBox.TYPE_ERROR)
		self.downloading(False)
    # and then we stop the entire process:
		reactor.stop()

	def plugin_remove(self, answer):
		self.downloading(False)
		if answer == True:
			PLUGINfilename =  self.PLUGINlocal
			if fileExists(self.LISTfilename):
				remove(self.LISTfilename)
			if fileExists(PLUGINfilename):
				remove(PLUGINfilename)
		self.switchList(self.LIST_SOURCE)

	def closeCB(self):
		if self.download:
			self.downloading(False)
		else:
			self.close()


#-----------------------------------------------------------------
class AddonConfigScreen(ConfigListScreen,Screen):
    skin = """
        <screen position="{screen.pos}" size="650,400" title="Addon-Manager Setup" >
        <widget name="config" position="40,10" size="570,325" scrollbarMode="showOnDemand" />
        <widget name="buttonred" position="40,360" size="100,40" backgroundColor="red" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
        <widget name="buttongreen" position="160,360" size="100,40" backgroundColor="green" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
        </screen>"""

    def __init__(self, session, args = 0):
        self.session = session
        #switch automatic to current skin
        current_w = getDesktop(0).size().width()
        current_h = getDesktop(0).size().height()
        print "[Addon-Manager] DESKTOPsize is",current_w,current_h
        size_w = 650
        size_h = 400

        # calculate Skin koordinates
        pos_w = (current_w - size_w)/2
        pos_h = (current_h - size_h)/2

        # set Skinvariables
        self.dict = {
				   'screen.size': "%i,%i"%(size_w,size_h),
				   'screen.pos': "%i,%i"%(pos_w,pos_h),
				   }

        self.skin = applySkinVars(AddonConfigScreen.skin,self.dict)
        Screen.__init__(self, session)
        self.list = []
        self.list.append(getConfigListEntry(_("Fontgroesse (10-22, 14=normal)"), config.AddonManager.Schriftart))
        self.list.append(getConfigListEntry(_("Downloadserver waehlen (1=Primary 2=Secondary)"), config.AddonManager.which_server))
        self.list.append(getConfigListEntry(_("Vorschau Einschalten (1=Ein, 0=Aus)"), config.AddonManager.preview_on))
        self.list.append(getConfigListEntry(_("Wartezeit in msec fuer Vorschau"), config.AddonManager.preview_timeout))
        self.list.append(getConfigListEntry(_("Installierte Plugins in Liste anzeigen (1=Ein, 0=Aus)"), config.AddonManager.marker_off))
        self.list.append(getConfigListEntry(_("Installierte Plugins in Liste farbig markieren"), config.AddonManager.marker_on))
        self.list.append(getConfigListEntry(_("Markierungsfarbe (0=rot, 1=gruen, 2=blau)"), config.AddonManager.mark_color))
        self.list.append(getConfigListEntry(_("Installations Konsole am Bildschirm (0=Aus, 1=Ein)"), config.AddonManager.ungenau))

        ConfigListScreen.__init__(self, self.list)
        self["buttonred"] = Label(_("cancel"))
        self["buttongreen"] = Label(_("ok"))
        self["setupActions"] = ActionMap(["SetupActions"],
        {
            "green": self.save,
            "red": self.cancel,
            "save": self.save,
            "cancel": self.cancel,
            "ok": self.save,
        }, -2)

    def save(self):
        global activesource, activenam
        for x in self["config"].list:
			      x[1].save()
        config.save()
        self.showpreview = config.AddonManager.preview_on.value
        self.previewtimeout = config.AddonManager.preview_timeout.value
        self.farbe = config.AddonManager.mark_color.value

        if config.AddonManager.which_server.value == 1:
		        activesource = "http://kati910.aaf-board.info/dbase"
		        activenam = "Primary-Server"
        else:
		        activesource = "http://kati910.aaf-board.info/dbase"
		        activenam = "Secondary-Server"
        #restore()
        self.close()

    def cancel(self):
        print "[Addon-Manager] cancel"
        for x in self["config"].list:
            x[1].cancel()
        self.close(False)


#-----------------------------------------------------------------
class RestoreConfigScreenVU(ConfigListScreen,Screen):

	def __init__(self, session):
		self.session = session
		Screen.__init__(self, session)
		self.skin = RESTORE_CONFIG_SKIN
		self.onShown.append(self.setWindowTitle)

		RestoreYesNo = [('y',_("yes")),('n',_("no"))]
		RestoreNoYes = [('n',_("no")),('y',_("yes"))]

		config.RestoreConfig = ConfigSubsection()
		config.RestoreConfig.settings_on = ConfigSelection(RestoreYesNo)
		config.RestoreConfig.binarys_on = ConfigSelection(RestoreYesNo)
		config.RestoreConfig.camconfig_on = ConfigSelection(RestoreYesNo)
		config.RestoreConfig.plugins_on = ConfigSelection(RestoreNoYes)
		config.RestoreConfig.network_on = ConfigSelection(RestoreYesNo)
		config.RestoreConfig.samba_on = ConfigSelection(RestoreYesNo)
		config.RestoreConfig.bilder_on = ConfigSelection(RestoreYesNo)
		config.RestoreConfig.sonstige_on = ConfigSelection(RestoreYesNo)
		config.RestoreConfig.am_on = ConfigSelection(RestoreNoYes)
		config.RestoreConfig.backup_on = ConfigSelection(RestoreYesNo)

		self.Clist = []
		self.Clist.append(getConfigListEntry(_("Restore Settings"), config.AddonManager2.sett_on))
		self.Clist.append(getConfigListEntry(_("Restore CamConfig"), config.AddonManager2.camconfig_on))
		self.Clist.append(getConfigListEntry(_("Restore Plugins"), config.AddonManager2.plug_on))
		self.Clist.append(getConfigListEntry(_("Restore Binarys"), config.AddonManager2.binarys_on))
		self.Clist.append(getConfigListEntry(_("Restore Netzwerk"), config.AddonManager2.network_on))
		self.Clist.append(getConfigListEntry(_("Restore Samba"), config.AddonManager2.samba_on))
		self.Clist.append(getConfigListEntry(_("Restore Bootbilder"), config.AddonManager2.bilder_on))
		self.Clist.append(getConfigListEntry(_("Restore sonstiges"), config.AddonManager2.sonstige_on))
		self.Clist.append(getConfigListEntry(_("Restore AddonManager"), config.AddonManager2.am_on))
		self.Clist.append(getConfigListEntry(_("mehrere Backup mit Datum zulassen"), config.AddonManager2.backup_on))

		ConfigListScreen.__init__(self, self.Clist)

		self["key_green"] = Label(_("save Settings"))
		self["key_yellow"] = Label(_("Backup"))
		self["key_red"] = Label(_("Restore"))
		infotext = _('this Settings are allways copied in the Flash/USB installation!')
		self["label1"] =  ScrollLabel()
		self["label1"].setText(infotext)

		self["setupActions"] = ActionMap(["OkCancelActions", "DirectionActions", "ColorActions"],
		{
			"green": self.save,
			"save": self.save,
			"red": self.restore,
			"yellow": self.backup,
			"cancel": self.cancel,
			"ok": self.save,
			"left": self.left,
			"right": self.right,
		}, -2)

	def setWindowTitle(self):
		self.setTitle(_("Backup / Restore Config"))

	def left(self):
		ConfigListScreen.keyLeft(self)

	def right(self):
		ConfigListScreen.keyRight(self)

	def save(self):
		for x in self["config"].list:
				x[1].save()
		config.save()
		#config.RestoreConfig.save()
		self.save_settings()
		print "[AddonManager] RestoreConfig save"

	def cancel(self):
		print "[AddonManager] RestoreConfig cancel"
		self.close()

	def backup(self):
		self.CpString = "/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/backup.sh"
		self.session.open(Console, title = _("Backup - Settings"), cmdlist = ["%s" % self.CpString], closeOnSuccess = False)

	def restore(self):
		self.session.open(SelectRestore)

	def save_settings(self):
		ffile = open("/var/etc/restore.cfg", "w")
		ffile.write('settings=' + config.AddonManager2.sett_on.value[0] + '\n' )
		ffile.write('binarys=' + config.AddonManager2.binarys_on.value[0] + '\n')
		ffile.write('camconfig=' + config.AddonManager2.camconfig_on.value[0] + '\n')
		ffile.write('plugins=' + config.AddonManager2.plug_on.value[0] + '\n')
		ffile.write('network=' + config.AddonManager2.network_on.value[0] + '\n')
		ffile.write('samba=' + config.AddonManager2.samba_on.value[0] + '\n')
		ffile.write('bilder=' + config.AddonManager2.bilder_on.value[0] + '\n')
		ffile.write('sonstige=' + config.AddonManager2.sonstige_on.value[0] + '\n')
		ffile.write('addonmanager=' + config.AddonManager2.am_on.value[0] + '\n')
		ffile.write('backup=' + config.AddonManager2.backup_on.value[0] + '\n')
		ffile.close()

#-----------------------------------------------------------------

class SelectRestore(ConfigListScreen,Screen):
	def __init__(self, session):
		font = "Regular;18"
		self.skin = SELECTRESTORE_SKIN
		Screen.__init__(self, session)

		self["actions"] = ActionMap(["OkCancelActions", "DirectionActions", "ColorActions", "MovieSelectionActions"],
		{
			"ok": self.KeyOk,
			"cancel": self.Exit,
			"right": self.rightDown,
			"left": self.leftUp,
			"up": self.up,
			"down": self.down,
			"red": self.delete,
			"green": self.KeyOk
		}, -1)
		self.search()

		if not pathExists(self.currDir):
			self.currDir = "/"

		self.filelist = FileList(self.currTmp, showDirectories = True, isTop = True , useServiceRef = False)
		self["filelist"] = self.filelist

		self["aktion"] = StaticText()
		self["filelist"].show()

	def up(self):
		self["filelist"].up()

	def down(self):
		self["filelist"].down()

	def leftUp(self):
		self["filelist"].pageUp()

	def rightDown(self):
		self["filelist"].pageDown()

	def search(self):
		os.system("rm -r /tmp/back")
		os.system("mkdir -p /tmp/back")
		self.currTmp = "/tmp/back"

		if pathExists("/var/swap"):
			self.currDir = "/var/swap"

		if pathExists("/media/hdd"):
			self.currDir = "/media/hdd"

		if box == "dm8000":
			CpString = "cd " + self.currDir + "; ls -A1d backup_vu* >/tmp/back/test"
			os.system(CpString)
			self.currBox = "backup_vu"
		else:
			CpString = "cd " + self.currDir + "; ls -A1d backup_fortis* >/tmp/back/test"
			os.system(CpString)
			self.currBox = "backup_fortis"

		text = ""
		file = open("/tmp/back/test", "r")
		for line in file:
			text = line.strip()
			CpString = "touch /tmp/back/" + text
			os.system(CpString)
		file.close
		os.system("rm /tmp/back/test")

	def delete(self):
		self.filename = None
		self.filename = self.filelist.getFilename()
		self.filename = self.currDir + "/" + self.filename
		print "[AddonManager] Filename=", self.filename
		message = "%s %s" % (_("\nDieses Backup loeschen?\n"), self.filename)
		if box <> "dm8000":
			evfd.getInstance().vfd_write_string("Delete Backup")
		self.session.openWithCallback(self.delete_now, MessageBox, message, MessageBox.TYPE_YESNO)

	def delete_now(self, answer):
		if answer == True:
			CpString = "rm -r " + self.filename
			os.system(CpString)
			self.search()
			self["filelist"].refresh()

	def KeyOk(self):
		self.filename = None
		self.filename = self.filelist.getFilename()
		self.fullname = self.currDir + "/" + self.filename
		print "[AddonManager] Select-Filename=", self.filename
		self["filelist"].refresh()
		self.CpString = "/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/restore.sh " + self.filename + " boot"
		self.session.open(Console, title = _("Restore - Settings"), cmdlist = ["%s" % self.CpString], closeOnSuccess = False)


	def Exit(self):
		self.close()

# -------------------------------------------------------------------
class FilterPanelList(MenuList):
	def __init__(self, list, font0 = 28, font1 = 16, itemHeight = 60, enableWrapAround = True):
		MenuList.__init__(self, [], False, eListboxPythonMultiContent)
		self.l.setFont(0, gFont("Regular", font0))
		self.l.setFont(1, gFont("Regular", font1))
		self.l.setItemHeight(itemHeight)

# -------------------------------------------------------------------
class FilterPanel(Screen, HelpableScreen):
	def __init__(self, session, Filter):
		self.session = session
		self.skin = """
			<screen name="FilterPanel" position="center,center" size="430,440" title="Filterauswahl" backgroundColor="#252525">
				<widget name="Mlist" position="10,5" size="400,400" zPosition="3" backgroundColor="#252525"  backgroundColorSelected="#565656" scrollbarMode="showOnDemand" />

				<eLabel position="0,410" zPosition="2" size="430,1" backgroundColor="#c1cdc1" />
				<widget source="key_blue" render="Label" position="260,417" zPosition="2" size="200,30" font="Regular;20" valign="center" halign="left" transparent="1" />
				<ePixmap position="200,420" size="36,20" pixmap="skin_default/buttons/key_blue.png" transparent="1" alphatest="on" />
				<widget source="key_red" render="Label" position="80,417" zPosition="2" size="150,30" font="Regular;20" valign="center" halign="left" transparent="1" />
				<ePixmap position="20,420" size="36,20" pixmap="skin_default/buttons/key_red.png" transparent="1" alphatest="on" />

			</screen>"""

		Screen.__init__(self, session)
		self.Mlist = []

		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('bootlogos'), _("bootlogos"), 'bootlogos')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('browsers'), _("browsers"), 'browsers')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('editors'), _("editors"), 'editors')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('emus'), _("emus"), 'emus')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('epg'), _("epg"), 'epg')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('fonts'), _("fonts"), 'fonts')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('games'), _("games"), 'games')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('infos'), _("infos"), 'infos')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('keymaps'), _("keymaps"), 'keymaps')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('mediacenter'), _("mediacenter"), 'mediacenter')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('picons'), _("picons"), 'picons')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('players'), _("players"), 'players')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('radiologos'), _("radiologos"), 'radiologos')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('settings'), _("settings"), 'settings')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('skins'), _("skins"), 'skins')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('spinner'), _("spinner"), 'spinner')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapbrowsers'), _("swapbrowsers"), 'swapbrowsers')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapeditors'), _("swapeditors"), 'swapeditors')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapemus'), _("swapemus"), 'swapemus')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapepg'), _("swapepg"), 'swapepg')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapgames'), _("swapgames"), 'swapgames')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapinfos'), _("swapinfos"), 'swapinfos')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapmediacenter'), _("swapmediacenter"), 'swapmediacenter')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapnetwork'), _("swapnetwork"), 'swapnetwork')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapplayers'), _("swapplayers"), 'swapplayers')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapscreensaver'), _("swapscreensaver"), 'swapscreensaver')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapskins'), _("swapskins"), 'swapskins')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('swapsystem'), _("swapsystem"), 'swapsystem')))
		self.Mlist.append(self.FilterEntryItem((self.FilterEntryComponent('system'), _("system"), 'system')))

		self.onChangedEntry = []
		if (getDesktop(0).size().width() == 1280):
				self["Mlist"] = FilterPanelList([], font0=24, font1=15, itemHeight=40)
		else:
				self["Mlist"] = FilterPanelList([], font0=24, font1=15, itemHeight=50)
		self["Mlist"].l.setList(self.Mlist)
		self["Mlist"].selectionEnabled(1)

		self["key_blue"] = StaticText()
		self["key_blue"].text = _("set Start")
		self["key_red"] = StaticText()
		self["key_red"].text = _("search")

		HelpableScreen.__init__(self)
		self["actions"] = HelpableActionMap(self, "AAFKeyActions",
			{
				"cancel": (self.Exit, "Beenden"),
				"left": (self.left, "Seite hoch"),
				"right": (self.right, "Seite runter"),
				"up": (self.up, "Hoch"),
				"down": (self.down, "Runter"),
				"ok": (self.ok, "OK"),
				"blue": (self.blue, "Blau"),
				"red": (self.virtualKB, "Red"),
			}, -2)

	def up(self):
		self["Mlist"].up()
		self["Mlist"].selectionEnabled(1)

	def down(self):
		self["Mlist"].down()
		self["Mlist"].selectionEnabled(1)

	def left(self):
		self["Mlist"].pageUp()

	def right(self):
		self["Mlist"].pageDown()

	def Exit(self):
		global menu
		menu = "stop"
		self.close()

	def ok(self):
		global menu
		menu = self['Mlist'].l.getCurrentSelection()[0][2]
		self.close()

	def blue(self):
		menu = self['Mlist'].l.getCurrentSelection()[0][2]
		fwrite = open("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/startservice.cfg", "w")
		fwrite.write(menu)
		fwrite.close()
		message = "%s %s" % (_("Dieser Filter wurde als Startfilter gesetzt!\n\n                       "), menu)
		self.session.open( MessageBox, message, MessageBox.TYPE_INFO, timeout=5)


	def FilterEntryComponent(self,file):
		png = LoadPixmap("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/pics/" + file + ".png")
		if png == None:
			png = LoadPixmap("/usr/lib/enigma2/python/Plugins/Extensions/AddonManager/pics/info.png")
		res = (png)
		return res

	def FilterEntryItem(self,entry):
		rot = 16711680
		gruen = 60928
		dgruen = 52480
		drot = 0xf47d19
		mblau = 8900346
		hblau = 11592447
		dblau = 5215437
		weiss = 0xffffff
		orange = 0xf47d19
		grau = 0x565656

		res = [entry]
		#	return (eListboxPythonMultiContent.TYPE_TEXT, pos[0], pos[1], size[0], size[1], font, flags, text, color, color_sel, backcolor, backcolor_sel, border_width, border_color)
		res.append(MultiContentEntryPixmapAlphaTest(pos=(2, 5), size=(100, 50), png=entry[0]))  # png vorn
		res.append(MultiContentEntryText(pos=(150, 15), size=(220, 35), font=0, text=entry[1], color=mblau, color_sel=mblau, backcolor_sel=grau))
		return res

	def virtualKB(self):
			self.search = ""
			self.session.openWithCallback(lambda x : self.VirtualKeyBoardCallback(x, ''), VirtualKeyBoard, title = (_("Suchstring eingeben:")), text = self.search)

	def VirtualKeyBoardCallback(self, callback = None, entry = None):
		global menu
		if callback is not None and len(callback):
			print "[AddonManager] virtual callback",str(callback)
			menu = callback
			self.close()


#-----------------------------------------------------------------

def tryOpen(filename):
	try:
		procFile = open(filename)
	except IOError:
		return ""
	return procFile


def main(session, **kwargs):
   session.open(PLUGINDownload,"/tmp/usb")
