Esempio n. 1
0
        public static async Task DmcSessionFirstHeartbeatAsync(
            NiconicoContext context,
            DmcWatchResponse watch,
            DmcSessionResponse sessionRes
            )
        {
            var session    = watch.Media.Delivery.Movie.Session;
            var sessionUrl = $"{session.Urls[0].UrlUnsafe}/{sessionRes.Data.Session.Id}?_format=json&_method=PUT";

            var message = new HttpRequestMessage(HttpMethod.Options, new Uri(sessionUrl));

            message.Headers.Add("Access-Control-Request-Method", "POST");
            message.Headers.Add("Access-Control-Request-Headers", "content-type");
#if WINDOWS_UWP
            message.Headers.UserAgent.Add(context.HttpClient.DefaultRequestHeaders.UserAgent.First());
#else
            message.Headers.UserAgent.Add(context.HttpClient.DefaultRequestHeaders.UserAgent.First());
#endif

            var result = await context.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);

            if (!result.IsSuccessStatusCode)
            {
                System.Diagnostics.Debug.WriteLine(result.ToString());
            }
        }
Esempio n. 2
0
        public static async Task DmcSessionExitHeartbeatAsync(
            NiconicoContext context,
            DmcWatchResponse watch,
            DmcSessionResponse sessionRes
            )
        {
            var session    = watch.Media.Delivery.Movie.Session;
            var sessionUrl = $"{session.Urls[0].UrlUnsafe}/{sessionRes.Data.Session.Id}?_format=json&_method=DELETE";

            var message = new HttpRequestMessage(HttpMethod.Post, new Uri(sessionUrl));

            message.Headers.Add("Access-Control-Request-Method", "POST");
            message.Headers.Add("Access-Control-Request-Headers", "content-type");
            message.Headers.UserAgent.Add(context.HttpClient.DefaultRequestHeaders.UserAgent.First());
            message.Headers.Add("Accept", "application/json");

            var requestJson = JsonConvert.SerializeObject(sessionRes.Data, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

#if WINDOWS_UWP
            message.Content = new HttpStringContent(requestJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
#else
            message.Content = new StringContent(requestJson, UnicodeEncoding.UTF8, "application/json");
#endif
            var result = await context.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);

            if (!result.IsSuccessStatusCode)
            {
                System.Diagnostics.Debug.WriteLine(result.ToString());
            }
        }
Esempio n. 3
0
 public Task DmcSessionExitHeartbeatAsync(
     Dmc.DmcWatchResponse watch,
     Dmc.DmcSessionResponse sessionRes
     )
 {
     return(Dmc.DmcClient.DmcSessionExitHeartbeatAsync(_context, watch, sessionRes));
 }
Esempio n. 4
0
 public Task DmcSessionLeaveAsync(
     Dmc.DmcWatchResponse watch,
     Dmc.DmcSessionResponse sessionRes
     )
 {
     return(Dmc.DmcClient.DmcSessionLeaveAsync(_context, watch, sessionRes));
 }
Esempio n. 5
0
 /// <summary>
 /// DMCサーバー上の動画を再生するためのリクエストを送信し、
 /// 動画再生のセッション情報を取得します。
 /// </summary>
 /// <param name="watchData"></param>
 /// <param name="videoQuality"></param>
 /// <param name="audioQuality"></param>
 /// <returns></returns>
 public Task <Dmc.DmcSessionResponse> GetDmcSessionResponse(
     Dmc.DmcWatchResponse watchData,
     Dmc.VideoContent videoQuality = null,
     Dmc.AudioContent audioQuality = null,
     bool hlsMode = false
     )
 {
     return(Dmc.DmcClient.GetDmcSessionResponseAsync(_context, watchData, videoQuality, audioQuality, hlsMode));
 }
Esempio n. 6
0
 public static Task <DmcSessionResponse> GetDmcSessionResponseAsync(
     NiconicoContext context,
     DmcWatchResponse watchData,
     VideoContent videoQuality = null,
     AudioContent audioQuality = null,
     bool hlsMode = false
     )
 {
     return(GetDmcSessionResponseDataAsync(context, watchData, videoQuality, audioQuality, hlsMode)
            .ContinueWith(prevTask => ParseDmcSessionResponse(prevTask.Result)));
 }
Esempio n. 7
0
        public static DmcWatchData ParseDmcWatchResponseData(string htmlString)
        {
            var htmlDocument = new HtmlAgilityPack.HtmlDocument();

            htmlDocument.LoadHtml(htmlString);

            try
            {
                var videoInfoNode      = htmlDocument.GetElementbyId("js-initial-watch-data");
                var watchDataRawString = videoInfoNode.GetAttributeValue("data-api-data", "");


                var jsonSerializer = new JsonSerializer();
                jsonSerializer.NullValueHandling     = NullValueHandling.Include;
                jsonSerializer.DefaultValueHandling  = DefaultValueHandling.Include;
                jsonSerializer.MissingMemberHandling = MissingMemberHandling.Ignore;
                jsonSerializer.StringEscapeHandling  = StringEscapeHandling.EscapeHtml;
                jsonSerializer.Converters.Add(new HtmlEncodingConverter());

                var htmlDecoded = WebUtility.HtmlDecode(watchDataRawString);

                DmcWatchResponse dmcWatchResponse = jsonSerializer.Deserialize <DmcWatchResponse>(new JsonTextReader(new StringReader(htmlDecoded)));

                var environmentRawString   = videoInfoNode.GetAttributeValue("data-environment", "");
                var environmentHtmlDecoded = WebUtility.HtmlDecode(environmentRawString);

                DmcWatchEnvironment dmcWatchEnvironment = null;

                try
                {
                    dmcWatchEnvironment = jsonSerializer.Deserialize <DmcWatchEnvironment>(new JsonTextReader(new StringReader(environmentHtmlDecoded)));
                }
                catch { }

                return(new DmcWatchData()
                {
                    DmcWatchResponse = dmcWatchResponse,
                    DmcWatchEnvironment = dmcWatchEnvironment
                });
            }
            catch (AggregateException e)
            {
                throw;
            }
            catch
            {
                throw;
            }
        }
Esempio n. 8
0
        public static async Task <string> GetDmcSessionResponseDataAsync(
            NiconicoContext context,
            DmcWatchResponse watchData,
            VideoContent videoQuality = null,
            AudioContent audioQuality = null,
            bool hlsMode = false
            )
        {
            var req = new DmcSessionRequest();

            var session        = watchData.Media.Delivery.Movie.Session;
            var videoQualities = watchData.Media.Delivery.Movie.Videos;
            var audioQualities = watchData.Media.Delivery.Movie.Audios;
            var encryption     = watchData.Media.Delivery.Encryption;

            // リクエストする動画品質を決定します
            // モバイルの時は最後の動画品質をモバイル画質として断定して指定
            // それ以外の場合、対象画質とそれ以下の有効な画質をすべて指定
            var requestVideoQuality = new List <string>();

            if (videoQuality?.IsAvailable ?? false)
            {
                requestVideoQuality.Add(videoQuality.Id);
            }
            else
            {
                var fallbackVideoQuality = videoQualities.Last(x => x.Metadata.LevelIndex == 0);
                requestVideoQuality.Add(fallbackVideoQuality.Id);
            }

            var requestAudioQuality = new List <string>();

            if (audioQuality?.IsAvailable ?? false)
            {
                requestAudioQuality.Add(audioQuality.Id);
            }
            else
            {
                var fallbackAudioQuality = audioQualities.Last(x => x.Metadata.LevelIndex == 0);
                requestAudioQuality.Add(fallbackAudioQuality.Id);
            }

            var sessionUrl       = $"{session.Urls[0].UrlUnsafe}?_format=json";
            var useSsl           = true;                                             // session.Urls[0].IsSsl;
            var wellKnownPort    = session.Urls[0].IsWellKnownPort;
            var protocolName     = session.Protocols[0];                             // http,hls
            var protocolAuthType = session.Protocols.ElementAtOrDefault(1) ?? "ht2"; // ht2

            req.Session = new RequestSession()
            {
                RecipeId         = session.RecipeId,
                ContentId        = session.ContentId,
                ContentType      = "movie",
                ContentSrcIdSets = new List <ContentSrcIdSet>()
                {
                    new ContentSrcIdSet()
                    {
                        ContentSrcIds = new List <ContentSrcId>()
                        {
                            new ContentSrcId()
                            {
                                SrcIdToMux = new SrcIdToMux()
                                {
                                    VideoSrcIds = requestVideoQuality,
                                    AudioSrcIds = requestAudioQuality
                                },
                            }
                        }
                    }
                },
                TimingConstraint = "unlimited",
                KeepMethod       = new KeepMethod()
                {
                    Heartbeat = new Heartbeat()
                    {
                        Lifetime = 120000
                    }
                },
                Protocol = new Protocol()
                {
                    Name       = "http",
                    Parameters = new Protocol.ProtocolParameters()
                    {
                        HttpParameters = new Protocol.HttpParameters()
                        {
                            Parameters = new Protocol.ParametersInfo()
                            {
                                HlsParameters = protocolName == "hls" ? new Protocol.HlsParameters()
                                {
                                    UseSsl           = useSsl ? "yes" : "no",
                                    UseWellKnownPort = wellKnownPort ? "yes" : "no",
                                    SegmentDuration  = 5000,
                                    TransferPreset   = "",
                                    Encryption       = encryption != null
                                    ? new Protocol.Encryption()
                                    {
                                        HlsEncryptionV1 = new Protocol.HlsEncryptionV1()
                                        {
                                            EncryptedKey = encryption.EncryptedKey,
                                            KeyUri       = encryption.KeyUri
                                        }
                                    }
                                    : null
                                }
                                : null
                                ,
                                HttpOutputDownloadParameters = protocolName == "http" ? new Protocol.HttpOutputDownloadParameters() : null
                            }
                        }
                    }
                },
                ContentUri           = "",
                SessionOperationAuth = new SessionOperationAuth_Request()
                {
                    SessionOperationAuthBySignature = new SessionOperationAuthBySignature_Request()
                    {
                        Token     = session.Token,
                        Signature = session.Signature
                    }
                },
                ContentAuth = new ContentAuth_Request()
                {
                    AuthType          = "ht2",
                    ContentKeyTimeout = (int)session.ContentKeyTimeout,
                    ServiceId         = "nicovideo",
                    ServiceUserId     = session.ServiceUserId
                },
                ClientInfo = new ClientInfo()
                {
                    PlayerId = session.PlayerId
                },
                Priority = session.Priority
            };

            var requestJson = JsonConvert.SerializeObject(req, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

//            var decodedJson = WebUtility.HtmlEncode(requestJson);
            var decodedJson = requestJson;

#if WINDOWS_UWP
            return(await context.PostAsync(sessionUrl, new HttpStringContent(decodedJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")));
#else
            return(await context.PostAsync(sessionUrl, new StringContent(decodedJson, UnicodeEncoding.UTF8, "application/json")));
#endif
        }
Esempio n. 9
0
 /// <summary>
 /// 動画のコメントをやりとりするJSON APIアクセスをラッピングしたCommentSessionContextを取得します。
 /// DMCサーバーに配置済みの動画で利用できます。Smileサーバーの動画では<see cref="GetCommentAsync(int, string, int, bool)"/>を利用してください。
 /// </summary>
 /// <param name="dmc"></param>
 /// <returns></returns>
 public Comment.CommentSessionContext GetCommentSessionContext(Dmc.DmcWatchResponse dmc)
 {
     return(new Comment.CommentSessionContext(_context, dmc));
 }