def build_last_change_event(self, instance=0, force=False): got_one = False root = ET.Element('Event') root.attrib['xmlns'] = self.event_metadata for instance, vdict in self._variables.items(): e = ET.SubElement(root, 'InstanceID') e.attrib['val'] = str(instance) for variable in vdict.values(): if (variable.name != 'LastChange' and variable.name[0:11] != 'A_ARG_TYPE_' and variable.never_evented == False and (variable.updated == True or force == True)): s = ET.SubElement(e, variable.name) s.attrib['val'] = str(variable.value) variable.updated = False got_one = True if variable.dependant_variable != None: dependants = variable.dependant_variable.get_allowed_values( ) if dependants != None and len(dependants) > 0: s.attrib['channel'] = dependants[0] if got_one == True: return ET.tostring(root, encoding='utf-8') else: return None
def new_subscriber(self, subscriber): notify = [] for vdict in self._variables.values(): notify += [v for v in vdict.values() if v.send_events == True] self.info("new_subscriber", subscriber, notify) if len(notify) <= 0: return root = ET.Element('e:propertyset') root.attrib['xmlns:e'] = 'urn:schemas-upnp-org:event-1-0' evented_variables = 0 for n in notify: e = ET.SubElement(root, 'e:property') if n.name == 'LastChange': if subscriber['seq'] == 0: text = self.build_last_change_event(n.instance, force=True) else: text = self.build_last_change_event(n.instance) if text is not None: ET.SubElement(e, n.name).text = text evented_variables += 1 else: ET.SubElement(e, n.name).text = str(n.value) evented_variables += 1 if evented_variables > 0: xml = ET.tostring(root, encoding='utf-8') d, p = event.send_notification(subscriber, xml) self._pending_notifications[d] = p d.addBoth(self.rm_notification, d) self._subscribers[subscriber['sid']] = subscriber
def _ConvertDictToXmlRecurse(parent, dictitem): assert type(dictitem) is not type([]) if isinstance(dictitem, dict): for (tag, child) in dictitem.iteritems(): if str(tag) == '_text': parent.text = str(child) ## elif str(tag) == '_attrs': ## for key, value in child.iteritems(): ## parent.set(key, value) elif type(child) is type([]): for listchild in child: elem = ElementTree.Element(tag) parent.append(elem) _ConvertDictToXmlRecurse(elem, listchild) else: if(not isinstance(dictitem, XmlDictObject) and not callable(dictitem)): attrs = dictitem dictitem = XmlDictObject() dictitem._attrs = attrs if tag in dictitem._attrs: parent.set(tag, child) elif not callable(tag) and not callable(child): elem = ElementTree.Element(tag) parent.append(elem) _ConvertDictToXmlRecurse(elem, child) else: if not callable(dictitem): parent.text = str(dictitem)
def toElement(self, **kwargs): root = Object.toElement(self, **kwargs) if self.childCount is not None: root.attrib['childCount'] = str(self.childCount) if self.createClass is not None: ET.SubElement(root, qname('createclass', UPNP_NS)).text = self.createClass if not isinstance(self.searchClass, (list, tuple)): self.searchClass = [self.searchClass] for i in self.searchClass: sc = ET.SubElement(root, qname('searchClass', UPNP_NS)) sc.attrib['includeDerived'] = '1' sc.text = i if self.searchable is not None: if self.searchable in (1, '1', True, 'true', 'True'): root.attrib['searchable'] = '1' else: root.attrib['searchable'] = '0' for res in self.res: root.append(res.toElement(**kwargs)) return root
def upnp_X_GetFeatureList(self, **kwargs): Log.w() attrib = { "xmlns": "urn:schemas-upnp-org:av:avs", "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation": "urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd" } features = ET.Element("Features") features.attrib.update(attrib) attrib = {"name": "samsung.com_BASICVIEW", "version": "1"} feature = ET.SubElement(features, "Feature") feature.attrib.update(attrib) #audio/video container id definition tag = ET.SubElement(feature, "container") tag.attrib.update({ "type": DIDLLite.AudioItem.upnp_class, "id": str(self._audio.get_id()) }) tag = ET.SubElement(feature, "container") tag.attrib.update({ "type": DIDLLite.VideoItem.upnp_class, "id": str(self._video.get_id()) }) return {"FeatureList": ET.tostring(features, "utf-8")}
def to_element(self): root = ET.Element(self.name) for key, value in self.items(): if isinstance(value, (dict, list)): root.append(value.to_element()) else: s = ET.SubElement(root, key) if isinstance(value, basestring): s.text = value else: s.text = str(value) return root
def toElement(self, **kwargs): root = Object.toElement(self, **kwargs) if self.director is not None: ET.SubElement(root, qname('director', UPNP_NS)).text = self.director if self.refID is not None: ET.SubElement(root, 'refID').text = self.refID if self.actors is not None: for actor in self.actors: ET.SubElement(root, qname('actor', DC_NS)).text = actor #if self.language is not None: # ET.SubElement(root, qname('language',DC_NS)).text = self.language if kwargs.get('transcoding', False) == True: res = self.res.get_matching(['*:*:*:*'], protocol_type='http-get') if len(res) > 0 and is_audio(res[0].protocolInfo): old_res = res[0] if (kwargs.get('upnp_client', '') == 'XBox'): transcoded_res = old_res.transcoded('mp3') if transcoded_res != None: root.append(transcoded_res.toElement(**kwargs)) else: root.append(old_res.toElement(**kwargs)) else: for res in self.res: root.append(res.toElement(**kwargs)) transcoded_res = old_res.transcoded('lpcm') if transcoded_res != None: root.append(transcoded_res.toElement(**kwargs)) elif len(res) > 0 and is_video(res[0].protocolInfo): old_res = res[0] for res in self.res: root.append(res.toElement(**kwargs)) transcoded_res = old_res.transcoded('mpegts') if transcoded_res != None: root.append(transcoded_res.toElement(**kwargs)) else: for res in self.res: root.append(res.toElement(**kwargs)) else: for res in self.res: root.append(res.toElement(**kwargs)) return root
def toString(self): """ sigh - having that optional preamble here breaks some of the older ContentDirectoryClients """ #preamble = """<?xml version="1.0" encoding="utf-8"?>""" #return preamble + ET.tostring(self,encoding='utf-8') return ET.tostring(self,encoding='utf-8')
def __init__(self, file): self.file = file dict.__init__(self) try: xml = ET.parse(file) except SyntaxError, msg: raise SyntaxError, msg
def save(self, file=None): if file == None: file = self.file e = ET.Element(self.name) for key, value in self.items(): if isinstance(value, (dict, list)): e.append(value.to_element()) else: s = ET.SubElement(e, key) if isinstance(value, basestring): s.text = value else: s.text = str(value) indent(e) db = ET.ElementTree(e) db.write(file, encoding='utf-8')
def toString(self): """ sigh - having that optional preamble here breaks some of the older ContentDirectoryClients """ #preamble = """<?xml version="1.0" encoding="utf-8"?>""" #return preamble + ET.tostring(self,encoding='utf-8') return ET.tostring(self, encoding='utf-8')
def new_subscriber(self, subscriber): notify = [] for vdict in self._variables.values(): notify += [v for v in vdict.values() if v.send_events == True] self.info("new_subscriber", subscriber, notify) if len(notify) <= 0: return root = ET.Element('e:propertyset') root.attrib['xmlns:e']='urn:schemas-upnp-org:event-1-0' evented_variables = 0 for n in notify: e = ET.SubElement( root, 'e:property') if n.name == 'LastChange': if subscriber['seq'] == 0: text = self.build_last_change_event(n.instance, force=True) else: text = self.build_last_change_event(n.instance) if text is not None: ET.SubElement( e, n.name).text = text evented_variables += 1 else: ET.SubElement( e, n.name).text = str(n.value) evented_variables += 1 if evented_variables > 0: xml = ET.tostring( root, encoding='utf-8') event.send_notification(subscriber, xml) self._subscribers[subscriber['sid']] = subscriber
def propagate_notification(self, notify): #print "propagate_notification", notify if len(self._subscribers) <= 0: return if len(notify) <= 0: return root = ET.Element('e:propertyset') root.attrib['xmlns:e']='urn:schemas-upnp-org:event-1-0' if isinstance( notify, variable.StateVariable): notify = [notify,] evented_variables = 0 for n in notify: e = ET.SubElement( root, 'e:property') if n.name == 'LastChange': text = self.build_last_change_event(instance=n.instance) if text is not None: ET.SubElement( e, n.name).text = text evented_variables += 1 else: s = ET.SubElement( e, n.name).text = str(n.value) evented_variables += 1 if n.dependant_variable != None: dependants = n.dependant_variable.get_allowed_values() if dependants != None and len(dependants) > 0: s.attrib['channel']=dependants[0] if evented_variables == 0: return xml = ET.tostring( root, encoding='utf-8') #print "propagate_notification", xml for s in self._subscribers.values(): event.send_notification(s, xml)
def fromElement(self, elt): Object.fromElement(self, elt) for child in elt.getchildren(): if child.tag.endswith('refID'): self.refID = child.text elif child.tag.endswith('res'): res = Resource.fromString(ET.tostring(child)) self.res.append(res)
def __init__(self, file): self.file = file dict.__init__(self) try: xml = ET.parse(file) except (SyntaxError, IOError): raise except Exception, msg: raise SyntaxError(msg)
def toElement(self, **kwargs): root = Item.toElement(self, **kwargs) if self.publisher is not None: ET.SubElement(root, qname('publisher', DC_NS)).text = self.publisher if self.language is not None: ET.SubElement(root, qname('language', DC_NS)).text = self.language if self.relation is not None: ET.SubElement(root, qname('relation', DC_NS)).text = self.relation if self.rights is not None: ET.SubElement(root, qname('rights', DC_NS)).text = self.rights return root
def toElement(self, **kwargs): root = Item.toElement(self, **kwargs) for attr_name, ns in self.valid_attrs.iteritems(): value = getattr(self, attr_name, None) if value: ET.SubElement(root, qname(attr_name, ns)).text = value return root
def fromString(cls, aString): instance = cls() elt = utils.parse_xml(aString, 'utf-8') elt = elt.getroot() for node in elt.getchildren(): upnp_class_name = node.findtext('{%s}class' % 'urn:schemas-upnp-org:metadata-1-0/upnp/') upnp_class = instance.get_upnp_class(upnp_class_name.strip()) new_node = upnp_class.fromString(ET.tostring(node)) instance.addItem(new_node) return instance
def render_NOTIFY(self, request): self.info("EventServer received notify from %s, code: %d" % (request.client, request.code)) data = request.content.getvalue() self.debug("EventServer notify data (%i) %s", len(data), data) request.setResponseCode(200) command = {"method": request.method, "path": request.path} headers = request.received_headers louie.send("UPnP.Event.Server.message_received", None, command, headers, data) if request.code != 200: self.info("data: %s", data) else: headers = request.getAllHeaders() sid = headers["sid"] try: tree = utils.parse_xml(data).getroot() ns = "urn:schemas-upnp-org:event-1-0" event = Event(sid) for prop in tree.findall("{%s}property" % ns): for var in prop.getchildren(): tag = var.tag idx = tag.find("}") + 1 self.debug("EventServer Event %s %s", var, ET.tostring(var)) if var.text is not None: event.update({tag[idx:]: var.text}) else: # this is solwise DMP1120w not escaping LastChange txt = ET.tostring(var)[12:-13] self.debug("EventServer Event %s", txt) event.update({tag[idx:]: txt}) self.control_point.propagate(event) except (SyntaxError, AttributeError): self.warning("malformed event notification from %r", request.client) self.exception("data: %r", data) return "" except Exception: self.exception("data: %r", data) return ""
def toElement(self, **kwargs): root = Item.toElement(self, **kwargs) if self.rating is not None: ET.SubElement(root, qname('rating', UPNP_NS)).text = str(self.rating) if self.storageMedium is not None: ET.SubElement(root, qname('storageMedium', UPNP_NS)).text = self.storageMedium if self.publisher is not None: ET.SubElement(root, qname('publisher', DC_NS)).text = self.contributor if self.rights is not None: ET.SubElement(root, qname('rights', DC_NS)).text = self.rights return root
def toElement(self, **kwargs): root = AudioItem.toElement(self, **kwargs) if self.album is not None: ET.SubElement(root, qname('album', UPNP_NS)).text = self.album if self.playlist is not None: ET.SubElement(root, qname('playlist', UPNP_NS)).text = self.playlist if self.storageMedium is not None: ET.SubElement(root, qname('storageMedium', UPNP_NS)).text = self.storageMedium if self.contributor is not None: ET.SubElement(root, qname('contributor', DC_NS)).text = self.contributor return root
def fromString(cls, aString): instance = cls() elt = utils.parse_xml(aString, 'utf-8') elt = elt.getroot() for node in elt.getchildren(): upnp_class_name = node.findtext( '{%s}class' % 'urn:schemas-upnp-org:metadata-1-0/upnp/') upnp_class = instance.get_upnp_class(upnp_class_name.strip()) new_node = upnp_class.fromString(ET.tostring(node)) instance.addItem(new_node) return instance
def propagate_notification(self, notify): #print "propagate_notification", notify if len(self._subscribers) <= 0: return if len(notify) <= 0: return root = ET.Element('e:propertyset') root.attrib['xmlns:e'] = 'urn:schemas-upnp-org:event-1-0' if isinstance(notify, variable.StateVariable): notify = [ notify, ] evented_variables = 0 for n in notify: e = ET.SubElement(root, 'e:property') if n.name == 'LastChange': text = self.build_last_change_event(instance=n.instance) if text is not None: ET.SubElement(e, n.name).text = text evented_variables += 1 else: s = ET.SubElement(e, n.name).text = str(n.value) evented_variables += 1 if n.dependant_variable != None: dependants = n.dependant_variable.get_allowed_values() if dependants != None and len(dependants) > 0: s.attrib['channel'] = dependants[0] if evented_variables == 0: return xml = ET.tostring(root, encoding='utf-8') #print "propagate_notification", xml for s in self._subscribers.values(): d, p = event.send_notification(s, xml) self._pending_notifications[d] = p d.addBoth(self.rm_notification, d)
def element_to_didl(item): """ a helper method to create a DIDLElement out of one ET element or XML fragment string """ if not isinstance(item, basestring): item = ET.tostring(item) didl = """<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0" xmlns:pv="http://www.pv.com/pvns/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">""" \ + item + \ """</DIDL-Lite>""" return didl
def element_to_didl(item): """ a helper method to create a DIDLElement out of one ET element or XML fragment string """ if not isinstance(item,basestring): item = ET.tostring(item) didl = """<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0" xmlns:pv="http://www.pv.com/pvns/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">""" \ + item + \ """</DIDL-Lite>""" return didl
def build_soap_error(status, description='without words'): """ builds an UPnP SOAP error msg """ root = ET.Element('s:Fault') ET.SubElement(root, 'faultcode').text = 's:Client' ET.SubElement(root, 'faultstring').text = 'UPnPError' e = ET.SubElement(root, 'detail') e = ET.SubElement(e, 'UPnPError') e.attrib['xmlns'] = 'urn:schemas-upnp-org:control-1-0' ET.SubElement(e, 'errorCode').text = str(status) ET.SubElement(e, 'errorDescription').text = UPNPERRORS.get( status, description) return build_soap_call(None, root, encoding=None)
def fromElement(self, elt): """ TODO: * creator * writeStatus """ self.elementName = elt.tag self.id = elt.attrib.get('id', None) self.parentID = elt.attrib.get('parentID', None) self.refID = elt.attrib.get('refID', None) if elt.attrib.get('restricted', None) in [1, 'true', 'True', '1', 'yes', 'Yes']: self.restricted = True else: self.restricted = False for child in elt.getchildren(): if child.tag.endswith('title'): self.title = child.text elif child.tag.endswith('albumArtURI'): self.albumArtURI = child.text elif child.tag.endswith('originalTrackNumber'): self.originalTrackNumber = int(child.text) elif child.tag.endswith('description'): self.description = child.text elif child.tag.endswith('longDescription'): self.longDescription = child.text elif child.tag.endswith('artist'): self.artist = child.text elif child.tag.endswith('genre'): if self.genre != None: if self.genres == None: self.genres = [ self.genre, ] self.genres.append(child.text) self.genre = child.text elif child.tag.endswith('album'): self.album = child.text elif child.tag.endswith('class'): self.upnp_class = child.text elif child.tag.endswith('server_uuid'): self.server_uuid = child.text elif child.tag.endswith('res'): res = Resource.fromString(ET.tostring(child)) self.res.append(res)
def __init__(self, server, control): root = ET.Element('scpd') root.attrib['xmlns']='urn:schemas-upnp-org:service-1-0' e = ET.SubElement(root, 'specVersion') ET.SubElement( e, 'major').text = '1' ET.SubElement( e, 'minor').text = '0' e = ET.SubElement( root, 'actionList') for action in server._actions.values(): s = ET.SubElement( e, 'action') ET.SubElement( s, 'name').text = action.get_name() al = ET.SubElement( s, 'argumentList') for argument in action.get_arguments_list(): a = ET.SubElement( al, 'argument') ET.SubElement( a, 'name').text = argument.get_name() ET.SubElement( a, 'direction').text = argument.get_direction() ET.SubElement( a, 'relatedStateVariable').text = argument.get_state_variable() e = ET.SubElement( root, 'serviceStateTable') for var in server._variables[0].values(): s = ET.SubElement( e, 'stateVariable') if var.send_events == True: s.attrib['sendEvents'] = 'yes' else: s.attrib['sendEvents'] = 'no' ET.SubElement( s, 'name').text = var.name ET.SubElement( s, 'dataType').text = var.data_type if(not var.has_vendor_values and len(var.allowed_values)): #if len(var.allowed_values): v = ET.SubElement( s, 'allowedValueList') for value in var.allowed_values: ET.SubElement( v, 'allowedValue').text = value if( var.allowed_value_range != None and len(var.allowed_value_range) > 0): complete = True for name,value in var.allowed_value_range.items(): if value == None: complete = False if complete == True: avl = ET.SubElement( s, 'allowedValueRange') for name,value in var.allowed_value_range.items(): if value != None: ET.SubElement( avl, name).text = str(value) self.xml = """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8') static.Data.__init__(self, self.xml, 'text/xml')
def build_soap_call(method, arguments, is_response=False, encoding=SOAP_ENCODING, envelope_attrib=None, typed=None): """ create a shell for a SOAP request or response element - set method to none to omit the method element and add the arguments directly to the body (for an error msg) - arguments can be a dict or an ET.Element """ envelope = ET.Element("s:Envelope") if envelope_attrib: for n in envelope_attrib: envelope.attrib.update({n[0]: n[1]}) else: envelope.attrib.update({"s:encodingStyle": "http://schemas.xmlsoap.org/soap/encoding/"}) envelope.attrib.update({"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"}) body = ET.SubElement(envelope, "s:Body") if method: # append the method call if is_response is True: method += "Response" re = ET.SubElement(body, method) if encoding: re.set(NS_SOAP_ENV + "encodingStyle", encoding) else: re = body # append the arguments if isinstance(arguments, (dict, OrderedDict)): type_map = {str: "xsd:string", unicode: "xsd:string", int: "xsd:int", float: "xsd:float", bool: "xsd:boolean"} for arg_name, arg_val in arguments.iteritems(): arg_type = type_map[type(arg_val)] if arg_type == "xsd:string" and type(arg_val) == unicode: arg_val = arg_val.encode("utf-8") if arg_type == "xsd:int" or arg_type == "xsd:float": arg_val = str(arg_val) if arg_type == "xsd:boolean": if arg_val == True: arg_val = "1" else: arg_val = "0" e = ET.SubElement(re, arg_name) if typed and arg_type: if not isinstance(type, ET.QName): arg_type = ET.QName("http://www.w3.org/1999/XMLSchema", arg_type) e.set(NS_XSI + "type", arg_type) e.text = arg_val else: if arguments == None: arguments = {} re.append(arguments) preamble = """<?xml version="1.0" encoding="utf-8"?>""" return preamble + ET.tostring(envelope, "utf-8")
def fromElement(self, elt): """ TODO: * creator * writeStatus """ self.elementName = elt.tag self.id = elt.attrib.get('id',None) self.parentID = elt.attrib.get('parentID',None) self.refID = elt.attrib.get('refID',None) if elt.attrib.get('restricted',None) in [1,'true','True','1','yes','Yes']: self.restricted = True else: self.restricted = False for child in elt.getchildren(): if child.tag.endswith('title'): self.title = child.text elif child.tag.endswith('albumArtURI'): self.albumArtURI = child.text elif child.tag.endswith('originalTrackNumber'): self.originalTrackNumber = int(child.text) elif child.tag.endswith('description'): self.description = child.text elif child.tag.endswith('longDescription'): self.longDescription = child.text elif child.tag.endswith('artist'): self.artist = child.text elif child.tag.endswith('genre'): if self.genre != None: if self.genres == None: self.genres = [self.genre,] self.genres.append(child.text) self.genre = child.text elif child.tag.endswith('album'): self.album = child.text elif child.tag.endswith('class'): self.upnp_class = child.text elif child.tag.endswith('server_uuid'): self.server_uuid = child.text elif child.tag.endswith('res'): res = Resource.fromString(ET.tostring(child)) self.res.append(res)
def toElement(self, **kwargs): root = ET.Element('res') if kwargs.get('upnp_client', '') in ('XBox', ): protocol, network, content_format, additional_info = self.protocolInfo.split( ':') if content_format in ['video/divx', 'video/x-msvideo']: content_format = 'video/avi' if content_format == 'audio/x-wav': content_format = 'audio/wav' additional_info = self.get_additional_info( upnp_client=kwargs.get('upnp_client', '')) root.attrib['protocolInfo'] = ':'.join( (protocol, network, content_format, additional_info)) else: protocol, network, content_format, additional_info = self.protocolInfo.split( ':') if content_format == 'video/x-msvideo': content_format = 'video/divx' additional_info = self.get_additional_info( upnp_client=kwargs.get('upnp_client', '')) root.attrib['protocolInfo'] = ':'.join( (protocol, network, content_format, additional_info)) root.text = self.data if self.bitrate is not None: root.attrib['bitrate'] = str(self.bitrate) if self.size is not None: root.attrib['size'] = str(self.size) if self.duration is not None: root.attrib['duration'] = self.duration if self.nrAudioChannels is not None: root.attrib['nrAudioChannels'] = self.nrAudioChannels if self.resolution is not None: root.attrib['resolution'] = self.resolution if self.importUri is not None: root.attrib['importUri'] = self.importUri return root
def upnp_X_GetFeatureList(self,**kwargs): Log.w() attrib = { "xmlns" : "urn:schemas-upnp-org:av:avs", "xmlns:xsi" : "http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation" : "urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd" } features = ET.Element("Features") features.attrib.update(attrib) attrib = { "name" : "samsung.com_BASICVIEW", "version" : "1" } feature = ET.SubElement(features, "Feature") feature.attrib.update(attrib) #audio/video container id definition tag = ET.SubElement(feature, "container") tag.attrib.update({ "type": DIDLLite.AudioItem.upnp_class, "id" : str(self._audio.get_id()) }) tag = ET.SubElement(feature, "container") tag.attrib.update({ "type": DIDLLite.VideoItem.upnp_class, "id" : str(self._video.get_id()) }) return {"FeatureList" : ET.tostring(features, "utf-8")}
def fromElement(self, elt): """ TODO: * creator * writeStatus """ self.elementName = elt.tag self.id = elt.attrib.get("id", None) self.parentID = elt.attrib.get("parentID", None) self.refID = elt.attrib.get("refID", None) if elt.attrib.get("restricted", None) in [1, "true", "True", "1", "yes", "Yes"]: self.restricted = True else: self.restricted = False for child in elt.getchildren(): if child.tag.endswith("title"): self.title = child.text elif child.tag.endswith("albumArtURI"): self.albumArtURI = child.text elif child.tag.endswith("originalTrackNumber"): self.originalTrackNumber = int(child.text) elif child.tag.endswith("description"): self.description = child.text elif child.tag.endswith("longDescription"): self.longDescription = child.text elif child.tag.endswith("artist"): self.artist = child.text elif child.tag.endswith("album"): self.album = child.text elif child.tag.endswith("class"): self.upnp_class = child.text elif child.tag.endswith("server_uuid"): self.server_uuid = child.text elif child.tag.endswith("res"): res = Resource.fromString(ET.tostring(child)) self.res.append(res)
def button_action(self, widget, event): x = int(event.x) y = int(event.y) path = self.treeview.get_path_at_pos(x, y) if path == None: return True row_path,column,_,_ = path if event.button == 3: clipboard = Gtk.clipboard_get(Gdk.SELECTION_CLIPBOARD) iter = self.store.get_iter(row_path) menu = Gtk.Menu() item = Gtk.MenuItem("copy value") value,= self.store.get(iter,4) item.connect("activate", lambda w: clipboard.set_text(value)) menu.append(item) item = Gtk.MenuItem("copy raw event") raw,= self.store.get(iter,5) try: from coherence.extern.et import ET, indent, parse_xml xml = parse_xml(raw) xml = xml.getroot() indent(xml,0) raw = ET.tostring(xml, encoding='utf-8') except: import traceback print traceback.format_exc() item.connect("activate", lambda w: clipboard.set_text(raw)) menu.append(item) menu.show_all() menu.popup(None,None,None,event.button,event.time) return True return False
def button_action(self, widget, event): x = int(event.x) y = int(event.y) path = self.treeview.get_path_at_pos(x, y) if path == None: return True row_path, column, _, _ = path if event.button == 3: clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD) iter = self.store.get_iter(row_path) menu = gtk.Menu() item = gtk.MenuItem("Copy value") value, = self.store.get(iter, 4) item.connect("activate", lambda w: clipboard.set_text(value)) menu.append(item) item = gtk.MenuItem("Copy raw event XML") raw, = self.store.get(iter, 5) try: from coherence.extern.et import ET, indent, parse_xml xml = parse_xml(raw) xml = xml.getroot() indent(xml, 0) raw = ET.tostring(xml, encoding='utf-8') except: import traceback print traceback.format_exc() item.connect("activate", lambda w: clipboard.set_text(raw)) menu.append(item) menu.show_all() menu.popup(None, None, None, event.button, event.time) return True return False
def build_last_change_event(self, instance=0, force=False): got_one = False root = ET.Element('Event') root.attrib['xmlns']=self.event_metadata for instance, vdict in self._variables.items(): e = ET.SubElement( root, 'InstanceID') e.attrib['val']=str(instance) for variable in vdict.values(): if( variable.name != 'LastChange' and variable.name[0:11] != 'A_ARG_TYPE_' and variable.never_evented == False and (variable.updated == True or force == True)): s = ET.SubElement( e, variable.name) s.attrib['val'] = str(variable.value) variable.updated = False got_one = True if variable.dependant_variable != None: dependants = variable.dependant_variable.get_allowed_values() if dependants != None and len(dependants) > 0: s.attrib['channel']=dependants[0] if got_one == True: return ET.tostring( root, encoding='utf-8') else: return None
def toString(self, **kwargs): return ET.tostring(self.toElement(**kwargs), encoding='utf-8')
def build_single_notification(self, instance, variable_name, value): root = ET.Element('e:propertyset') root.attrib['xmlns:e'] = 'urn:schemas-upnp-org:event-1-0' e = ET.SubElement(root, 'e:property') s = ET.SubElement(e, variable_name).text = str(value) return ET.tostring(root, encoding='utf-8')
def reply(r): #print "browse_reply - %s of %s returned" % (r['NumberReturned'],r['TotalMatches']) from coherence.upnp.core import DIDLLite from coherence.extern.et import ET child = self.store.iter_children(iter) if child: upnp_class, = self.store.get(child,UPNP_CLASS_COLUMN) if upnp_class == 'placeholder': self.store.remove(child) title, = self.store.get(iter,NAME_COLUMN) try: title = title[:title.rindex('(')] self.store.set_value(iter,NAME_COLUMN, "%s(%d)" % (title,int(r['TotalMatches']))) except ValueError: pass elt = parse_xml(r['Result'], 'utf-8') elt = elt.getroot() for child in elt: #stored_didl_string = DIDLLite.element_to_didl(child) stored_didl_string = DIDLLite.element_to_didl(ET.tostring(child)) didl = DIDLLite.DIDLElement.fromString(stored_didl_string) item = didl.getItems()[0] #print item.title, item.id, item.upnp_class if item.upnp_class.startswith('object.container'): icon = self.folder_icon service, = self.store.get(iter,SERVICE_COLUMN) child_count = item.childCount try: title = "%s (%d)" % (item.title,item.childCount) except TypeError: title = "%s (n/a)" % item.title child_count = -1 else: icon=None service = '' child_count = -1 title = item.title if item.upnp_class.startswith('object.item.audioItem'): icon = self.audio_icon elif item.upnp_class.startswith('object.item.videoItem'): icon = self.video_icon elif item.upnp_class.startswith('object.item.imageItem'): icon = self.image_icon res = item.res.get_matching(['*:*:*:*'], protocol_type='http-get') if len(res) > 0: res = res[0] service = res.data new_iter = self.store.append(iter, (title,item.id,item.upnp_class,child_count,'',service,icon,stored_didl_string,None)) if item.upnp_class.startswith('object.container'): self.store.append(new_iter, ('...loading...','','placeholder',-1,'','',None,'',None)) if((int(r['TotalMatches']) > 0 and force==False) or expand==True): view.expand_row(row_path, False) if(requested_count != int(r['NumberReturned']) and int(r['NumberReturned']) < (int(r['TotalMatches'])-starting_index)): print "seems we have been returned only a part of the result" print "requested %d, starting at %d" % (requested_count,starting_index) print "got %d out of %d" % (int(r['NumberReturned']), int(r['TotalMatches'])) print "requesting more starting now at %d" % (starting_index+int(r['NumberReturned'])) self.browse(view,row_path,column, starting_index=starting_index+int(r['NumberReturned']), force=True)
def build_xml(self): root = ET.Element('scpd') root.attrib['xmlns'] = 'urn:schemas-upnp-org:service-1-0' e = ET.SubElement(root, 'specVersion') ET.SubElement(e, 'major').text = '1' ET.SubElement(e, 'minor').text = '0' e = ET.SubElement(root, 'actionList') for action in self.service_server._actions.values(): s = ET.SubElement(e, 'action') ET.SubElement(s, 'name').text = action.get_name() al = ET.SubElement(s, 'argumentList') for argument in action.get_arguments_list(): a = ET.SubElement(al, 'argument') ET.SubElement(a, 'name').text = argument.get_name() ET.SubElement(a, 'direction').text = argument.get_direction() ET.SubElement(a, 'relatedStateVariable' ).text = argument.get_state_variable() e = ET.SubElement(root, 'serviceStateTable') for var in self.service_server._variables[0].values(): s = ET.SubElement(e, 'stateVariable') if var.send_events == True: s.attrib['sendEvents'] = 'yes' else: s.attrib['sendEvents'] = 'no' ET.SubElement(s, 'name').text = var.name ET.SubElement(s, 'dataType').text = var.data_type if (not var.has_vendor_values and len(var.allowed_values)): #if len(var.allowed_values): v = ET.SubElement(s, 'allowedValueList') for value in var.allowed_values: ET.SubElement(v, 'allowedValue').text = value if (var.allowed_value_range != None and len(var.allowed_value_range) > 0): complete = True for name, value in var.allowed_value_range.items(): if value == None: complete = False if complete == True: avl = ET.SubElement(s, 'allowedValueRange') for name, value in var.allowed_value_range.items(): if value != None: ET.SubElement(avl, name).text = str(value) return """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8')
def reply(r): #print "browse_reply - %s of %s returned" % (r['NumberReturned'],r['TotalMatches']) from coherence.upnp.core import DIDLLite from coherence.extern.et import ET child = self.store.iter_children(iter) if child: upnp_class, = self.store.get(child, UPNP_CLASS_COLUMN) if upnp_class == 'placeholder': self.store.remove(child) title, = self.store.get(iter, NAME_COLUMN) try: title = title[:title.rindex('(')] self.store.set_value( iter, NAME_COLUMN, "%s(%d)" % (title, int(r['TotalMatches']))) except ValueError: pass elt = parse_xml(r['Result'], 'utf-8') elt = elt.getroot() for child in elt: #stored_didl_string = DIDLLite.element_to_didl(child) stored_didl_string = DIDLLite.element_to_didl( ET.tostring(child)) didl = DIDLLite.DIDLElement.fromString(stored_didl_string) item = didl.getItems()[0] #print item.title, item.id, item.upnp_class if item.upnp_class.startswith('object.container'): icon = self.folder_icon service, = self.store.get(iter, SERVICE_COLUMN) child_count = item.childCount try: title = "%s (%d)" % (item.title, item.childCount) except TypeError: title = "%s (n/a)" % item.title child_count = -1 else: icon = None service = '' child_count = -1 title = item.title if item.upnp_class.startswith('object.item.audioItem'): icon = self.audio_icon elif item.upnp_class.startswith('object.item.videoItem'): icon = self.video_icon elif item.upnp_class.startswith('object.item.imageItem'): icon = self.image_icon res = item.res.get_matching(['*:*:*:*'], protocol_type='http-get') if len(res) > 0: res = res[0] service = res.data new_iter = self.store.append( iter, (title, item.id, item.upnp_class, child_count, '', service, icon, stored_didl_string, None)) if item.upnp_class.startswith('object.container'): self.store.append(new_iter, ('...loading...', '', 'placeholder', -1, '', '', None, '', None)) if ((int(r['TotalMatches']) > 0 and force == False) or expand == True): view.expand_row(row_path, False) if (requested_count != int(r['NumberReturned']) and int(r['NumberReturned']) < (int(r['TotalMatches']) - starting_index)): print "seems we have been returned only a part of the result" print "requested %d, starting at %d" % (requested_count, starting_index) print "got %d out of %d" % (int( r['NumberReturned']), int(r['TotalMatches'])) print "requesting more starting now at %d" % ( starting_index + int(r['NumberReturned'])) self.browse(view, row_path, column, starting_index=starting_index + int(r['NumberReturned']), force=True)
def __init__(self, hostname, uuid, urlbase, device_type='BasicDevice', version=2, friendly_name='Coherence UPnP BasicDevice', model_description='Coherence UPnP BasicDevice', model_name='Coherence UPnP BasicDevice', presentation_url='', services=[], devices=[], icons=[]): uuid = str(uuid) root = ET.Element('root') root.attrib['xmlns']='urn:schemas-upnp-org:device-1-0' device_type = 'urn:schemas-upnp-org:device:%s:%d' % (device_type, version) e = ET.SubElement(root, 'specVersion') ET.SubElement( e, 'major').text = '1' ET.SubElement( e, 'minor').text = '0' ET.SubElement(root, 'URLBase').text = urlbase d = ET.SubElement(root, 'device') ET.SubElement( d, 'deviceType').text = device_type ET.SubElement( d, 'friendlyName').text = friendly_name ET.SubElement( d, 'manufacturer').text = 'beebits.net' ET.SubElement( d, 'manufacturerURL').text = 'http://coherence.beebits.net' ET.SubElement( d, 'modelDescription').text = model_description ET.SubElement( d, 'modelName').text = model_name ET.SubElement(d, 'modelNumber').text = __version__ ET.SubElement( d, 'modelURL').text = 'http://coherence.beebits.net' ET.SubElement( d, 'serialNumber').text = '0000001' ET.SubElement( d, 'UDN').text = uuid ET.SubElement( d, 'UPC').text = '' ET.SubElement( d, 'presentationURL').text = presentation_url if len(services): e = ET.SubElement( d, 'serviceList') for service in services: id = service.get_id() s = ET.SubElement( e, 'service') try: namespace = service.namespace except: namespace = 'schemas-upnp-org' if( hasattr(service,'version') and service.version < version): v = service.version else: v = version ET.SubElement(s, 'serviceType').text = 'urn:%s:service:%s:%d' % (namespace, id, int(v)) try: namespace = service.id_namespace except: namespace = 'upnp-org' ET.SubElement( s, 'serviceId').text = 'urn:%s:serviceId:%s' % (namespace,id) ET.SubElement( s, 'SCPDURL').text = '/' + uuid[5:] + '/' + id + '/' + service.scpd_url ET.SubElement( s, 'controlURL').text = '/' + uuid[5:] + '/' + id + '/' + service.control_url ET.SubElement( s, 'eventSubURL').text = '/' + uuid[5:] + '/' + id + '/' + service.subscription_url if len(devices): e = ET.SubElement( d, 'deviceList') if len(icons): e = ET.SubElement(d, 'iconList') for icon in icons: i = ET.SubElement(e, 'icon') for k,v in icon.items(): if k == 'url': if v.startswith('file://'): ET.SubElement(i, k).text = '/'+uuid[5:]+'/'+os.path.basename(v) continue ET.SubElement(i, k).text = str(v) #if self.has_level(LOG_DEBUG): # indent( root) self.xml = """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8') static.Data.__init__(self, self.xml, 'text/xml')
def reply(r,service): if iter: child = model.iter_children(iter) if child: upnp_class = model.get(child, self.MS_UPNP_CLASS_COLUMN)[0] if upnp_class == 'placeholder': model.remove(child) title = model.get(iter, self.MS_NAME_COLUMN)[0] if title: try: title = title[:title.rindex('(')] model.set_value(iter, self.MS_NAME_COLUMN, "%s(%d)" % (title, int(r['TotalMatches']))) except ValueError: pass elt = parse_xml(r['Result'], 'utf-8') elt = elt.getroot() for child in elt: stored_didl_string = DIDLLite.element_to_didl(ET.tostring(child)) didl = DIDLLite.DIDLElement.fromString(stored_didl_string) item = didl.getItems()[0] if item.upnp_class.startswith('object.container'): icon = self.folder_icon #service = model.get(iter, self.MS_SERVICE_PATH_COLUMN)[0] child_count = item.childCount try: title = "%s (%d)" % (item.title, item.childCount) except TypeError: title = "%s (n/a)" % item.title child_count = -1 else: icon = None service = '' child_count = -1 title = item.title if item.upnp_class.startswith('object.item.audioItem'): icon = self.audio_icon elif item.upnp_class.startswith('object.item.videoItem'): icon = self.video_icon elif item.upnp_class.startswith('object.item.imageItem'): icon = self.image_icon res = item.res.get_matching(['*:*:*:*'], protocol_type='http-get') if len(res) > 0: res = res[0] service = res.data new_iter = model.append(iter, (title, item.id, item.upnp_class, child_count, '',service,icon,stored_didl_string,None)) if item.upnp_class.startswith('object.container'): model.append(new_iter, ('...loading...', '', 'placeholder', -1, '', '', None, '', None)) if ((int(r['TotalMatches']) > 0 and force==False) or \ expand==True): if view: view.expand_row(row_path, False) if(requested_count != int(r['NumberReturned']) and \ int(r['NumberReturned']) < (int(r['TotalMatches'])-starting_index)): self.browse(view, row_path, column, starting_index=starting_index+int(r['NumberReturned']), force=True)
def init_var_and_actions(self): desc_file = util.sibpath(__file__, os.path.join('xml-service-descriptions', '%s%d.xml' % (self.id, int(self.version)))) tree = ET.parse(desc_file) for action_node in tree.findall('.//action'): name = action_node.findtext('name') implementation = 'required' if action_node.find('Optional') != None: implementation = 'optional' arguments = [] needs_callback = False for argument in action_node.findall('.//argument'): arg_name = argument.findtext('name') arg_direction = argument.findtext('direction') arg_state_var = argument.findtext('relatedStateVariable') arguments.append(action.Argument(arg_name, arg_direction, arg_state_var)) if( arg_state_var[0:11] == 'A_ARG_TYPE_' and arg_direction == 'out'): needs_callback = True #print arg_name, arg_direction, needs_callback """ check for action in backend """ callback = getattr(self.backend, "upnp_%s" % name, None) if callback == None: """ check for action in ServiceServer """ callback = getattr(self, "upnp_%s" % name, None) if( needs_callback == True and callback == None): """ we have one or more 'A_ARG_TYPE_' variables issue a warning for now """ if implementation == 'optional': self.info('%s has a missing callback for %s action %s, action disabled' % (self.id,implementation,name)) continue else: self.warning('%s has a missing callback for %s action %s, service disabled' % (self.id,implementation,name)) raise LookupError,"missing callback" new_action = action.Action(self, name, implementation, arguments) self._actions[name] = new_action if callback != None: new_action.set_callback(callback) self.info('Add callback %s for %s/%s' % (callback, self.id, name)) backend_vendor_value_defaults = getattr(self.backend, "vendor_value_defaults", None) service_value_defaults = None if backend_vendor_value_defaults: service_value_defaults = backend_vendor_value_defaults.get(self.id,None) backend_vendor_range_defaults = getattr(self.backend, "vendor_range_defaults", None) service_range_defaults = None if backend_vendor_range_defaults: service_range_defaults = backend_vendor_range_defaults.get(self.id) for var_node in tree.findall('.//stateVariable'): instance = 0 name = var_node.findtext('name') implementation = 'required' if action_node.find('Optional') != None: implementation = 'optional' send_events = var_node.findtext('sendEventsAttribute') data_type = var_node.findtext('dataType') values = [] for allowed in var_node.findall('.//allowedValue'): values.append(allowed.text) self._variables.get(instance)[name] = variable.StateVariable(self, name, implementation, instance, send_events, data_type, values) default_value = var_node.findtext('defaultValue') if default_value: self._variables.get(instance)[name].set_default_value(default_value) if var_node.find('sendEventsAttribute') != None: never_evented = var_node.find('sendEventsAttribute').attrib.get( '{urn:schemas-beebits-net:service-1-0}X_no_means_never', None) if never_evented is not None: self._variables.get(instance)[name].set_never_evented(never_evented) dependant_variable = var_node.findtext('{urn:schemas-beebits-net:service-1-0}X_dependantVariable') if dependant_variable: self._variables.get(instance)[name].dependant_variable = dependant_variable allowed_value_list = var_node.find('allowedValueList') if allowed_value_list != None: vendor_values = allowed_value_list.attrib.get( '{urn:schemas-beebits-net:service-1-0}X_withVendorDefines', None) if service_value_defaults: variable_value_defaults = service_value_defaults.get(name, None) if variable_value_defaults: self.info("overwriting %s default value with %s" % (name, variable_value_defaults)) self._variables.get(instance)[name].set_allowed_values(variable_value_defaults) if vendor_values != None: self._variables.get(instance)[name].has_vendor_values = True allowed_value_range = var_node.find('allowedValueRange') if allowed_value_range: vendor_values = allowed_value_range.attrib.get( '{urn:schemas-beebits-net:service-1-0}X_withVendorDefines', None) range = {} for e in list(allowed_value_range): range[e.tag] = e.text if( vendor_values != None): if service_range_defaults: variable_range_defaults = service_range_defaults.get(name) if( variable_range_defaults != None and variable_range_defaults.get(e.tag) != None): self.info("overwriting %s attribute %s with %s" % (name, e.tag, str(variable_range_defaults[e.tag]))) range[e.tag] = variable_range_defaults[e.tag] elif e.text == None: self.info("missing vendor definition for %s, attribute %s" % (name, e.tag)) self._variables.get(instance)[name].set_allowed_value_range(**range) if vendor_values != None: self._variables.get(instance)[name].has_vendor_values = True for v in self._variables.get(0).values(): if isinstance( v.dependant_variable, str): v.dependant_variable = self._variables.get(instance).get(v.dependant_variable)
def init_var_and_actions(self): desc_file = util.sibpath( __file__, os.path.join('xml-service-descriptions', '%s%d.xml' % (self.id, int(self.version)))) tree = ET.parse(desc_file) for action_node in tree.findall('.//action'): name = action_node.findtext('name') implementation = 'required' needs_callback = False if action_node.attrib.get( '{urn:schemas-beebits-net:service-1-0}X_needs_backend', None) != None: needs_callback = True if action_node.find('Optional') != None: implementation = 'optional' if (action_node.find('Optional').attrib.get( '{urn:schemas-beebits-net:service-1-0}X_needs_backend', None ) != None or action_node.attrib.get( '{urn:schemas-beebits-net:service-1-0}X_needs_backend', None) != None): needs_callback = True arguments = [] for argument in action_node.findall('.//argument'): arg_name = argument.findtext('name') arg_direction = argument.findtext('direction') arg_state_var = argument.findtext('relatedStateVariable') arguments.append( action.Argument(arg_name, arg_direction, arg_state_var)) if (arg_state_var[0:11] == 'A_ARG_TYPE_' and arg_direction == 'out'): needs_callback = True #print arg_name, arg_direction, needs_callback """ check for action in backend """ callback = getattr(self.backend, "upnp_%s" % name, None) if callback == None: """ check for action in ServiceServer """ callback = getattr(self, "upnp_%s" % name, None) if (needs_callback == True and callback == None): """ we have one or more 'A_ARG_TYPE_' variables issue a warning for now """ if implementation == 'optional': self.info( '%s has a missing callback for %s action %s, action disabled' % (self.id, implementation, name)) continue else: if ((hasattr(self, 'implementation') and self.implementation == 'required') or not hasattr(self, 'implementation')): self.warning( '%s has a missing callback for %s action %s, service disabled' % (self.id, implementation, name)) raise LookupError, "missing callback" new_action = action.Action(self, name, implementation, arguments) self._actions[name] = new_action if callback != None: new_action.set_callback(callback) self.info('Add callback %s for %s/%s' % (callback, self.id, name)) backend_vendor_value_defaults = getattr(self.backend, "vendor_value_defaults", None) service_value_defaults = None if backend_vendor_value_defaults: service_value_defaults = backend_vendor_value_defaults.get( self.id, None) backend_vendor_range_defaults = getattr(self.backend, "vendor_range_defaults", None) service_range_defaults = None if backend_vendor_range_defaults: service_range_defaults = backend_vendor_range_defaults.get(self.id) for var_node in tree.findall('.//stateVariable'): instance = 0 name = var_node.findtext('name') implementation = 'required' if action_node.find('Optional') != None: implementation = 'optional' #if implementation == 'optional': # for action_object in self._actions.values(): # if name in [a.get_state_variable() for a in action_object.arguments_list]: # break # else: # continue send_events = var_node.findtext('sendEventsAttribute') data_type = var_node.findtext('dataType') values = [] for allowed in var_node.findall('.//allowedValue'): values.append(allowed.text) self._variables.get(instance)[name] = variable.StateVariable( self, name, implementation, instance, send_events, data_type, values) dependant_variable = var_node.findtext( '{urn:schemas-beebits-net:service-1-0}X_dependantVariable') if dependant_variable: self._variables.get( instance)[name].dependant_variable = dependant_variable default_value = var_node.findtext('defaultValue') if default_value: self._variables.get(instance)[name].set_default_value( default_value) if var_node.find('sendEventsAttribute') != None: never_evented = var_node.find( 'sendEventsAttribute' ).attrib.get( '{urn:schemas-beebits-net:service-1-0}X_no_means_never', None) if never_evented is not None: self._variables.get(instance)[name].set_never_evented( never_evented) allowed_value_list = var_node.find('allowedValueList') if allowed_value_list != None: vendor_values = allowed_value_list.attrib.get( '{urn:schemas-beebits-net:service-1-0}X_withVendorDefines', None) if service_value_defaults: variable_value_defaults = service_value_defaults.get( name, None) if variable_value_defaults: self.info("overwriting %s default value with %s" % (name, variable_value_defaults)) self._variables.get(instance)[name].set_allowed_values( variable_value_defaults) if vendor_values != None: self._variables.get( instance)[name].has_vendor_values = True allowed_value_range = var_node.find('allowedValueRange') if allowed_value_range: vendor_values = allowed_value_range.attrib.get( '{urn:schemas-beebits-net:service-1-0}X_withVendorDefines', None) range = {} for e in list(allowed_value_range): range[e.tag] = e.text if (vendor_values != None): if service_range_defaults: variable_range_defaults = service_range_defaults.get( name) if (variable_range_defaults != None and variable_range_defaults.get( e.tag) != None): self.info( "overwriting %s attribute %s with %s" % (name, e.tag, str(variable_range_defaults[e.tag]))) range[e.tag] = variable_range_defaults[e.tag] elif e.text == None: self.info( "missing vendor definition for %s, attribute %s" % (name, e.tag)) self._variables.get(instance)[name].set_allowed_value_range( **range) if vendor_values != None: self._variables.get( instance)[name].has_vendor_values = True elif service_range_defaults: variable_range_defaults = service_range_defaults.get(name) if variable_range_defaults != None: self._variables.get( instance)[name].set_allowed_value_range( **variable_range_defaults) self._variables.get( instance)[name].has_vendor_values = True for v in self._variables.get(0).values(): if isinstance(v.dependant_variable, str): v.dependant_variable = self._variables.get(instance).get( v.dependant_variable)
def build_single_notification(self, instance, variable_name, value): root = ET.Element('e:propertyset') root.attrib['xmlns:e']='urn:schemas-upnp-org:event-1-0' e = ET.SubElement( root, 'e:property') s = ET.SubElement( e, variable_name).text = str(value) return ET.tostring( root, encoding='utf-8')
def ConvertDictToXml(xmldict): roottag = xmldict.keys()[0] root = ElementTree.Element(roottag) _ConvertDictToXmlRecurse(root, xmldict[roottag]) return root
def __init__(self, hostname, uuid, urlbase, xmlns = 'urn:schemas-upnp-org:device-1-0', device_uri_base = 'urn:schemas-upnp-org:device', device_type = 'BasicDevice', version = 2, friendly_name = 'Coherence UPnP BasicDevice', manufacturer = 'beebits.net', manufacturer_url = 'http://coherence.beebits.net', model_description = 'Coherence UPnP BasicDevice', model_name = 'Coherence UPnP BasicDevice', model_number = __version__, model_url = 'http://coherence.beebits.net', serial_number = '0000001', presentation_url = '', services = [], devices = [], icons = [], dlna_caps = []): uuid = str(uuid) root = ET.Element('root') root.attrib['xmlns'] = xmlns device_type_uri = ':'.join((device_uri_base, device_type, str(version))) e = ET.SubElement(root, 'specVersion') ET.SubElement(e, 'major').text = '1' ET.SubElement(e, 'minor').text = '0' #ET.SubElement(root, 'URLBase').text = urlbase + uuid[5:] + '/' d = ET.SubElement(root, 'device') if device_type == 'MediaServer': x = ET.SubElement(d, 'dlna:X_DLNADOC') x.attrib['xmlns:dlna'] = 'urn:schemas-dlna-org:device-1-0' x.text = 'DMS-1.50' x = ET.SubElement(d, 'dlna:X_DLNADOC') x.attrib['xmlns:dlna'] = 'urn:schemas-dlna-org:device-1-0' x.text = 'M-DMS-1.50' elif device_type == 'MediaRenderer': x = ET.SubElement(d, 'dlna:X_DLNADOC') x.attrib['xmlns:dlna'] = 'urn:schemas-dlna-org:device-1-0' x.text = 'DMR-1.50' x = ET.SubElement(d, 'dlna:X_DLNADOC') x.attrib['xmlns:dlna'] = 'urn:schemas-dlna-org:device-1-0' x.text = 'M-DMR-1.50' if len(dlna_caps) > 0: if isinstance(dlna_caps, basestring): dlna_caps = [dlna_caps] for cap in dlna_caps: x = ET.SubElement(d, 'dlna:X_DLNACAP') x.attrib['xmlns:dlna'] = 'urn:schemas-dlna-org:device-1-0' x.text = cap ET.SubElement(d, 'deviceType').text = device_type_uri ET.SubElement(d, 'friendlyName').text = friendly_name ET.SubElement(d, 'manufacturer').text = manufacturer ET.SubElement(d, 'manufacturerURL').text = manufacturer_url ET.SubElement(d, 'modelDescription').text = model_description ET.SubElement(d, 'modelName').text = model_name ET.SubElement(d, 'modelNumber').text = model_number ET.SubElement(d, 'modelURL').text = model_url ET.SubElement(d, 'serialNumber').text = serial_number ET.SubElement(d, 'UDN').text = uuid ET.SubElement(d, 'UPC').text = '' ET.SubElement(d, 'presentationURL').text = presentation_url if len(services): e = ET.SubElement(d, 'serviceList') for service in services: l_id = service.get_id() s = ET.SubElement(e, 'service') try: namespace = service.namespace except: namespace = 'schemas-upnp-org' if(hasattr(service, 'version') and service.version < version): v = service.version else: v = version ET.SubElement(s, 'serviceType').text = 'urn:%s:service:%s:%d' % (namespace, l_id, int(v)) try: namespace = service.id_namespace except: namespace = 'upnp-org' ET.SubElement(s, 'serviceId').text = 'urn:%s:serviceId:%s' % (namespace, l_id) ET.SubElement(s, 'SCPDURL').text = '/' + uuid[5:] + '/' + l_id + '/' + service.scpd_url ET.SubElement(s, 'controlURL').text = '/' + uuid[5:] + '/' + l_id + '/' + service.control_url ET.SubElement(s, 'eventSubURL').text = '/' + uuid[5:] + '/' + l_id + '/' + service.subscription_url if len(devices): e = ET.SubElement(d, 'deviceList') if len(icons): e = ET.SubElement(d, 'iconList') for icon in icons: icon_path = '' if icon.has_key('url'): if icon['url'].startswith('file://'): icon_path = icon['url'][7:] elif icon['url'] == '.face': icon_path = os.path.join(os.path.expanduser('~'), ".face") else: from pkg_resources import resource_filename icon_path = os.path.abspath(resource_filename(__name__, os.path.join('..', '..', '..', 'misc', 'device-icons', icon['url']))) if os.path.exists(icon_path) == True: i = ET.SubElement(e, 'icon') for k, v in icon.items(): if k == 'url': if v.startswith('file://'): ET.SubElement(i, k).text = '/' + uuid[5:] + '/' + os.path.basename(v) continue elif v == '.face': ET.SubElement(i, k).text = '/' + uuid[5:] + '/' + 'face-icon.png' continue else: ET.SubElement(i, k).text = '/' + uuid[5:] + '/' + os.path.basename(v) continue ET.SubElement(i, k).text = str(v) #if self.has_level(LOG_DEBUG): # indent( root) self.xml = """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring(root, encoding = 'utf-8') static.Data.__init__(self, self.xml, 'text/xml')
def tostring(self): root = ConvertDictToXml(self.db) tree = ElementTree.ElementTree(root).getroot() indent(tree,0) xml = self.preamble + ElementTree.tostring(tree, encoding='utf-8') return xml
def toString(self,**kwargs): return ET.tostring(self.toElement(**kwargs),encoding='utf-8')
def toElement(self, **kwargs): root = ImageItem.toElement(self, **kwargs) if self.album is not None: ET.SubElement(root, qname('album', UPNP_NS)).text = self.album return root