Esempio n. 1
0
        public static async Task <string> GetDmcWatchResponseDataAsync(NiconicoContext context, string requestId)
        {
            if (!NiconicoRegex.IsVideoId(requestId))
            {
                //				throw new ArgumentException();
            }

            var dict = new Dictionary <string, string>();
            var url  = $"{NiconicoUrls.VideoWatchPageUrl}{requestId}";

            url += "?" + HttpQueryExtention.DictionaryToQuery(dict);

            try
            {
                var message = new HttpRequestMessage(HttpMethod.Get, new Uri(url));

                var res = await context.SendAsync(message);

                if (res.ReasonPhrase == "Forbidden")
                {
                    throw new WebException("require payment.");
                }

                var text = await res.Content.ReadAsStringAsync();

                return(text);
            }
            catch (Exception e)
            {
                throw new WebException("access failed watch/" + requestId, e);
            }
        }
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 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. 4
0
        // ユーザーの投稿動画関連

        public static Task <string> GetUserDataAsync(NiconicoContext context, uint user_id, uint page, Sort sortMethod, Order sortDir)
        {
            var url = NiconicoUrls.MakeUserVideoRssUrl(user_id.ToString(), page, sortMethod.ToShortString(), sortDir.ToShortString());

            return(context
                   .GetStringAsync(url));
        }
Esempio n. 5
0
        async Task LoginAfterResolveUserDetailAction(NiconicoContext context)
        {
            Context = context;

            Mntone.Nico2.Users.Info.InfoResponse userInfo = null;

            try
            {
                await Task.Delay(50);

                userInfo = await Context.User.GetInfoAsync();

                if (userInfo == null)
                {
                    IsLoggedIn = false;
                    throw new Exception("ログインに失敗");
                }
            }
            catch (Exception e)
            {
                IsLoggedIn = false;
                HandleLoginError(e);
            }

            IsLoggedIn       = true;
            UserId           = userInfo.Id;
            IsPremiumAccount = userInfo.IsPremium;

            try
            {
                var user = await Context.User.GetUserDetail(_UserId.ToString());

                UserName    = user?.Nickname ?? _UserId.ToString();
                UserIconUrl = user?.ThumbnailUri;
            }
            catch (Exception ex)
            {
                IsLoggedIn = false;
                Debug.WriteLine("ユーザー名取得処理に失敗 + " + _UserId);
                Debug.WriteLine(ex.ToString());
#if DEBUG
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
#endif
            }

            LogIn?.Invoke(this, new NiconicoSessionLoginEventArgs()
            {
                UserId      = UserId.Value,
                IsPremium   = userInfo.IsPremium,
                UserName    = UserName,
                UserIconUrl = UserIconUrl,
            });



            Debug.WriteLine("Login Done! " + ServiceStatus);
        }
Esempio n. 6
0
        public static async Task <bool> UpdateMylistGroupAsync(NiconicoContext context, string mylistId, string name, string description, bool isPublic, MylistSortKey defaultSortKey, MylistSortOrder defaultSortOrder)
        {
            var dict = new Dictionary <string, string>();

            dict.Add("name", name);
            dict.Add("description", description);
            dict.Add("isPublic", isPublic.ToString1Or0());
            dict.Add("defaultSortKey", defaultSortKey.ToQueryString());
            dict.Add("defaultSortOrder", defaultSortOrder.ToQueryString());

            var request = new HttpRequestMessage(HttpMethod.Put, new Uri($"https://nvapi.nicovideo.jp/v1/users/me/mylists/{mylistId}"));

#if WINDOWS_UWP
            request.Content         = new HttpFormUrlEncodedContent(dict);
            request.Headers.Referer = new Uri($"https://www.nicovideo.jp/my/mylist/{mylistId}");
#else
            request.Content          = new FormUrlEncodedContent(dict);
            request.Headers.Referrer = new Uri($"https://www.nicovideo.jp/my/mylist/{mylistId}");
#endif
            request.Headers.Add("X-Request-With", "https://www.nicovideo.jp");


            var res = await context.SendAsync(request);

            var json = await res.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <MylistUpdateResultResponse>(json);
            return(result.Meta.Status == 200);
        }
Esempio n. 7
0
        public static async Task <string> PostReservationAsync(NiconicoContext context, string vid, bool overwrite)
        {
            var dict = new Dictionary <string, string>();

            if (vid.StartsWith("lv"))
            {
                vid = vid.Remove(0, 2);
            }

            if (!int.TryParse(vid, out var vidNumber))
            {
                throw new ArgumentException("vid can not accept NiconicoLiveContentId.");
            }

            dict.Add(nameof(vid), vid);
            dict.Add(nameof(overwrite), overwrite.ToString1Or0());

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri("http://live.nicovideo.jp/api/timeshift.reservations"))
            {
#if WINDOWS_UWP
                Content = new HttpFormUrlEncodedContent(dict)
#else
                Content = new FormUrlEncodedContent(dict)
#endif
            };

            requestMessage.Headers.Add("origin", "https://live.nicovideo.jp");
            var response = await context.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead);

            return(await response.Content.ReadAsStringAsync());
        }
Esempio n. 8
0
        public static async Task <FollowChannelResponse> GetFollowChannelAsync(NiconicoContext context, uint limit = 25, uint offset = 0)
        {
            var uri = $"https://public.api.nicovideo.jp/v1/user/followees/channels.json?limit={limit}&offset={offset}";
            await context.PrepareCorsAsscessAsync(HttpMethod.Get, uri);

            return(await context.GetJsonAsAsync <FollowChannelResponse>(uri));
        }
Esempio n. 9
0
        public async Task LogInAsync()
        {
            var(context, status, authority, userId) = await AccountTestHelper.CreateNiconicoContextAndLogInWithTestAccountAsync();

            _context     = context;
            _loginUserId = userId;
        }
Esempio n. 10
0
        public static async Task <FollowTagsResponse> GetFollowTagsAsync(NiconicoContext context)
        {
            var uri = $"https://nvapi.nicovideo.jp/v1/users/me/following/tags";
            await context.PrepareCorsAsscessAsync(HttpMethod.Get, uri);

            return(await context.GetJsonAsAsync <FollowTagsResponse>(uri));
        }
Esempio n. 11
0
        public static async Task <ContentManageResult> RemoveFollowCommunityAsync(NiconicoContext context, string communityId)
        {
            var token = await GetCommunityLeaveTokenAsync(context, communityId);

            var url  = NiconicoUrls.CommunityLeavePageUrl + token.CommunityId;
            var dict = new Dictionary <string, string>();

            dict.Add("time", token.Time);
            dict.Add("commit_key", token.CommitKey);
            dict.Add("commit", token.Commit);

#if WINDOWS_UWP
            var content = new HttpFormUrlEncodedContent(dict);
#else
            var content = new FormUrlEncodedContent(dict);
#endif


            var request = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.Headers.Add("Referer", url);
            request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

            request.Content = content;
            var postResult = await context.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            Debug.WriteLine(postResult);

            return(postResult.IsSuccessStatusCode ? ContentManageResult.Success : ContentManageResult.Failed);
        }
Esempio n. 12
0
        private static async Task <ChannelFollowApiInfo> GetFollowChannelApiInfo(NiconicoContext context, string channelScreenName)
        {
            var html = await context.GetStringAsync("http://ch.nicovideo.jp/" + channelScreenName);

            var document = new HtmlDocument();

            document.LoadHtml(html);
            var bookmarkAnchorNode = document.DocumentNode.Descendants("a").Single(x =>
            {
                if (x.Attributes.Contains("class") && x.Attributes["class"].Value.Contains("bookmark"))
                {
                    return(x.Attributes["class"].Value.Split(' ').FirstOrDefault() == "bookmark");
                }
                else
                {
                    return(false);
                }
            });

            return(new ChannelFollowApiInfo()
            {
                AddApi = bookmarkAnchorNode.Attributes["api_add"].Value,
                DeleteApi = bookmarkAnchorNode.Attributes["api_delete"].Value,
                Params = System.Net.WebUtility.HtmlDecode(bookmarkAnchorNode.Attributes["params"].Value)
            });
        }
Esempio n. 13
0
        public static async Task <string> GetTagSearchDataAsync(
            NiconicoContext context
            , string tag
            , uint from
            , uint limit
            , Sort?sort
            , Order?order
            )
        {
            var dict = new Dictionary <string, string>();

            dict.Add("__format", "json");

            dict.Add(nameof(tag), tag);
            dict.Add(nameof(from), from.ToString());
            dict.Add(nameof(limit), limit.ToString());
            if (order.HasValue)
            {
                dict.Add(nameof(order), order.Value == Order.Ascending ? "a" : "d");
            }
            if (sort.HasValue)
            {
                dict.Add(nameof(sort), sort.Value.ToShortString());
            }

            return(await context.GetStringAsync(NiconicoUrls.NICOVIDEO_CE_NICOAPI_V1_TAG_SEARCH, dict));
        }
Esempio n. 14
0
        public static async Task <ContentManageResult> AddFollowCommunityAsync(NiconicoContext context, string communityId)
        {
            var communityIdWoCo      = communityId.Substring(2);
            var communityJoinPageUrl = new Uri($"https://com.nicovideo.jp/motion/{communityId}");

            var uri = $"https://com.nicovideo.jp/api/v1/communities/{communityIdWoCo}/follows.json";
            //            await PrepareCorsAsscessAsync(HttpMethod.Post, uri);

            var request = new HttpRequestMessage(HttpMethod.Post, new Uri(uri));

#if WINDOWS_UWP
            request.Headers.Referer = communityJoinPageUrl;
            request.Headers.Host    = new Windows.Networking.HostName("com.nicovideo.jp");
#else
            request.Headers.Referrer = communityJoinPageUrl;
            request.Headers.Host     = "com.nicovideo.jp";
#endif
            request.Headers.Add("Origin", "https://com.nicovideo.jp");
            request.Headers.Add("X-Requested-By", communityJoinPageUrl.OriginalString);

            var message = await context.SendAsync(request);

            var json = await message.Content.ReadAsStringAsync();

            var result = Newtonsoft.Json.JsonConvert.DeserializeObject <FollowResultResponse>(json);


            return(result.Meta.Status == 200 || result.Meta.Status == 201 ? ContentManageResult.Success : ContentManageResult.Failed);
        }
Esempio n. 15
0
        public static async Task <FollowCommunityResponse> GetFollowCommunityAsync(NiconicoContext context, uint limit = 25, uint page = 0)
        {
            var uri = $"https://public.api.nicovideo.jp/v1/user/followees/communities.json?limit={limit}&page={page}";
            await context.PrepareCorsAsscessAsync(HttpMethod.Get, uri);

            return(await context.GetJsonAsAsync <FollowCommunityResponse>(uri, FollowCommunityResponseConverter.Settings));
        }
Esempio n. 16
0
        public async Task <NiconicoSignInStatus> CheckSignedInStatus()
        {
            NiconicoSignInStatus result = NiconicoSignInStatus.Failed;

            try
            {
                await _SigninLock.WaitAsync();

                if (Util.InternetConnection.IsInternet() && NiconicoContext != null)
                {
                    result = await ConnectionRetryUtil.TaskWithRetry(
                        () => NiconicoContext.GetIsSignedInAsync()
                        , retryInterval : 1000
                        );
                }
            }
            catch
            {
                // ログイン処理時には例外を捕捉するが、ログイン状態チェックでは例外は無視する
                result = NiconicoSignInStatus.Failed;
            }
            finally
            {
                UpdateServiceStatus(result);

                _SigninLock.Release();
            }

            return(result);
        }
Esempio n. 17
0
        /// <summary>
        /// タイムシフト予約の削除用トークンを取得します。(要ログインセッション)
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static async Task <ReservationToken> GetReservationToken(NiconicoContext context)
        {
            var timeshiftPageHtmlText = await context.GetStringAsync("http://live.nicovideo.jp/my_timeshift_list");

            HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
            htmlDocument.LoadHtml(timeshiftPageHtmlText);

            var confirmNode = htmlDocument.DocumentNode
                              .Descendants("input")
                              .FirstOrDefault(x => x.Id == "confirm")
            ;

            // will return string like "ulck_0123456789"
            if (confirmNode != null)
            {
                return(new ReservationToken()
                {
                    Token = confirmNode.GetAttributeValue("value", "")
                });
            }
            else
            {
                return(null);
            }
        }
Esempio n. 18
0
        public static async Task <string> GetCommentDataAsync(NiconicoContext context, int userId, string commentServerUrl, int threadId, bool isKeyRequired)
        {
            var paramDict = new Dictionary <string, string>();

            paramDict.Add("user_id", userId is 0 ? "" : userId.ToString());
            paramDict.Add("version", "20090904");
            paramDict.Add("thread", threadId.ToString());
            paramDict.Add("res_from", "-1000");

            // 公式動画の場合はThreadKeyとforce_184を取得する
            if (isKeyRequired)
            {
                var threadKeyResponse = await GetThreadKeyDataAsync(context, threadId)
                                        .ContinueWith(prevTask => ParseThreadKey(prevTask.Result));

                if (threadKeyResponse != null)
                {
                    paramDict.Add("threadkey", threadKeyResponse.ThreadKey);
                    paramDict.Add("force_184", threadKeyResponse.Force184);
                }
            }

            var param      = HttpQueryExtention.DictionaryToQuery(paramDict);
            var commentUrl = $"{commentServerUrl}thread?{Uri.EscapeUriString(param)}";

            return(await context.GetStringAsync(commentUrl));
        }
        public static Task <string> GetMylistSearchDataAsync(
            NiconicoContext context
            , string str
            , uint from
            , uint limit
            , Sort?sort
            , Order?order
            )
        {
            var dict = new Dictionary <string, string>();

            dict.Add("__format", "json");

            dict.Add(nameof(str), str);
            dict.Add(nameof(from), from.ToString());
            dict.Add(nameof(limit), limit.ToString());
            if (order.HasValue)
            {
                dict.Add(nameof(order), order.Value.ToChar().ToString());
            }

            if (sort.HasValue)
            {
                dict.Add(nameof(sort), sort.Value.ToShortString());
            }


            return(context.GetStringAsync(NiconicoUrls.NICOVIDEO_CE_NICOAPI_V1_MYLIST_SEARCH, dict));
        }
Esempio n. 20
0
        public static async Task <UserDetailResponse.UserDetails> GetUserDetailAsync(NiconicoContext context, string user_id)
        {
            var htmlText = await context
                           .GetConvertedStringAsync($"https://www.nicovideo.jp/user/{user_id}");

            return(ParseUserDetailData(htmlText).Container.Details);
        }
Esempio n. 21
0
        public static async Task <FollowMylistResponse> GetFollowMylistAsync(NiconicoContext context, uint sampleItemCount = 3)
        {
            var uri = $"https://nvapi.nicovideo.jp/v1/users/me/following/mylists?sampleItemCount={sampleItemCount}";
            await context.PrepareCorsAsscessAsync(HttpMethod.Get, uri);

            return(await context.GetJsonAsAsync <FollowMylistResponse>(uri, Mylist.Converter.Settings));
        }
Esempio n. 22
0
        public static Task <string> GetMylistGroupDataAsync(NiconicoContext context, string group_id)
        {
            var dict = new Dictionary <string, string>();

            dict.Add(nameof(group_id), group_id);
            return(context.PostAsync(NiconicoUrls.MylistGroupGetUrl, dict));
        }
Esempio n. 23
0
        public static async Task <string> __DeleteFollowChannelAsync(NiconicoContext context, string channelId)
        {
            var info = await context.Channel.GetChannelInfo(channelId);

            var apiInfo = await GetFollowChannelApiInfo(context, info.ScreenName);

            return(await context.GetStringAsync($"{apiInfo.DeleteApi}?{apiInfo.Params}"));
        }
 public async Task SeriesVideosTestAsync(string seriesId)
 {
     var context = new NiconicoContext()
     {
         AdditionalUserAgent = "OpenNiconico_Test@tor4kichi"
     };
     var response = await context.Video.GetSeriesVideosAsync(seriesId);
 }
Esempio n. 25
0
            public static async Task <NicoliveVideoInfoResponse> GetLiveInfoAsync(NiconicoContext context, string liveId)
            {
                var json = await GetLiveInfoJsonAsync(context, liveId);

                var resContainer = JsonSerializerExtensions.Load <NicoliveVideoInfoResponseContainer>(json);

                return(resContainer.NicoliveVideoResponse);
            }
 public async Task UserSeriesTestAsync(string userId)
 {
     var context = new NiconicoContext()
     {
         AdditionalUserAgent = "OpenNiconico_Test@tor4kichi"
     };
     var response = await context.User.GetUserSeiresAsync(userId, 0);
 }
Esempio n. 27
0
        public static async Task <MylistGroupItemsResponse> GetMylistGroupItemsAsync(NiconicoContext context, long mylistId, MylistSortKey sortKey, MylistSortOrder sortOrder, uint pageSize, uint pageCount)
        {
            // Note: CORSのOPTIONSを先に送る奴が必要になるかも
            var uri = $"https://nvapi.nicovideo.jp/v2/mylists/{mylistId}?sortKey={sortKey.ToQueryString()}&sortOrder={sortOrder.ToQueryString()}&pageSize={pageSize}&page={pageCount + 1}";
            await context.PrepareCorsAsscessAsync(HttpMethod.Get, uri);

            return(await context.GetJsonAsAsync <MylistGroupItemsResponse>(uri, Converter.Settings));
        }
Esempio n. 28
0
            private static Task <string> GetLiveCommunityVideoJsonAsync(NiconicoContext context, string communityOrChannelId)
            {
                var dict = new Dictionary <string, string>();

                dict.Add("community_id", communityOrChannelId);
                dict.Add("__format", "json");
                return(context.GetStringAsync(NiconicoUrls.CeLiveCommunityVideoApi, dict));
            }
Esempio n. 29
0
            private static Task <string> GetLiveInfoJsonAsync(NiconicoContext context, string liveId)
            {
                var dict = new Dictionary <string, string>();

                dict.Add("v", liveId);
                dict.Add("__format", "json");
                return(context.GetStringAsync(NiconicoUrls.CeLiveVideoInfoApi, dict));
            }
Esempio n. 30
0
 public static Task <VideoInfoResponse> GetVideoInfoAsync(
     NiconicoContext context
     , string videoId
     )
 {
     return(GetVideoDataAsync(context, videoId)
            .ContinueWith(prevTask => ParseVideoInfoResponseJson(prevTask.Result)));
 }