Inheritance: Livet.NotificationObject
コード例 #1
0
        //マイリストを移動
        public void MoveMylist(MylistListEntryViewModel source, MylistListViewModel dest)
        {
            string token = GetMylistToken(source.Owner.Group);

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

            pair["group_id"]        = source.Owner.Group.Id;
            pair["target_group_id"] = dest.Group.Id;
            pair["id_list[0][]"]    = source.Entry.ItemId;
            pair["token"]           = token;


            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistMoveAPI);

            //とりあえずマイリストだったら
            if (source.Owner.Group.Id == "0")
            {
                request.RequestUri = new Uri(DefListMoveAPI);
            }

            request.Content = new FormUrlEncodedContent(pair);

            var text = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;

            //移動先がとりあえずマイリストだったら
            if (dest.Group.Id == "0")
            {
                AddDefMylist(source.Entry.Id, token);
            }
        }
コード例 #2
0
        //過去のニコレポを取得
        public IList <NicoNicoNicoRepoDataEntry> NextNicoRepo()
        {
            //もう過去の二コレポは存在しない
            if (NextUrl == null || NextUrl.Equals("end"))
            {
                return(null);
            }

            //ビヘイビア暴発
            if (PrevUrl == NextUrl)
            {
                return(null);
            }

            //APIと言うのか謎
            var api = PrevUrl = NextUrl;

            //html
            var html = NicoNicoWrapperMain.GetSession().GetAsync(api).Result;

            IList <NicoNicoNicoRepoDataEntry> data = new List <NicoNicoNicoRepoDataEntry>();

            //XPathでhtmlから抜き出す
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml2(html);

            StoreData(doc, data);

            return(data);
        }
コード例 #3
0
ファイル: NicoNicoVitaApi.cs プロジェクト: Velmy/SRNicoNico
        public static NicoNicoVitaApiVideoData GetVideoData(string cmsid)
        {
            string result = NicoNicoWrapperMain.GetSession().GetAsync(VideoDataApiUrl + cmsid).Result;

            var json     = DynamicJson.Parse(result);
            var response = json.nicovideo_video_response;

            var ret = new NicoNicoVitaApiVideoData();

            if (!response.video())
            {
                ret.Success = false;
                return(ret);
            }

            ret.Id             = response.video.id;
            ret.Title          = response.video.title;
            ret.FirstRetrieve  = NicoNicoUtil.DateFromVitaFormatDate(response.video.first_retrieve);
            ret.ViewCounter    = int.Parse(response.video.view_counter);
            ret.CommentCounter = int.Parse(response.thread.num_res);
            ret.MylistCounter  = int.Parse(response.video.mylist_counter);
            ret.Length         = NicoNicoUtil.ConvertTime(long.Parse(response.video.length_in_seconds));
            ret.Description    = response.video.description;
            ret.ThumbnailUrl   = response.video.thumbnail_url;
            return(ret);
        }
コード例 #4
0
        //ニコレポ取得
        public IList <NicoNicoNicoRepoDataEntry> GetNicoRepo()
        {
            //APIと言うのか謎
            var api = PrevUrl = @"http://www.nicovideo.jp/my/top/" + Id + @"?innerPage=1&mode=next_page";

            //html
            var html = NicoNicoWrapperMain.GetSession().GetAsync(api).Result;

            IList <NicoNicoNicoRepoDataEntry> data = new List <NicoNicoNicoRepoDataEntry>();

            //XPathでhtmlから抜き出す
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml2(html);

            //ニコレポが存在しなかったら存在しないというエントリを返す
            if (doc.DocumentNode.SelectSingleNode("/div[@class='nicorepo']/div[@class='nicorepo-page']/div").Attributes["class"].Value.Equals("empty"))
            {
                NicoNicoNicoRepoDataEntry entry = new NicoNicoNicoRepoDataEntry();

                entry.ImageUrl    = entry.IconUrl = null;
                entry.Description = "ニコレポが存在しません。";
                data.Add(entry);

                return(data);
            }

            StoreData(doc, data);

            return(data);
        }
コード例 #5
0
        //マイリストを削除
        public void DeleteMylist(IEnumerable <MylistListEntryViewModel> source)
        {
            string token = GetMylistToken(source.First().Owner.Group);

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

            pair["group_id"] = source.First().Owner.Group.Id;
            pair["token"]    = token;

            var encodedContent = new FormUrlEncodedContent(pair);

            var text = encodedContent.ReadAsStringAsync().Result;

            text += MakeIdList(source);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistDeleteAPI);

            if (source.First().Owner.Group.Id == "0")
            {
                request.RequestUri = new Uri(DefListDeleteAPI);
            }

            request.Content = new StringContent(text);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            var ret = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;
        }
コード例 #6
0
        public static NicoNicoVitaApiMylistData GetMylistData(string mylistId)
        {
            string detail = "0"; //より細かい1も存在
            string result = NicoNicoWrapperMain.GetSession().GetAsync(MylistDataApiUrl + detail + "&group_id=" + mylistId).Result;

            var json     = DynamicJson.Parse(result);
            var response = json.nicovideo_mylistgroup_response;

            NicoNicoVitaApiMylistData ret = new NicoNicoVitaApiMylistData();

            ret.Id                = response.mylistgroup.id;
            ret.UserId            = response.mylistgroup.user_id;
            ret.ViewCount         = response.mylistgroup.view_counter;
            ret.Name              = response.mylistgroup.name;
            ret.Description       = response.mylistgroup.description;
            ret.isPublic          = response.mylistgroup.@public == "1" ? true : false;
            ret.DefaultSort       = int.Parse(response.mylistgroup.default_sort);
            ret.DefaultSortMethod = response.mylistgroup.default_sort_method;
            ret.SortOrder         = int.Parse(response.mylistgroup.sort_order);
            ret.DefaultSortOrder  = response.mylistgroup.default_sort_order;
            ret.IconId            = response.mylistgroup.icon_id;
            ret.UpdateTime        = NicoNicoUtil.DateFromVitaFormatDate(response.mylistgroup.update_time);
            ret.CreateTime        = NicoNicoUtil.DateFromVitaFormatDate(response.mylistgroup.create_time);
            ret.Count             = int.Parse(response.mylistgroup.count);

            NicoNicoVitaApiUserData re = NicoNicoVitaUserApi.GetUserData(ret.UserId);

            ret.UserName = re.Name;

            return(ret);
        }
コード例 #7
0
        //とりあえずマイリストに登録
        public MylistResult AddDefMylist(string cmsid, string token)
        {
            Dictionary <string, string> pair = new Dictionary <string, string>();

            pair["item_id"] = cmsid;
            pair["token"]   = token;

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, DefListAddAPI);

            request.Content = new FormUrlEncodedContent(pair);

            var text = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;

            var json = DynamicJson.Parse(text);

            //エラー時
            if (json.error())
            {
                //もうすでに登録済み
                if (json.error.code == "EXIST")
                {
                    return(MylistResult.EXIST);
                }
            }
            if (json.status())
            {
                if (json.status == "ok")
                {
                    return(MylistResult.SUCCESS);
                }
            }
            //失敗
            return(MylistResult.FAILED);
        }
コード例 #8
0
        public string GetMylistToken()
        {
            var api = "http://www.nicovideo.jp/my/mylist";

            var result = NicoNicoWrapperMain.GetSession().GetAsync(api).Result;

            return(result.Substring(result.IndexOf("NicoAPI.token = \"") + 17, 60));
        }
コード例 #9
0
        //ユーザーIDからユーザーネームを取得する
        public static string LookupUserName(string userId)
        {
            string uri = UserLookUpURL + userId;

            string json = NicoNicoUtil.XmlToJson(NicoNicoWrapperMain.GetSession().GetAsync(uri).Result);

            return(DynamicJson.Parse(json).response.user.nickname);
        }
コード例 #10
0
        //ストーリーボードのデータを取得する
        private NicoNicoStoryBoardData GetStoryBoardInternalData()
        {
            var result = NicoNicoWrapperMain.GetSession().GetResponseAsync(StoryBoardApiBaseUrl + "&sb=1").Result;

            //見つからなかったり見せてもらえなかったりしたら
            if (result.StatusCode == HttpStatusCode.Forbidden || result.StatusCode == HttpStatusCode.NotFound || result.Content.Headers.ContentDisposition.FileName.Contains("smile"))
            {
                return(null);
            }

            byte[] response = result.Content.ReadAsByteArrayAsync().Result;

            string xml = new string(Encoding.ASCII.GetChars(response));

            xml = xml.Substring(39);
            string json = NicoNicoUtil.XmlToJson(xml);

            json = json.Replace("@", "");

            var root = DynamicJson.Parse(json);

            if (root.smile.storyboard.IsArray)
            {
                foreach (var entry in root.smile.storyboard)
                {
                    return(new NicoNicoStoryBoardData()
                    {
                        Id = entry.IsDefined("id") ? entry.id : 1,
                        Cols = int.Parse(entry.board_cols),
                        Rows = int.Parse(entry.board_rows),
                        Count = int.Parse(entry.board_number),
                        Width = int.Parse(entry.thumbnail_width),
                        Height = int.Parse(entry.thumbnail_height),
                        Interval = int.Parse(entry.thumbnail_interval),
                        Number = int.Parse(entry.thumbnail_number)
                    });
                }
            }
            else
            {
                var entry = root.smile.storyboard;

                return(new NicoNicoStoryBoardData()
                {
                    Id = entry.IsDefined("id") ? entry.id : "1",
                    Cols = int.Parse(entry.board_cols),
                    Rows = int.Parse(entry.board_rows),
                    Count = int.Parse(entry.board_number),
                    Width = int.Parse(entry.thumbnail_width),
                    Height = int.Parse(entry.thumbnail_height),
                    Interval = int.Parse(entry.thumbnail_interval),
                    Number = int.Parse(entry.thumbnail_number)
                });
            }

            return(null);
        }
コード例 #11
0
        //とりあえずマイリストを取得する
        public List <NicoNicoMylistData> GetDefMylist()
        {
            //とりあえずマイリスト
            var json = DynamicJson.Parse(NicoNicoWrapperMain.GetSession().GetAsync(DefListAPI).Result);

            List <NicoNicoMylistData> ret = new List <NicoNicoMylistData>();

            StoreItem(json, ret);

            return(ret);
        }
コード例 #12
0
        //指定したマイリストを削除
        public void DeleteMylistGroup(string groupId, string token)
        {
            Dictionary <string, string> pair = new Dictionary <string, string>();

            pair["group_id"] = groupId;
            pair["token"]    = token;

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistGroupDeleteAPI);

            request.Content = new FormUrlEncodedContent(pair);

            var text = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;
        }
コード例 #13
0
        //マイリストの情報を更新
        public void UpdateMylistGroup(NicoNicoMylistGroupData group, string token)
        {
            Dictionary <string, string> pair = new Dictionary <string, string>();

            pair["group_id"]     = group.Id;
            pair["name"]         = group.Name;
            pair["default_sort"] = "1";
            pair["description"]  = group.Description;
            pair["token"]        = token;

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistGroupUpdateAPI);

            request.Content = new FormUrlEncodedContent(pair);

            var text = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;
        }
コード例 #14
0
        //マイリストを作成
        public void CreateMylistGroup(string name, string desc, string token)
        {
            Dictionary <string, string> pair = new Dictionary <string, string>();

            pair["name"]         = name;
            pair["default_sort"] = "1";
            pair["description"]  = desc;
            pair["token"]        = token;


            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistGroupCreateAPI);

            request.Content = new FormUrlEncodedContent(pair);

            var text = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;
        }
コード例 #15
0
        public static NicoNicoVitaApiUserData GetUserData(string userId)
        {
            string result = NicoNicoWrapperMain.GetSession().GetAsync(UserDataApiUrl + userId).Result;

            var json     = DynamicJson.Parse(result);
            var response = json.nicovideo_user_response;

            NicoNicoVitaApiUserData ret = new NicoNicoVitaApiUserData();

            ret.Id         = response.user.id;
            ret.Name       = response.user.nickname;
            ret.IconUrl    = response.user.thumbnail_url;
            ret.UserSecret = int.Parse(response.vita_option.user_secret);

            return(ret);
        }
コード例 #16
0
        public List <NicoNicoCommentEntry> GetUploaderComment()
        {
            try {
                var list = new List <NicoNicoCommentEntry>();


                Video.CommentStatus = "投稿者コメント取得中";

                //---投稿者コメント取得---
                var root   = new XmlDocument();
                var packet = root.CreateElement("packet");
                var thread = root.CreateElement("thread");
                thread.SetAttribute("thread", GetFlv.ThreadID);
                thread.SetAttribute("version", "20090904");
                thread.SetAttribute("res_from", "-1000");
                thread.SetAttribute("fork", "1");

                packet.AppendChild(thread);
                root.AppendChild(packet);

                var request = new HttpRequestMessage(HttpMethod.Post, GetFlv.CommentServerUrl);
                request.Content = new StringContent(root.InnerXml);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");

                var a = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;

                var doc = new HtmlDocument();
                doc.LoadHtml2(a);

                StoreEntry(doc, list);
                //------

                if (list.Count == 0)
                {
                    Video.CommentStatus = "投稿者コメント取得失敗";
                    return(null);
                }
                list.Sort();

                Video.CommentStatus = "投稿者コメント取得完了";

                return(list);
            } catch (RequestTimeout) {
                Video.CommentStatus = "投稿者コメント取得失敗(タイムアウト)";
                return(null);
            }
        }
コード例 #17
0
        //マイリストを移動
        public void MoveMylist(IEnumerable <MylistListEntryViewModel> source, MylistListViewModel dest)
        {
            string token = GetMylistToken(source.First().Owner.Group);

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

            pair["group_id"]        = source.First().Owner.Group.Id;
            pair["target_group_id"] = dest.Group.Id;
            pair["token"]           = token;

            //id_list以外のペアを指定
            var encodedContent = new FormUrlEncodedContent(pair);

            //エンコードされたデータを取得
            var text = encodedContent.ReadAsStringAsync().Result;

            //id_listを付け足す
            text += MakeIdList(source);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistMoveAPI);

            //ソースがとりあえずマイリストだったら
            if (source.First().Owner.Group.Id == "0")
            {
                request.RequestUri = new Uri(DefListMoveAPI);
            }

            //データw指定
            request.Content = new StringContent(text);

            //コンテンツタイプを設定
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            //移動先がとりあえずマイリストだったら
            if (dest.Group.Id == "0")
            {
                foreach (MylistListEntryViewModel vm in source)
                {
                    AddDefMylist(vm.Entry.Id, token);
                }
            }
            else
            {
                var ret = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;
            }
        }
コード例 #18
0
        //指定したIDのマイリストを取得する
        public List <NicoNicoMylistData> GetMylist(string groupId)
        {
            //0なら"とりあえずマイリスト"を返す
            if (groupId == "0")
            {
                return(GetDefMylist());
            }

            //指定したマイリスト
            var json = DynamicJson.Parse(NicoNicoWrapperMain.GetSession().GetAsync(MylistGetAPI + groupId).Result);

            List <NicoNicoMylistData> ret = new List <NicoNicoMylistData>();

            StoreItem(json, ret);

            return(ret);
        }
コード例 #19
0
        //取得したストーリーボードのデータにBitmapオブジェクトを追加して返す
        public NicoNicoStoryBoardData GetStoryBoardData()
        {
            //エコノミーだったら
            if (StoryBoardApiBaseUrl.Contains("low"))
            {
                return(null);
            }

            NicoNicoStoryBoardData data = GetStoryBoardInternalData();

            //ストーリーボードが無かったら
            if (data == null)
            {
                return(null);
            }

            //APIURL
            string uri = StoryBoardApiBaseUrl + "&sb=" + data.Id + "&board=";


            int bitmapindex = 0;

            for (int i = 1; i <= data.Count; i++)
            {
                var response = NicoNicoWrapperMain.GetSession().GetStreamAsync(uri + i).Result;

                Bitmap bitmap = new Bitmap(response);

                for (int j = 0; j < data.Cols; j++)
                {
                    for (int k = 0; k < data.Rows; k++)
                    {
                        Rectangle rect = new Rectangle(data.Width * k, data.Height * j, data.Width, data.Height);

                        data.BitmapCollection[bitmapindex] = bitmap.Clone(rect, bitmap.PixelFormat);
                        bitmapindex += data.Interval;
                    }
                }
            }

            return(data);
        }
コード例 #20
0
        //マイリストをコピー
        public void CopyMylist(IEnumerable <MylistListEntryViewModel> source, MylistListViewModel dest)
        {
            string token = GetMylistToken(source.First().Owner.Group);

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

            pair["group_id"]        = source.First().Owner.Group.Id;
            pair["target_group_id"] = dest.Group.Id;
            pair["token"]           = token;

            //フォームエンコード済み文字列を取得
            var encodedContent = new FormUrlEncodedContent(pair);
            var text           = encodedContent.ReadAsStringAsync().Result;

            //IDリスト作成
            text += MakeIdList(source);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, MylistCopyAPI);

            if (source.First().Owner.Group.Id == "0")
            {
                request.RequestUri = new Uri(DefListCopyAPI);
            }

            request.Content = new StringContent(text);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");


            if (dest.Group.Id == "0")
            {
                foreach (MylistListEntryViewModel vm in source)
                {
                    AddDefMylist(vm.Entry.Id, token);
                }
            }
            else
            {
                var ret = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;
            }
        }
コード例 #21
0
        //ユーザー定義の二コレポリストを取得
        private List <NicoNicoNicoRepoListEntry> GetUserDefinitionNicoRepoList()
        {
            //htmlからCSRFトークンを抜き出す
            string html = NicoNicoWrapperMain.GetSession().GetAsync(NicoRepoWebUrl).Result;

            //CSRFトークン
            string token = html.Substring(html.IndexOf("Mypage_globals.hash = \"") + 23, 60);

            string response = NicoNicoWrapperMain.GetSession().GetAsync(NicoRepoListApiUrl + token).Result;

            Console.WriteLine(NicoRepoListApiUrl + token);
            var json = DynamicJson.Parse(response);


            List <NicoNicoNicoRepoListEntry> ret = new List <NicoNicoNicoRepoListEntry>();

            foreach (var entry in json.nicorepolists)
            {
                NicoNicoNicoRepoListEntry list = new NicoNicoNicoRepoListEntry(entry.title, entry.id);

                ret.Add(list);
            }
            return(ret);
        }
コード例 #22
0
        //コメント取得
        public List <NicoNicoCommentEntry> GetComment()
        {
            /**string threadKey = NicoNicoWrapperMain.GetSession().HttpClient.GetStringAsync(GetThreadKeyApiUrl + ThreadId).Result;
             *
             *          if(IsPremium) {
             *
             *                  string waybackKey = NicoNicoWrapperMain.GetSession().HttpClient.GetStringAsync(GetWayBackKeyApiUrl + ThreadId).Result;
             *          }*/

            Video.Status = "ユーザーコメント取得中";
            List <NicoNicoCommentEntry> list = new List <NicoNicoCommentEntry>();


            //---ユーザーコメント取得---
            //コメント取得APIに渡すGETパラメーター
            string leaves = "thread_leaves?thread=" + ThreadId + "&body=0-" + Length / 60 + 1 + ":100,1000&scores=1";

            try {
                HttpRequestMessage message  = new HttpRequestMessage(HttpMethod.Get, ServerUrl + leaves);
                string             response = NicoNicoWrapperMain.GetSession().GetAsync(message).Result;

                //thread_leavesが失敗したら(コメント数が少ないと失敗しやすいっぽい?)
                if (response.IndexOf("resultcode=\"11\"") >= 0)
                {
                    Video.Status = "ユーザーコメント取得失敗(リカバリー中)";

                    string recv = "thread?version=20090904&thread=" + ThreadId + "&res_from=-1000";
                    response = NicoNicoWrapperMain.GetSession().GetAsync(ServerUrl + recv).Result;
                }

                //公式動画
                if (response.IndexOf("resultcode=\"9\"") >= 0)
                {
                    Video.Status = "ユーザーコメント取得失敗(公式動画)リカバリー中";
                    string threadKey = NicoNicoWrapperMain.GetSession().GetAsync(GetThreadKeyApiUrl + ThreadId).Result;

                    string recv = leaves + "&" + threadKey + "&user_id=" + UserId;
                    response = NicoNicoWrapperMain.GetSession().GetAsync(ServerUrl + recv).Result;
                }
                StoreEntry(response, list);
                //------

                Video.Status = "投稿者コメント取得中";

                //---投稿者コメント取得---
                string thread      = "thread?version=20090904&thread=" + ThreadId + "&res_from=-1000&fork=1";
                string authComment = NicoNicoWrapperMain.GetSession().GetAsync(ServerUrl + thread).Result;

                StoreEntry(authComment, list);
                //------

                if (list.Count == 0)
                {
                    Video.Status = "コメント取得に失敗しました。";
                    return(null);
                }
                list.Sort();

                Video.Status = "コメント取得完了";

                return(list);
            } catch (AggregateException) {
                Video.Status = "コメント取得に失敗しました。(タイムアウト)";
                return(null);
            }
        }
コード例 #23
0
        //コメント取得
        public List <NicoNicoCommentEntry> GetComment()
        {
            Video.CommentStatus = "取得中";
            var list = new List <NicoNicoCommentEntry>();

            //---ユーザーコメント取得---
            var root   = new XmlDocument();
            var packet = root.CreateElement("packet");

            var thread = root.CreateElement("thread");

            thread.SetAttribute("thread", GetFlv.ThreadID);
            thread.SetAttribute("version", "20090904");
            thread.SetAttribute("user_id", GetFlv.UserId);
            thread.SetAttribute("userkey", GetFlv.UserKey);
            thread.SetAttribute("scores", "1");

            var leaves = root.CreateElement("thread_leaves");

            leaves.SetAttribute("thread", GetFlv.ThreadID);
            leaves.SetAttribute("user_id", GetFlv.UserId);
            leaves.SetAttribute("userkey", GetFlv.UserKey);
            leaves.SetAttribute("scores", "1");
            leaves.InnerText = "0-" + ((GetFlv.Length / 60) + 1) + ":100,1000";

            //公式動画だったらThreadkeyも取得する
            if (ApiData.IsOfficial)
            {
                try {
                    var query = new GetRequestQuery(GetThreadKeyApiUrl);
                    query.AddQuery("thread", GetFlv.ThreadID);
                    query.AddQuery("language_id", 0);

                    var threadKeyRaw = NicoNicoWrapperMain.Session.GetAsync(query.TargetUrl).Result;
                    var temp         = threadKeyRaw.Split('&');
                    var threadKey    = temp[0].Split('=')[1];
                    var force184     = temp[1].Split('=')[1];

                    thread.SetAttribute("threadkey", threadKey);
                    thread.SetAttribute("force_184", force184);
                    leaves.SetAttribute("threadkey", threadKey);
                    leaves.SetAttribute("force_184", force184);

                    thread.RemoveAttribute("userkey");
                    leaves.RemoveAttribute("userkey");
                } catch (RequestTimeout) {
                    Video.CommentStatus = "取得失敗";
                }
            }
            packet.AppendChild(thread);
            packet.AppendChild(leaves);
            root.AppendChild(packet);

            try {
                var request = new HttpRequestMessage(HttpMethod.Post, GetFlv.CommentServerUrl);
                request.Content = new StringContent(root.InnerXml);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");

                var a = NicoNicoWrapperMain.GetSession().GetAsync(request).Result;

                var doc = new HtmlDocument();
                doc.LoadHtml2(a);

                var resultcode = doc.DocumentNode.SelectSingleNode("/packet/thread").Attributes["resultcode"].Value;

                if (resultcode == "11")
                {
                    Video.Status = "取得失敗(復帰中)";

                    var recv = new GetRequestQuery(GetFlv.CommentServerUrl + "thread");
                    recv.AddQuery("version", "20090904");
                    recv.AddQuery("thread", GetFlv.ThreadID);
                    recv.AddQuery("res_from", "-1000");

                    a = NicoNicoWrapperMain.GetSession().GetAsync(recv.TargetUrl).Result;
                    doc.LoadHtml2(a);
                }

                StoreEntry(doc, list);
                //------

                if (list.Count == 0)
                {
                    Video.CommentStatus = "取得失敗";
                    return(null);
                }
                list.Sort();

                Ticket  = doc.DocumentNode.SelectSingleNode("packet/thread").Attributes["ticket"].Value;
                LastRes = int.Parse(doc.DocumentNode.SelectSingleNode("packet/thread").Attributes["last_res"].Value);

                Video.CommentStatus = "取得完了";

                return(list);
            } catch (RequestTimeout) {
                Video.CommentStatus = "取得失敗(タイムアウト)";
                return(null);
            }
        }
コード例 #24
0
ファイル: NicoNicoHistory.cs プロジェクト: Velmy/SRNicoNico
        //たまに失敗するから注意
        public List <NicoNicoHistoryData> GetHistroyData()
        {
            History.Status = "視聴履歴取得中";
            int retry = 1;

start:
            //たまに失敗する

            HttpResponseMessage result = NicoNicoWrapperMain.GetSession().GetResponseAsync(HistoryUrl).Result;

            //失敗
            if (result.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                History.Status = "視聴履歴取得失敗(" + retry++ + "回)";
                goto start;
            }

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml2(result.Content.ReadAsStringAsync().Result);

            var info = doc.DocumentNode.SelectNodes(GetVideoInfoXPath);

            List <NicoNicoHistoryData> ret = new List <NicoNicoHistoryData>();

            if (info == null)
            {
                History.Status = "視聴履歴はありません。";

                return(ret);
            }

            foreach (HtmlNode node in info)
            {
                NicoNicoHistoryData data = new NicoNicoHistoryData();

                //---各種情報取得---
                data.ThumbnailUrl = node.SelectSingleNode("child::div[@class='thumbContainer']/a/img").Attributes["src"].Value;

                //削除されていない動画だったら
                if (!data.ThumbnailUrl.Contains("deleted"))
                {
                    data.Length = node.SelectSingleNode("child::div[@class='thumbContainer']/span").InnerText;
                }
                else
                {
                    data.ThumbnailUrl = "http://www.nicovideo.jp/" + data.ThumbnailUrl;
                }
                data.WatchDate  = node.SelectSingleNode("child::div[@class='section']/p").ChildNodes["#text"].InnerText;
                data.WatchCount = node.SelectSingleNode("child::div[@class='section']/p/span").InnerText;

                data.Title = HttpUtility.HtmlDecode(node.SelectSingleNode("child::div[@class='section']/h5/a").InnerText);
                data.Id    = node.SelectSingleNode("child::div[@class='section']/h5/a").Attributes["href"].Value.Substring(6);

                data.ViewCounter    = node.SelectSingleNode("child::div[@class='section']/ul[@class='metadata']/li[@class='play']").InnerText;
                data.CommentCounter = node.SelectSingleNode("child::div[@class='section']/ul[@class='metadata']/li[@class='comment']").InnerText;
                data.MylistCounter  = node.SelectSingleNode("child::div[@class='section']/ul[@class='metadata']/li[@class='mylist']/a").InnerText;
                data.PostDate       = node.SelectSingleNode("child::div[@class='section']/ul[@class='metadata']/li[@class='posttime']").InnerText;


                ret.Add(data);
            }

            History.Status = "視聴履歴取得完了";

            return(ret);
        }
コード例 #25
0
        //リクエストのレスポンスを返す
        public NicoNicoSearchResult Search()
        {
            string typeString;  //表示文字列
            string type;        //クエリ文字列

            if (Type == SearchType.Keyword)
            {
                typeString = "テキスト";
                type       = "search";
            }
            else
            {
                typeString = "タグ";
                type       = "tag";
            }
            SearchVM.Status = "検索中(" + typeString + ":" + Keyword + ")";

            NicoNicoSearchResult result = new NicoNicoSearchResult();

            //テキスト検索のとき、urlの場合はそれも検索結果に表示する
            if (Type == SearchType.Keyword)
            {
                Match match = Regex.Match(Keyword, @"^(:?http://(:?www.nicovideo.jp/watch/|nico.ms/))?(?<cmsid>\w{0,2}\d+).*?$");
                if (match.Success)
                {
                    NicoNicoVitaApiVideoData data = NicoNicoVitaApi.GetVideoData(match.Groups["cmsid"].Value);
                    NicoNicoVideoInfoEntry   node = new NicoNicoVideoInfoEntry();
                    node.Cmsid          = data.Id;
                    node.Title          = HttpUtility.HtmlDecode(data.Title);
                    node.ViewCounter    = data.ViewCounter;
                    node.CommentCounter = data.CommentCounter;
                    node.MylistCounter  = data.MylistCounter;
                    node.ThumbnailUrl   = data.ThumbnailUrl;
                    node.Length         = data.Length;
                    node.FirstRetrieve  = data.FirstRetrieve.Replace('-', '/');

                    result.List.Add(node);

                    result.Total++;
                }
            }

            //URLに検索キーワードやその他いろいろをGETリクエストする
            string search = SearchURL + type + "/" + Keyword + "?mode=watch" + Sort + Order + "&page=" + CurrentPage++;

            string jsonString = NicoNicoWrapperMain.GetSession().GetAsync(search).Result;

            //取得したJsonの全体
            var json = DynamicJson.Parse(jsonString);

            //検索結果総数
            if (json.count())
            {
                result.Total += (ulong)json.count;
            }

            //Jsonからリストを取得、データを格納
            if (json.list())
            {
                foreach (var entry in json.list)
                {
                    NicoNicoVideoInfoEntry node = new NicoNicoVideoInfoEntry();

                    node.Cmsid          = entry.id;
                    node.Title          = entry.title_short;
                    node.ViewCounter    = (int)entry.view_counter;
                    node.CommentCounter = (int)entry.num_res;
                    node.MylistCounter  = (int)entry.mylist_counter;
                    node.ThumbnailUrl   = entry.thumbnail_url;
                    node.Length         = entry.length;
                    node.FirstRetrieve  = entry.first_retrieve;

                    result.List.Add(node);
                }
            }
            SearchVM.Status = "検索完了(" + typeString + ":" + Keyword + ")";


            return(result);
        }
コード例 #26
0
        //動画ページを指定
        public static WatchApiData GetWatchApiData(string videoPage)
        {
            //動画ページのhtml取得
            var response = NicoNicoWrapperMain.GetSession().GetResponseAsync(videoPage).Result;

            //チャンネル、公式動画
            if (response.StatusCode == HttpStatusCode.MovedPermanently)
            {
                response = NicoNicoWrapperMain.GetSession().GetResponseAsync(response.Headers.Location.OriginalString).Result;
            }
            //削除された動画
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }
            //混雑中
            if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                return(null);
            }

            string html = response.Content.ReadAsStringAsync().Result;

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml2(html);

            //htmlからAPIデータだけを綺麗に抜き出す すごい
            var container = doc.DocumentNode.QuerySelector("#watchAPIDataContainer");

            if (container == null)
            {
                return(null);
            }

            var data = container.InnerHtml;

            //html特殊文字をデコードする
            data = HttpUtility.HtmlDecode(data);

            //jsonとしてAPIデータを展開していく
            var json = DynamicJson.Parse(data);

            //GetFlvの結果
            string flv = json.flashvars.flvInfo;

            //2重にエンコードされてるので二回
            flv = HttpUtility.UrlDecode(flv);
            flv = HttpUtility.UrlDecode(flv);


            WatchApiData ret = new WatchApiData();

            //&で繋がれているので剥がす
            var getFlv = flv.Split(new char[] { '&' }).ToDictionary(source => source.Substring(0, source.IndexOf('=')),
                                                                    source => Uri.UnescapeDataString(source.Substring(source.IndexOf('=') + 1)));

            ret.GetFlv = new NicoNicoGetFlvData(getFlv);

            //動画情報
            var videoDetail = json.videoDetail;

            //---情報を詰める---
            ret.Cmsid          = videoDetail.id;
            ret.MovieType      = json.flashvars.movie_type;
            ret.Title          = HttpUtility.HtmlDecode(videoDetail.title); //html特殊文字をデコード
            ret.Thumbnail      = videoDetail.thumbnail;
            ret.Description    = videoDetail.description;
            ret.PostedAt       = videoDetail.postedAt;
            ret.Length         = (int)videoDetail.length;
            ret.ViewCounter    = (int)videoDetail.viewCount;
            ret.CommentCounter = (int)videoDetail.commentCount;
            ret.MylistCounter  = (int)videoDetail.mylistCount;
            ret.YesterdayRank  = videoDetail.yesterday_rank == null ? "圏外" : videoDetail.yesterday_rank + "位";
            ret.HighestRank    = videoDetail.highest_rank == null ? "圏外" : videoDetail.highest_rank + "位";
            ret.Token          = json.flashvars.csrfToken;

            if (json.uploaderInfo())
            {
                //投稿者情報
                var uploaderInfo = json.uploaderInfo;

                ret.UploaderId          = uploaderInfo.id;
                ret.UploaderIconUrl     = uploaderInfo.icon_url;
                ret.UploaderName        = uploaderInfo.nickname;
                ret.UploaderIsFavorited = uploaderInfo.is_favorited;
            }
            else if (json.channelInfo())
            {
                //投稿者情報
                var channelInfo = json.channelInfo;

                ret.UploaderId          = channelInfo.id;
                ret.UploaderIconUrl     = channelInfo.icon_url;
                ret.UploaderName        = channelInfo.name;
                ret.UploaderIsFavorited = channelInfo.is_favorited == 1 ? true : false;

                ret.IsChannelVideo = true;
            }


            ret.Description = HyperLinkParser.Parse(ret.Description);

            ret.TagList = new ObservableCollection <VideoTagViewModel>();

            foreach (var tag in videoDetail.tagList)
            {
                NicoNicoTag entry = new NicoNicoTag()
                {
                    Id  = tag.id,
                    Tag = tag.tag,
                    Dic = tag.dic(),
                    Lck = tag.lck == "1" ? true : false,
                    Cat = tag.cat()
                };
                ret.TagList.Add(new VideoTagViewModel(entry));
            }
            //------

            //有料動画
            if (ret.GetFlv.VideoUrl == null || ret.GetFlv.VideoUrl.Count() == 0)
            {
                ret.IsPaidVideo = true;
                return(ret);
            }

            //念のためCookieを設定
            var cookie = response.Headers.GetValues("Set-Cookie");

            foreach (string s in cookie)
            {
                foreach (string ss in s.Split(';'))
                {
                    App.SetCookie(new Uri("http://nicovideo.jp/"), ss);
                }
            }
            return(ret);
        }