Пример #1
0
    def test_basic(self):
        """
        """
        msg = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash6)
        self.assertEquals(remoting.encode(msg).getvalue(), "\x00" * 6)

        msg = remoting.Envelope(pyamf.AMF3, pyamf.ClientTypes.FlashCom)
        self.assertEquals(remoting.encode(msg).getvalue(), "\x03\x01" + "\x00" * 4)
Пример #2
0
    def test_basic(self):
        """
        """
        msg = remoting.Envelope(pyamf.AMF0)
        self.assertEquals(remoting.encode(msg).getvalue(), '\x00' * 6)

        msg = remoting.Envelope(pyamf.AMF3)
        self.assertEquals(remoting.encode(msg).getvalue(),
            '\x00\x03' + '\x00' * 4)
Пример #3
0
    def test_amf_parse(self):
        mq = MethodQueryCanonicalizer('POST', 'application/x-amf', 0, BytesIO())

        req = Request(target='t', body="")
        ev_1 = Envelope(AMF3)
        ev_1['/0'] = req

        req = Request(target='t', body="alt_content")
        ev_2 = Envelope(AMF3)
        ev_2['/0'] = req

        assert mq.amf_parse(encode(ev_1).getvalue(), None) != \
               mq.amf_parse(encode(ev_2).getvalue(), None)
Пример #4
0
    def test_response(self):
        """
        Test encoding of request body.
        """
        msg = remoting.Envelope(pyamf.AMF0)

        msg['/1'] = remoting.Response(body=[1, 2, 3])

        self.assertEqual(len(msg), 1)

        x = msg['/1']

        self.assertTrue(isinstance(x, remoting.Response))
        self.assertEqual(x.envelope, msg)
        self.assertEqual(x.body, [1, 2, 3])
        self.assertEqual(x.status, 0)
        self.assertEqual(x.headers, msg.headers)

        self.assertEqual(
            remoting.encode(msg).getvalue(),
            '\x00\x00\x00\x00'
            '\x00\x01\x00\x0b/1/onResult\x00\x04null\x00\x00\x00\x00\n\x00\x00'
            '\x00\x03\x00?\xf0\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00'
            '\x00\x00\x00\x00@\x08\x00\x00\x00\x00\x00\x00'
        )
Пример #5
0
    def execute_single(self, request):
        """
        Builds, sends and handles the response to a single request, returning
        the response.
        """
        if self.logger:
            self.logger.debug('Executing single request: %s', request)

        self.removeRequest(request)

        body = remoting.encode(
            self.getAMFRequest([request]),
            strict=self.strict
        )

        http_request = urllib2.Request(
            self._root_url, body.getvalue(),
            self._get_execute_headers()
        )

        if self.proxy_args:
            http_request.set_proxy(*self.proxy_args)

        envelope = self._getResponse(http_request)

        return envelope[request.id]
Пример #6
0
def get_episode_info(key, content_id, url, exp_id):
    conn = httplib.HTTPConnection("c.brightcove.com")
    envelope = build_amf_request(key, content_id, url, exp_id)
    conn.request("POST", "/services/messagebroker/amf?playerKey="+key, str(remoting.encode(envelope).read()),{'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    return response
Пример #7
0
	def __GetBrightCoveData(self):
		""" Retrieves the Url's from a brightcove stream

		Arguments:
		playerKey : string - Key identifying the current request
		contentId : int    - ID of the content to retrieve
		url       : string - Url of the page that calls the video SWF
		seed      : string - Constant which depends on the website

		Keyword Arguments:
		experienceId : id     - <unknown parameter>

		Returns a dictionary with the data

		"""

		# Seed = 61773bc7479ab4e69a5214f17fd4afd21fe1987a
		envelope = self.__BuildBrightCoveAmfRequest(self.playerKey, self.contentId, self.url, self.experienceId, self.seed, self.contentRefId)

		if self.proxy:
			connection = httplib.HTTPConnection(self.proxy.Proxy, self.proxy.Port)
		else:
			connection = httplib.HTTPConnection("c.brightcove.com")
		print envelope
		jj = remoting.encode(envelope).read()			

		connection.request("POST", "http://c.brightcove.com/services/messagebroker/amf?playerKey=" + str(self.playerKey), str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
		response = connection.getresponse().read()
		#print 	response	
		response = remoting.decode(response).bodies[0][1].body
		print response
		if self.logger:
			self.logger.Trace(response)
		self.full_response = response
		return response['programmedContent']['videoPlayer']['mediaDTO']
Пример #8
0
def get_clip_info(clip_name):
    conn = httplib.HTTPConnection("www.tele5.de")
    envelope = build_amf_request(clip_name)
    conn.request("POST", "/gateway/gateway.php", str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    return response
Пример #9
0
def get_episode_info(video_player_key, video_content_id, video_url, video_player_id):
	envelope = build_amf_request(video_player_key, video_content_id, video_url, video_player_id)
	connection_url = "http://c.brightcove.com/services/messagebroker/amf?playerKey=" + video_player_key
	values = bytes(remoting.encode(envelope).read())
	header = {'Content-Type' : 'application/x-amf'}
	response = remoting.decode(_connection.getAMF(connection_url, values,  header)).bodies[0][1].body
	return response
Пример #10
0
def GetPlayableUrl(amf_constant, url, experience_id, player_key, content_id=None, content_ref_id=None):       
    
    from pyamf import remoting
    from entertainment.net import Net
    net = Net()
    
    amf_request_data = BuildAmfRequest(amf_constant, url, experience_id, player_key, content_id=content_id, content_ref_id=content_ref_id)
    amf_encoded_request_data = remoting.encode(amf_request_data).read()
    
    amf_encoded_response_data = net.http_POST_BINARY(
                                    'http://c.brightcove.com', 
                                    "/services/messagebroker/amf?playerKey=" + player_key.encode('ascii'),
                                     amf_encoded_request_data, 
                                     headers = {'content-type': 'application/x-amf'} ).content
                                     
    amf_response_data = remoting.decode(amf_encoded_response_data).bodies[0][1].body
    
    playable_url = amf_response_data['programmedContent']['videoPlayer']['mediaDTO']['FLVFullLengthURL']
    
    # do something with renditions ... to get best quality
    # renditions = amf_response_data['programmedContent']['videoPlayer']['mediaDTO']['renditions']
    # sample renditions below
    '''
    'renditions': [{'videoCodec': u'ON2', 'defaultURL': u'http://brightcove03-f.akamaihd.net/3abnEnglishF_3ABN_250@100395', 
    'encodingRate': 250000, 'audioOnly': False, 'videoContainer': 1, 'mediaDeliveryType': 0, 'frameWidth': 384, 'size': 0.0, 'frameHeight': 512}, 
    {'videoCodec': u'ON2', 'defaultURL': u'http://brightcove03-f.akamaihd.net/3abnEnglishF_3ABN_600@100395', 'encodingRate': 600000, 'audioOnly': False, 
    'videoContainer': 1, 'mediaDeliveryType': 0, 'frameWidth': 480, 'size': 0.0, 'frameHeight': 640}, 
    {'videoCodec': u'ON2', 'defaultURL': u'http://brightcove03-f.akamaihd.net/3abnEnglishF_3ABN_64@100395', 'encodingRate': 64000, 'audioOnly': False, 
    'videoContainer': 1, 'mediaDeliveryType': 0, 'frameWidth': 240, 'size': 0.0, 'frameHeight': 320}, 
    {'videoCodec': u'ON2', 'defaultURL': u'http://brightcove03-f.akamaihd.net/3abnEnglishF_3ABN_1200@100395', 'encodingRate': 1200000, 'audioOnly': False, 
    'videoContainer': 1, 'mediaDeliveryType': 0, 'frameWidth': 480, 'size': 0.0, 'frameHeight': 720}]
    '''
    
    return playable_url
Пример #11
0
    def get(self, url):
        try:
            from pyamf import remoting
        except ImportError:
            log.error("You need to install pyamf to download content from kanal5 and kanal9")
            log.error("In debian the package is called python-pyamf")
            sys.exit(2)

        player_id = 811317479001
        publisher_id = 22710239001
        const = "9f79dd85c3703b8674de883265d8c9e606360c2e"
        env = remoting.Envelope(amfVersion=3)
        env.bodies.append(("/1", remoting.Request(target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", body=[const, player_id, self.other, publisher_id], envelope=env)))
        env = str(remoting.encode(env).read())
        url = "http://" + url + "/services/messagebroker/amf?playerKey=AQ~~,AAAABUmivxk~,SnCsFJuhbr0vfwrPJJSL03znlhz-e9bk"
        header = "application/x-amf"
        data = get_http_data(url, "POST", header, env)
        streams = {}

        for i in remoting.decode(data).bodies[0][1].body['renditions']:
            stream = {}
            stream["uri"] = i["defaultURL"]
            streams[i["encodingRate"]] = stream

        test = select_quality(self.options, streams)

        filename = test["uri"]
        match = re.search("(rtmp[e]{0,1}://.*)\&(.*)$", filename)
        other = "-W %s -y %s " % ("http://admin.brightcove.com/viewer/us1.25.04.01.2011-05-24182704/connection/ExternalConnection_2.swf", match.group(2))
        download_rtmp(self.options, match.group(1), self.output, self.live, other, self.resume)
Пример #12
0
    def __GetBrightCoveData(self):
        """ Retrieves the Url's from a brightcove stream
        
        Arguments:
        playerKey : string - Key identifying the current request
        contentId : int    - ID of the content to retrieve
        url       : string - Url of the page that calls the video SWF
        seed      : string - Constant which depends on the website
        
        Keyword Arguments:
        experienceId : id     - <unknown parameter>
        
        Returns a dictionary with the data
        
        """

        # Seed = 61773bc7479ab4e69a5214f17fd4afd21fe1987a
        envelope = self.__BuildBrightCoveAmfRequest(
            self.playerKey, self.contentId, self.url, self.experienceId, self.seed
        )

        connection = httplib.HTTPConnection("c.brightcove.com")
        connection.request(
            "POST",
            "/services/messagebroker/amf?playerKey=" + self.playerKey,
            str(remoting.encode(envelope).read()),
            {"content-type": "application/x-amf"},
        )
        response = connection.getresponse().read()
        response = remoting.decode(response).bodies[0][1].body

        # self.logger.debug(response)
        return response["programmedContent"]["videoPlayer"]["mediaDTO"]
Пример #13
0
def get_clip_info(const, playerID, videoPlayer, publisherID):
    conn = httplib.HTTPConnection("c.brightcove.com")
    envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
    conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    return response  
Пример #14
0
    def _makeRequestBody(self, service, body, raw=False):
        if not raw:
            body = [body]

        e = remoting.Envelope(pyamf.AMF3)
        e['/1'] = remoting.Request(service, body=body)
        return remoting.encode(e)
Пример #15
0
    def test_process_request(self):
        def echo(data):
            return data

        self.gw.addService(echo)

        env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
        request = remoting.Request("echo", body=["hello"])
        env["/1"] = request

        d = client.getPage(
            "http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()
        )

        def cb(result):
            response = remoting.decode(result)

            self.assertEquals(response.amfVersion, pyamf.AMF0)
            self.assertEquals(response.clientType, pyamf.ClientTypes.Flash9)

            self.assertTrue("/1" in response)
            body_response = response["/1"]

            self.assertEquals(body_response.status, remoting.STATUS_OK)
            self.assertEquals(body_response.body, "hello")

        return d.addCallback(cb)
    def execute_single(self, request):
        """
        Builds, sends and handles the response to a single request, returning
        the response.

        @param request:
        @type request:
        @rtype:
        """
        self.logger.debug('Executing single request: %s' % request)
        body = remoting.encode(self.getAMFRequest([request]))
        headers = {'Content-Type': remoting.CONTENT_TYPE,
                   'User-Agent': self.user_agent}

        if self.referer is not None:
            headers['Referer'] = self.referer

        self.logger.debug('Sending POST request to %s' % self._root_url)
        self.connection.request('POST', self._root_url, body.getvalue(),
                                headers)

        envelope = self._getResponse()
        self.removeRequest(request)

        return envelope[request.id]
Пример #17
0
    def test_timezone(self):
        import datetime

        self.executed = False

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEquals(d, now + td)
            self.executed = True

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        msg = remoting.Envelope(amfVersion=pyamf.AMF0, clientType=0)
        msg["/1"] = remoting.Request(target="echo", body=[now])

        stream = remoting.encode(msg)

        d = client.getPage("http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=stream.getvalue())

        def cb(response):
            envelope = remoting.decode("".join(response))
            message = envelope["/1"]

            self.assertEquals(message.status, remoting.STATUS_OK)
            self.assertEquals(message.body, now)

        return d.addCallback(cb)
Пример #18
0
    def test_expose_request(self):
        self.gw.expose_request = True
        self.executed = False

        env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
        request = remoting.Request("echo", body=["hello"])
        env["/1"] = request

        def echo(http_request, data):
            self.assertTrue(isinstance(http_request, http.Request))

            self.assertTrue(hasattr(http_request, "amf_request"))
            amf_request = http_request.amf_request

            self.assertEquals(request.target, "echo")
            self.assertEquals(request.body, ["hello"])
            self.executed = True

            return data

        self.gw.addService(echo)

        d = client.getPage(
            "http://127.0.0.1:%d/" % (self.port,), method="POST", postdata=remoting.encode(env).getvalue()
        )

        return d.addCallback(lambda x: self.assertTrue(self.executed))
    def execute(self):
        """
        Builds, sends and handles the responses to all requests listed in
        C{self.requests}.
        """
        body = remoting.encode(self.getAMFRequest(self.requests))
        headers = {'Content-Type': remoting.CONTENT_TYPE,
                   'User-Agent': self.user_agent}

        if self.referer is not None:
            headers['Referer'] = self.referer

        self.logger.debug('Sending POST request to %s' % self._root_url)
        self.connection.request('POST', self._root_url, body.getvalue(),
                                headers)

        envelope = self._getResponse()

        for response in envelope:
            request = self.getRequest(response[0])
            response = response[1]

            request.setResponse(response)

            self.removeRequest(request)
Пример #20
0
def write_envelope(version, filename):
    envelope = Envelope(amfVersion=version)
    message = Response(records)
    envelope.__setitem__('message', message);
    stream = remoting.encode(envelope)
    file = open(filename, 'w+')
    file.write(stream.getvalue())
Пример #21
0
    def test_timezone(self):
        import datetime

        http_request = http.HttpRequest()
        self.executed = False

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEqual(d, now + td)
            self.executed = True

            return d

        gw = django.DjangoGateway({'test.test': echo}, timezone_offset=-18000,
            expose_request=False)

        msg = remoting.Envelope(amfVersion=pyamf.AMF0)
        msg['/1'] = remoting.Request(target='test.test', body=[now])

        http_request.method = 'POST'
        http_request.raw_post_data = remoting.encode(msg).getvalue()

        res = remoting.decode(gw(http_request).content)
        self.assertTrue(self.executed)

        self.assertEqual(res['/1'].body, now)
Пример #22
0
    def test_timezone(self):
        import datetime

        self.executed = False

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEquals(d, now + td)
            self.executed = True

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        msg = remoting.Envelope(amfVersion=pyamf.AMF0)
        msg['/1'] = remoting.Request(target='echo', body=[now])

        stream = remoting.encode(msg)
        self.environ['wsgi.input'] = stream
        self.gw.post()

        envelope = remoting.decode(self.response.out.getvalue())
        message = envelope['/1']

        self.assertEquals(message.body, now)
        self.assertTrue(self.executed)
Пример #23
0
    def test_process_request(self):
        def echo(data):
            return data

        self.gw.addService(echo)

        env = remoting.Envelope(pyamf.AMF3)
        request = remoting.Request('echo', body=['hello'])
        env['/1'] = request

        d = client.getPage("http://127.0.0.1:%d/" % (self.port,),
                method="POST", postdata=remoting.encode(env).getvalue())

        def cb(result):
            response = remoting.decode(result)

            self.assertEquals(response.amfVersion, pyamf.AMF3)

            self.assertTrue('/1' in response)
            body_response = response['/1']

            self.assertEquals(body_response.status, remoting.STATUS_OK)
            self.assertEquals(body_response.body, 'hello')

        return d.addCallback(cb)
Пример #24
0
    def execute(self):
        """
        Builds, sends and handles the responses to all requests listed in
        C{self.requests}.
        """
        requests = self.requests[:]

        for r in requests:
            self.removeRequest(r)

        body = remoting.encode(
            self.getAMFRequest(requests),
            strict=self.strict
        )

        http_request = urllib2.Request(
            self._root_url, body.getvalue(),
            self._get_execute_headers()
        )

        if self.proxy_args:
            http_request.set_proxy(*self.proxy_args)

        envelope = self._getResponse(http_request)

        return envelope
Пример #25
0
    def test_timezone(self):
        import datetime

        self.executed = False

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEquals(d, now + td)
            self.executed = True

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        msg = remoting.Envelope(amfVersion=pyamf.AMF0)
        msg['/1'] = remoting.Request(target='echo', body=[now])

        stream = remoting.encode(msg)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(stream)),
            'wsgi.input': stream
        }

        response = self.gw(env, lambda *args: None)
        envelope = remoting.decode(''.join(response))
        message = envelope['/1']

        self.assertEquals(message.body, now)
Пример #26
0
    def test_encoding_error(self):
        encode = _twisted.remoting.encode

        def force_error(amf_request, context=None):
            raise pyamf.EncodeError

        def echo(request, data):
            return data

        self.gw.addService(echo)

        env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
        request = remoting.Request('echo', body=['hello'])
        env['/1'] = request

        d = client.getPage("http://127.0.0.1:%d/" % (self.port,),
                method="POST", postdata=remoting.encode(env).getvalue())

        _twisted.remoting.encode = force_error
        def switch(x):
            _twisted.remoting.encode = encode

        d = self.assertFailure(d, error.Error)

        def check(exc):
            self.assertEquals(int(exc.args[0]), http.INTERNAL_SERVER_ERROR)
            self.assertTrue(exc.args[1].startswith('500 Internal Server Error'))

        d.addCallback(check)

        return d.addBoth(switch)
Пример #27
0
    def test_deferred_service(self):
        def echo(data):
            x = defer.Deferred()
            reactor.callLater(0, x.callback, data)

            return x

        self.gw.addService(echo)

        env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
        request = remoting.Request('echo', body=['hello'])
        env['/1'] = request

        d = client.getPage("http://127.0.0.1:%d/" % (self.port,),
                method="POST", postdata=remoting.encode(env).getvalue())

        def cb(result):
            response = remoting.decode(result)

            self.assertEquals(response.amfVersion, pyamf.AMF0)
            self.assertEquals(response.clientType, pyamf.ClientTypes.Flash9)

            self.assertTrue('/1' in response)
            body_response = response['/1']

            self.assertEquals(body_response.status, remoting.STATUS_OK)
            self.assertEquals(body_response.body, 'hello')

        return d.addCallback(cb)
Пример #28
0
    def test_expose_request(self):
        self.gw.expose_request = True
        self.executed = False

        env = remoting.Envelope(pyamf.AMF3)
        request = remoting.Request('echo', body=['hello'])
        env['/1'] = request

        request = remoting.encode(env)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def echo(http_request, data):
            self.assertTrue('pyamf.request' in http_request)
            request = http_request['pyamf.request']

            self.assertTrue(isinstance(request, remoting.Request))

            self.assertEquals(request.target, 'echo')
            self.assertEquals(request.body, ['hello'])
            self.executed = True

            return data

        self.gw.addService(echo)

        response = self.gw(env, lambda *args: None)

        self.assertTrue(self.executed)
Пример #29
0
    def execute(self):
        if self.logger:
            self.logger.debug('Sending POST request to %s', self.url.geturl())
            self.logger.debug('User-Agent: %s', self.user_agent)
            for key, value in self.http_headers.iteritems():
                self.logger.debug('%s: %s', key, value)

        # Make sure these requests won't get added to another batch
        requests = self.requests
        self.requests = []

        port = self.url.port or 80
        body = remoting.encode(self._createAMFRequest(requests),
                                   strict=self.strict).getvalue()

        factory = HTTPClientFactory(self.url.geturl(), 'POST', body,
                                    self.http_headers, self.user_agent)
        factory.deferred.addCallbacks(self._handleHTTPResponse,
                                      self._handleHTTPError,
                                      [factory],
                                      errbackArgs=[factory])
        factory.deferred.addCallback(remoting.decode, strict=self.strict)
        factory.deferred.addCallbacks(self._handleAMFResponse,
                                      self._handleAMFError,
                                      [requests],
                                      errbackArgs=[requests])
        reactor.connectTCP(self.url.hostname, port, factory)
Пример #30
0
def get_kanal5(video_player):
	player_id = 811317479001
	publisher_id = 22710239001
	const = '9f79dd85c3703b8674de883265d8c9e606360c2e'

	env = remoting.Envelope(amfVersion=3)
	env.bodies.append(
		(
			"/1", 
			remoting.Request(
				target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", 
				body=[const, player_id, video_player, publisher_id],
				envelope=env
			)
		)
	)
	env = str(remoting.encode(env).read())

	conn = httplib.HTTPConnection("c.brightcove.com")
	conn.request("POST", "/services/messagebroker/amf?playerKey=AQ~~,AAAABUmivxk~,SnCsFJuhbr0vfwrPJJSL03znlhz-e9bk", env, {'content-type': 'application/x-amf'})
	response = conn.getresponse().read()
	rtmp = ''
	for rendition in remoting.decode(response).bodies[0][1].body['renditions']:
		rtmp += '"%sx%s:%s";' % (rendition['frameWidth'], rendition['frameHeight'], rendition['defaultURL'])
	return rtmp
Пример #31
0
    def test_tuple(self):
        def echo(data):
            return data

        self.gw.addService(echo)

        env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
        request = remoting.Request('echo', body=[('Hi', 'Mom')])
        env['/1'] = request

        d = client.getPage("http://127.0.0.1:%d/" % (self.port, ),
                           method="POST",
                           postdata=remoting.encode(env).getvalue())

        def cb(result):
            response = remoting.decode(result)
            body_response = response['/1']

            self.assertEquals(body_response.status, remoting.STATUS_OK)
            self.assertEquals(body_response.body, ['Hi', 'Mom'])

        return d.addCallback(cb)
Пример #32
0
    def test_request(self):
        """
        Test encoding of request body.
        """
        msg = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash6)

        msg['/1'] = remoting.Request('test.test', body='hello')

        self.assertEquals(len(msg), 1)

        x = msg['/1']

        self.assertTrue(isinstance(x, remoting.Request))
        self.assertEquals(x.envelope, msg)
        self.assertEquals(x.target, 'test.test')
        self.assertEquals(x.body, 'hello')
        self.assertEquals(x.headers, msg.headers)

        self.assertEquals(
            remoting.encode(msg).getvalue(),
            '\x00\x00\x00\x00\x00\x01\x00\ttest.test\x00\x02/1\x00\x00\x00\x00'
            '\x02\x00\x05hello')
Пример #33
0
    def execute(self):
        """
        Builds, sends and handles the responses to all requests listed in
        C{self.requests}.
        """
        requests = self.requests[:]

        for r in requests:
            self.removeRequest(r)

        body = remoting.encode(self.getAMFRequest(requests),
            strict=self.strict)

        http_request = urllib2.Request(self._root_url, body.getvalue(),
            self._get_execute_headers())

        if self.proxy_args:
            http_request.set_proxy(*self.proxy_args)

        envelope = self._getResponse(http_request)

        return envelope
Пример #34
0
    def execute(self):
        """
        Builds, sends and handles the responses to all requests listed in
        C{self.requests}.
        """
        body = remoting.encode(self.getAMFRequest(self.requests), strict=self.strict)

        self.logger.debug('Sending POST request to %s' % self._root_url)
        self.connection.request('POST', self._root_url,
            body.getvalue(),
            self._get_execute_headers()
        )

        envelope = self._getResponse()

        for response in envelope:
            request = self.getRequest(response[0])
            response = response[1]

            request.setResponse(response)

            self.removeRequest(request)
Пример #35
0
    def test_response(self):
        """
        Test encoding of request body.
        """
        msg = remoting.Envelope(pyamf.AMF0)

        msg['/1'] = remoting.Response(body=[1, 2, 3])

        self.assertEqual(len(msg), 1)

        x = msg['/1']

        self.assertTrue(isinstance(x, remoting.Response))
        self.assertEqual(x.envelope, msg)
        self.assertEqual(x.body, [1, 2, 3])
        self.assertEqual(x.status, 0)
        self.assertEqual(x.headers, msg.headers)

        self.assertEqual(remoting.encode(msg).getvalue(), '\x00\x00\x00\x00'
            '\x00\x01\x00\x0b/1/onResult\x00\x04null\x00\x00\x00\x00\n\x00\x00'
            '\x00\x03\x00?\xf0\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00'
            '\x00\x00\x00\x00@\x08\x00\x00\x00\x00\x00\x00')
Пример #36
0
    def execute_single(self, request):
        """
        Builds, sends and handles the response to a single request, returning
        the response.

        @param request:
        @type request:
        @rtype:
        """
        self.logger.debug('Executing single request: %s' % request)
        body = remoting.encode(self.getAMFRequest([request]), strict=self.strict)

        self.logger.debug('Sending POST request to %s' % self._root_url)
        self.connection.request('POST', self._root_url,
            body.getvalue(),
            self._get_execute_headers()
        )

        envelope = self._getResponse()
        self.removeRequest(request)

        return envelope[request.id]
Пример #37
0
    def setUp(self):
        import gzip

        env = remoting.Envelope(pyamf.AMF3)
        r = remoting.Response(['foo' * 50000] * 200)

        env['/1'] = r

        response = remoting.encode(env).getvalue()

        buf = util.BufferedByteStream()
        x = gzip.GzipFile(fileobj=buf, mode='wb')

        x.write(response)

        x.close()

        self.canned_response = buf.getvalue()

        BaseServiceTestCase.setUp(self)

        self.headers['Content-Encoding'] = 'gzip'
Пример #38
0
    def rewrite_stream(self, stream, rwinfo):
        try:
            from pyamf import remoting

            iobuff = BytesIO()
            while True:
                buff = stream.read()
                if not buff:
                    break
                iobuff.write(buff)

            iobuff.seek(0)
            res = remoting.decode(iobuff)

            # TODO: revisit this
            inputdata = rwinfo.url_rewriter.rewrite_opts.get('pywb.inputdata')

            if inputdata:
                new_list = []

                for src, target in zip(inputdata.bodies, res.bodies):
                    #print(target[0] + ' = ' + src[0])

                    #print('messageId => corrId ' + target[1].body.correlationId + ' => ' + src[1].body[0].messageId)
                    target[1].body.correlationId = src[1].body[0].messageId

                    new_list.append((src[0], target[1]))

                res.bodies = new_list

            return BytesIO(remoting.encode(res).getvalue())

        except Exception as e:
            import traceback
            traceback.print_exc()
            print(e)

            stream.seek(0)
            return stream
Пример #39
0
    def execute_single(self, request):
        """
        Builds, sends and handles the response to a single request, returning
        the response.
        """
        if self.logger:
            self.logger.debug('Executing single request: %s', request)

        self.removeRequest(request)

        body = remoting.encode(self.getAMFRequest([request]),
                               strict=self.strict)

        http_request = urllib.request.Request(self._root_url, body.getvalue(),
                                              self._get_execute_headers())

        if self.proxy_args:
            http_request.set_proxy(*self.proxy_args)

        envelope = self._getResponse(http_request)

        return envelope[request.id]
Пример #40
0
    def test_request(self):
        """
        Test encoding of request body.
        """
        msg = remoting.Envelope(pyamf.AMF0)

        msg['/1'] = remoting.Request('test.test', body=['hello'])

        self.assertEqual(len(msg), 1)

        x = msg['/1']

        self.assertTrue(isinstance(x, remoting.Request))
        self.assertEqual(x.envelope, msg)
        self.assertEqual(x.target, 'test.test')
        self.assertEqual(x.body, ['hello'])
        self.assertEqual(x.headers, msg.headers)

        self.assertEqual(
            remoting.encode(msg).getvalue(),
            b'\x00\x00\x00\x00\x00\x01\x00\ttest.test\x00\x02/1\x00\x00\x00'
            b'\x00\n\x00\x00\x00\x01\x02\x00\x05hello'
        )
Пример #41
0
    def doRequest(self,
                  service,
                  body=missing,
                  type=pyamf.AMF3,
                  raw=False,
                  decode=True):
        if not raw:
            if body is self.missing:
                body = []
            else:
                body = [body]

            env = remoting.Envelope(type)
            request = remoting.Request(service, body=body)
            env['/1'] = request

            body = remoting.encode(env).getvalue()

        d = self.getPage(body)

        if decode:
            d.addCallback(lambda result: remoting.decode(result))

        return d
Пример #42
0
def playBrightCoveStream(bc_videoID):
    from pyamf import remoting
    import httplib
    bc_playerID = 813474149001
    bc_publisherID = 165012893
    bc_const = "cf760beae3fbdde270b76f2109537e13144e6fbd"
    conn = httplib.HTTPConnection("c.brightcove.com")
    envelope = remoting.Envelope(amfVersion=3)
    envelope.bodies.append(
        ("/1",
         remoting.Request(
             target=
             "com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
             body=[bc_const, bc_playerID, bc_videoID, bc_publisherID],
             envelope=envelope)))
    conn.request("POST",
                 "/services/messagebroker/amf?playerId=" + str(bc_playerID),
                 str(remoting.encode(envelope).read()),
                 {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    streamUrl = ""
    for item in sorted(response['renditions'],
                       key=lambda item: item['encodingRate'],
                       reverse=False):
        encRate = item['encodingRate']
        if encRate <= selfAddon.getSetting("ss-qua"):
            streamUrl = item['defaultURL']
    if streamUrl.find("http://") == 0:
        return streamUrl + "?videoId=" + bc_videoID + "&lineUpId=&pubId=" + str(
            bc_publisherID) + "&playerId=" + str(
                bc_playerID) + "&affiliateId=&v=&fp=&r=&g="
    else:
        url = streamUrl[0:streamUrl.find("&")]
        playpath = streamUrl[streamUrl.find("&") + 1:]
        return url + ' playpath=' + playpath
Пример #43
0
# save cookies
jar = login_request.cookies

# build message for CF backend
msg = messaging.RemotingMessage(operation='loadRoles',
                                source='model.remote.remoteRoleManager',
                                destination='ColdFusion',
                                messageId=str(uuid.uuid4()).upper(),
                                body=[0, 'cc'])
# make an envelope
req = remoting.Request(target='null', body=[msg])
ev = remoting.Envelope(pyamf.AMF3)
ev['/0'] = req
# encode id
bin_msg = remoting.encode(ev)
# send -> the xml formatted request you can find in AMF folder
resp = requests.post(
    ''.join(['http://', host, '/flex2gateway/']),
    data=bin_msg.getvalue(),
    headers={'Content-Type': 'application/x-amf'},
    cookies=jar,
    #proxies = proxies
)
# get the response -> the xml formatted response you can find in AMF folder
resp_msg = remoting.decode(resp.content)
#print(resp_msg.bodies)
# iterate in a dirty way...
# resp_mgs.bodies -> list
resp_msg_list = resp_msg.bodies
# resp_msg_list -> tuple
Пример #44
0
def this_is_spider(module_path):
    msg = messaging.RemotingMessage(messageId=str(uuid.uuid1()).upper(),
                                    clientId=str(uuid.uuid1()).upper(),
                                    operation='getAllShowHourData',
                                    destination='GISCommonDataUtilForWms',
                                    timeToLive=0,
                                    timestamp=0,
                                    body=[],
                                    source=None)
    # 第一个是查询参数,第二个是页数,第三个是控制每页显示的数量(默认每页只显示15条)
    #msg.body = [HqPara()]
    msg.headers['DSEndpoint'] = None
    msg.headers['DSId'] = str(uuid.uuid1()).upper()
    # 按AMF协议编码数据
    req = remoting.Request('null', body=(msg, ))
    env = remoting.Envelope(amfVersion=pyamf.AMF3)
    env.bodies = [('/1', req)]
    data = bytes(remoting.encode(env).read())
    # 提交请求
    url = 'http://wms.zjemc.org.cn/wms/messagebroker/amfWms'
    req = urllib2.Request(url,
                          data,
                          headers={'Content-Type': 'application/x-amf'})
    # 解析返回数据
    opener = urllib2.build_opener()

    # 解码AMF协议返回的数据
    resp = remoting.decode(opener.open(req).read())
    result = str(resp.bodies)
    number1_a = result.find("u'\u8bf8\u5bb6'")  #诸家
    result_1 = result[number1_a:]
    number1_b = result_1.find('}')
    result_1_f = result_1[:number1_b]
    number1_c = result_1_f.find('[')
    number1_d = result_1_f.find(']')
    result_1_g = result_1_f[number1_c + 1:number1_d]
    result_1_h = result_1_g.split(',')

    number2_a = result.find("u'\u5357\u661f\u6865\u6e2f'")  #南星桥港
    result_2 = result[number2_a:]
    number2_b = result_2.find('}')
    result_2_f = result_2[:number2_b]
    number2_c = result_2_f.find('[')
    number2_d = result_2_f.find(']')
    result_2_g = result_2_f[number2_c + 1:number2_d]
    result_2_h = result_2_g.split(',')

    number3_a = result.find("u'\u5927\u9ebb'")  #大麻
    result_3 = result[number3_a:]
    number3_b = result_3.find('}')
    result_3_f = result_3[:number3_b]
    number3_c = result_3_f.find('[')
    number3_d = result_3_f.find(']')
    result_3_g = result_3_f[number3_c + 1:number3_d]
    result_3_h = result_3_g.split(',')

    number4_a = result.find("u'\u8054\u5408\u6865'")  #联合桥
    result_4 = result[number4_a:]
    number4_b = result_4.find('}')
    result_4_f = result_4[:number4_b]
    number4_c = result_4_f.find('[')
    number4_d = result_4_f.find(']')
    result_4_g = result_4_f[number4_c + 1:number4_d]
    result_4_h = result_4_g.split(',')

    number5_a = result.find("u'\u665a\u6751'")  #晚村
    result_5 = result[number5_a:]
    number5_b = result_5.find('}')
    result_5_f = result_5[:number5_b]
    number5_c = result_5_f.find('[')
    number5_d = result_5_f.find(']')
    result_5_g = result_5_f[number5_c + 1:number5_d]
    result_5_h = result_5_g.split(',')

    number6_a = result.find("u'\u4e4c\u9547'")  #乌镇
    result_6 = result[number6_a:]
    number6_b = result_6.find('}')
    result_6_f = result_6[:number6_b]
    number6_c = result_6_f.find('[')
    number6_d = result_6_f.find(']')
    result_6_g = result_6_f[number6_c + 1:number6_d]
    result_6_h = result_6_g.split(',')

    number7_a = result.find("u'\u4e4c\u9547\u5317'")  #乌镇北
    result_7 = result[number7_a:]
    number7_b = result_7.find('}')
    result_7_f = result_7[:number7_b]
    number7_c = result_7_f.find('[')
    number7_d = result_7_f.find(']')
    result_7_g = result_7_f[number7_c + 1:number7_d]
    result_7_h = result_7_g.split(',')

    number8_a = result.find("u'\u65b0\u584d\u5927\u901a'")  #新塍大通
    result_8 = result[number8_a:]
    number8_b = result_8.find('}')
    result_8_f = result_8[:number8_b]
    number8_c = result_8_f.find('[')
    number8_d = result_8_f.find(']')
    result_8_g = result_8_f[number8_c + 1:number8_d]
    result_8_h = result_8_g.split(',')

    number9_a = result.find("u'\u676d\u7533\u516c\u8def\u6865'")  #杭申公路桥
    result_9 = result[number9_a:]
    number9_b = result_9.find('}')
    result_9_f = result_9[:number9_b]
    number9_c = result_9_f.find('[')
    number9_d = result_9_f.find(']')
    result_9_g = result_9_f[number9_c + 1:number9_d]
    result_9_h = result_9_g.split(',')
    result_total = [{
        'name': '南星桥港',
        'value': result_2_h
    }, {
        'name': '大麻',
        'value': result_3_h
    }, {
        'name': '联合桥',
        'value': result_4_h
    }, {
        'name': '晚村',
        'value': result_5_h
    }, {
        'name': '乌镇',
        'value': result_6_h
    }, {
        'name': '乌镇北',
        'value': result_7_h
    }, {
        'name': '新塍大通',
        'value': result_8_h
    }, {
        'name': '杭申公路桥',
        'value': result_9_h
    }]
    json_url1 = module_path + 'json_szsj1.json'
    text1 = open(json_url1, 'w')
    data_json = json.dumps(result_total, ensure_ascii=False)
    text1.write(data_json)
    text1.close()
Пример #45
0
def playBrightCoveStream(bc_videoID):
    bc_playerID = 761157706001
    bc_publisherID = 710858724001
    bc_const = "cf760beae3fbdde270b76f2109537e13144e6fbd"
    conn = httplib.HTTPConnection("c.brightcove.com")
    envelope = remoting.Envelope(amfVersion=3)
    envelope.bodies.append(("/1", remoting.Request(target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", body=[bc_const, bc_playerID, bc_videoID, bc_publisherID], envelope=envelope)))
    conn.request("POST", "/services/messagebroker/amf?playerId=" + str(bc_playerID), str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    streamUrl = ""
    for item in sorted(response['renditions'], key=lambda item: item['encodingRate'], reverse=False):
        encRate = item['encodingRate']
        if encRate < maxBitRate:
            streamUrl = item['defaultURL']
    if streamUrl.find("http://") == 0:
        listItem = xbmcgui.ListItem(path=streamUrl+"?videoId="+bc_videoID+"&lineUpId=&pubId="+str(bc_publisherID)+"&playerId="+str(bc_playerID)+"&affiliateId=&v=&fp=&r=&g=")
    else:
        url = streamUrl[0:streamUrl.find("&")]
        playpath = streamUrl[streamUrl.find("&")+1:]
        listItem = xbmcgui.ListItem(path=url+' playpath='+playpath)
    xbmcplugin.setResolvedUrl(pluginhandle, True, listItem)
Пример #46
0
def playBrightCoveStream(bc_videoID, title, thumb, isSingle):
    bc_playerID = 586587148001
    bc_publisherID = 1659832546
    bc_const = "ef59d16acbb13614346264dfe58844284718fb7b"
    conn = httplib.HTTPConnection("c.brightcove.com")
    envelope = remoting.Envelope(amfVersion=3)
    envelope.bodies.append(("/1", remoting.Request(target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", body=[bc_const, bc_playerID, bc_videoID, bc_publisherID], envelope=envelope)))
    conn.request("POST", "/services/messagebroker/amf?playerId=" + str(bc_playerID), str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    streamUrl = ""
    for item in sorted(response['renditions'], key=lambda item: item['encodingRate'], reverse=False):
        encRate = item['encodingRate']
        if encRate < maxBitRate:
            streamUrl = item['defaultURL']    
    if not streamUrl:
        streamUrl = response['FLVFullLengthURL']
    if streamUrl:
        if isSingle:
            listitem = xbmcgui.ListItem(title, thumbnailImage=thumb)
            xbmc.Player().play(streamUrl, listitem)
        else:
            listitem = xbmcgui.ListItem(title, path=streamUrl, thumbnailImage=thumb)
            xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
        if autoPlay:
            while True:
                if xbmc.Player().isPlaying() and xbmc.getCondVisibility("Player.Paused"):
                    xbmc.Player().pause()
                    break
                xbmc.sleep(100)
            xbmc.sleep(500)
            while xbmc.getCondVisibility("Player.Paused"):
               if xbmc.Player().isPlaying():
                    xbmc.Player().pause()
                    break
               xbmc.sleep(100)
Пример #47
0
def playBrightCoveStream(bc_videoID):
        bc_playerID = 1277164692001
        bc_publisherID = 1113255272001
        bc_const = "f079ea2204e0e0bd5fe43221b533e35790610514"
        conn = httplib.HTTPConnection("c.brightcove.com")
        envelope = remoting.Envelope(amfVersion=3)
        envelope.bodies.append(("/1", remoting.Request(target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", body=[bc_const, bc_playerID, bc_videoID, bc_publisherID], envelope=envelope)))
        conn.request("POST", "/services/messagebroker/amf?playerId=" + str(bc_playerID), str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
        response = conn.getresponse().read()
        response = remoting.decode(response).bodies[0][1].body
        streamUrl = ""
        for item in sorted(response['renditions'], key=lambda item:item['encodingRate'], reverse=False):
          encRate = item['encodingRate']
          if encRate < maxBitRate:
            streamUrl = item['defaultURL']
        if streamUrl.find("http://")==0:
          listItem = xbmcgui.ListItem(path=streamUrl)
        else:
          url = streamUrl[0:streamUrl.find("&")]
          playpath = streamUrl[streamUrl.find("&")+1:]
          listItem = xbmcgui.ListItem(path=url+' playpath='+playpath)
        xbmcplugin.setResolvedUrl(pluginhandle,True,listItem)
Пример #48
0
 def get_clip_info(self, contentID, url):
  import pyamf
  #from pyamf import register_class
  from pyamf import remoting
  import httplib
  conn = httplib.HTTPConnection("c.brightcove.com")
  pyamf.register_class(ViewerExperienceRequest, 'com.brightcove.experience.ViewerExperienceRequest')
  pyamf.register_class(ContentOverride, 'com.brightcove.experience.ContentOverride')
  viewer_exp_req = ViewerExperienceRequest(url, [ContentOverride(contentID)], self.urls['experienceID'], "")
  env = remoting.Envelope(amfVersion = 3)
  env.bodies.append(("/1",  remoting.Request(target = "com.brightcove.experience.ExperienceRuntimeFacade.getDataForExperience", body = [self.urls['const'], viewer_exp_req], envelope = env)))
  #conn.request("POST", "/services/messagebroker/amf?playerKey=" + self.urls['playerKey'], str(remoting.encode(env).read()), {'content-type': 'application/x-amf'})
  conn.request("POST", "/services/messagebroker/amf?playerId=" + self.urls['playerID'], str(remoting.encode(env).read()), {'content-type': 'application/x-amf'})
  resp = conn.getresponse().read()
  response = remoting.decode(resp).bodies[0][1].body
  self._printResponse(env, response)
  return response['programmedContent']['videoPlayer']['mediaDTO']['renditions']
Пример #49
0
def get_clip_info(const, playerID, videoPlayer, publisherID):
    conn = httplib.HTTPConnection("c.brightcove.com")
    envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
    conn.request("POST", "/services/messagebroker/amf?playerKey=AQ~~,AAAAiDenBUk~,YtnxvBxGO01r9gxOuuHWiaCghjgdvn7c", str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    return response
Пример #50
0
    def __call__(self, environ, start_response):
        """
        @rtype: C{StringIO}
        @return: File-like object.
        """
        if environ['REQUEST_METHOD'] != 'POST':
            return self.badRequestMethod(environ, start_response)

        body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
        stream = None

        context = pyamf.get_context(pyamf.AMF0)

        # Decode the request
        try:
            request = remoting.decode(body, context)
        except pyamf.DecodeError:
            self.logger.debug(gateway.format_exception())

            response = "400 Bad Request\n\nThe request body was unable to " \
                "be successfully decoded."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            start_response('400 Bad Request', [
                ('Content-Type', 'text/plain'),
                ('Content-Length', str(len(response))),
            ])

            return [response]

        # Process the request
        try:
            response = self.getResponse(request, environ)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.logger.debug(gateway.format_exception())

            response = "500 Internal Server Error\n\nThe request was " \
                "unable to be successfully processed."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            start_response('500 Internal Server Error', [
                ('Content-Type', 'text/plain'),
                ('Content-Length', str(len(response))),
            ])

            return [response]

        # Encode the response
        try:
            stream = remoting.encode(response, context)
        except pyamf.EncodeError:
            self.logger.debug(gateway.format_exception())

            response = "500 Internal Server Error\n\nThe request was " \
                "unable to be encoded."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            start_response('500 Internal Server Error', [
                ('Content-Type', 'text/plain'),
                ('Content-Length', str(len(response))),
            ])

            return [response]

        response = stream.getvalue()

        start_response('200 OK', [
            ('Content-Type', remoting.CONTENT_TYPE),
            ('Content-Length', str(len(response))),
        ])

        return [response]
Пример #51
0
    def post(self):
        body = self.request.body_file.read()
        stream = None

        context = pyamf.get_context(pyamf.AMF0)

        # Decode the request
        try:
            request = remoting.decode(body, context, strict=self.strict)
        except:
            fe = gateway.format_exception()
            self.logger.exception(fe)

            response = "400 Bad Request\n\nThe request body was unable to " \
                "be successfully decoded."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % fe

            self.error(400)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.headers['Server'] = gateway.SERVER_NAME
            self.response.out.write(response)

            return

        self.logger.debug("AMF Request: %r" % request)

        # Process the request
        try:
            response = self.getResponse(request)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            fe = gateway.format_exception()
            self.logger.exception(fe)

            response = "500 Internal Server Error\n\nThe request was " \
                "unable to be successfully processed."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % fe

            self.error(500)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.headers['Server'] = gateway.SERVER_NAME
            self.response.out.write(response)

            return

        self.logger.debug("AMF Response: %r" % response)

        # Encode the response
        try:
            stream = remoting.encode(response, context, strict=self.strict)
        except:
            fe = gateway.format_exception()
            self.logger.exception(fe)

            response = "500 Internal Server Error\n\nThe request was " \
                "unable to be encoded."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % fe

            self.error(500)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.headers['Server'] = gateway.SERVER_NAME
            self.response.out.write(response)

            return

        response = stream.getvalue()

        self.response.headers['Content-Type'] = remoting.CONTENT_TYPE
        self.response.headers['Content-Length'] = str(len(response))
        self.response.headers['Server'] = gateway.SERVER_NAME

        self.response.out.write(response)
Пример #52
0
def get_clip_info(const, playerID, videoPlayer, publisherID):
    conn = httplib.HTTPConnection("c.brightcove.com")
    envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
    conn.request("POST", "/services/messagebroker/amf?playerKey=AQ~~,AAAAFR9Ptpk~,qrsh31CHJoFjltWH9CfvxE3UxqGVBf9B", str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    return response
Пример #53
0
    def __call__(self, environ, start_response):
        """
        @rtype: C{StringIO}
        @return: File-like object.
        """
        if environ['REQUEST_METHOD'] != 'POST':
            return self.badRequestMethod(environ, start_response)

        body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
        stream = None
        timezone_offset = self._get_timezone_offset()

        # Decode the request
        try:
            request = remoting.decode(body, strict=self.strict,
                logger=self.logger, timezone_offset=timezone_offset)
        except (pyamf.DecodeError, IOError):
            if self.logger:
                self.logger.exception('Error decoding AMF request')

            response = "400 Bad Request\n\nThe request body was unable to " \
                "be successfully decoded."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            start_response('400 Bad Request', [
                ('Content-Type', 'text/plain'),
                ('Content-Length', str(len(response))),
                ('Server', gateway.SERVER_NAME),
            ])

            return [response]
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Unexpected error decoding AMF request')

            response = ("500 Internal Server Error\n\nAn unexpected error "
                "occurred whilst decoding.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            start_response('500 Internal Server Error', [
                ('Content-Type', 'text/plain'),
                ('Content-Length', str(len(response))),
                ('Server', gateway.SERVER_NAME),
            ])

            return [response]

        if self.logger:
            self.logger.debug("AMF Request: %r" % request)

        # Process the request
        try:
            response = self.getResponse(request, environ)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Error processing AMF request')

            response = ("500 Internal Server Error\n\nThe request was "
                "unable to be successfully processed.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            start_response('500 Internal Server Error', [
                ('Content-Type', 'text/plain'),
                ('Content-Length', str(len(response))),
                ('Server', gateway.SERVER_NAME),
            ])

            return [response]

        if self.logger:
            self.logger.debug("AMF Response: %r" % response)

        # Encode the response
        try:
            stream = remoting.encode(response, strict=self.strict,
                timezone_offset=timezone_offset)
        except:
            if self.logger:
                self.logger.exception('Error encoding AMF request')

            response = ("500 Internal Server Error\n\nThe request was "
                "unable to be encoded.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            start_response('500 Internal Server Error', [
                ('Content-Type', 'text/plain'),
                ('Content-Length', str(len(response))),
                ('Server', gateway.SERVER_NAME),
            ])

            return [response]

        response = stream.getvalue()

        start_response('200 OK', [
            ('Content-Type', remoting.CONTENT_TYPE),
            ('Content-Length', str(len(response))),
            ('Server', gateway.SERVER_NAME),
        ])

        return [response]
Пример #54
0
    def post(self):
        body = self.request.body_file.read()
        stream = None
        timezone_offset = self._get_timezone_offset()

        # Decode the request
        try:
            request = remoting.decode(body,
                                      strict=self.strict,
                                      logger=self.logger,
                                      timezone_offset=timezone_offset)
        except (DecodeError, IOError):
            if self.logger:
                self.logger.exception('Error decoding AMF request')

            response = ("400 Bad Request\n\nThe request body was unable to "
                        "be successfully decoded.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            self.error(400)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.headers['Server'] = gateway.SERVER_NAME
            self.response.out.write(response)

            return
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Unexpected error decoding AMF request')

            response = ('500 Internal Server Error\n\n'
                        'An unexpected error occurred.')

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            self.error(500)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.headers['Server'] = gateway.SERVER_NAME
            self.response.out.write(response)

            return

        if self.logger:
            self.logger.debug("AMF Request: %r" % request)

        # Process the request
        try:
            response = self.getResponse(request)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Error processing AMF request')

            response = ("500 Internal Server Error\n\nThe request was " \
                "unable to be successfully processed.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            self.error(500)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.headers['Server'] = gateway.SERVER_NAME
            self.response.out.write(response)

            return

        if self.logger:
            self.logger.debug("AMF Response: %r" % response)

        # Encode the response
        try:
            stream = remoting.encode(response,
                                     strict=self.strict,
                                     logger=self.logger,
                                     timezone_offset=timezone_offset)
        except:
            if self.logger:
                self.logger.exception('Error encoding AMF request')

            response = ("500 Internal Server Error\n\nThe request was " \
                "unable to be encoded.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            self.error(500)
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.headers['Server'] = gateway.SERVER_NAME
            self.response.out.write(response)

            return

        response = stream.getvalue()

        self.response.headers['Content-Type'] = remoting.CONTENT_TYPE
        self.response.headers['Content-Length'] = str(len(response))
        self.response.headers['Server'] = gateway.SERVER_NAME

        self.response.out.write(response)
Пример #55
0
    'strictArray': [1, 2, 3],
    'date': datetime.date(2012, 12, 31),
    'xmlDocument': xmlDocument,
    'typedObject': foo,
})

message1 = Response({'text': 'hello'})

envelope.headers['a'] = 'b'
envelope.headers['c'] = 'd'
envelope.headers['e'] = 'f'

envelope.__setitem__('msg1', message0)
envelope.__setitem__('msg2', message1)

stream = remoting.encode(envelope)

file = open('amf0-all.amf', 'w+')
file.write(stream.getvalue())

#-----------------------------------------------
# AMF0 recordset
#-----------------------------------------------

envelope = Envelope(amfVersion=0)

records = [{
    'id': 1,
    'name': 'Phil'
}, {
    'id': 2,
Пример #56
0
    def __call__(self, http_request):
        """
        Processes and dispatches the request.

        @param http_request: The C{HTTPRequest} object.
        @type http_request: C{HTTPRequest}
        @return: The response to the request.
        @rtype: C{HTTPResponse}
        """
        if http_request.method != 'POST':
            return http.HttpResponseNotAllowed(['POST'])

        stream = None
        timezone_offset = self._get_timezone_offset()

        # Decode the request
        try:
            request = remoting.decode(http_request.raw_post_data,
                strict=self.strict, logger=self.logger,
                timezone_offset=timezone_offset)
        except (pyamf.DecodeError, IOError):
            fe = gateway.format_exception()

            if self.logger:
                self.logger.exception(fe)

            response = "400 Bad Request\n\nThe request body was unable to " \
                "be successfully decoded."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % fe

            return http.HttpResponseBadRequest(mimetype='text/plain', content=response)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            fe = gateway.format_exception()

            if self.logger:
                self.logger.exception(fe)

            response = ('500 Internal Server Error\n\n'
                'An unexpected error occurred.')

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % fe

            return http.HttpResponseServerError(mimetype='text/plain',
                content=response)

        if self.logger:
            self.logger.info("AMF Request: %r" % request)

        # Process the request
        try:
            response = self.getResponse(http_request, request)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            fe = gateway.format_exception()

            if self.logger:
                self.logger.exception(fe)

            response = "500 Internal Server Error\n\nThe request was " \
                "unable to be successfully processed."

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % fe

            return http.HttpResponseServerError(mimetype='text/plain',
                content=response)

        if self.logger:
            self.logger.info("AMF Response: %r" % response)

        # Encode the response
        try:
            stream = remoting.encode(response, strict=self.strict,
                logger=self.logger, timezone_offset=timezone_offset)
        except:
            fe = gateway.format_exception()

            if self.logger:
                self.logger.exception(fe)

            response = ("500 Internal Server Error\n\nThe request was "
                "unable to be encoded.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % fe

            return http.HttpResponseServerError(mimetype='text/plain', content=response)

        buf = stream.getvalue()

        http_response = http.HttpResponse(mimetype=remoting.CONTENT_TYPE)
        http_response['Server'] = gateway.SERVER_NAME
        http_response['Content-Length'] = str(len(buf))

        http_response.write(buf)

        return http_response
Пример #57
0
 def get_clip_info_ps3(self, contentID):
  import pyamf
  #from pyamf import register_class
  from pyamf import remoting
  import httplib
  conn = httplib.HTTPConnection("c.brightcove.com")
  env = remoting.Envelope(amfVersion = 3)
  env.bodies.append(("/1",  remoting.Request(target = "com.brightcove.player.runtime.PlayerMediaFacade.findMediaByReferenceId", body = [self.urls['const2_PS3'], self.urls['experienceID_PS3'], str(contentID), self.urls['publisherID']], envelope = env)))
  conn.request("POST", "/services/messagebroker/amf?playerKey=" + self.urls['playerKey'], str(remoting.encode(env).read()), {'content-type': 'application/x-amf'})
  resp = conn.getresponse().read()
  response = remoting.decode(resp).bodies[0][1].body
  if self.IOS:
   return response['IOSRenditions']
  else:
   return response['renditions']
Пример #58
0
from pyamf.flex import messaging
import csv
# 很显然operation是 getInitData 初始化数据
msg = messaging.RemotingMessage(messageId=str(uuid.uuid1()).upper(),
                                clientId=str(uuid.uuid1()).upper(),
                                operation='getInitData',
                                destination='reportStatService',
                                timeToLive=0,
                                timestamp=0)
msg.body = []
msg.headers['DSEndpoint'] = None
msg.headers['DSId'] = str(uuid.uuid1()).upper()
req = remoting.Request('null', body=(msg, ))
env = remoting.Envelope(amfVersion=pyamf.AMF3)
env.bodies = [('/1', req)]
data = bytes(remoting.encode(env).read())
url = 'http://jgsb.agri.cn/messagebroker/amf'
req = request.Request(url, data, headers={'Content-Type': 'application/x-amf'})
opener = request.build_opener()
response = opener.open(req).read()
amf_parse_info = remoting.decode(response)
breed_info = amf_parse_info.bodies[0][1].body.body[0]
fp = open('breed_code.csv', 'w')
csvFile = csv.writer(fp)
for item in breed_info:
    items_info = item['children']
    for item2 in items_info:
        csvFile.writerow((item2['itemname'], item2['itemcode']))
fp2 = open('market_code.csv', 'w')
market_info = amf_parse_info.bodies[0][1].body.body[1]
csvFile = csv.writer(fp2)
Пример #59
0
    def __call__(self, http_request):
        """
        Processes and dispatches the request.
        """
        if http_request.method != 'POST':
            return http.HttpResponseNotAllowed(['POST'])

        stream = None
        timezone_offset = self._get_timezone_offset()

        try:
            body = http_request.body
        except AttributeError:
            body = http_request.raw_post_data

        # Decode the request
        try:
            request = remoting.decode(body,
                                      strict=self.strict,
                                      logger=self.logger,
                                      timezone_offset=timezone_offset)
        except (pyamf.DecodeError, IOError):
            if self.logger:
                self.logger.exception('Error decoding AMF request')

            response = ("400 Bad Request\n\nThe request body was unable to "
                        "be successfully decoded.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            # support for Django 0.96
            http_response = http.HttpResponse(content_type='text/plain',
                                              content=response)

            http_response.status_code = 400

            return http_response
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Unexpected error decoding AMF request')

            response = ('500 Internal Server Error\n\n'
                        'An unexpected error occurred.')

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            return http.HttpResponseServerError(content_type='text/plain',
                                                content=response)

        # Process the request
        try:
            response = self.getResponse(http_request, request)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            if self.logger:
                self.logger.exception('Error processing AMF request')

            response = ("500 Internal Server Error\n\nThe request was "
                        "unable to be successfully processed.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            return http.HttpResponseServerError(content_type='text/plain',
                                                content=response)

        # Encode the response
        try:
            stream = remoting.encode(response,
                                     strict=self.strict,
                                     logger=self.logger,
                                     timezone_offset=timezone_offset)
        except:
            if self.logger:
                self.logger.exception('Error encoding AMF request')

            response = ("500 Internal Server Error\n\nThe request was "
                        "unable to be encoded.")

            if self.debug:
                response += "\n\nTraceback:\n\n%s" % gateway.format_exception()

            return http.HttpResponseServerError(content_type='text/plain',
                                                content=response)

        buf = stream.getvalue()

        http_response = http.HttpResponse(content_type=remoting.CONTENT_TYPE)
        http_response['Server'] = gateway.SERVER_NAME
        http_response['Content-Length'] = str(len(buf))

        http_response.write(buf)

        return http_response
Пример #60
0
def generate_amf_request(request_body=None):
    req = Request(target='UserService', body=request_body)
    ev = Envelope(pyamf.AMF3)
    ev['/0'] = req

    return encode(ev).getvalue()