Пример #1
0
 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')
Пример #2
0
    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 get_containers_x_children(feature_list):
     root = ET.Element('u:X_GetFeatureListResponse')
     root.attrib['xmlns:u']='urn:schemas-upnp-org:service:ContentDirectory:1'
     e = ET.SubElement(root, 'FeatureList')
     e.text = create_containers(feature_list)
     r = """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8')
     return r
Пример #4
0
 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
Пример #5
0
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
Пример #6
0
    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')
Пример #7
0
    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 create_containers(containers={}):
     root = ET.Element('Features')
     root.attrib['xmlns']='urn:schemas-upnp-org:av:avs'
     root.attrib['xmlns:xsi']='http://www.w3.org/2001/XMLSchema-instance'
     root.attrib['xsi:schemaLocation']='urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd' 
     e = ET.SubElement(root, 'Feature')
     e.attrib['name'] = "samsung.com_BASICVIEW"
     e.attrib['version'] = str(1)
     
     if (len(containers)):
         for key, container in containers.items():
             i = ET.SubElement(e, 'container')
             id = str(container)
             i.attrib['id'] = id 
             if key == "imageItem":
                 i.attrib['type'] = "object.item.imageItem"
             elif key == "audioItem":
                 i.attrib['type'] = "object.item.audioItem"
             elif key == "videoItem":
                 i.attrib['type'] = "object.item.videoItem"
     xml = """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8')
     return xml
Пример #9
0
    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)
Пример #10
0
 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
Пример #11
0
 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')
Пример #12
0
 def tostring(self):
     root = ConvertDictToXml(self.db,self.element2attr_mappings)
     tree = ElementTree.ElementTree(root).getroot()
     indent(tree,0)
     xml = self.preamble + ElementTree.tostring(tree, encoding='utf-8')
     return xml
Пример #13
0
 def toString(self,**kwargs):
     return ET.tostring(self.toElement(**kwargs),encoding='utf-8')
Пример #14
0
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':
                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')
Пример #15
0
    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.ResourceManager 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')