Example #1
0
    def _parse(self, tree, types, defaults):
        def setFromTag(parent, key, data, bool=False):
            elements = parent.findall(key)
            if len(elements):
                val = elements[0].text
                if bool:
                    val = val == "True"
                if val != None:
                    data[key] = val

        keys = [
            'active', 'hdd_replacement', 'ip', 'sharedir', 'sharename',
            'options', 'username', 'password'
        ]
        bool_keys = ['active', 'hdd_replacement']
        for i in range(0, len(types)):
            mounttype = types[i]
            for parent in tree.findall(mounttype):
                for mount in parent.findall("mount"):
                    data = deepcopy(defaults[i])
                    try:
                        for key in keys:
                            setFromTag(mount, key, data, key in bool_keys)
                        Log.d("%s share %s" % (
                            mounttype.upper(),
                            data,
                        ))
                        if data["active"]:
                            self._numActive += 1
                        self._mounts[data['sharename']] = data
                    except Exception, e:
                        Log.w("Error reading %s share: %s" %
                              (mounttype.upper(), e))
Example #2
0
	def _onUrlReady(self, url, format, *args):
		Log.d(url)
		if url:
			self._url = url
			self._format = format
		else:
			self._url = "broken..."
Example #3
0
 def _onPixmapReady(self, picInfo=None):
     Log.d(picInfo)
     self._picInfo = picInfo
     self._nextPixmap = self._picload.getData()
     if self._immediateShow:
         self._immediateShow = False
         self._onTimeout()
Example #4
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)
Example #5
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)
Example #6
0
 def _onUrlReady(self, url, fmt, suburi=None, *args):
     Log.d(url)
     if url:
         self._url = url
         self._format = fmt
     else:
         self._url = "broken..."
Example #7
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
Example #8
0
	def _parse(self, tree, types, defaults):
		def setFromTag(parent, key, data, bool=False):
			elements = parent.findall(key)
			if len(elements):
					val = elements[0].text
					if bool:
						val = val == "True"
					if val != None:
						data[key] = val

		keys = ['active', 'hdd_replacement', 'ip', 'sharedir', 'sharename', 'options', 'username', 'password']
		bool_keys = ['active', 'hdd_replacement']
		for i in range(0, len(types)):
			mounttype = types[i]
			for parent in tree.findall(mounttype):
				for mount in parent.findall("mount"):
					data = deepcopy(defaults[i])
					try:
						for key in keys:
							setFromTag(mount, key, data, key in bool_keys)
						Log.d("%s share %s" %(mounttype.upper(), data,))
						if data["active"]:
							self._numActive += 1
						#Workaround for nfs shares previously being saved without their leading /
						if mounttype == "nfs" and not data['sharedir'].startswith("/"):
							data['sharedir'] = "/%s" %(data['sharedir'],)
						self._mounts[data['sharename']] = data
					except Exception, e:
						Log.w("Error reading %s share: %s" %(mounttype.upper(), e))
Example #9
0
	def onMessage(self, payload, isBinary):
		if isBinary:
			Log.w("Binary message received: {0} bytes".format(len(payload)))
		else:
			msg = json.loads(payload, 'utf8')
			Log.d("> %s" % (msg))
			self.onJSONMessage(msg)
Example #10
0
	def sendJSON(self, msg):
		if not msg.has_key("id"):
			self._requestID += 1
			msg['id'] = self._requestID
		msg = json.dumps(msg).encode('utf8')
		Log.d("< %s" % (msg))
		self.sendMessage(msg)
	def _onPixmapReady(self, picInfo=None):
		Log.d(picInfo)
		self._picInfo = picInfo
		self._nextPixmap = self._picload.getData()
		if self._immediateShow:
			self._immediateShow = False
			self._onTimeout()
Example #12
0
    def __getInterfaceAttribs(self, iface):
        Log.d(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
Example #13
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
Example #14
0
	def _onCredentialsPollBodyReady(self, body):
		if self._canceled:
			Log.d("Auth Request canceled")
			return
		result = json.loads(body)
		error = result.get("error", None)
		if error:
			if error == "authorization_pending":
				print "not ready, yet"
				reactor.callLater(self._user_code.interval, self._pollForResult)
			elif error == "slow_down":
				print "too fast, slowing down"
				self._device_code.interval = self._device_code.interval * 2
			elif error == "expired_token":
				self._onError(self.ERROR_CREDENTIALS_REQUEST_EXPIRED)
			else:
				print result
				self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error)
		elif "access_token" in result:
			access_token = result.get("access_token")
			refresh_token = result.get("refresh_token")
			token_expiry = str( int(time()) + int(result.get("expires_in")) )
			self._credentials = OAuth2Credentials(access_token, self.CLIENT_ID, self.CLIENT_SECRET, refresh_token, token_expiry, self.AUTH_REQUEST_URI, self.USER_AGENT)
			for fnc in self.onCredentialsReady:
				fnc(self._credentials)
		else:
			self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, error)
Example #15
0
 def updateSummary(self):
     if not self._currentStep:
         return
     self.summaries.setTitle(self._currentStep.title)
     summaryText = self._currentStep.text
     if isinstance(self._currentStep, SetupListStep):
         current = self.list.current
         if current:
             style = self.list.style
             Log.d("%s - %s" % (current, style))
             if style in ("default", "iconized"):
                 summaryText = current[1]
             elif style == "networkservice":
                 summaryText = current[1].name()
             elif style == "inputdevice":
                 deviceName = current[1].name() or current[1].shortName(
                 ) or _("DM Remote")
                 summaryText = "%s (%s)" % (deviceName,
                                            current[1].address())
         else:
             summaryText = _("n/A")
     elif isinstance(self._currentStep, SetupConfigStep):
         current = self.configList.current
         summaryText = (current and "%s\n%s" %
                        (current[0], _(current[1].getText()))) or _("n/A")
     Log.d("%s" % (summaryText, ))
     self.summaries.setText(summaryText)
Example #16
0
	def search(self, searchTerm=None, startIndex=1, maxResults=50,
					orderby=Search.ORDER_RELEVANCE, time='all_time',
					lr="", categories="", relatedToVideoId=None,
					safeSearch=Search.SAFE_SEARCH_NONE, channelId=None,
					callback=None):
		Log.d()
		self._currentQuery = Search(self._youtube)
		return self._currentQuery.list(callback, searchTerm=searchTerm, order=orderby, maxResults=maxResults, relatedToVideoId=relatedToVideoId, channelId=channelId, safeSearch=safeSearch)
Example #17
0
	def _onStandby(self, element):
		Log.d()
		from Screens.Standby import inStandby
		inStandby.onClose.append(self._onLeaveStandby)
		if self.config.streamserver.source.value == str(eStreamServer.INPUT_MODE_LIVE) and self.config.streamserver.mediator.enabled.value:
			Log.i("Going into Standby, mode is Follow Live, stopping proxy stream")
			self._mediatorStateBeforeStandby = self.config.streamserver.mediator.enabled.value
			self.config.streamserver.mediator.enabled.value = False
Example #18
0
 def _onLeaveStandby(self):
     Log.d()
     if config.streamserver.source.value == str(
             self.INPUT_MODE_LIVE) and self._mediatorStateBeforeStandby:
         Log.i(
             "Leaving Standby, mode is Follow live, recovering upload state=%s"
             % (self._mediatorStateBeforeStandby, ))
         config.streamserver.mediator.enabled.value = self._mediatorStateBeforeStandby
Example #19
0
	def _onRequestBodyError(self, failure):
		if self._canceled:
			Log.d("Auth Request canceled")
			return
		if isinstance(failure.value, PartialDownloadError):
			self._onRequestBodyReady(failure.value.response)
		else:
			self._onError(self.ERROR_AUTH_REQUEST, str(failure))
Example #20
0
	def _onStandby(self, element):
		Log.d()
		from Screens.Standby import inStandby
		inStandby.onClose.append(self._onLeaveStandby)
		if self.config.streamserver.source.value == str(eStreamServer.INPUT_MODE_LIVE) and self.config.streamserver.mediator.enabled.value:
			Log.i("Going into Standby, mode is Follow Live, stopping proxy stream")
			self._mediatorStateBeforeStandby = self.config.streamserver.mediator.enabled.value
			self.config.streamserver.mediator.enabled.value = False
Example #21
0
	def _onCredentialsPollBodyError(self, failure):
		if self._canceled:
			Log.d("Auth Request canceled")
			return
		if isinstance(failure.value, PartialDownloadError):
			self._onCredentialsPollBodyReady(failure.value.response)
		else:
			self._onError(self.ERROR_CREDENTIALS_REQUEST_PARSE, str(failure))
Example #22
0
    def getList(self):
        lst = []
        ifaces = iNetworkInfo.getConfiguredInterfaces()
        Log.d(ifaces)
        for key in ifaces.iterkeys():
            iface = ifaces[key]
            lst.append(self.__getInterfaceAttribs(iface))

        return lst
Example #23
0
 def calcRssi(self, base, min_rssi, max_rssi, val):
     factor = float(base) / abs(min_rssi - max_rssi)
     if val < min_rssi:
         val = min_rssi
     if val > max_rssi:
         val = max_rssi
     val = int((val - min_rssi) * factor)
     Log.d(val)
     return val
 def sendSystemAudioKey(self, keyid):
     if keyid not in self.SYSTEM_AUDIO_KEYS:
         return
     keyid = self.KEY_MAP_SEND[keyid]
     if keyid == self._lastKey and not self._isRepeatAllowed():
         Log.d("skipping keypress for %s to honor minimum delay" % keyid)
         return
     self._keyPressed(keyid)
     self._cec.sendSystemAudioKey(keyid)
Example #25
0
	def _nextForCache(self):
		self._currentEntry += 1
		if self._currentEntry > self._endEntry:
			return

		if self._currentEntry < len(self._items):
			item = self._items[self._currentEntry][0]
			Log.d(item.preview)
			self._loadPixmapForCache(self._currentEntry, item.preview)
 def _onSharesApplied(self):
     Log.d()
     for sharename, data in self._mounts.items():
         mountpoint = AutoMount.MOUNT_BASE + sharename
         data['isMounted'] = True
         desc = data['sharename']
         if data['hdd_replacement']:  #hdd replacement hack
             self._linkAsHdd(mountpoint)
         harddiskmanager.addMountedPartition(mountpoint, desc)
Example #27
0
	def sendSystemAudioKey(self, keyid):
		if keyid not in self.SYSTEM_AUDIO_KEYS:
			return
		keyid = self.KEY_MAP_SEND[keyid]
		if keyid == self._lastKey and not self._isRepeatAllowed():
			Log.d("skipping keypress for %s to honor minimum delay" %keyid)
			return
		self._keyPressed(keyid)
		hdmi_cec.sendSystemAudioKey(keyid)
Example #28
0
	def _onSharesApplied(self):
		Log.d()
		for sharename, data in self._mounts.items():
			mountpoint = AutoMount.MOUNT_BASE + sharename
			data['isMounted'] = True
			desc = data['sharename']
			if data['hdd_replacement']: #hdd replacement hack
				self._linkAsHdd(mountpoint)
			harddiskmanager.addMountedPartition(mountpoint, desc)
Example #29
0
    def moveToChar(self, char):
        Log.d("Next char: %s" % (char, ))
        index = self.l.getNextBeginningWithChar(char)
        indexup = self.l.getNextBeginningWithChar(char.upper())
        if indexup != 0:
            if (index > indexup or index == 0):
                index = indexup

        self.instance.moveSelectionTo(index)
        Log.i("Moving to character %s" % (char, ))
	def _onPixmapReady(self, picInfo=None):
		Log.d(picInfo)
		if not self._isEnabled:
			self._reset()
			return
		self._picInfo = picInfo
		self._nextPixmap = self._picload.getData()
		if self._immediateShow:
			self._immediateShow = False
			self._onTimeout()
 def sendKey(self, dest, keyid, translate=False):
     if translate:
         if keyid not in self.KEY_MAP_SEND:
             return
         keyid = self.KEY_MAP_SEND[keyid]
     if keyid == self._lastKey and not self._isRepeatAllowed():
         Log.d("skipping keypress for %s to honor minimum delay" % keyid)
         return
     self._keyPressed(keyid)
     self._cec.sendKey(dest, keyid)
Example #32
0
	def sendKey(self, dest, keyid, translate=False):
		if translate:
			if not keyid in self.KEY_MAP_SEND.keys():
				return
			keyid = self.KEY_MAP_SEND[keyid]
		if keyid == self._lastKey and not self._isRepeatAllowed():
			Log.d("skipping keypress for %s to honor minimum delay" %keyid)
			return
		self._keyPressed(keyid)
		hdmi_cec.sendKey(dest, keyid)
Example #33
0
	def moveToChar(self, char):
		Log.d("Next char: %s" %(char,))
		index = self.l.getNextBeginningWithChar(char)
		indexup = self.l.getNextBeginningWithChar(char.upper())
		if indexup != 0:
			if (index > indexup or index == 0):
				index = indexup

		self.instance.moveSelectionTo(index)
		Log.i("Moving to character %s" %(char,))
Example #34
0
 def applySkin(self, desktop, parent):
     if self.skinAttributes is None:
         return False
     for (attrib, value) in self.skinAttributes:
         if attrib == "seperation" or attrib == "separation":
             Log.d("separation=%i" % (int(value), ))
             self.l.setSeparation(int(value))
         elif attrib == "dividerHeight":
             Log.d("dividerHeight=%i" % (int(value), ))
             self.l.setDividerHeight(int(value))
     return GUIComponent.applySkin(self, desktop, parent)
Example #35
0
	def _onConsoleFinished(self, *args):
		kwargs = {}
		if len(args) > 2:
			kw = args[2]
			if isinstance(kw, dict):
				kwargs = kw
		Log.d("args=%s\nkwargs=%s" %(args, kwargs))
		callback = kwargs.get('callback', None)
		if callback:
			args = kwargs.get('args', [])
			callback(*args)
Example #36
0
 def _onConsoleFinished(self, *args):
     kwargs = {}
     if len(args) > 2:
         kw = args[2]
         if isinstance(kw, dict):
             kwargs = kw
     Log.d("args=%s\nkwargs=%s" % (args, kwargs))
     callback = kwargs.get('callback', None)
     if callback:
         args = kwargs.get('args', [])
         callback(*args)
Example #37
0
 def getInterface(self):
     ifaces = iNetworkInfo.getConfiguredInterfaces()
     Log.d(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"
     ]
Example #38
0
 def _onGenreServicesReady(self, genre, result={}, isFinished=True):
     Log.d("Got new services for genre %s" % (genre.name, ))
     for service in result:
         svc = StalkerService(service)
         genre.services[svc.id] = svc
         self._allServices[svc.id] = svc
     for fnc in self.onGenreServices:
         fnc(genre)
     if isFinished:
         Log.i("%s services total for genre %s" %
               (len(genre.services), genre.name))
         self._loadNextGenre()
			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()
Example #40
0
 def bodyCB(body):
     if isinstance(body, Failure):
         if isinstance(body.value, PartialDownloadError):
             body = body.value.response
         else:
             Log.w(body)
             callback(None)
             return
     try:
         result = json.loads(unicode(body))
         Log.d(result)
         callback(result)
     except Exception as e:
         Log.w(body)
         callback(None)
			def onUrlReady(uri, format, suburi=""):
				Log.d("%s # %s (%s)" %(uri, suburi, format))
				try:
					if not service.ptrValid():
						Log.w("Service became invalid!")
						return
					if uri:
						try:
							service.setResolvedUri(uri, eServiceReference.idGST, suburi or "")
						except:
							service.setResolvedUri(uri, eServiceReference.idGST)
					else:
						service.failedToResolveUri()
				except:
					service.failedToResolveUri()
Example #42
0
	def _onEvent(self, evt):
		self._instantiateSaver()
		if not (self._enabled and config.plugins.screensaver.enabled.value):
			self._screenSaver.enabled = False
			return
		if evt == iPlayableService.evPlay:
			Log.i("play event, checking for video")
			service = self.session.nav.getCurrentService()
			info = service and service.info()
			if not info:
				return
			width = info.getInfo(iServiceInformation.sVideoWidth)
			Log.d(width)
			self._screenSaver.enabled = width <= 0
		elif evt in (iPlayableService.evStopped, iPlayableService.evPause):
			self._screenSaver.enabled = True
Example #43
0
	def _pollForResult(self):
		if self._canceled:
			Log.d("Auth Request canceled")
			return
		if self._user_code.expired():
			self._onError(self.ERROR_CREDENTIALS_REQUEST_EXPIRED)
			return
		d = self._agent.request(
			'POST',
			self.AUTH_RESPONSE_URI,
			Headers({
				'User-Agent' : [self.USER_AGENT],
				'Content-Type' : ["application/x-www-form-urlencoded"],
			}),
			StringProducer("client_id=%s&client_secret=%s&code=%s&grant_type=%s" % (self.CLIENT_ID, self.CLIENT_SECRET, str(self._user_code.device_code), self.GRANT_TYPE_DEVICE_AUTH))
		)
		d.addCallbacks(self._onCredentialsPollResponse, self._onCredentialsPollError)
		self._responseDeferred = d
		return d;
Example #44
0
	def _onSharesApplied(self):
		Log.d()
		for sharename, data in self._mounts.items():
			mountpoint = AutoMount.MOUNT_BASE + sharename
			Log.d("mountpoint: %s" %(mountpoint,))
			if os_path.exists(mountpoint):
				if os_path.ismount(mountpoint):
					Log.d("'%s' is mounted" %(mountpoint,))
					data['isMounted'] = True
					desc = data['sharename']
					if data['hdd_replacement']: #hdd replacement hack
						self._linkAsHdd(mountpoint)
					harddiskmanager.addMountedPartition(mountpoint, desc)
				else:
					Log.d("'%s' is NOT mounted" %(mountpoint,))
					sharename = self._mounts.get(data['sharename'], None)
					if sharename:
						data['isMounted'] = False
					if os_path.exists(mountpoint):
						if not os_path.ismount(mountpoint):
							removeDir(mountpoint)
							harddiskmanager.removeMountedPartition(mountpoint)
Example #45
0
	def _onRequestBodyReady(self, body):
		if self._canceled:
			Log.d("Auth Request canceled")
			return
		self._parseAuthRequestResponse(body)
		self._pollForResult()
Example #46
0
	def _onLeaveStandby(self):
		Log.d()
		if self.config.streamserver.source.value == str(eStreamServer.INPUT_MODE_LIVE) and self._mediatorStateBeforeStandby:
			Log.i("Leaving Standby, mode is Follow live, recovering upload state=%s" %(self._mediatorStateBeforeStandby,))
			self.config.streamserver.mediator.enabled.value = self._mediatorStateBeforeStandby
Example #47
0
	def upnp_Search(self, *args, **kwargs):
		self.init_cover_root()
		Log.d("%s" % (kwargs,))
		ContainerID = kwargs['ContainerID']
		StartingIndex = int(kwargs['StartingIndex'])
		RequestedCount = int(kwargs['RequestedCount'])
		SearchCriteria = kwargs['SearchCriteria']

		total = 0
		root_id = 0
		item = None
		items = []
		parent_container = None
		SearchCriteria = SearchCriteria.split(" ")
		if "derivedfrom" in SearchCriteria:
			if SearchCriteria[0] == "upnp:class":
				Log.d("Searching by class! %s" % (SearchCriteria,))
				if SearchCriteria[2].find(DIDLLite.AudioItem.upnp_class) >= 0:
					parent_container = str(self._audio_all_id)
				elif SearchCriteria[2].find(DIDLLite.VideoItem.upnp_class) >= 0:
					parent_container = str(self._video_all_id)
				Log.d(parent_container)
		if not parent_container:
			parent_container = str(ContainerID)
		didl = DIDLLite.DIDLElement(upnp_client=kwargs.get('X_UPnPClient', ''),
			parent_container=parent_container,
			transcoding=self.server.content_directory_server.transcoding)

		def build_response(tm):
			r = {'Result': didl.toString(), 'TotalMatches': tm,
				 'NumberReturned': didl.numItems()}

			if hasattr(item, 'update_id'):
				r['UpdateID'] = item.update_id
			elif hasattr(self, 'update_id'):
				r['UpdateID'] = self.update_id # FIXME
			else:
				r['UpdateID'] = 0

			return r

		def got_error(r):
			return r

		def process_result(result, total=None, found_item=None):
			if result == None:
				result = []

			l = []

			def process_items(result, tm):
				if result == None:
					result = []
				for i in result:
					if i[0] == True:
						didl.addItem(i[1])

				return build_response(tm)

			for i in result:
				d = defer.maybeDeferred(i.get_item)
				l.append(d)

			if found_item != None:
				def got_child_count(count):
					dl = defer.DeferredList(l)
					dl.addCallback(process_items, count)
					return dl

				d = defer.maybeDeferred(found_item.get_child_count)
				d.addCallback(got_child_count)

				return d
			elif total == None:
				total = item.get_child_count()

			dl = defer.DeferredList(l)
			dl.addCallback(process_items, total)
			return dl

		def proceed(result):
			if kwargs.get('X_UPnPClient', '') == 'XBox' and hasattr(result, 'get_artist_all_tracks'):
				d = defer.maybeDeferred(result.get_artist_all_tracks, StartingIndex, StartingIndex + RequestedCount)
			else:
				d = defer.maybeDeferred(result.get_children, StartingIndex, StartingIndex + RequestedCount)
			d.addCallback(process_result, found_item=result)
			d.addErrback(got_error)
			return d

		try:
			root_id = parent_container
		except:
			pass

		wmc_mapping = getattr(self, "wmc_mapping", None)
		if kwargs.get('X_UPnPClient', '') == 'XBox':
			if wmc_mapping and wmc_mapping.has_key(parent_container):
				""" fake a Windows Media Connect Server
				"""
				root_id = wmc_mapping[parent_container]
				if callable(root_id):
					item = root_id()
					if item is not None:
						if isinstance(item, list):
							total = len(item)
							if int(RequestedCount) == 0:
								items = item[StartingIndex:]
							else:
								items = item[StartingIndex:StartingIndex + RequestedCount]
							return process_result(items, total=total)
						else:
							if isinstance(item, defer.Deferred):
								item.addCallback(proceed)
								return item
							else:
								return proceed(item)

				item = self.get_by_id(root_id)
				if item == None:
					return process_result([], total=0)

				if isinstance(item, defer.Deferred):
					item.addCallback(proceed)
					return item
				else:
					return proceed(item)


		item = self.get_by_id(root_id)
		Log.w(item)
		if item == None:
			Log.w(701)
			return failure.Failure(errorCode(701))

		if isinstance(item, defer.Deferred):
			item.addCallback(proceed)
			return item
		else:
			return proceed(item)
	def _onTunerSelected(self, data):
		Log.d(data)
		if data and len(data) > 1:
			name, tuner = data
			self._selectModulationType(tuner)
Example #49
0
	def _onCredentialsPollError(self, error):
		self._responseDeferred = None
		if self._canceled:
			Log.d("Auth Request canceled")
			return
		self._onError(self.ERROR_CREDENTIALS_REQUEST, str(error))
Example #50
0
	def _onCredentialsPollResponse(self, response):
		self._responseDeferred = None
		if self._canceled:
			Log.d("Auth Request canceled")
			return
		readBody(response).addCallback(self._onCredentialsPollBodyReady).addErrback(self._onCredentialsPollBodyError)
Example #51
0
	def _onRequestError(self, error):
		self._requestDeferred = None
		if self._canceled:
			Log.d("Auth Request canceled")
		self._onError(self.ERROR_AUTH_REQUEST, str(error))
	def onConnect(self, request):
		Log.d("Client connecting: {0}".format(request.peer))
		return None