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 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') d, p = event.send_notification(subscriber, xml) self._pending_notifications[d] = p d.addBoth(self.rm_notification, d) 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 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): """ 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 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): 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 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 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 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 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_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 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 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 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 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 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 __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: 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: 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 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 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): #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, 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 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 toString(self,**kwargs): return ET.tostring(self.toElement(**kwargs),encoding='utf-8')
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 omitt 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': arg_val = arg_val.lower() 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 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)