Esempio n. 1
0
 def shutdown(self):
     Log.i("%s" % (self.coherence, ))
     if True:
         Log.w(
             "shutdown is broken... will continue running. please restart enigma2 instead!"
         )
         return
     if self.coherence:
         self._callPlugins(reason=1)
         self.__mediaServerClients = {}
         self.__mediaRendererClients = {}
         self.__mediaDevices = {}
         self.__devices = []
         self.__deferredShutDown = self.coherence.shutdown(force=True)
         self.__deferredShutDown.addCallback(self._onShutdownFinished)
         self._controlPoint.disconnect(
             self._onMediaServerDetected,
             'Coherence.UPnP.ControlPoint.MediaServer.detected')
         self._controlPoint.disconnect(
             self._onMediaServerRemoved,
             'Coherence.UPnP.ControlPoint.MediaServer.removed')
         self._controlPoint.disconnect(
             self._onMediaRendererDetected,
             'Coherence.UPnP.ControlPoint.MediaRenderer.detected')
         self._controlPoint.disconnect(
             self._onMediaRendererRemoved,
             'Coherence.UPnP.ControlPoint.MediaRenderer.removed')
         self._controlPoint.disconnect(
             self._onMediaDeviceDectected,
             'Coherence.UPnP.Device.detection_completed')
         self._controlPoint.disconnect(self._onMediaDeviceRemoved,
                                       'Coherence.UPnP.RootDevice.removed')
         self.coherence = None
         self._controlPoint = None
Esempio n. 2
0
	def play(self):
		Log.i()
		self.setSeekState(self.SEEK_STATE_PLAY, onlyGUI=True)
		self.__delayed_close_timer.stop()
		self.setMetadata()
		if self.shown:
			self.checkSkipShowHideLock()
Esempio n. 3
0
 def handleActiveSource(self, physicalAddress):
     Log.i("%s %s" % (physicalAddress, self._activeSource))
     if physicalAddress == (0xff, 0xff):
         return
     if physicalAddress != self._activeSource:
         self._activeSource = physicalAddress
         self.onActiveSourceChanged()
Esempio n. 4
0
 def reload(self):
     if not fileExists(self.CONFIG_FILE):
         return True
     try:
         with open(self.CONFIG_FILE) as f:
             self._config = {}
             for line in f:
                 Log.i("parsing: %s" % (line, ))
                 if line.startswith("#"):
                     Log.d("skipping comment")
                     continue
                 try:
                     num, data = line.strip().split("=")
                     pairs = data.split(",")
                     tuner_data = {}
                     for pair in pairs:
                         key, value = pair.split(":")
                         tuner_data[key] = value
                     self._config[int(num)] = TunerEntry(tuner_data)
                 except Exception as e:
                     Log.w(e)
                     continue
     except Exception as e:
         Log.w(e)
         return False
     Log.i(self._config)
     return True
Esempio n. 5
0
 def _onSoftwareToolsReady(self, retval=None):
     if retval is None:
         return
     if retval:
         self.recalcNext(iSoftwareTools.lastDownloadDate)
         if iSoftwareTools.available_updates is not 0:
             title = _("There are %s updates available.") % (
                 iSoftwareTools.available_updates, )
             Log.w(title)
             Log.i(iSoftwareTools.available_updatelist)
             Notifications.AddNotificationWithCallback(
                 self._onUpdateAnswer,
                 MessageBox,
                 text=_("Do you want to update now?"),
                 windowTitle=title)
             for fnc in self.onUpdatesAvailable:
                 fnc(iSoftwareTools.available_updates)
         else:
             self._session.toastManager.showToast(
                 _("Your Dreambox software is update to date!"))
             Log.i("There are no updates available.")
     else:
         if iSoftwareTools.NetworkConnectionAvailable:
             Log.w("Package-Feed not available.")
         else:
             Log.w("No network connection available.")
             self._onlineChangedConn = eNetworkManager.getInstance(
             ).onlineChanged.connect(self.onOnlineStateChanged)
Esempio n. 6
0
	def startCmd(self, cmd, args = None):
		self.args = args
		if cmd == self.CMD_UPDATE:
			self.runCmd("update")
			self.update_done = True
		elif cmd == self.CMD_UPGRADE:
			append = ""
			if args["use_maintainer"]:
				append += " --force-maintainer"
			if args["test_only"]:
				append += " -test"
			self.runCmd("upgrade" + append)
		elif cmd == self.CMD_LIST:
			if args['installed_only']:
				self.runCmd("list-installed")
			else:
				self.runCmd("list")
		elif cmd == self.CMD_INSTALL:
			if args['package'].startswith('/'):
				self.preInstCmd = eConsoleAppContainer()
				self.preInstCmd_appClosed_conn = self.preInstCmd.appClosed.connect(self.preInstCmdFinished)
				self.preInstCmd_dataAvail_conn = self.preInstCmd.dataAvail.connect(self.cmdData)
				Log.i("A local package is to be installed: executing apt-get update before doing so")
				self.preInstCmd.execute("apt-get update")
			else:
				self.runCmd("install " + args['package'])
		elif cmd == self.CMD_REMOVE:
			append = ""
			if args["autoremove"]:
				append = "--autoremove "
			self.runCmd("remove " + append + args['package'])
		self.setCurrentCommand(cmd)
Esempio n. 7
0
	def isAuthenticated(self, request):
		self._assignLocalNetworks(iNetworkInfo.getConfiguredInterfaces())
		if request.transport:
			host = IPNetwork(request.transport.getPeer().host)
			#If streamauth is disabled allow all acces from localhost
			if not config.plugins.Webinterface.streamauth.value:
				if self._isLocalHost(host.ip):
					Log.i("Streaming auth is disabled - Bypassing Authcheck because host '%s' is local!" %host)
					return True
			if not config.plugins.Webinterface.localauth.value:
				if self._isLocalClient(host.ip):
					Log.i("Local auth is disabled - Bypassing Authcheck because host '%s' is local!" %host)
					return True

		# get the Session from the Request
		http_session = request.getSession().sessionNamespaces

		# if the auth-information has not yet been stored to the http_session
		if not http_session.has_key('authenticated'):
			if request.getUser() and request.getPassword():
				http_session['authenticated'] = check_passwd(request.getUser(), request.getPassword())
			else:
				http_session['authenticated'] = False

		#if the auth-information already is in the http_session
		else:
			if http_session['authenticated'] is False:
				http_session['authenticated'] = check_passwd(request.getUser(), request.getPassword() )

		#return the current authentication status
		return http_session['authenticated']
Esempio n. 8
0
	def _onUpstreamStateChanged(self, state):
		if state > self._streamServer.UPSTREAM_STATE_WAITING and self._currentService and not self._encoderService:
			Log.i("Upstream running.")
		if state <= self._streamServer.UPSTREAM_STATE_WAITING and self._encoderService:
			Log.i("Upstream idle.")
		for fnc in self.onUpstreamStateChanged:
			fnc(state)
Esempio n. 9
0
	def install(logical, physical):
		Log.i("physical address: %s | logical address: %s" %(physical, logical))
		try:
			with open(CecBoot.UBOOT_SCRIPT_FILE, "w") as f:
				f.write(CecBoot.UBOOT_SCRIPT.format(logical=logical, physical=physical))
		except:
			Log.w("Could not write bootloader script!")
Esempio n. 10
0
	def uninstall():
		Log.i()
		if fileExists(CecBoot.UBOOT_SCRIPT_FILE):
			try:
				remove(CecBoot.UBOOT_SCRIPT_FILE)
			except:
				Log.w("Could not delete CeC u-boot script")
Esempio n. 11
0
	def _listRates(self):
		if self.mode not in config.av.videorate:
			return []

		rateList = sorted(config.av.videorate[self.mode].getChoices(), key=lambda rate: rate[0], reverse=True)
		Log.i(rateList)
		return rateList
Esempio n. 12
0
	def __getInterfaceAttribs(self, iface):
		Log.i(iface)
		attribs = [iface.ethernet.interface, iface.ethernet.mac]
		ip4 = iface.ipv4
		ip6 = iface.ipv6
		if ip4:
			attribs.extend((
				ip4.method,
				ip4.address,
				ip4.netmask,
				ip4.gateway,
			))
		else:
			attribs.extend(["N/A", "N/A", "N/A", "N/A"])

		if ip6:
			attribs.extend((
				ip6.method,
				ip6.address,
				ip6.netmask,
				ip6.gateway,
			))
		else:
			attribs.extend(["N/A", "N/A", "N/A", "N/A"])
		return attribs
        def resolve(self, service, uri):
            Log.i(uri)
            uri = uri.replace('mp_hlsproxy://', '').replace('mp_hlsp://', '')

            def onUrlReady(uri):
                try:
                    if not service.ptrValid():
                        Log.w("Service became invalid!")
                        return
                    if uri:
                        self._bitrate = self._getBandwidth()
                        path = config.mediaportal.storagepath.value
                        ip = "127.0.0.1"  #".".join(str(x) for x in config.mediaportal.hls_proxy_ip.value)
                        import uuid
                        uid = uuid.uuid1()
                        uri = 'http://%s:%d/?url=%s&bitrate=%d&path=%s&uid=%s' % (
                            ip, mp_globals.hls_proxy_port, uri, self._bitrate,
                            path, uid)
                        service.setResolvedUri(uri, eServiceReference.idGST)
                    else:
                        service.failedToResolveUri()
                except:
                    service.failedToResolveUri()

            onUrlReady(uri)

            return True
Esempio n. 14
0
	def _checkPackageRestore(self):
		from Plugins.SystemPlugins.SoftwareManager.SoftwareTools import iSoftwareTools
		bak = self._backupFile
		if not fileExists(bak):
			Log.i("Package backup does not exist... (%s)" %(bak,))
			return

		def doRestore(unused):
			available = []
			for p in iSoftwareTools.available_packetlist:
				available.append(p[0])

			with open(bak) as f:
				packagesAvailable = []
				packagesMissing = []
				for packagename in f:
					packagename = packagename.strip()
					if packagename in available:
						if not iSoftwareTools.installed_packetlist.has_key(packagename):
							packagesAvailable.append(packagename)
							Log.w("%s is NOT installed!" %packagename)
					else:
						packagesMissing.append(packagename)
				if packagesAvailable:
					self._session.open(PackageRestoreWizard, packagesAvailable, packagesMissing)
			self._moveBackupList()
		if iSoftwareTools.installed_packetlist and iSoftwareTools.available_packetlist:
			doRestore(None)
		else:
			def loadInstalled(unused):
				iSoftwareTools.startIpkgListInstalled(callback=doRestore)
			iSoftwareTools.startIpkgListAvailable(loadInstalled)
Esempio n. 15
0
 def _onUpstreamStateChanged(self, state):
     if state > self._streamServer.UPSTREAM_STATE_WAITING and self._currentService and not self._encoderService:
         Log.i("Upstream running.")
     if state <= self._streamServer.UPSTREAM_STATE_WAITING and self._encoderService:
         Log.i("Upstream idle.")
     for fnc in self.onUpstreamStateChanged:
         fnc(state)
Esempio n. 16
0
	def _userInputRequested(self, svcpath):
		Log.i(svcpath)
		dialog_values = self._nm.getUserInputRequestFields()
		for key,value in dialog_values.iteritems():
			Log.i("%s => %s" %(key, value))

		windowTitle = _("Network")
		svc = self._nm.getService(svcpath)
		if svc:
			windowTitle = svc.name()

		prev = dialog_values.get("PreviousPassphrase", None)
		if prev:
			del dialog_values["PreviousPassphrase"]
		#filter WPS until it's fixed
		wps = dialog_values.get("WPS", None)
		if wps:
			del dialog_values["WPS"]

		input_config = []
		if len(dialog_values) > 0:
			for key, value in dialog_values.iteritems():
				input_config.append( self._createInputConfig(key, value, prev) ),
			self._userInputScreen = self.session.openWithCallback(self._onUserMultiInput, MultiInputBox, title=_("Input required"), windowTitle=windowTitle, config=input_config)
		else:
			self._nm.sendUserReply(StringMap()) #Cancel
Esempio n. 17
0
	def __init__(self, *args, **kwargs):
		#we do have http basic auth, so whenever the user manages to load the page he is already authenticated
		self._authenticated = True
		self._failedAuthCount = 0
		self._sessionId = None
		self._requestID = 0
		Log.i("Protocol instance spawned!")
Esempio n. 18
0
		def doStart(*args, **kwargs):
			if self._controlPoint:
				Log.w("already running!")
				return
			Log.i("starting now!")
			self._startPending = False
			self.coherence = Coherence({
				'logging': {
					'level' : 'warning', 
					'subsystem' : [
						{'name' : 'msearch', 'level' : 'warning'},
						{'name' : 'ssdp', 'level' : 'warning'}
					]}
				})
			self._controlPoint = ControlPoint(self.coherence, auto_client=['MediaServer','MediaRenderer'])
			self.coherence.ctrl = self._controlPoint
			self.__mediaServerClients = {}
			self.__mediaRendererClients = {}
			self.__mediaDevices = {}
			self.__devices = []
			self._controlPoint.connect(self._onMediaServerDetected, 'Coherence.UPnP.ControlPoint.MediaServer.detected')
			self._controlPoint.connect(self._onMediaServerRemoved, 'Coherence.UPnP.ControlPoint.MediaServer.removed')
			self._controlPoint.connect(self._onMediaRendererDetected, 'Coherence.UPnP.ControlPoint.MediaRenderer.detected')
			self._controlPoint.connect(self._onMediaRendererRemoved, 'Coherence.UPnP.ControlPoint.MediaRenderer.removed')
			self._controlPoint.connect(self._onMediaDeviceDectected, 'Coherence.UPnP.Device.detection_completed')
			self._controlPoint.connect(self._onMediaDeviceRemoved, 'Coherence.UPnP.RootDevice.removed')
			self.__deferredShutDown = None
			if self._session:
				self._callPlugins(reason=0)
Esempio n. 19
0
 def updateTimezoneDefaults():
     Log.i("%s / %s / %s" % (timezones.defaultRegion, timezones.defaultZone,
                             timezones.defaultCountry))
     config.timezone.region.setChoices(default=timezones.defaultRegion,
                                       choices=timezones.regions)
     zones, defaultZone = getZoneChoices()
     config.timezone.zone.setChoices(default=defaultZone, choices=zones)
Esempio n. 20
0
    def _userInputRequested(self, svcpath):
        Log.i(svcpath)
        dialog_values = self._nm.getUserInputRequestFields()
        for key, value in dialog_values.iteritems():
            Log.i("%s => %s" % (key, value))

        windowTitle = _("Network")
        svc = self._nm.getService(svcpath)
        if svc:
            windowTitle = svc.name()

        prev = dialog_values.get("PreviousPassphrase", None)
        if prev:
            del dialog_values["PreviousPassphrase"]
        #filter WPS until it's fixed
        wps = dialog_values.get("WPS", None)
        if wps:
            del dialog_values["WPS"]

        input_config = []
        if len(dialog_values) > 0:
            for key, value in dialog_values.iteritems():
                input_config.append(self._createInputConfig(key, value, prev)),
            self._userInputScreen = self.session.openWithCallback(
                self._onUserMultiInput,
                MultiInputBox,
                title=_("Input required"),
                windowTitle=windowTitle,
                config=input_config)
        else:
            self._nm.sendUserReply(StringMap())  #Cancel
Esempio n. 21
0
	def isAuthenticated(self, request):
		self._assignLocalNetworks(iNetworkInfo.getConfiguredInterfaces())
		if request.transport:
			host = IPNetwork(request.transport.getPeer().host)
			#If streamauth is disabled allow all acces from localhost
			if not config.plugins.Webinterface.streamauth.value:
				if self._isLocalHost(host.ip):
					Log.i("Streaming auth is disabled - Bypassing Authcheck because host '%s' is local!" %host)
					return True
			if not config.plugins.Webinterface.localauth.value:
				if self._isLocalClient(host.ip):
					Log.i("Local auth is disabled - Bypassing Authcheck because host '%s' is local!" %host)
					return True

		# get the Session from the Request
		http_session = request.getSession().sessionNamespaces

		# if the auth-information has not yet been stored to the http_session
		if not http_session.has_key('authenticated'):
			if request.getUser() and request.getPassword():
				http_session['authenticated'] = check_passwd(request.getUser(), request.getPassword())
			else:
				http_session['authenticated'] = False

		#if the auth-information already is in the http_session
		else:
			if http_session['authenticated'] is False:
				http_session['authenticated'] = check_passwd(request.getUser(), request.getPassword() )

		#return the current authentication status
		return http_session['authenticated']
Esempio n. 22
0
        def resolve(self, service, uri):
            Log.i(uri)
            watch_url = None
            try:
                uri = uri.split("://")[1]
                watch_url = "http://twitch.tv/%s" % (uri, )
            except:
                pass

            def onUrlReady(uri, fmt):
                Log.w("%s (%s)" % (uri, fmt))
                try:
                    if not service.ptrValid():
                        Log.w("Service became invalid!")
                        return
                    if uri:
                        service.setResolvedUri(uri, eServiceReference.idDVB)
                    else:
                        service.failedToResolveUri()
                except:
                    service.failedToResolveUri()

            Log.i(watch_url)
            if watch_url:
                TwitchVideoUrlResolver(watch_url, [onUrlReady], async=True)
            else:
                service.failedToResolveUri()
            return True
Esempio n. 23
0
	def reload(self, force=True):
		self._isReloading = True
		if force:
			self._ipv4Changed = False
			self._ipv6Changed = False
		if not self._ipv6Changed:
			ip4 = self._service.ipv4()
			if not dict(ip4):
				ip6 = self._service.ipv4Config()
			self._config_ip4_method.value = ip4.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF)
			self._config_ip4_address.value = toIP4List( ip4.get("Address", "0.0.0.0") )
			self._config_ip4_mask.value = toIP4List( ip4.get(eNetworkService.KEY_NETMASK, "0.0.0.0") )
			self._config_ip4_gw.value = toIP4List( ip4.get(eNetworkService.KEY_GATEWAY, "0.0.0.0") )
		if not self._ipv6Changed:
			ip6 = self._service.ipv6()
			Log.i("%s / %s" %(dict(ip6), dict(self._service.ipv6Config())) )
			if not dict(ip6):
				ip6 = self._service.ipv6Config()
			self._config_ip6_method.value = ip6.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF)
			self._config_ip6_address.value = ip6.get(eNetworkService.KEY_ADDRESS, "::")
			self._config_ip6_prefix_length.value = ord( ip6.get(eNetworkService.KEY_PREFIX_LENGTH, chr(1)) or chr(1) )
			self._config_ip6_gw.value = ip6.get(eNetworkService.KEY_GATEWAY, "::")
			self._config_ip6_privacy.value = ip6.get(eNetworkService.KEY_PRIVACY, eNetworkService.IPV6_PRIVACY_DISABLED)
		self._isReloading = False
		self._changed(None)
Esempio n. 24
0
	def getActiveDnsText(self):
		nameservers = list(self._service.nameservers())
		text = ""
		if nameservers:
			text = _("Active Nameservers:\n%s") %(", ".join(nameservers))
			Log.i(text)
		return text
Esempio n. 25
0
	def _checkPackageRestore(self):
		from Plugins.SystemPlugins.SoftwareManager.SoftwareTools import iSoftwareTools
		bak = self._backupFile
		if not fileExists(bak):
			Log.i("Package backup does not exist... (%s)" %(bak,))
			return

		def doRestore(unused):
			available = []
			for p in iSoftwareTools.available_packetlist:
				available.append(p[0])

			with open(bak) as f:
				packagesAvailable = []
				packagesMissing = []
				for packagename in f:
					packagename = packagename.strip()
					if packagename in available:
						if packagename not in iSoftwareTools.installed_packetlist:
							packagesAvailable.append(packagename)
							Log.w("%s is NOT installed!" %packagename)
					else:
						packagesMissing.append(packagename)
				if packagesAvailable:
					self._session.open(PackageRestoreWizard, packagesAvailable, packagesMissing)
			self._moveBackupList()
		if iSoftwareTools.installed_packetlist and iSoftwareTools.available_packetlist:
			doRestore(None)
		else:
			def loadInstalled(unused):
				iSoftwareTools.startIpkgListInstalled(callback=doRestore)
			iSoftwareTools.startIpkgListAvailable(loadInstalled)
Esempio n. 26
0
    def get(id=-1, name=None, type=MediaCore.TYPE_AUDIO, create=False):
        # If we'er called with only the name given we'll try to get the id.
        # If we cannot find a matching playlist, we return None
        db = eMediaDatabase.getInstance()
        if id < 0:
            res = db.getPlaylistByName(name, type)
        else:
            res = db.getPlaylist(id)
        if res.error(
        ) or not res.data():  #Playlist unkown (not yet saved/created!)
            Log.w("%s / %s" % (res.errorDatabaseText(), res.errorDriverText()))
            if create:
                Log.i("creating new playlist")
                return DatabasePlaylist.create(name, type)
            else:
                Log.w("Unkown Playlist for id=%s, name=%s and type=%s" %
                      (id, name, type))
                return None

        data = res.data()[0]
        id = int(data[eMediaDatabase.FIELD_ID])
        name = data[eMediaDatabase.FIELD_NAME]
        Log.i("Playlist %s found. Id is %s" % (name, id))
        playlist = DatabasePlaylist(id, name=name, type=type)
        playlist.reload()
        return playlist
 def openMountEdit(self, item):
     if item and item.type != NetworkItem.TYPE_HOST:
         mounts = iAutoMount.getMounts()
         self.sharecache_file = None
         if item.type == NetworkItem.TYPE_NFS:  # share entry selected
             data = iAutoMount.DEFAULT_OPTIONS_NFS
         if item.type == NetworkItem.TYPE_SMB:  # share entry selected
             data = iAutoMount.DEFAULT_OPTIONS_CIFS
             self.sharecache_file = eEnv.resolve(
                 "${sysconfdir}/enigma2/") + item.name.strip(
                 ) + '.cache'  #Path to cache directory
             if os_path.exists(self.sharecache_file):
                 print '[Networkbrowser] Loading userinfo from ', self.sharecache_file
                 try:
                     self.hostdata = load_cache(self.sharecache_file)
                     data['username'] = self.hostdata['username']
                     data['password'] = self.hostdata['password']
                 except:
                     pass
         data['active'] = True
         data['ip'] = item.host
         data['sharename'] = item.name
         data['sharedir'] = item.path
         for sharename, sharedata in mounts.items():
             if sharedata['ip'] == item.host and sharedata[
                     'sharedir'] == item.path:
                 data = sharedata
                 break
         Log.i(data)
         self.session.openWithCallback(self.MountEditClosed, AutoMountEdit,
                                       self.skin_path, data)
Esempio n. 28
0
		def resolve(self, service, uri):
			Log.i(uri)
			watch_url = None
			try:
				uri = uri.split("://")[1]
				watch_url = "http://twitch.tv/%s" %(uri,)
			except:
				pass
			def onUrlReady(uri, fmt):
				Log.w("%s (%s)" %(uri, fmt))
				try:
					if not service.ptrValid():
						Log.w("Service became invalid!")
						return
					if uri:
						service.setResolvedUri(uri, eServiceReference.idDVB)
					else:
						service.failedToResolveUri()
				except:
					service.failedToResolveUri()
			Log.i(watch_url)
			if watch_url:
				TwitchVideoUrlResolver(watch_url, [onUrlReady], async=True)
			else:
				service.failedToResolveUri()
			return True
Esempio n. 29
0
 def addToPlaylist(self, ref, extra=None):
     if ref and ref.valid():
         self._player.addToPlaylist(ref, extra)
         return True
     else:
         Log.i("ERROR: No valid ref!")
         return False
Esempio n. 30
0
 def addCurrentToPlaylist(self, play=False):
     Log.i("called")
     if self.canAddSelected():
         if self._list.canDescend():
             folder = self._list.getSelectedItem()
             if self.addFolderToPlaylist(folder):
                 self.setStatus(self.getItemName(folder))
                 return True
             else:
                 self.setStatus(self.getItemName(folder), error=True)
         else:
             item, itemName, ref, extra = self.getSelectedItemData()
             if not item:
                 self.setStatus(_("Nothing to add..."))
             else:
                 if self._list.isValidType(item):
                     if play:
                         fnc = self.addAndPlay
                     else:
                         fnc = self.addToPlaylist
                     if fnc(ref, extra):
                         self.setStatus(itemName)
                         return True
                     else:
                         self.setStatus(itemName, error=True)
                 else:
                     if self._type == MediaCore.TYPE_AUDIO:
                         self.setStatus(
                             _("Cannot add this file. It's not audio!"),
                             error=True)
                     if self._type == MediaCore.TYPE_VIDEO:
                         self.setStatus(
                             _("Cannot add this file. It's no video!"),
                             error=True)
     return False
Esempio n. 31
0
 def play(self):
     Log.i()
     self.setSeekState(self.SEEK_STATE_PLAY, onlyGUI=True)
     self.__delayed_close_timer.stop()
     self.setMetadata()
     if self.shown:
         self.checkSkipShowHideLock()
Esempio n. 32
0
	def _onUnboundRemoteKeyPressed(self, address, key):
		if key < 2 or key > 11 or key == self._lastUnboundKey:
			return
		self._lastUnboundKey = key
		Log.i("pressed %s on %s" %(key, address))

		# compare device addresses
		device = self._currentInputDevice
		if not device or (address != device.address()):
			self._setPendingPin("")
			Log.w("wrong address! %s" %(address))
			return

		pin = self._pins.get(address, None)
		if pin is None:
			self._setPendingPin("")
			return

		value = { 2 : 1, 3 : 2, 4 : 3, 5 : 4, 6 : 5, 7 : 6, 8 : 7, 9 : 8, 10 : 9, 11: 0 }.get(key, -1)
		pending = self._pendingPin.text.replace("-", "")

		if not pin.startswith(pending):
			self._setPendingPin(str(value))
		else:
			self._setPendingPin("%s%s" %(pending, value))
		if self._pendingPin.text == pin:
			self._pendingPin.text = _("PIN MATCH!")
			self._pins[device.address()] = self._genPin()
			self._connectDevice(device)
Esempio n. 33
0
	def onStandby(self, sender):
		Log.i("%s %s (%s)" %(sender, self.session, config.cec.receivepower.value))
		if not config.cec.receivepower.value:
			return
		if sender == eCec.ADDR_TV and self.session:
			if not Standby.inStandby and self.session.current_dialog and self.session.current_dialog.ALLOW_SUSPEND and self.session.in_exec:
				self.session.open(Standby.Standby)
Esempio n. 34
0
 def getActiveTimeserversText(self):
     timeservers = list(self._nm.getTimeservers())
     text = ""
     if timeservers:
         text = _("Active time servers:\n%s") % (", ".join(timeservers))
         Log.i(text)
     return text
Esempio n. 35
0
	def reload(self):
		self._list = []
		db = eMediaDatabase.getInstance()
		res = None
		if self._id < 0: #no @staticmethod get() used, probably....
			self._valid = False
			self.listChanged()
			Log.w("A Playlist with the name/id %s/%s does not exist!" %(self._name, self._id))
			return

		res = db.getPlaylistItemsById(self._id)
		if res and not res.error():
			for data in res.data():
				data = dict(data)
				file_uri = data.get(eMediaDatabase.FIELD_FILE_URI, None)
				if not file_uri:
					Log.w("Playlist entry invalid, %s" % data)
					continue
				if file_uri.endswith('.ts'):
					ref = eServiceReference(eServiceReference.idDVB, 0, file_uri)
				elif file_uri.endswith('.m2ts'):
					ref = eServiceReference(3, 0, file_uri)
				else:
					ref = eServiceReference(eServiceReference.idGST, 0, file_uri)
				self.add(ref, data, True)
			self._valid = True
		else:
			Log.i("Error loading playlist %s:%s\n%s\n%s" % (self._id, self._name, res.errorDatabaseText(), res.errorDriverText()))
			self._valid = False
		self.listChanged()
Esempio n. 36
0
	def save(self):
		#c-ify
		vector = StringMapVector()
		pos = 1
		for item in self._list:
			item = item[2]
			stringMap = StringMap()
			for k, v in item.iteritems():
				stringMap[k] = str(v)
			stringMap[eMediaDatabase.FIELD_POS] = str(pos)
			pos += 1
			vector.append(stringMap)
		db = eMediaDatabase.getInstance()
		res = db.savePlaylist(self._id, self._name, self._type, vector)
		error = res.error()
		if error:
			Log.w("Error saving playlist %s\n%s\n%s" % (self._id, res.errorDatabaseText(), res.errorDriverText()))
			return not error
		#if self._id <= 0:
		data = res.data()
		self._id = -1
		if data and len(data) > 0:
			self._id = int(res.data()[0].get(eMediaDatabase.FIELD_ID, -1))
		if self._id == -1:
			error = True
		self._valid = not error
		if not error:
			Log.i("Playlist '%s (%s)' saved" %(self._name, self._id))
		else:
			Log.w("Error saving playlist!")
		return not error
		def resolve(self, service, uri):
			Log.i(uri)
			watch_url = None
			try:
				uri = uri.split("://")[1]
				uri = uri.split("/")
				if uri[0] == "live":
					watch_url = "https://youtube.com/user/%s/live" %(uri[1],)
				else:
					video_id = uri[0]
					watch_url = "https://youtube.com/watch?v=%s" % (video_id,)
			except:
				pass
			def onUrlReady(uri, format):
				Log.d("%s (%s)" %(uri, format))
				try:
					if not service.ptrValid():
						Log.w("Service became invalid!")
						return
					if uri:
						if VideoUrlRequest.isHls(format):
							service.setResolvedUri(uri, eServiceReference.idDVB)
						else:
							service.setResolvedUri(uri, eServiceReference.idGST)
					else:
						service.failedToResolveUri()
				except:
					service.failedToResolveUri()
			Log.i(watch_url)
			if watch_url:
				VideoUrlRequest(watch_url, [onUrlReady], async=True)
			else:
				service.failedToResolveUri()
			return True
Esempio n. 38
0
	def reload(self):
		self._list = []
		db = eMediaDatabase.getInstance()
		res = None
		if self._id < 0: #no @staticmethod get() used, probably....
			self._valid = False
			self.listChanged()
			Log.w("A Playlist with the name/id %s/%s does not exist!" %(self._name, self._id))
			return

		res = db.getPlaylistItemsById(self._id)
		if res and not res.error():
			for data in res.data():
				data = dict(data)
				file_uri = data.get(eMediaDatabase.FIELD_FILE_URI, None)
				if not file_uri:
					Log.w("Playlist entry invalid, %s" % data)
					continue
				if file_uri.endswith('.ts'):
					ref = eServiceReference(eServiceReference.idDVB, 0, file_uri)
				elif file_uri.endswith('.m2ts'):
					ref = eServiceReference(3, 0, file_uri)
				else:
					ref = eServiceReference(eServiceReference.idGST, 0, file_uri)
				self.add(ref, data, True)
			self._valid = True
		else:
			Log.i("Error loading playlist %s:%s\n%s\n%s" % (self._id, self._name, res.errorDatabaseText(), res.errorDriverText()))
			self._valid = False
		self.listChanged()
Esempio n. 39
0
	def openMountEdit(self, item):
		if item and item.type != NetworkItem.TYPE_HOST:
			mounts = iAutoMount.getMounts()
			self.sharecache_file = None
			if item.type == NetworkItem.TYPE_NFS: # share entry selected
				data = iAutoMount.DEFAULT_OPTIONS_NFS
			if item.type == NetworkItem.TYPE_SMB: # share entry selected
				data = iAutoMount.DEFAULT_OPTIONS_CIFS
				self.sharecache_file = eEnv.resolve("${sysconfdir}/enigma2/") + item.name.strip() + '.cache' #Path to cache directory
				if os_path.exists(self.sharecache_file):
					print '[Networkbrowser] Loading userinfo from ',self.sharecache_file
					try:
						self.hostdata = load_cache(self.sharecache_file)
						data['username'] = self.hostdata['username']
						data['password'] = self.hostdata['password']
					except:
						pass
			data['active'] = True
			data['ip'] = item.host
			data['sharename'] = item.name
			data['sharedir'] = item.path
			for sharename, sharedata in mounts.items():
				if sharedata['ip'] == item.host and sharedata['sharedir'] == item.path:
					data = sharedata
					break
			Log.i(data)
			self.session.openWithCallback(self.MountEditClosed,AutoMountEdit, self.skin_path, data)
Esempio n. 40
0
    def __getInterfaceAttribs(self, iface):
        Log.i(iface)
        attribs = [iface.ethernet.interface, iface.ethernet.mac]
        ip4 = iface.ipv4
        ip6 = iface.ipv6
        if ip4:
            attribs.extend((
                ip4.method,
                ip4.address,
                ip4.netmask,
                ip4.gateway,
            ))
        else:
            attribs.extend(["N/A", "N/A", "N/A", "N/A"])

        if ip6:
            attribs.extend((
                ip6.method,
                ip6.address,
                ip6.netmask,
                ip6.gateway,
            ))
        else:
            attribs.extend(["N/A", "N/A", "N/A", "N/A"])
        return attribs
Esempio n. 41
0
	def save(self):
		#c-ify
		vector = StringMapVector()
		pos = 1
		for item in self._list:
			item = item[2]
			stringMap = StringMap()
			for k, v in item.iteritems():
				stringMap[k] = str(v)
			stringMap[eMediaDatabase.FIELD_POS] = str(pos)
			pos += 1
			vector.append(stringMap)
		db = eMediaDatabase.getInstance()
		res = db.savePlaylist(self._id, self._name, self._type, vector)
		error = res.error()
		if error:
			Log.w("Error saving playlist %s\n%s\n%s" % (self._id, res.errorDatabaseText(), res.errorDriverText()))
			return not error
		#if self._id <= 0:
		data = res.data()
		self._id = -1
		if data and len(data) > 0:
			self._id = int(res.data()[0].get(eMediaDatabase.FIELD_ID, -1))
		if self._id == -1:
			error = True
		self._valid = not error
		if not error:
			Log.i("Playlist '%s (%s)' saved" %(self._name, self._id))
		else:
			Log.w("Error saving playlist!")
		return not error
Esempio n. 42
0
	def _applyShare(self, data, callback):
		Log.i("activeMounts: %s" %(self._numActive,))
		if data['active']:
			mountpoint = AutoMount.MOUNT_BASE + data['sharename']
			if os_path.exists(mountpoint) is False:
				createDir(mountpoint)
			tmpsharedir = data['sharedir'].replace(" ", "\\ ").replace("$", "\\$")

			if data['mounttype'] == 'nfs':
				opts = self.sanitizeOptions(data['options'].split(','))
				remote = '%s:/%s' % (data['ip'], tmpsharedir)
				harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="nfs")

			elif data['mounttype'] == 'cifs':
				opts = self.sanitizeOptions(data['options'].split(','), cifs=True)
				password = data['password']
				username = data['username'].replace(" ", "\\ ")
				if password:
					username = data['username'].replace(" ", "\\ ")
					opts.extend([
						'username=%s' % (data['username']),
						'password=%s' % (data['password']),
						])
				else:
					opts.extend(['guest'])
				opts.extend(['sec=ntlmv2'])
				remote = "//%s/%s" % (data['ip'], tmpsharedir)
				harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="cifs")
		else:
			mountpoint = AutoMount.MOUNT_BASE + data['sharename']
			self.removeMount(mountpoint)
		if callback:
			callback(True)
Esempio n. 43
0
 def reload(self, force=True):
     self._isReloading = True
     if force:
         self._ipv4Changed = False
         self._ipv6Changed = False
     if not self._ipv6Changed:
         ip4 = self._service.ipv4()
         if not dict(ip4):
             ip6 = self._service.ipv4Config()
         self._config_ip4_method.value = ip4.get(eNetworkService.KEY_METHOD,
                                                 eNetworkService.METHOD_OFF)
         self._config_ip4_address.value = toIP4List(
             ip4.get("Address", "0.0.0.0"))
         self._config_ip4_mask.value = toIP4List(
             ip4.get(eNetworkService.KEY_NETMASK, "0.0.0.0"))
         self._config_ip4_gw.value = toIP4List(
             ip4.get(eNetworkService.KEY_GATEWAY, "0.0.0.0"))
     if not self._ipv6Changed:
         ip6 = self._service.ipv6()
         Log.i("%s / %s" % (dict(ip6), dict(self._service.ipv6Config())))
         if not dict(ip6):
             ip6 = self._service.ipv6Config()
         self._config_ip6_method.value = ip6.get(eNetworkService.KEY_METHOD,
                                                 eNetworkService.METHOD_OFF)
         self._config_ip6_address.value = ip6.get(
             eNetworkService.KEY_ADDRESS, "::")
         self._config_ip6_prefix_length.value = ord(
             ip6.get(eNetworkService.KEY_PREFIX_LENGTH, chr(1)) or chr(1))
         self._config_ip6_gw.value = ip6.get(eNetworkService.KEY_GATEWAY,
                                             "::")
         self._config_ip6_privacy.value = ip6.get(
             eNetworkService.KEY_PRIVACY,
             eNetworkService.IPV6_PRIVACY_DISABLED)
     self._isReloading = False
     self._changed(None)
Esempio n. 44
0
def StreamServerControl__onUriParametersChanged(parameters):
    self = streamServerControl

    Log.i("%s" % (parameters))
    params = parse_qs(parameters)

    print "[StreamserverSeek] Old params: %s" % params
    self._seekToMin = 0
    if int(self.config.streamserver.source.value
           ) == eStreamServer.INPUT_MODE_BACKGROUND:
        ts = False
        if "ts" in params:
            ts = params.get("ts", [False])[0]
            del params["ts"]
        self._seekToMin = 0
        min = 0
        if "min" in params:
            tmp = params.get("min", [False])[0]
            if "min" in params:
                del params["min"]
            try:
                min = int(tmp)
            except Exception, e:
                pass
        if ts and os.path.isfile(ts):
            params["ref"] = ["1:0:0:0:0:0:0:0:0:0:" + urllib.quote(ts)]
            if min and min > 0:
                self._seekToMin = min
                print "[StreamserverSeek] Will seek to %d minutes" % self._seekToMin
        print "[StreamserverSeek] New params: %s" % params
Esempio n. 45
0
	def reload(self):
		if not fileExists(self.CONFIG_FILE):
			return True
		try:
			with open(self.CONFIG_FILE) as f:
				self._config = {}
				for line in f:
					Log.i("parsing: %s" % (line,))
					if line.startswith("#"):
						Log.d("skipping comment")
						continue
					try:
						num, data = line.strip().split("=")
						pairs = data.split(",")
						tuner_data = {}
						for pair in pairs:
							key, value = pair.split(":")
							tuner_data[key] = value
						self._config[int(num)] = TunerEntry(tuner_data)
					except Exception as e:
						Log.w(e)
						continue
		except Exception as e:
			Log.w(e)
			return False
		Log.i(self._config)
		return True
Esempio n. 46
0
	def _openGUI(self):
		if self.mimetype is None:
			self.mimetype = "video/mpeg"

		#picture are using the picviewer plugin
		if self.mimetype.startswith("image"):
			self.showPicture()
		else:#video or audio
			self._isPic = False
			if self._picView is not None:
				self._picView.close()

		#audio & video
		if not self._oldService:
			self._oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		if self.mimetype.startswith('audio'):
			if self._audioGUI == None:
				Log.i("Starting AudioGUI")
				self._audioGUI = self.session.open(AudioGUI, self)
				self._audioGUI.onClose.append(self._reset)
				self._currentGui = self._audioGUI
			return self._audioGUI
		elif self.mimetype.startswith('video'):
		#if True:
			if self._videoGUI == None:
				Log.i("Starting VideoGUI")
				self._videoGUI = self.session.open(VideoGUI, self)
				self._videoGUI.onClose.append(self._reset)
				self._currentGui = self._videoGUI
			return self._videoGUI
Esempio n. 47
0
	def _applyShare(self, data, callback):
		Log.d()
		if data['active']:
			mountpoint = AutoMount.MOUNT_BASE + data['sharename']
			Log.i("mountpoint: %s" %(mountpoint,))
			createDir(mountpoint)
			tmpsharedir = data['sharedir'].replace(" ", "\\040")

			if data['mounttype'] == 'nfs':
				opts = self.sanitizeOptions(data['options'].split(','))
				remote = '%s:%s' % (data['ip'], tmpsharedir)
				harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="nfs")

			elif data['mounttype'] == 'cifs':
				opts = self.sanitizeOptions(data['options'].split(','), cifs=True)
				if data['password']:
					opts.extend([
						'username=%s' % (data['username']),
						'password=%s' % (data['password']),
						])
				else:
					opts.extend(['guest'])
				remote = "//%s/%s" % (data['ip'], tmpsharedir)
				harddiskmanager.modifyFstabEntry(remote, mountpoint, mode="add_deactivated", extopts=opts, fstype="cifs")
		else:
			mountpoint = AutoMount.MOUNT_BASE + data['sharename']
			self.removeMount(mountpoint)
		if callback:
			callback(True)
Esempio n. 48
0
	def addToPlaylist(self, ref, extra=None):
		if ref and ref.valid():
			self._player.addToPlaylist(ref, extra)
			return True
		else:
			Log.i("ERROR: No valid ref!")
			return False
Esempio n. 49
0
	def addCurrentToPlaylist(self, play=False):
		Log.i("called")
		if self.canAddSelected():
			if self._list.canDescend():
				folder = self._list.getSelectedItem()
				if self.addFolderToPlaylist(folder):
					self.setStatus(self.getItemName(folder))
					return True
				else:
					self.setStatus(self.getItemName(folder), error=True)
			else:
				item, itemName, ref, extra = self.getSelectedItemData()
				if not item:
					self.setStatus(_("Nothing to add..."))
				else:
					if self._list.isValidType(item):
						if play:
							fnc = self.addAndPlay
						else:
							fnc = self.addToPlaylist
						if fnc(ref, extra):
							self.setStatus(itemName)
							return True
						else:
							self.setStatus(itemName, error=True)
					else:
						if self._type == MediaCore.TYPE_AUDIO:
							self.setStatus(_("Cannot add this file. It's not audio!"), error=True)
						if self._type == MediaCore.TYPE_VIDEO:
							self.setStatus(_("Cannot add this file. It's no video!"), error=True)
		return False
Esempio n. 50
0
        def resolve(self, service, uri):
            Log.i(uri)
            uri = uri.replace('mp_euronews://', '').lower().strip()
            if uri == 'en':
                uri = 'www'
            uri = "https://%s.euronews.com/api/watchlive.json" % uri

            def onUrlReady(uri):
                try:
                    if not service.ptrValid():
                        Log.w("Service became invalid!")
                        return
                    if uri:
                        service.setResolvedUri(uri, eServiceReference.idGST)
                    else:
                        service.failedToResolveUri()
                except:
                    service.failedToResolveUri()

            if uri:
                twAgentGetPage(uri).addCallback(self.parseLive, service)
            else:
                service.failedToResolveUri()

            return True
Esempio n. 51
0
    def _openGUI(self):
        if self.mimetype is None:
            self.mimetype = "video/mpeg"

        #picture are using the picviewer plugin
        if self.mimetype.startswith("image"):
            self.showPicture()
        else:  #video or audio
            self._isPic = False
            if self._picView is not None:
                self._picView.close()

        #audio & video
        if not self._oldService:
            self._oldService = self.session.nav.getCurrentlyPlayingServiceReference(
            )
        if self.mimetype.startswith('audio'):
            if self._audioGUI == None:
                Log.i("Starting AudioGUI")
                self._audioGUI = self.session.open(AudioGUI, self)
                self._audioGUI.onClose.append(self._reset)
                self._currentGui = self._audioGUI
            return self._audioGUI
        elif self.mimetype.startswith('video'):
            #if True:
            if self._videoGUI == None:
                Log.i("Starting VideoGUI")
                self._videoGUI = self.session.open(VideoGUI, self)
                self._videoGUI.onClose.append(self._reset)
                self._currentGui = self._videoGUI
            return self._videoGUI
Esempio n. 52
0
 def getActiveDnsText(self):
     nameservers = list(self._service.nameservers())
     text = ""
     if nameservers:
         text = _("Active name servers:\n%s") % (", ".join(nameservers))
         Log.i(text)
     return text
Esempio n. 53
0
	def _countTuner(self, tunerEntry):
		if not tunerEntry.ipAddress in self._check_count_lut:
			self._check_count_lut[tunerEntry.ipAddress] = {}
		host_entry = self._check_count_lut[tunerEntry.ipAddress]
		if not tunerEntry.tunerType in host_entry:
			host_entry[tunerEntry.tunerType] = 0
		host_entry[tunerEntry.tunerType] += 1
		Log.i("tuner count for %s is now %s" % (tunerEntry, host_entry[tunerEntry.tunerType]))
Esempio n. 54
0
	def addAndPlay(self, ref, extra=None):
		if ref and ref.valid():
			self._player.addAndPlay(ref, extra)
		else:
			Log.i("ERROR: No valid ref!")
			return False
		self._close()
		return True
Esempio n. 55
0
	def getService(self):
		Log.i("self._playing=%s" % self._playing)
		if self._playing >= 0 and len(self.list) > self._playing:
			service = self._list[self._playing][0]
			if service:
				return service
		Log.w("NO SERVICE!")
		return None
Esempio n. 56
0
	def playPrev(self):
		if self.getPrevServiceCB != None:
			newservice = self.getPrevServiceCB()
			Log.i("newservice is %s" % newservice)
			if newservice:
				self.playService(newservice)

		self.leavePlayerConfirmed([True, "quit"])
Esempio n. 57
0
	def setVideoWindow(self, x, y, w, h):
		w = self._adjustVideoLimits(w, 128, 1280)
		h = self._adjustVideoLimits(h, 72, 720)
		x = self._adjustVideoLimits(x, 0, 1280)
		y = self._adjustVideoLimits(y, 0, 720)

		Log.i("x=%s, y=%s, w=%s, h=%s" % (x, y, w, h))
		self.scaleRect(eRect(x, y, w, h), self._doSetVideoWindow)
Esempio n. 58
0
	def seek(self, position):
		Log.i("position=%s" %position)
		self.stopPolling() #don't send a new position until we're done seeking
		seekable = self.getSeekable()
		if seekable != None:
			seekable.seekTo( long(int(position) * 90000) )

		self.startPolling() #start sending position again
Esempio n. 59
0
 def getInterface(self):
     ifaces = iNetworkInfo.getConfiguredInterfaces()
     Log.i(ifaces)
     for key in ifaces.iterkeys():
         iface = ifaces[key]
         if iface.ethernet.interface == self.iface:
             return self.__getInterfaceAttribs(iface)
     return ["N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A"]