Exemplo n.º 1
0
        AMFObject getViewerExperience(string contentRefId, string videoUrl)
        {
            AMFObject contentOverride = new AMFObject("com.brightcove.experience.ContentOverride");

            contentOverride.Add("contentId", double.NaN);
            contentOverride.Add("target", "videoPlayer");
            contentOverride.Add("contentRefId", contentRefId);
            contentOverride.Add("featuredRefId", null);
            contentOverride.Add("contentRefIds", null);
            contentOverride.Add("featuredId", double.NaN);
            contentOverride.Add("contentIds", null);
            contentOverride.Add("contentType", 0);
            AMFArray array = new AMFArray();

            array.Add(contentOverride);

            AMFObject ViewerExperienceRequest = new AMFObject("com.brightcove.experience.ViewerExperienceRequest");

            ViewerExperienceRequest.Add("TTLToken", String.Empty);
            ViewerExperienceRequest.Add("playerKey", String.Empty);
            ViewerExperienceRequest.Add("deliveryType", double.NaN);
            ViewerExperienceRequest.Add("contentOverrides", array);
            ViewerExperienceRequest.Add("URL", videoUrl);

            ViewerExperienceRequest.Add("experienceId", playerId);

            AMFSerializer ser = new AMFSerializer();

            byte[] data = ser.Serialize(ViewerExperienceRequest, hashValue);

            string requestUrl = "http://c.brightcove.com/services/messagebroker/amf?playerid=" + playerId;

            return(GetResponse(requestUrl, data));
        }
Exemplo n.º 2
0
        protected byte[] CreateRequest(V3Message v3Msg, IDictionary headers)
        {
            Header[] headersArray = null;

            if (headers != null)
            {
                headersArray = new Header[headers.Count];
                int i = 0;

                foreach (String headerName in headers.Keys)
                {
                    headersArray[i] = new Header(headerName, false, -1, new ConcreteObject(headers[headerName]));
                }
            }
            else
            {
                headersArray = new Header[0];
            }

            Body[] bodiesArray = new Body[1];
            bodiesArray[0] = new Body("null", "null", -1, null);

            Request request = new Request(3, headersArray, bodiesArray);

            request.setResponseBodyData(new object[] { v3Msg });

            return(AMFSerializer.SerializeToBytes(request));
        }
Exemplo n.º 3
0
            /// <summary>
            /// One of the two main entry points into the encoder. Called by WCF to write a message of less than a specified size to a byte array buffer at the specified offset.
            /// </summary>
            /// <param name="message">The <see cref="T:System.ServiceModel.Channels.Message"/> to write to the message buffer.</param>
            /// <param name="maxMessageSize">The maximum message size that can be written.</param>
            /// <param name="bufferManager">The <see cref="T:System.ServiceModel.Channels.BufferManager"/> that manages the buffer to which the message is written.</param>
            /// <param name="messageOffset">The offset of the segment that begins from the start of the byte array that provides the buffer.</param>
            /// <returns>
            /// A <see cref="T:System.ArraySegment`1"/> of type byte that provides the buffer to which the message is serialized.
            /// </returns>
            public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                MemoryStream  memoryStream = new MemoryStream();
                AMFMessage    amfMessage   = message.Properties["amf"] as AMFMessage;
                AMFSerializer serializer   = new AMFSerializer(memoryStream);

                serializer.WriteMessage(amfMessage);
                serializer.Flush();
                // To avoid a buffer copy, we grab a reference to the stream's internal buffer.
                // The byte[] we receive may contain extra nulls after the actual data, due to the
                // buffer management mechanisms of the MemoryStream. Thus, to obtain the message's
                // length, we need to examine memoryStream.Position rather than messageBytes.Length.
                byte[] messageBytes  = memoryStream.GetBuffer();
                int    messageLength = (int)memoryStream.Position;

                memoryStream.Close();

                int totalLength = messageLength + messageOffset;

                byte[] finalBuffer = bufferManager.TakeBuffer(totalLength);
                Array.Copy(messageBytes, 0, finalBuffer, messageOffset, messageLength);

                ArraySegment <byte> byteArray = new ArraySegment <byte>(finalBuffer, messageOffset, messageLength);

                return(byteArray);
            }
Exemplo n.º 4
0
        public override void Invoke(AMFContext context)
        {
            AMFSerializer serializer = new AMFSerializer(context.OutputStream);

            serializer.UseLegacyCollection = _useLegacyCollection;
            serializer.UseLegacyThrowable  = _useLegacyThrowable;
            serializer.WriteMessage(context.MessageOutput);
            serializer.Flush();


            //Serialization/deserialization debugging
            //Note: this will not work correctly with optimizers (different ClassDefinitions from server and client)

            /*
             * MemoryStream ms = new MemoryStream();
             * AMFSerializer testSerializer = new AMFSerializer(ms);
             * testSerializer.UseLegacyCollection = _useLegacyCollection;
             * testSerializer.UseLegacyThrowable = _useLegacyThrowable;
             * testSerializer.WriteMessage(context.MessageOutput);
             * testSerializer.Flush();
             * ms.Position = 0;
             * AMFDeserializer testDeserializer = new AMFDeserializer(ms);
             * testDeserializer.UseLegacyCollection = _useLegacyCollection;
             * AMFMessage amfMessageOut = testDeserializer.ReadAMFMessage();
             * ms.Position = 0;
             * byte[] buffer = ms.ToArray();
             * context.OutputStream.Write(buffer, 0, buffer.Length);
             */
        }
Exemplo n.º 5
0
        public override Dictionary <string, string> GetPlaybackOptions(string url)
        {
            Log.Info("!!" + url);
            url = url.TrimEnd('/');
            int    ii      = url.LastIndexOf('/');
            int    p       = url.IndexOf('&', ii);
            string videoId = url.Substring(ii + 1, p - ii - 1);

            Dictionary <string, string> options = new Dictionary <string, string>();

            AMFSerializer ser = new AMFSerializer();

            object[] values = new object[4];
            values[0] = videoId;
            values[1] = null;
            values[2] = null;
            values[3] = "false";
            byte[]    data = ser.Serialize2("viddlerGateway.getVideoInfo", values);
            AMFObject obj  = AMFObject.GetResponse(@"http://www.viddler.com/amfgateway.action", data);

            AMFArray files = obj.GetArray("files");

            for (int i = 0; i < files.Count; i++)
            {
                AMFObject file = files.GetObject(i);
                string    nm   = String.Format("{0}x{1} {2}K",
                                               file.GetDoubleProperty("width"), file.GetDoubleProperty("height"),
                                               file.GetDoubleProperty("bitrate"));
                string filename = file.GetStringProperty("filename");
                string path     = file.GetStringProperty("path");
                options.Add(nm, decryptPath(path));
            }
            return(options);
        }
Exemplo n.º 6
0
		public override void Invoke(AMFContext context) {
			AMFSerializer serializer = new AMFSerializer(context.OutputStream);
			serializer.UseLegacyCollection = _useLegacyCollection;
			serializer.UseLegacyThrowable = _useLegacyThrowable;
			serializer.WriteMessage(context.MessageOutput);
			serializer.Flush();


			//Serialization/deserialization debugging
			//Note: this will not work correctly with optimizers (different ClassDefinitions from server and client)
			/*
			MemoryStream ms = new MemoryStream();
			AMFSerializer testSerializer = new AMFSerializer(ms);
			testSerializer.UseLegacyCollection = _useLegacyCollection;
			testSerializer.UseLegacyThrowable = _useLegacyThrowable;
			testSerializer.WriteMessage(context.MessageOutput);
			testSerializer.Flush();
			ms.Position = 0;
			AMFDeserializer testDeserializer = new AMFDeserializer(ms);
			testDeserializer.UseLegacyCollection = _useLegacyCollection;
			AMFMessage amfMessageOut = testDeserializer.ReadAMFMessage();
			ms.Position = 0;
			byte[] buffer = ms.ToArray();
			context.OutputStream.Write(buffer, 0, buffer.Length);
			*/
		}
Exemplo n.º 7
0
        public override Dictionary<string, string> GetPlaybackOptions(string url)
        {

            Log.Info("!!" + url);
            url = url.TrimEnd('/');
            int ii = url.LastIndexOf('/');
            int p = url.IndexOf('&', ii);
            string videoId = url.Substring(ii + 1, p - ii - 1);

            Dictionary<string, string> options = new Dictionary<string, string>();

            AMFSerializer ser = new AMFSerializer();

            object[] values = new object[4];
            values[0] = videoId;
            values[1] = null;
            values[2] = null;
            values[3] = "false";
            byte[] data = ser.Serialize2("viddlerGateway.getVideoInfo", values);
            AMFObject obj = AMFObject.GetResponse(@"http://www.viddler.com/amfgateway.action", data);

            AMFArray files = obj.GetArray("files");
            for (int i = 0; i < files.Count; i++)
            {
                AMFObject file = files.GetObject(i);
                string nm = String.Format("{0}x{1} {2}K",
                    file.GetDoubleProperty("width"), file.GetDoubleProperty("height"),
                    file.GetDoubleProperty("bitrate"));
                string filename = file.GetStringProperty("filename");
                string path = file.GetStringProperty("path");
                options.Add(nm, decryptPath(path));
            }
            return options;
        }
Exemplo n.º 8
0
        /// <summary>
        /// 发送基于x-amf3的http请求
        /// </summary>
        /// <param name="requestUrl">请求url</param>
        /// <param name="amfMessage">amf3的报文体</param>
        /// <param name="cookieContainer">请求的cookie</param>
        public static WebResponse Amf3RequestHelper(string requestUrl, AMFMessage amfMessage, CookieContainer cookieContainer = null)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUrl);

            req.Method          = "POST";
            req.ContentType     = "application/x-amf";
            req.UserAgent       = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
            req.CookieContainer = cookieContainer;
            req.LoadConfig(requestUrl);
            using (Stream stream = req.GetRequestStream())
            {
                using (AMFSerializer AMFSerializer = new AMFSerializer(stream))
                {
                    AMFSerializer.WriteMessage(amfMessage);
                }
            }
            try
            {
                return(req.GetResponse());
            }
            catch (WebException ex)
            {
                if (ex.Message.Contains("502"))
                {
                    Console.WriteLine("连接远程服务器时发生错误!", ex);
                    throw new Exception("地址:" + requestUrl + "连接失败,(ERROR:-1)");
                }
                throw ex;
            }
        }
Exemplo n.º 9
0
        public override void Invoke(AMFContext context)
        {
            AMFSerializer serializer = new AMFSerializer(context.OutputStream);

            serializer.UseLegacyCollection = _useLegacyCollection;
            serializer.WriteMessage(context.MessageOutput);
            serializer.Flush();
        }
Exemplo n.º 10
0
        public override Task Invoke(AMFContext context)
        {
            AMFSerializer serializer = new AMFSerializer(context.OutputStream);

            serializer.UseLegacyCollection = _useLegacyCollection;
            serializer.WriteMessage(context.MessageOutput);
            serializer.Flush();
            return(Task.FromResult <object>(null));
        }
            //One of the two main entry points into the encoder. Called by WCF to encode a Message into a buffered byte array.
            public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                MemoryStream  memoryStream = new MemoryStream();
                AMFMessage    amfMessage   = message.Properties["amf"] as AMFMessage;
                AMFSerializer serializer   = new AMFSerializer(memoryStream);

                serializer.WriteMessage(amfMessage);
                serializer.Flush();
                byte[] buffer = memoryStream.ToArray();
                ArraySegment <byte> byteArray = new ArraySegment <byte>(buffer);

                return(byteArray);
            }
Exemplo n.º 12
0
        protected AMFArray GetResultsFromFindByMediaId(Match m)
        {
            AMFSerializer ser = new AMFSerializer();

            object[] values = new object[4];
            values[0] = hashValue;
            values[1] = Convert.ToDouble(playerId);
            values[2] = Convert.ToDouble(m.Groups["mediaId"].Value);
            values[3] = Convert.ToDouble(array4);
            byte[] data = ser.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", values);
            lastResponse = AMFObject.GetResponse(requestUrl, data);
            return(lastResponse.GetArray("renditions"));
        }
Exemplo n.º 13
0
        protected AMFArray GetResultsFromFindByMediaId(Match m, string videoUrl)
        {
            AMFSerializer ser = new AMFSerializer();

            object[] values = new object[4];
            values[0] = hashValue;
            values[1] = Convert.ToDouble(m.Groups["experienceId"].Value);
            values[2] = Convert.ToDouble(videoUrl.Substring(videoUrl.LastIndexOf("/") + 1));
            values[3] = Convert.ToDouble(array4);
            byte[]    data = ser.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", values, AMFVersion.AMF3);
            AMFObject obj  = AMFObject.GetResponse(requestUrl + m.Groups["playerKey"].Value, data);

            return(obj.GetArray("renditions"));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Сериализует объект в буффер AMF.
        /// </summary>
        /// <param name="sourceObject">Исходный объект.</param>
        /// <param name="version">Версия AMF.</param>
        /// <returns></returns>
        public static byte[] SerializeToAmf(this object sourceObject, ushort version)
        {
            using (MemoryStream memoryStream = new MemoryStream())                                           // Открываем поток для записи данных в буфер.
                using (AMFSerializer amfSerializer = new AMFSerializer(memoryStream))                        // Инициализируем сериализатор для AMF.
                {
                    AMFMessage amfMessage = new AMFMessage(version);                                         // Создаём сообщение для передачи серверу с заданным номером версии AMF.
                    AMFBody    amfBody    = new AMFBody(AMFBody.OnResult, null, GenerateType(sourceObject)); // Создаём тело для сообщения AMF.

                    amfMessage.AddBody(amfBody);                                                             // Добавляем body для сообщения AMF.
                    amfSerializer.WriteMessage(amfMessage);                                                  // Сериализуем сообщение.

                    return(memoryStream.ToArray());                                                          // Преобразовывает поток памяти в буфер и возвращает.
                }
        }
Exemplo n.º 15
0
        public byte[] LoadAmfMessageIntoBinMessage(AMFMessage message)
        {
            byte[]       buffer = null;
            MemoryStream stream = new MemoryStream();

            AMFSerializer amfSerializers = new AMFSerializer(stream);

            amfSerializers.WriteMessage(message);
            amfSerializers.Flush();
            buffer          = new byte[amfSerializers.BaseStream.Length];
            stream.Position = 0;
            stream.Read(buffer, 0, buffer.Length);

            return(buffer);
        }
Exemplo n.º 16
0
 public static byte[] SerializeAMF3(T item)
 {
     using (var amfData = new MemoryStream())
     {
         var ser = new AMFSerializer(amfData)
         {
             UseLegacyCollection = false
         };
         using (var fcm = new FluorineClassMappingApplicationContext())
         {
             ser.WriteData(fcm, ObjectEncoding.AMF3, item);
             amfData.Position = 0;
             return(amfData.ToArray());
         }
     }
 }
Exemplo n.º 17
0
        private void BeginRequestFlashCall(IAsyncResult ar)
        {
            try {
                AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData;
                if (amfRequestData != null)
                {
                    Stream        requestStream = amfRequestData.Request.EndGetRequestStream(ar);
                    AMFSerializer amfSerializer = new AMFSerializer(requestStream);
                    amfSerializer.WriteMessage(amfRequestData.AmfMessage);
                    amfSerializer.Flush();
                    amfSerializer.Close();

                    amfRequestData.Request.BeginGetResponse(BeginResponseFlashCall, amfRequestData);
                }
            } catch (Exception ex) {
                _netConnection.RaiseNetStatus(ex);
            }
        }
Exemplo n.º 18
0
 private void BeginRequestFlexCall(IAsyncResult ar)
 {
     try
     {
         RequestData asyncState = ar.AsyncState as RequestData;
         if (asyncState != null)
         {
             AMFSerializer serializer = new AMFSerializer(asyncState.Request.EndGetRequestStream(ar));
             serializer.WriteMessage(asyncState.AmfMessage);
             serializer.Flush();
             serializer.Close();
             asyncState.Request.BeginGetResponse(new AsyncCallback(this.BeginResponseFlexCall), asyncState);
         }
     }
     catch (Exception exception)
     {
         this._netConnection.RaiseNetStatus(exception);
     }
 }
Exemplo n.º 19
0
        private async void sendBtn_Click(object sender, EventArgs e)
        {
            object[]   arguments = { Convert.ToInt32(textBox1.Text) };
            AMFMessage _amf      = new AMFMessage(3);

            _amf.AddHeader(new AMFHeader("id", false, Hash.createChecksum(arguments)));
            _amf.AddHeader(new AMFHeader("needClassName", false, true));
            _amf.AddBody(new AMFBody("MovieStarPlanet.WebService.UserSession.AMFUserSessionService.GetActorNameFromId", "/1", arguments));
            MemoryStream  mStream   = new MemoryStream();
            AMFSerializer serialize = new AMFSerializer(mStream);

            serialize.WriteMessage(_amf);
            HttpClient client = new HttpClient();

            byte[] AMFBytes = Encoding.Default.GetBytes(Encoding.Default.GetString(mStream.ToArray()));

            ///Set referer to send AMF without 404 error
            Uri referer = new Uri("https://assets.mspcdns.com/msp/91.0.2/Main_20200728_110605.swf");

            client.DefaultRequestHeaders.Referrer = referer;

            try
            {
                string gateway = "https://ws-" + comboBox1.Text + ".mspapis.com/msp/91.0.6/Gateway.aspx?method=MovieStarPlanet.WebService.UserSession.AMFUserSessionService.GetActorNameFromId";
                var    AMFHttpClientByteArray = new ByteArrayContent(AMFBytes);
                AMFHttpClientByteArray.Headers.ContentType = new MediaTypeHeaderValue("application/x-amf");

                var response = await client.PostAsync(gateway, AMFHttpClientByteArray);

                //Response
                string responseString = response.Content.ReadAsStringAsync().Result;
                string final          = JsonConvert.SerializeObject(responseString);
                MessageBox.Show(final);
            }

            catch (WebException exception)
            {
                MessageBox.Show("Error!" + exception);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// 用户认证
        /// </summary>
        /// <returns></returns>
        private byte[] AuthenticateUser(string userID, string psd, string responseNo)
        {
            RemotingMessage rtMsg = new RemotingMessage();

            rtMsg.source      = null;
            rtMsg.operation   = "authenticateUser";
            rtMsg.clientId    = Guid.NewGuid().ToString().ToUpper();
            rtMsg.messageId   = Guid.NewGuid().ToString().ToUpper();
            rtMsg.destination = "userRO";
            rtMsg.timestamp   = 0;
            rtMsg.timeToLive  = 0;
            rtMsg.headers.Add(RemotingMessage.FlexClientIdHeader, Guid.NewGuid().ToString().ToUpper());
            rtMsg.headers.Add(RemotingMessage.EndpointHeader, "my-amf");

            List <object> bodys = new List <object>();

            bodys.Add(userID);
            bodys.Add(psd);

            rtMsg.body = bodys.ToArray();

            AMFMessage _amf3 = new AMFMessage(3);// 创建 AMF

            List <RemotingMessage> lstR = new List <RemotingMessage>();

            lstR.Add(rtMsg);

            AMFBody _amfbody = new AMFBody("null", "/" + responseNo, lstR.ToArray());

            _amf3.AddBody(_amfbody);

            MemoryStream  _Memory     = new MemoryStream();         //内存流
            AMFSerializer _Serializer = new AMFSerializer(_Memory); //序列化

            _Serializer.WriteMessage(_amf3);                        //将消息写入

            return(_Memory.ToArray());
        }
Exemplo n.º 21
0
        AMFObject getViewerExperience(string contentRefId, string videoUrl)
        {
            AMFObject contentOverride = new AMFObject("com.brightcove.experience.ContentOverride");
            contentOverride.Add("contentId", double.NaN);
            contentOverride.Add("target", "videoPlayer");
            contentOverride.Add("contentRefId", contentRefId);
            contentOverride.Add("featuredRefId", null);
            contentOverride.Add("contentRefIds", null);
            contentOverride.Add("featuredId", double.NaN);
            contentOverride.Add("contentIds", null);
            contentOverride.Add("contentType", 0);
            AMFArray array = new AMFArray();
            array.Add(contentOverride);

            AMFObject ViewerExperienceRequest = new AMFObject("com.brightcove.experience.ViewerExperienceRequest");
            ViewerExperienceRequest.Add("TTLToken", String.Empty);
            ViewerExperienceRequest.Add("playerKey", String.Empty);
            ViewerExperienceRequest.Add("deliveryType", double.NaN);
            ViewerExperienceRequest.Add("contentOverrides", array);
            ViewerExperienceRequest.Add("URL", videoUrl);

            ViewerExperienceRequest.Add("experienceId", playerId);

            AMFSerializer ser = new AMFSerializer();
            byte[] data = ser.Serialize(ViewerExperienceRequest, hashValue);

            string requestUrl = "http://c.brightcove.com/services/messagebroker/amf?playerid=" + playerId;

            return GetResponse(requestUrl, data);
        }
Exemplo n.º 22
0
        public override List <VideoInfo> GetVideos(Category category)
        {
            List <VideoInfo> result = new List <VideoInfo>();

            /*
             * sample AMF input for findPagingMediaCollectionByReferenceId (expressed in pretty-printed JSON for clarity - captured using Firebug)
             *
             *  ["1ddf0ed58803c0533b0f82a8ff68ae50e0e12f52",1706768404001,"cn-johnny-test-playlist-clip",0,50,1873145815]
             */

            object[] amfInput = new object[6];
            amfInput[0] = hashValue;
            amfInput[1] = Convert.ToDouble(playerId);
            amfInput[2] = string.Format(@"cn-{0}-playlist-clip", ((RssLink)category).Url);
            amfInput[3] = Convert.ToDouble(@"0");
            amfInput[4] = Convert.ToDouble(@"50");
            amfInput[5] = Convert.ToDouble(publisherId);

            AMFSerializer serializer = new AMFSerializer();
            AMFObject     response   = AMFObject.GetResponse(brightcoveUrl, serializer.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findPagingMediaCollectionByReferenceId", amfInput));

            //Log.Debug("AMF Response: {0}", response.ToString());
            string lineUpId = response.GetDoubleProperty("id").ToString();

            Log.Debug("LineUpId: {0}", lineUpId);

            AMFArray videoDTOs = response.GetArray("videoDTOs");

            if (videoDTOs != null)
            {
                for (int i = 0; i < videoDTOs.Count; i++)
                {
                    AMFObject videoDTO = videoDTOs.GetObject(i);

                    string url = videoDTO.GetStringProperty("FLVFullLengthURL");

                    // typical URL from FLVFullLengthURL
                    // rtmpe://cp102794.edgefcs.net/ondemand/&tv/johnnyTest/video/johnnyTest_clip2_eps19_en
                    //
                    // following rtmpdump style command works
                    // rtmpdump
                    // --rtmp 'rtmpe://cp102794.edgefcs.net:1935/ondemand?videoId=3066558001&lineUpId=1664607936001&pubId=1873145815&playerId=1706768404001&affiliateId='
                    // --flv 'johnnyTest_clip2_eps19_en.mp4'
                    // --playpath 'tv/johnnyTest/video/johnnyTest_clip2_eps19_en?videoId=3066558001&lineUpId=1664607936001&pubId=1873145815&playerId=1706768404001&affiliateId='

                    Match rtmpUrlMatch = rtmpUrlRegex.Match(url);

                    if (rtmpUrlMatch.Success)
                    {
                        string videoId = videoDTO.GetDoubleProperty("id").ToString();
                        string query   = string.Format(@"videoId={0}&lineUpId={1}&pubId={2}&playerId={3}&affiliateId=",
                                                       videoId, lineUpId, publisherId, playerId);
                        string rtmpUrl = String.Format("{0}://{1}/{2}?{3}",
                                                       rtmpUrlMatch.Groups["rtmp"].Value,
                                                       rtmpUrlMatch.Groups["host"].Value,
                                                       rtmpUrlMatch.Groups["app"].Value,
                                                       query);
                        string playPath = string.Format(@"{0}?{1}", rtmpUrlMatch.Groups["leftover"].Value, query);
                        Log.Debug(@"RTMP URL: {0}, playPath: {1}", rtmpUrl, playPath);

                        VideoInfo video = new VideoInfo()
                        {
                            Title       = videoDTO.GetStringProperty("displayName"),
                            Thumb       = videoDTO.GetStringProperty("thumbnailURL"),
                            Description = videoDTO.GetStringProperty("longDescription"),
                            Length      = TimeSpan.FromSeconds(videoDTO.GetDoubleProperty("length") / 1000).ToString(),
                            VideoUrl    = new RtmpUrl(rtmpUrl)
                            {
                                PlayPath = playPath
                            }.ToString()
                        };

                        result.Add(video);
                    }
                }
            }
            else
            {
                Log.Error(@"No videos found for {0}", category.Name);
            }
            return(result);
        }
Exemplo n.º 23
0
        protected AMFArray GetResultsFromViewerExperienceRequest(Match m, string videoUrl)
        {
            AMFObject contentOverride = new AMFObject("com.brightcove.experience.ContentOverride");
            System.Text.RegularExpressions.Group g;
            if ((g = m.Groups["contentId"]).Success)
            {
                Log.Debug("param contentId=" + g.Value);
                contentOverride.Add("contentId", (double)Int64.Parse(g.Value));
            }
            else
                contentOverride.Add("contentId", double.NaN);
            contentOverride.Add("target", "videoPlayer");
            if ((g = m.Groups["contentRefId"]).Success)
            {
                Log.Debug("param contentRefId=" + g.Value);
                contentOverride.Add("contentRefId", g.Value);
            }
            else
                contentOverride.Add("contentRefId", null);

            contentOverride.Add("featuredRefId", null);
            contentOverride.Add("contentRefIds", null);
            contentOverride.Add("featuredId", double.NaN);
            contentOverride.Add("contentIds", null);
            contentOverride.Add("contentType", 0);
            AMFArray array = new AMFArray();
            array.Add(contentOverride);

            AMFObject ViewerExperienceRequest = new AMFObject("com.brightcove.experience.ViewerExperienceRequest");
            ViewerExperienceRequest.Add("TTLToken", String.Empty);
            if ((g = m.Groups["playerKey"]).Success)
            {
                Log.Debug("param playerKey=" + g.Value);
                ViewerExperienceRequest.Add("playerKey", g.Value);
            }
            else
                ViewerExperienceRequest.Add("playerKey", playerKey);
            ViewerExperienceRequest.Add("deliveryType", double.NaN);
            ViewerExperienceRequest.Add("contentOverrides", array);
            ViewerExperienceRequest.Add("URL", videoUrl);
            Log.Debug("param URL=" + videoUrl);

            if ((g = m.Groups["experienceId"]).Success)
            {
                Log.Debug("param experienceId=" + g.Value);
                ViewerExperienceRequest.Add("experienceId", (double)Int64.Parse(g.Value));
            }
            else
                ViewerExperienceRequest.Add("experienceId", double.NaN);

            AMFSerializer ser = new AMFSerializer();
            byte[] data = ser.Serialize(ViewerExperienceRequest, "com.brightcove.experience.ExperienceRuntimeFacade.getDataForExperience", hashValue);

            AMFObject response = AMFObject.GetResponse(requestUrl, data);
            return response.GetArray("programmedContent").GetObject("videoPlayer").GetObject("mediaDTO").GetArray("renditions");
        }
Exemplo n.º 24
0
 protected AMFArray GetResultsFromFindByMediaId(Match m)
 {
     AMFSerializer ser = new AMFSerializer();
     object[] values = new object[4];
     values[0] = hashValue;
     values[1] = Convert.ToDouble(playerId);
     values[2] = Convert.ToDouble(m.Groups["mediaId"].Value);
     values[3] = Convert.ToDouble(array4);
     byte[] data = ser.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", values);
     AMFObject obj = AMFObject.GetResponse(requestUrl, data);
     return obj.GetArray("renditions");
 }
        public override List<VideoInfo> GetVideos(Category category)
        {
            List<VideoInfo> result = new List<VideoInfo>();

            /*
             sample AMF input for findPagingMediaCollectionByReferenceId (expressed in pretty-printed JSON for clarity - captured using Firebug)
            
                ["1ddf0ed58803c0533b0f82a8ff68ae50e0e12f52",1706768404001,"cn-johnny-test-playlist-clip",0,50,1873145815]
            */
           
            object[] amfInput = new object[6];
            amfInput[0] = hashValue;
            amfInput[1] = Convert.ToDouble(playerId);
            amfInput[2] = string.Format(@"cn-{0}-playlist-clip", ((RssLink) category).Url);
            amfInput[3] = Convert.ToDouble(@"0");
            amfInput[4] = Convert.ToDouble(@"50");
            amfInput[5] = Convert.ToDouble(publisherId);
            
            AMFSerializer serializer = new AMFSerializer();
            AMFObject response = AMFObject.GetResponse(brightcoveUrl, serializer.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findPagingMediaCollectionByReferenceId", amfInput));

            //Log.Debug("AMF Response: {0}", response.ToString());
            string lineUpId = response.GetDoubleProperty("id").ToString();
            Log.Debug("LineUpId: {0}", lineUpId);
            
            AMFArray videoDTOs = response.GetArray("videoDTOs");
            
            if (videoDTOs != null)
            {
                for (int i = 0; i < videoDTOs.Count; i++)
                {
                    AMFObject videoDTO = videoDTOs.GetObject(i);
                    
                    string url = videoDTO.GetStringProperty("FLVFullLengthURL");
                    
                    // typical URL from FLVFullLengthURL
                    // rtmpe://cp102794.edgefcs.net/ondemand/&tv/johnnyTest/video/johnnyTest_clip2_eps19_en
                    //
                    // following rtmpdump style command works
                    // rtmpdump 
                    // --rtmp 'rtmpe://cp102794.edgefcs.net:1935/ondemand?videoId=3066558001&lineUpId=1664607936001&pubId=1873145815&playerId=1706768404001&affiliateId='
                    // --flv 'johnnyTest_clip2_eps19_en.mp4'
                    // --playpath 'tv/johnnyTest/video/johnnyTest_clip2_eps19_en?videoId=3066558001&lineUpId=1664607936001&pubId=1873145815&playerId=1706768404001&affiliateId='
                    
                    Match rtmpUrlMatch = rtmpUrlRegex.Match(url);
                    
                    if (rtmpUrlMatch.Success)
                    {
                        string videoId = videoDTO.GetDoubleProperty("id").ToString();
                        string query = string.Format(@"videoId={0}&lineUpId={1}&pubId={2}&playerId={3}&affiliateId=",
                                                     videoId, lineUpId, publisherId, playerId);
                        string rtmpUrl = String.Format("{0}://{1}/{2}?{3}",
                                                       rtmpUrlMatch.Groups["rtmp"].Value,
                                                       rtmpUrlMatch.Groups["host"].Value,
                                                       rtmpUrlMatch.Groups["app"].Value,
                                                       query);
                        string playPath = string.Format(@"{0}?{1}", rtmpUrlMatch.Groups["leftover"].Value, query);
                        Log.Debug(@"RTMP URL: {0}, playPath: {1}", rtmpUrl, playPath);
                        
                        VideoInfo video = new VideoInfo() {
                            Title = videoDTO.GetStringProperty("displayName"),
                            Thumb = videoDTO.GetStringProperty("thumbnailURL"),
                            Description = videoDTO.GetStringProperty("longDescription"),
                            Length = TimeSpan.FromSeconds(videoDTO.GetDoubleProperty("length")/1000).ToString(),
                            VideoUrl = new RtmpUrl(rtmpUrl) {
                                PlayPath = playPath
                            }.ToString()
                        };
                        
                        result.Add(video);
                    }
                    
                }
            }
            else
            {
                Log.Error(@"No videos found for {0}", category.Name);
            }
            return result;
        }
Exemplo n.º 26
0
 protected AMFArray GetResultsFromFindByMediaId(Match m, string videoUrl)
 {
     AMFSerializer ser = new AMFSerializer();
     object[] values = new object[4];
     values[0] = hashValue;
     values[1] = Convert.ToDouble(m.Groups["experienceId"].Value);
     values[2] = Convert.ToDouble(videoUrl.Substring(videoUrl.LastIndexOf("/") + 1));
     values[3] = Convert.ToDouble(array4);
     byte[] data = ser.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", values, AMFVersion.AMF3);
     AMFObject obj = AMFObject.GetResponse(requestUrl + m.Groups["playerKey"].Value, data);
     return obj.GetArray("renditions");
 }
Exemplo n.º 27
0
        public override string GetVideoUrl(VideoInfo video)
        {
            string   result     = string.Empty;
            string   videoId    = string.Empty;
            AMFArray renditions = null;

            if (RequestType.Equals(BrightCoveType.FindMediaById))
            {
                /*
                 * sample AMF input (expressed as JSON)
                 * ["466faf0229239e70a6df8fe66fc04f25f50e6fa7",48543011001,1401332946001,15364602001]
                 */
                videoId = video.VideoUrl;

                object[] values = new object[4];
                values[0] = hashValue;
                values[1] = Convert.ToDouble(playerId);
                values[2] = Convert.ToDouble(videoId);
                values[3] = Convert.ToDouble(publisherId);

                AMFSerializer serializer = new AMFSerializer();
                AMFObject     response   = AMFObject.GetResponse(brightcoveUrl, serializer.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", values, AMFVersion.AMF3));
                //Log.Debug("AMF Response: {0}", response.ToString());

                renditions = response.GetArray("renditions");
            }
            else
            {
                /*
                 * sample AMF input for ViewerExperience (expressed in pretty-printed JSON for clarity - captured using Flashbug in Firebug)
                 * [
                 *  {"targetURI":"com.brightcove.experience.ExperienceRuntimeFacade.getDataForExperience",
                 *   "responseURI":"/1",
                 *   "length":"461 B",
                 *   "data":["82c0aa70e540000aa934812f3573fd475d131a63",
                 *      {"contentOverrides":[
                 *          {"contentType":0,
                 *           "target":"videoPlayer",
                 *           "featuredId":null,
                 *           "contentId":1411956407001,
                 *           "featuredRefId":null,
                 *           "contentIds":null,
                 *           "contentRefId":null,
                 *           "contentRefIds":null,
                 *           "__traits":
                 *              {"type":"com.brightcove.experience.ContentOverride",
                 *               "members":["contentType","target","featuredId","contentId","featuredRefId","contentIds","contentRefId","contentRefIds"],
                 *               "count":8,
                 *               "externalizable":false,
                 *               "dynamic":false}}],
                 *        "TTLToken":"",
                 *        "deliveryType":null,
                 *        "playerKey":"AQ~~,AAAABDk7A3E~,xYAUE9lVY9-LlLNVmcdybcRZ8v_nIl00",
                 *        "URL":"http://ww3.tvo.org/video/171480/safe-houses",
                 *        "experienceId":756015080001,
                 *        "__traits":
                 *          {"type":"com.brightcove.experience.ViewerExperienceRequest",
                 *           "members":["contentOverrides","TTLToken","deliveryType","playerKey","URL","experienceId"],
                 *           "count":6,
                 *           "externalizable":false,
                 *           "dynamic":false}}]}]
                 */
                videoId = getBrightCoveVideoIdForViewerExperienceRequest(video.VideoUrl);
                if (!string.IsNullOrEmpty(videoId))
                {
                    // content override
                    AMFObject contentOverride = new AMFObject(@"com.brightcove.experience.ContentOverride");
                    contentOverride.Add("contentId", videoId);
                    contentOverride.Add("contentIds", null);
                    contentOverride.Add("contentRefId", null);
                    contentOverride.Add("contentRefIds", null);
                    contentOverride.Add("contentType", 0);
                    contentOverride.Add("featuredId", double.NaN);
                    contentOverride.Add("featuredRefId", null);
                    contentOverride.Add("target", "videoPlayer");
                    AMFArray contentOverrideArray = new AMFArray();
                    contentOverrideArray.Add(contentOverride);

                    // viewer experience request
                    AMFObject viewerExperenceRequest = new AMFObject(@"com.brightcove.experience.ViewerExperienceRequest");
                    viewerExperenceRequest.Add("contentOverrides", contentOverrideArray);
                    viewerExperenceRequest.Add("experienceId", Convert.ToDouble(playerId));
                    viewerExperenceRequest.Add("deliveryType", null);
                    viewerExperenceRequest.Add("playerKey", string.Empty);
                    viewerExperenceRequest.Add("URL", video.VideoUrl);
                    viewerExperenceRequest.Add("TTLToken", string.Empty);

                    //Log.Debug("About to make AMF call: {0}", viewerExperenceRequest.ToString());
                    AMFSerializer serializer = new AMFSerializer();
                    AMFObject     response   = AMFObject.GetResponse(brightcoveUrl, serializer.Serialize(viewerExperenceRequest, "com.brightcove.experience.ExperienceRuntimeFacade.getDataForExperience", hashValue));
                    //Log.Debug("AMF Response: {0}", response.ToString());

                    renditions = response.GetArray("programmedContent").GetObject("videoPlayer").GetObject("mediaDTO").GetArray("renditions");
                }
            }

            if (renditions == null)
            {
                return(result);
            }

            video.PlaybackOptions = new Dictionary <string, string>();
            // keep track of bitrates and URLs
            Dictionary <string, string> urlsDictionary = new Dictionary <string, string>();

            for (int i = 0; i < renditions.Count; i++)
            {
                AMFObject rendition = renditions.GetObject(i);
                int       bitrate   = rendition.GetIntProperty("encodingRate");
                string    optionKey = String.Format("{0}x{1} {2}K",
                                                    rendition.GetIntProperty("frameWidth"),
                                                    rendition.GetIntProperty("frameHeight"),
                                                    bitrate / 1024);
                string url = HttpUtility.UrlDecode(rendition.GetStringProperty("defaultURL"));
                Log.Debug("Option: {0} URL: {1}", optionKey, url);

                // typical rtmp url from "defaultURL" is:
                // rtmp://brightcove.fcod.llnwd.net/a500/d20/&mp4:media/1351824783/1351824783_1411974095001_109856X-640x360-1500k.mp4&1330020000000&1b163106256f448754aff72969869479
                //
                // following rtmpdump style command works
                // rtmpdump
                // --app 'a500/d20/?videoId=1411956407001&lineUpId=&pubId=18140038001&playerId=756015080001&playerTag=&affiliateId='
                // --auth 'mp4:media/1351824783/1351824783_1411974097001_109856X-400x224-300k.mp4&1330027200000&23498dd8f4659cd07ad1b6c4ee5a013d'
                // --rtmp 'rtmp://brightcove.fcod.llnwd.net/a500/d20/?videoId=1411956407001&lineUpId=&pubId=18140038001&playerId=756015080001&playerTag=&affiliateId='
                // --flv 'TVO_org_-_Safe_as_Houses.flv'
                // --playpath 'mp4:media/1351824783/1351824783_1411974097001_109856X-400x224-300k.mp4'

                Match rtmpUrlMatch = rtmpUrlRegex.Match(url);

                if (rtmpUrlMatch.Success)
                {
                    string leftover = rtmpUrlMatch.Groups["leftover"].Value;
                    string query    = string.Format(@"videoId={0}&lineUpId=&pubId={1}&playerId={2}&playerTag=&affiliateId=",
                                                    videoId, publisherId, playerId);

                    int questionMarkPosition = leftover.IndexOf('?');
                    // use existing query (if present) in the new query string
                    if (questionMarkPosition != -1)
                    {
                        query = string.Format(@"{0}{1}", leftover.Substring(questionMarkPosition + 1, leftover.Length - questionMarkPosition - 1), query);
                    }

                    string app     = String.Format("{0}?{1}", rtmpUrlMatch.Groups["app"], query);
                    string auth    = leftover;
                    string rtmpUrl = String.Format("{0}://{1}/{2}?{3}",
                                                   rtmpUrlMatch.Groups["rtmp"].Value,
                                                   rtmpUrlMatch.Groups["host"].Value,
                                                   rtmpUrlMatch.Groups["app"].Value,
                                                   query);
                    int    ampersandPosition = leftover.IndexOf('&');
                    string playPath          = ampersandPosition == -1 ? leftover : leftover.Substring(0, ampersandPosition);
                    Log.Debug(@"rtmpUrl: {0}, PlayPath: {1}, App: {2}, Auth: {3}", rtmpUrl, playPath, app, auth);
                    urlsDictionary.Add(optionKey, new RtmpUrl(rtmpUrl)
                    {
                        PlayPath = playPath,
                        App      = app,
                        Auth     = auth
                    }.ToString());
                }
            }

            // sort the URLs ascending by bitrate
            foreach (var item in urlsDictionary.OrderBy(u => u.Key, new BitrateComparer()))
            {
                video.PlaybackOptions.Add(item.Key, item.Value);
                // return last URL as the default (will be the highest bitrate)
                result = item.Value;
            }
            return(result);
        }
Exemplo n.º 28
0
        protected AMFArray GetResultsFromViewerExperienceRequest(Match m, string videoUrl)
        {
            AMFObject contentOverride = new AMFObject("com.brightcove.experience.ContentOverride");

            System.Text.RegularExpressions.Group g;
            if ((g = m.Groups["contentId"]).Success)
            {
                Log.Debug("param contentId=" + g.Value);
                contentOverride.Add("contentId", (double)Int64.Parse(g.Value));
            }
            else
            {
                contentOverride.Add("contentId", double.NaN);
            }
            contentOverride.Add("target", "videoPlayer");
            if ((g = m.Groups["contentRefId"]).Success)
            {
                Log.Debug("param contentRefId=" + g.Value);
                contentOverride.Add("contentRefId", g.Value);
            }
            else
            {
                contentOverride.Add("contentRefId", null);
            }

            contentOverride.Add("featuredRefId", null);
            contentOverride.Add("contentRefIds", null);
            contentOverride.Add("featuredId", double.NaN);
            contentOverride.Add("contentIds", null);
            contentOverride.Add("contentType", 0);
            AMFArray array = new AMFArray();

            array.Add(contentOverride);

            AMFObject ViewerExperienceRequest = new AMFObject("com.brightcove.experience.ViewerExperienceRequest");

            ViewerExperienceRequest.Add("TTLToken", String.Empty);
            if ((g = m.Groups["playerKey"]).Success)
            {
                Log.Debug("param playerKey=" + g.Value);
                ViewerExperienceRequest.Add("playerKey", g.Value);
            }
            else
            {
                ViewerExperienceRequest.Add("playerKey", playerKey);
            }
            ViewerExperienceRequest.Add("deliveryType", double.NaN);
            ViewerExperienceRequest.Add("contentOverrides", array);
            ViewerExperienceRequest.Add("URL", videoUrl);
            Log.Debug("param URL=" + videoUrl);

            if ((g = m.Groups["experienceId"]).Success)
            {
                Log.Debug("param experienceId=" + g.Value);
                ViewerExperienceRequest.Add("experienceId", (double)Int64.Parse(g.Value));
            }
            else
            {
                ViewerExperienceRequest.Add("experienceId", double.NaN);
            }

            AMFSerializer ser = new AMFSerializer();

            byte[] data = ser.Serialize(ViewerExperienceRequest, "com.brightcove.experience.ExperienceRuntimeFacade.getDataForExperience", hashValue);

            lastResponse = AMFObject.GetResponse(requestUrl, data);
            return(lastResponse.GetArray("programmedContent").GetObject("videoPlayer").GetObject("mediaDTO").GetArray("renditions"));
        }