Esempio n. 1
0
    def test_invalid_header_data_length(self):
        remoting.decode('\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a'
            '\x00\x00\x00\x00\x00\x00')

        self.failUnlessRaises(pyamf.DecodeError, remoting.decode,
            '\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a\x00\x00\x00'
            '\x00\x00\x00', strict=True)
Esempio n. 2
0
    def test_invalid_header_data_length(self):
        remoting.decode('\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a'
            '\x00\x00\x00\x00\x00\x00')

        self.failUnlessRaises(pyamf.DecodeError, remoting.decode,
            '\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a\x00\x00\x00'
            '\x00\x00\x00', strict=True)
Esempio n. 3
0
    def test_amf_version(self):
        for x in ('\x00', '\x03'):
            try:
                remoting.decode(x)
            except IOError:
                pass

        self.failUnlessRaises(pyamf.DecodeError, remoting.decode, '\x10')
Esempio n. 4
0
    def test_amf_version(self):
        for x in ("\x00", "\x03"):
            try:
                remoting.decode(x)
            except EOFError:
                pass

        self.failUnlessRaises(pyamf.DecodeError, remoting.decode, "\x10")
Esempio n. 5
0
    def test_amf_version(self):
        for x in ('\x00', '\x03'):
            try:
                remoting.decode(x)
            except IOError:
                pass

        self.failUnlessRaises(pyamf.DecodeError, remoting.decode, '\x10')
Esempio n. 6
0
 def test_client_version(self):
     """
     Tests the AMF client version.
     """
     for x in ('\x00', '\x01', '\x03'):
         try:
             remoting.decode('\x00' + x)
         except IOError:
             pass
Esempio n. 7
0
    def test_invalid_body_data_length(self):
        remoting.decode('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1'
            '\x00\x00\x00\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01'
            '\x61\x02\x00\x01\x61\x00\x00\x09')

        self.failUnlessRaises(pyamf.DecodeError, remoting.decode,
            '\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1\x00\x00\x00'
            '\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01\x61\x02\x00'
            '\x01\x61\x00\x00\x09', strict=True)
Esempio n. 8
0
 def test_client_version(self):
     """
     Tests the AMF client version.
     """
     for x in ('\x00', '\x01', '\x03'):
         try:
             remoting.decode('\x00' + x)
         except IOError:
             pass
Esempio n. 9
0
    def test_invalid_header_data_length(self):
        remoting.decode("\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a" "\x00\x00\x00\x00\x00\x00")

        self.failUnlessRaises(
            pyamf.DecodeError,
            remoting.decode,
            "\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a\x00\x00\x00" "\x00\x00\x00",
            strict=True,
        )
Esempio n. 10
0
 def test_client_version(self):
     """
     Tests the AMF client version.
     """
     for x in ("\x00", "\x01", "\x03"):
         try:
             remoting.decode("\x00" + x)
         except EOFError:
             pass
Esempio n. 11
0
    def test_invalid_body_data_length(self):
        remoting.decode('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1'
            '\x00\x00\x00\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01'
            '\x61\x02\x00\x01\x61\x00\x00\x09')

        self.failUnlessRaises(pyamf.DecodeError, remoting.decode,
            '\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1\x00\x00\x00'
            '\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01\x61\x02\x00'
            '\x01\x61\x00\x00\x09', strict=True)
Esempio n. 12
0
    def test_invalid_header_data_length(self):
        remoting.decode(
            b'\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a'
            b'\x00\x00\x00\x00\x00\x00'
        )

        self.assertRaises(
            pyamf.DecodeError,
            remoting.decode,
            b'\x00\x00\x00\x01\x00\x04name\x00\x00\x00\x00\x06\x0a\x00\x00\x00'
            b'\x00\x00\x00',
            strict=True
        )
Esempio n. 13
0
    def test_invalid_body_data_length(self):
        remoting.decode(
            "\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1"
            "\x00\x00\x00\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01"
            "\x61\x02\x00\x01\x61\x00\x00\x09"
        )

        self.failUnlessRaises(
            pyamf.DecodeError,
            remoting.decode,
            "\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1\x00\x00\x00"
            "\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01\x61\x02\x00"
            "\x01\x61\x00\x00\x09",
            strict=True,
        )
Esempio n. 14
0
    def test_invalid_body_data_length(self):
        remoting.decode(
            b'\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1'
            b'\x00\x00\x00\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01'
            b'\x61\x02\x00\x01\x61\x00\x00\x09'
        )

        self.assertRaises(
            pyamf.DecodeError,
            remoting.decode,
            b'\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00\x02/1\x00\x00\x00'
            b'\x13\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01\x61\x02\x00'
            b'\x01\x61\x00\x00\x09',
            strict=True
        )
Esempio n. 15
0
    def test_required_header(self):
        msg = remoting.decode(
            '\x00\x00\x00\x01\x00\x04name\x01\x00\x00\x00'
            '\x05\x0a\x00\x00\x00\x00\x00\x00'
        )

        self.assertTrue(msg.headers.is_required('name'))
    def getContent(self, response):
        amf_parse_info = remoting.decode(response)
        # print(amf_parse_info)
        info = amf_parse_info.bodies[0][1].body.body['wmsWeekDataVos']
        # print(info)
        factor_key = [
            'pH', 'DO(mg/l)', 'COD_Mn(mg/l)', 'TP(mg/l)', 'NH3-N(mg/l)'
        ]
        level_key = ['pH_级别', 'DO_级别', 'COD_Mn_级别', 'TP_级别', 'NH3-N_级别']
        data_list = []
        for record in info:
            # print(record)
            data = {}
            data['监测站点'] = record['mtName']
            data['监测时间'] = record['monitorTime']
            data['所属区域'] = record['boundaryArea']
            data['功能要求'] = record['levelStandard']
            data['水质类别'] = record['level']
            data['longitude'] = record['longitude']
            data['latitude'] = record['latitude']
            factor_value = eval(str(record['factorValues'])[35:-1])
            level_value = eval(str(record['factorLevel'])[35:-1])

            for key, value in zip(factor_key, factor_value):
                data[key] = value

            for key, value in zip(level_key, level_value):
                data[key] = value

            data_list.append((data))

        return data_list
Esempio n. 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)
        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)
Esempio n. 18
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)
Esempio n. 19
0
 def get_data(self):
     data = {
         "clientId": None,
         "destination": "GenericDestination",
         "correlationId": None,
         "source":
         "com.backendless.services.persistence.PersistenceService",
         "operation": "first",
         "messageRefType": None,
         "headers": {
             "application-type": "ANDROID",
             "api-version": "1.0"
         },
         "timestamp": 0,
         "body": ["ConfigCharlie"],
         "timeToLive": 0,
         "messageId": None,
     }
     msg = messaging.RemotingMessage(**data)
     req = remoting.Request(target="null", body=[msg])
     ev = remoting.Envelope(pyamf.AMF3)
     ev["null"] = req
     resp = requests.post(self.url,
                          data=remoting.encode(ev).getvalue(),
                          headers={"Content-Type": "application/x-amf"})
     resp_msg = remoting.decode(resp.content)
     config = json.dumps(resp_msg.bodies[0][1].body.body,
                         default=lambda obj: repr(obj))
     return json.loads(config)
Esempio n. 20
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']
Esempio n. 21
0
def playBrightCoveStream(bc_videoID):
    bc_playerID = 29323562001
    bc_publisherID = 293884104
    bc_const = "7aa45a3f2e7aadf8fa76da04bef79fb11f4a3fc2"
    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 == "":
        streamUrl = response['FLVFullLengthURL']
    if streamUrl != "":
        url = streamUrl[0:streamUrl.find("&")]
        playpath = streamUrl[streamUrl.find("&") + 1:]
        listItem = xbmcgui.ListItem(path=url + ' playpath=' + playpath)
        xbmcplugin.setResolvedUrl(pluginhandle, True, listItem)
Esempio n. 22
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
Esempio n. 23
0
 def call(self, cmd, callback=None, error_callback=None, args=[]):
     req = remoting.Request(target=cmd, body=args)
     env = remoting.Envelope(pyamf.AMF0)
     env['/0'] = req
     req_data = remoting.encode(env).getvalue()
     resp = self._session.post(
         self.__url,
         data=req_data,
         headers={'Content-Type': 'application/x-amf'})
     if resp.status_code == 200:
         resp_msg = remoting.decode(resp.content)['/0']
         resp_status = resp_msg.status
         if resp_status == STATUS_OK:
             if callback != None:
                 callback(resp_msg.body)
             return (resp_status, resp_msg.body)
         elif resp_status == STATUS_ERROR:
             if error_callback != None:
                 error_callback(resp_msg.body)
             return (resp_status, resp_msg.body)
         elif resp_status == STATUS_DEBUG:
             print('Amf DEBUG response:')
             print(resp_msg.body)
             return (resp_status, resp_msg.body)
     return (-1, None)
Esempio n. 24
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
Esempio n. 25
0
    def amf_parse(self, string, environ):
        try:
            from pyamf import remoting

            res = remoting.decode(BytesIO(string))

            #print(res)
            body = res.bodies[0][1].body[0]

            values = {}

            if hasattr(body, 'body'):
                values['body'] = body.body

            if hasattr(body, 'source'):
                values['source'] = body.source

            if hasattr(body, 'operation'):
                values['op'] = body.operation

            if environ is not None:
                environ['pywb.inputdata'] = res

            query = urlencode(values)
            #print(query)
            return query

        except Exception as e:
            import traceback
            traceback.print_exc()
            print(e)
            return None
Esempio n. 26
0
    def test_decode(self):
        from pyamf.remoting import decode

        e = decode(self.bytes)

        a, b, c, d, e, f, g = e['/3'].body

        self.assertEqual(a, {
            'value': u'*****@*****.**',
            'format': u'urn:TribalDDB:identity:email'
        })
        self.assertEqual(b, {
            'type': u'urn:TribalDDB:authentication:password',
            'value': u'passwrd'}
        )
        self.assertEqual(c, {
            'PostalCode': u'12345',
            'DateOfBirth': {'month': 4, 'day': 15, 'year': 1990},
            'EmailAddress': u'*****@*****.**',
            'FirstName': u'wer',
            'LastName': u'ewrwer'}
        )
        self.assertEqual(d, {'CsId': 0, 'TrtmntId': 100986, 'LocalCsId': 0})
        self.assertEqual(e, {'CTC': u'555'})
        self.assertEqual(f, [{'liveModeEnable': False, 'id': 1076}])
        self.assertEqual(g, u'wwwwwwwwwwwwwwww')
Esempio n. 27
0
    def test_required_header(self):
        msg = remoting.decode(
            '\x00\x00\x00\x01\x00\x04name\x01\x00\x00\x00'
            '\x05\x0a\x00\x00\x00\x00\x00\x00'
        )

        self.assertTrue(msg.headers.is_required('name'))
Esempio n. 28
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
Esempio n. 29
0
    def test_simple_body(self):
        self.failUnlessRaises(IOError, remoting.decode,
            '\x00\x00\x00\x00\x00\x01')

        msg = remoting.decode('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00'
            '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00'
            '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09')

        self.assertEquals(msg.amfVersion, 0)
        self.assertEquals(msg.clientType, 0)
        self.assertEquals(len(msg.headers), 0)
        self.assertEquals(len(msg), 1)
        self.assertTrue('/1' in msg)

        m = msg['/1']

        self.assertEquals(m.target, 'test.test')
        self.assertEquals(m.body, [{'a': 'a'}])

        y = [x for x in msg]

        self.assertEquals(len(y), 1)

        x = y[0]
        self.assertEquals(('/1', m), x)
Esempio n. 30
0
def amf_parse(string, environ):
    try:
        from pyamf import remoting

        res = remoting.decode(BytesIO(string))

        #print(res)
        body = res.bodies[0][1].body[0]

        values = {}

        if hasattr(body, 'body'):
            values['body'] = body.body

        if hasattr(body, 'source'):
            values['source'] = body.source

        if hasattr(body, 'operation'):
            values['op'] = body.operation

        if environ is not None:
            environ['pywb.inputdata'] = res

        query = urlencode(values)
        #print(query)
        return query

    except Exception as e:
        import traceback
        traceback.print_exc()
        print(e)
        return None
Esempio n. 31
0
    def test_unknown_request(self):
        gw = _django.DjangoGateway()

        request = util.BufferedByteStream()
        request.write(
            "\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00"
            "\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00"
            "\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09"
        )
        request.seek(0, 0)

        http_request = HttpRequest()
        http_request.method = "POST"
        http_request.raw_post_data = request.getvalue()

        http_response = gw(http_request)
        envelope = remoting.decode(http_response.content)

        message = envelope["/1"]

        self.assertEquals(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEquals(body.code, "Service.ResourceNotFound")
def playLiveStream():
    bc_playerID = 3546024667001
    bc_publisherID = 3213846503001
    content = opener.open(urlMain + "/" + siteVersion + "/Live").read()
    match = re.compile('name="@videoPlayer" value="(.+?)"',
                       re.DOTALL).findall(content)
    bc_const = "AQ~~,AAAC7Egt3lk~,ef2hDIwZtHuA9aR9af3pB4XK5IWi-srn"
    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, match[0], 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 = response['FLVFullLengthURL'].replace("/z/",
                                                     "/i/") + "/master.m3u8"
    content = opener.open(streamUrl).read()
    match = re.compile('RESOLUTION=(.+?)x(.+?),.*?\n(.+?)\n',
                       re.DOTALL).findall(content)
    for resX, resY, url in match:
        if int(resY) <= qualityLive:
            streamUrl = url
    if streamUrl:
        listitem = xbmcgui.ListItem(path=streamUrl)
        xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
Esempio n. 33
0
def main():
    """
    Run AMF decoder on input file.
    """
    (options, args) = parse_options()

    print 'Using pyamf from: %s' % (pyamf,)
    print 'Strict = ' + str(options.strict)

    for arg in args:
        for fname in glob.glob(arg):
            if fnmatch(fname, '*.amf*'):
                body = read_file(fname)

                try:
                    print "\nDecoding file:", fname
                    request = remoting.decode(body, None, options.strict)

                    if options.debug:
                        for name, message in request:
                            print "  %s: %s" % (name, message)
                except pyamf.UnknownClassAlias, c:
                    if options.debug:
                        print '\n    Warning: %s' % c
                except pyamf.DecodeError, c:
                    if options.debug:
                        print '\n    Warning: %s' % c
                except:
Esempio n. 34
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"]
Esempio n. 35
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
Esempio n. 36
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
Esempio n. 37
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)
Esempio n. 38
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
Esempio n. 39
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~~,AAAAC_GBGZE~,q40QbnxHunHkwKuAvWxESNjERBgcAQY8", str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
	response = conn.getresponse().read()
	response = remoting.decode(response).bodies[0][1].body
	return response  
Esempio n. 40
0
    def test_unknown_request(self):
        request = util.BufferedByteStream()
        request.write('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00'
            '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00'
            '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09')
        request.seek(0, 0)

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

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '200 OK')
            self.assertTrue(('Content-Type', 'application/x-amf') in headers)

        response = self.gw(env, start_response)
        envelope = remoting.decode(''.join(response))

        message = envelope['/1']

        self.assertEquals(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEquals(body.code, 'Service.ResourceNotFound')
        self.assertTrue(self.executed)
Esempio n. 41
0
    def test_unknown_request(self):
        request = util.BufferedByteStream()
        request.write(
            '\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00'
            '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00'
            '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09')
        request.seek(0, 0)

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

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '200 OK')
            self.assertTrue(('Content-Type', 'application/x-amf') in headers)

        response = self.gw(env, start_response)
        envelope = remoting.decode(''.join(response))

        message = envelope['/1']

        self.assertEquals(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEquals(body.code, 'Service.ResourceNotFound')
        self.assertTrue(self.executed)
Esempio n. 42
0
    def test_decode(self):
        from pyamf.remoting import decode

        e = decode(self.bytes)

        a, b, c, d, e, f, g = e['/3'].body

        self.assertEqual(a, {
            'value': '*****@*****.**',
            'format': 'urn:TribalDDB:identity:email'
        })
        self.assertEqual(b, {
            'type': 'urn:TribalDDB:authentication:password',
            'value': 'passwrd'
        })
        self.assertEqual(
            c, {
                'PostalCode': '12345',
                'DateOfBirth': {
                    'month': 4,
                    'day': 15,
                    'year': 1990
                },
                'EmailAddress': '*****@*****.**',
                'FirstName': 'wer',
                'LastName': 'ewrwer'
            })
        self.assertEqual(d, {'CsId': 0, 'TrtmntId': 100986, 'LocalCsId': 0})
        self.assertEqual(e, {'CTC': '555'})
        self.assertEqual(f, [{'liveModeEnable': False, 'id': 1076}])
        self.assertEqual(g, 'wwwwwwwwwwwwwwww')
Esempio n. 43
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~~,AAAAC_GBGZE~,q40QbnxHunHkwKuAvWxESNjERBgcAQY8", str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    return response  
Esempio n. 44
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)

        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)
Esempio n. 45
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
Esempio n. 46
0
    def test_timezone(self):
        import datetime

        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

        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.assertEqual(message.body, now)
        self.assertTrue(self.executed)
Esempio n. 47
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']
Esempio n. 48
0
    def test_timezone(self):
        import datetime

        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 = make_http_request('POST',
                                         remoting.encode(msg).getvalue())

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

        self.assertEqual(res['/1'].body, now)
Esempio n. 49
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)
Esempio n. 50
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
Esempio n. 51
0
    def test_multiple_request_header_references(self):
        msg = remoting.decode(
            '\x00\x03\x00\x01\x00\x0b\x43\x72\x65\x64\x65\x6e\x74\x69\x61\x6c'
            '\x73\x00\x00\x00\x00\x2c\x11\x0a\x0b\x01\x0d\x75\x73\x65\x72\x69'
            '\x64\x06\x1f\x67\x65\x6e\x6f\x70\x72\x6f\x5c\x40\x67\x65\x72\x61'
            '\x72\x64\x11\x70\x61\x73\x73\x77\x6f\x72\x64\x06\x09\x67\x67\x67'
            '\x67\x01\x00\x01\x00\x0b\x63\x72\x65\x61\x74\x65\x47\x72\x6f\x75'
            '\x70\x00\x02\x2f\x31\x00\x00\x00\x1c\x0a\x00\x00\x00\x01\x11\x0a'
            '\x0b\x01\x09\x73\x74\x72\x41\x06\x09\x74\x65\x73\x74\x09\x73\x74'
            '\x72\x42\x06\x02\x01')

        self.assertEquals(msg.amfVersion, 0)
        self.assertEquals(msg.clientType, 3)
        self.assertEquals(len(msg.headers), 1)
        self.assertEquals(msg.headers['Credentials'], {
            'password': '******',
            'userid': 'genopro\\@gerard'
        })
        self.assertEquals(len(msg), 1)
        self.assertTrue('/1' in msg)

        m = msg['/1']

        self.assertEquals(m.target, 'createGroup')
        self.assertEquals(m.body, [{'strB': 'test', 'strA': 'test'}])
Esempio n. 52
0
    def test_simple_body(self):
        self.failUnlessRaises(IOError, remoting.decode,
                              '\x00\x00\x00\x00\x00\x01')

        msg = remoting.decode(
            '\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00'
            '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00'
            '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09')

        self.assertEquals(msg.amfVersion, 0)
        self.assertEquals(msg.clientType, 0)
        self.assertEquals(len(msg.headers), 0)
        self.assertEquals(len(msg), 1)
        self.assertTrue('/1' in msg)

        m = msg['/1']

        self.assertEquals(m.target, 'test.test')
        self.assertEquals(m.body, [{'a': 'a'}])

        y = [x for x in msg]

        self.assertEquals(len(y), 1)

        x = y[0]
        self.assertEquals(('/1', m), x)
    def _getResponse(self):
        """
        Gets and handles the HTTP response from the remote gateway.
        """
        self.logger.debug('Waiting for response...')
        http_response = self.connection.getresponse()
        self.logger.debug('Got response status: %s' % http_response.status)
        self.logger.debug('Content-Type: %s' % http_response.getheader('Content-Type'))

        if http_response.status != HTTP_OK:
            self.logger.debug('Body: %s' % http_response.read())

            if hasattr(httplib, 'responses'):
                raise remoting.RemotingError, "HTTP Gateway reported status %d %s" % (
                    http_response.status, httplib.responses[http_response.status])

            raise remoting.RemotingError, "HTTP Gateway reported status %d" % (
                http_response.status,)

        content_type = http_response.getheader('Content-Type')

        if content_type != remoting.CONTENT_TYPE:
            self.logger.debug('Body = %s' % http_response.read())

            raise remoting.RemotingError, "Incorrect MIME type received. (got: %s)" % content_type

        content_length = http_response.getheader('Content-Length')
        bytes = ''

        self.logger.debug('Content-Length: %s' % content_length)
        self.logger.debug('Server: %s' % http_response.getheader('Server'))

        if content_length is None:
            bytes = http_response.read()
        else:
            bytes = http_response.read(content_length)

        self.logger.debug('Read %d bytes for the response' % len(bytes))

        response = remoting.decode(bytes)
        self.logger.debug('Response: %s' % response)

        if remoting.APPEND_TO_GATEWAY_URL in response.headers:
            self.original_url += response.headers[remoting.APPEND_TO_GATEWAY_URL]

            self._setUrl(self.original_url)
        elif remoting.REPLACE_GATEWAY_URL in response.headers:
            self.original_url = response.headers[remoting.REPLACE_GATEWAY_URL]

            self._setUrl(self.original_url)

        if remoting.REQUEST_PERSISTENT_HEADER in response.headers:
            data = response.headers[remoting.REQUEST_PERSISTENT_HEADER]

            for k, v in data.iteritems():
                self.headers[k] = v

        http_response.close()

        return response
Esempio n. 54
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
    print response
    return response
Esempio n. 55
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~~,AAAAD7FExsE~,dWW_A2fca-0o0T8SJiLGfd39phbKu16R", str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
    response = conn.getresponse().read()
    response = remoting.decode(response).bodies[0][1].body
    print response
    return response  
Esempio n. 56
0
    def test_can_parse_custom_object(self):
        a = CustomObject()
        a.secret = "a"

        encoded = generate_amf_request(request_body=[a])
        decoded = decode(BytesIO(encoded))

        assert Amf.get_representation(decoded) == \
               '<Envelope>[<Request target=UserService>[<CustomObject>{"secret": "a"}</CustomObject>]</Request>]</Envelope>'
Esempio n. 57
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
Esempio n. 58
0
    def decode_bc(content, v):
        if content == '':
            return ''

        return ''.join([
            '"%sx%s:%s";' % (rendition['frameWidth'], rendition['frameHeight'],
                             rendition['defaultURL']) for rendition in
            remoting.decode(content).bodies[0][1].body['renditions']
        ])