Beispiel #1
0
        [TestCase(2560, 3)]   //メモリで動作
        public void DynamicTest(int block, int count)
        {
            var ws = new WebStream(-1);//limitを指定しないで-1でダイナミックに初期化する

            var dmy = new byte[block];

            for (var i = 0; i < block; i++)
            {
                dmy[i] = (byte)i;
            }
            for (var i = 0; i < count; i++)
            {
                ws.Add(dmy);
            }

            var buf = new byte[block];

            for (var i = 0; i < count; i++)
            {
                var len = ws.Read(buf, 0, buf.Length);
                Assert.AreEqual(len, block);
                Assert.AreEqual(buf[0], 0);
                Assert.AreEqual(buf[1], 1);
                Assert.AreEqual(buf[2], 2);
            }
            ws.Dispose();
        }
        private async Task <Config> GetStandardConfig(CrunchySession token, string epid, Quality qlty)
        {
            KeyValuePair <string, string> vf = QualityConvert(qlty);

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

            form.Add("req", "RpcApiVideoPlayer_GetStandardConfig");
            form.Add("media_id", epid);
            form.Add("video_format", vf.Value);
            form.Add("video_quality", vf.Key);
            form.Add("auto_play", "1");
            form.Add("show_pop_out_controls", "1");
            form.Add("current_page", "http://www.crunchyroll.com/");
            WebStream ws = await WebStream.Post("http://www.crunchyroll.com/xml/", form, null, LibSet[UserAgentS], null, token.cookies.ToCookieCollection(), SocketTimeout, true, "http://www.crunchyroll.com/swf/StandardVideoPlayer.swf", _info.ProxyFromGlobalRequirements(_global));

            string dta = null;

            if (ws != null && ws.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(ws);
                string       str    = reader.ReadToEnd();
                int          be     = str.IndexOf("<stream_info>", StringComparison.InvariantCulture);
                int          en     = str.IndexOf("</default:preload>", StringComparison.InvariantCulture);
                str = "<config>" + str.Substring(be, en - be) + "</config>";
                XmlSerializer ser = new XmlSerializer(typeof(Config));
                reader.Dispose();
                ws.Dispose();
                return((Config)ser.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(str))));
            }
            ws?.Dispose();
            return(null);
        }
Beispiel #3
0
        public void AddTest(int block, int count)
        {
            var max = block * count;
            var ws  = new WebStream(max);

            var dmy = new byte[block];

            for (var i = 0; i < block; i++)
            {
                dmy[i] = (byte)i;
            }
            for (var i = 0; i < count; i++)
            {
                ws.Add(dmy);
            }

            var buf = new byte[block];

            for (var i = 0; i < count; i++)
            {
                var len = ws.Read(buf, 0, buf.Length);
                Assert.AreEqual(len, block);
                Assert.AreEqual(buf[0], 0);
                Assert.AreEqual(buf[1], 1);
                Assert.AreEqual(buf[2], 2);
            }
            ws.Dispose();
        }
Beispiel #4
0
        public async Task DoNextFragment()
        {
            try

            {
                KeyValuePair <int, int>?v = bootstrap.GetNextRead();
                if (v == null)
                {
                    return;
                }
                string    url = string.Format(FormatFrag, baseurl, media.Url, v.Value.Key, v.Value.Value + 1, keydata, manifest.Pv20.Substring(1));
                WebStream ws  = await GetStream(url);

                if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                {
                    ws?.Dispose();
                    throw new IOException("Error " + ws.StatusCode + " trying to download fragment");
                }
                await ProcessFragment(ws, v.Value.Value);

                ws?.Dispose();
            }
            catch (Exception e)
            {
                int a = 1;
            }
        }
Beispiel #5
0
        /// <summary>
        /// Web上のストリームを返す
        /// </summary>
        /// <param name="url">URL</param>
        /// <returns>Web上のストリーム</returns>
        public static WebStream GetWebStream(Uri url)
        {
            WebStream ws = new WebStream(url);

            switch (PocketLadio.UserSetting.ProxyUse)
            {
            case UserSetting.ProxyConnect.Unuse:
                ws.ProxyUse = WebStream.ProxyConnect.Unuse;
                break;

            case UserSetting.ProxyConnect.OsSetting:
                ws.ProxyUse = WebStream.ProxyConnect.OsSetting;
                break;

            case UserSetting.ProxyConnect.OriginalSetting:
                ws.ProxyUse = WebStream.ProxyConnect.OriginalSetting;
                break;
            }
            ws.ProxyServer = PocketLadio.UserSetting.ProxyServer;
            ws.ProxyPort   = PocketLadio.UserSetting.ProxyPort;
            ws.TimeOut     = PocketLadioInfo.WebRequestTimeoutMillSec;
            ws.UserAgent   = PocketLadioInfo.UserAgent;
            ws.CreateWebStream();

            return(ws);
        }
Beispiel #6
0
        /// <summary>
        /// Save M3U8 stream
        /// </summary>
        /// <param name="uri">Uri to stream</param>
        /// <param name="outputPath">Output path</param>
        /// <param name="duration">Duration of stream</param>
        /// <returns>Conversion result</returns>
        public static IConversion SaveM3U8Stream(Uri uri, string outputPath, TimeSpan?duration = null)
        {
            var stream = new WebStream(uri, "M3U8", duration);

            return(New()
                   .AddStream(stream)
                   .SetOutput(outputPath));
        }
Beispiel #7
0
    public void Start()
    {
        texture = new Texture2D(2, 2);
        // create HTTP request

        instance = this;
        //StartCoroutine (GetFrame ());
    }
Beispiel #8
0
        /// <summary>
        /// Web上のストリームをダウンロードする
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="fileName">保存するファイル名</param>
        /// <param name="doDownloadProgressMinimum">ファイルサイズの最小値(0)をセットするデリゲート</param>
        /// <param name="doSetDownloadProgressMaximum">ファイルサイズをセットするデリゲート</param>
        /// <param name="doSetDownloadProgressValue">ダウンロード済みのファイルサイズをセットするデリゲート</param>
        public static void FetchFile(Uri url, string fileName,
                                     FetchEventHandler fetchEventHandler,
                                     FetchEventHandler fetchingEventHandler,
                                     FetchEventHandler fetchedEventHandler)
        {
            WebStream ws = null;

            try
            {
                ws = new WebStream(url);

                switch (PocketLadio.UserSetting.ProxyUse)
                {
                case UserSetting.ProxyConnect.Unuse:
                    ws.ProxyUse = WebStream.ProxyConnect.Unuse;
                    break;

                case UserSetting.ProxyConnect.OsSetting:
                    ws.ProxyUse = WebStream.ProxyConnect.OsSetting;
                    break;

                case UserSetting.ProxyConnect.OriginalSetting:
                    ws.ProxyUse = WebStream.ProxyConnect.OriginalSetting;
                    break;
                }
                ws.ProxyServer = PocketLadio.UserSetting.ProxyServer;
                ws.ProxyPort   = PocketLadio.UserSetting.ProxyPort;
                ws.TimeOut     = PocketLadioInfo.WebRequestTimeoutMillSec;
                ws.UserAgent   = PocketLadioInfo.UserAgent;
                ws.CreateWebStream();

                WebFileFetch fetch = new WebFileFetch(ws);
                if (fetchEventHandler != null)
                {
                    fetch.Fetch += fetchEventHandler;
                }
                if (fetchingEventHandler != null)
                {
                    fetch.Fetching += fetchingEventHandler;
                }
                if (fetchedEventHandler != null)
                {
                    fetch.Fetched += fetchedEventHandler;
                }

                fetch.FetchFile(fileName);
            }
            finally
            {
                if (ws != null)
                {
                    ws.Close();
                }
            }
        }
Beispiel #9
0
        internal async Task <FileSystemResult <T> > CreateMetadataStream <T>(string url, byte[] postdata = null, string contenttype = "application/x-www-form-urlencoded", HttpMethod method = null) where T : class
        {
            bool retry = false;

            do
            {
                if (method == null)
                {
                    method = HttpMethod.Get;
                }
                WebParameters pars = new WebParameters(new Uri(url));
                pars.Method = method;
                if (postdata != null)
                {
                    pars.PostData     = postdata;
                    pars.PostEncoding = contenttype;
                    if (method == null || method == HttpMethod.Get)
                    {
                        pars.Method = HttpMethod.Post;
                    }
                }
                if (UserAgent != null)
                {
                    pars.UserAgent = UserAgent;
                }

                if (Token != null)
                {
                    NameValueCollection nm = new NameValueCollection();
                    nm.Add("Authorization", "Bearer " + Token.AccessToken);
                    pars.Headers = nm;
                }
                using (WebStream w = await WebStreamFactory.Instance.CreateStreamAsync(pars))
                {
                    if ((w.StatusCode == HttpStatusCode.OK) || (w.StatusCode == HttpStatusCode.Created) || (w.StatusCode == HttpStatusCode.Accepted) || (w.StatusCode == HttpStatusCode.NoContent)) //TODO move this to a parameter
                    {
                        StreamReader rd = new StreamReader(w);
                        string       d  = await rd.ReadToEndAsync();

                        if (typeof(T).Name.Equals("string", StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(new FileSystemResult <T>((T)(object)d));
                        }
                        return(new FileSystemResult <T>(JsonConvert.DeserializeObject <T>(d)));
                    }
                    if (w.StatusCode != HttpStatusCode.Unauthorized || retry)
                    {
                        return(new FileSystemResult <T>("'url' responds with Http code: " + w.StatusCode));
                    }
                    retry = true;
                    await MayRefreshToken(true);
                }
            } while (true);
        }
        public async Task <ISession> Authenticate(Dictionary <string, object> authenticationmetadata)
        {
            CrunchySession session = new CrunchySession();

            try
            {
                Response r = await _info.VerifyBaseAuthentication(authenticationmetadata);

                if (r.Status != ResponseStatus.Ok)
                {
                    r.PropagateError(session);
                    return(session);
                }
                Dictionary <string, string> form = new Dictionary <string, string>();
                form.Add("formname", "RpcApiUser_Login");
                form.Add("fail_url", "http://www.crunchyroll.com/login");
                form.Add("name", authenticationmetadata.GetStringFromMetadata(DownloadPluginInfo.Username));
                form.Add("password", authenticationmetadata.GetStringFromMetadata(DownloadPluginInfo.Password));
                string    postdata = form.PostFromDictionary();
                WebStream ws       = await WebStream.Post("https://www.crunchyroll.com/?a=formhandler", form, null, LibSet[UserAgentS], null, null, SocketTimeout, false, null, _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.Found)
                {
                    ws.Cookies = await SetLocale(LocaleFromString(authenticationmetadata.GetStringFromMetadata(CrunchyPluginInfo.Language)), ws.Cookies);

                    if (!VerifyLogin(ws.Cookies))
                    {
                        session.Status       = ResponseStatus.InvalidLogin;
                        session.ErrorMessage = "Invalid Account Information";
                        session.cookies      = new Dictionary <string, string>();
                    }
                    else
                    {
                        session.cookies = ws.Cookies.ToDictionary();
                        session.Status  = ResponseStatus.Ok;
                    }
                }
                else
                {
                    SetWebError(session);
                }
                ws?.Dispose();
            }
            catch (Exception e)
            {
                session.Status       = ResponseStatus.SystemError;
                session.ErrorMessage = e.ToString();
            }
            return(session);
        }
        public async Task <ISession> Authenticate(Dictionary <string, object> authenticationmetadata)
        {
            _authmeta = authenticationmetadata;
            DaiSukiSession session = new DaiSukiSession();

            try
            {
                Response r = await _info.VerifyBaseAuthentication(authenticationmetadata);

                if (r.Status != ResponseStatus.Ok)
                {
                    r.PropagateError(session);
                    return(session);
                }
                Dictionary <string, string> form = new Dictionary <string, string>();
                form.Add("emailAddress", authenticationmetadata.GetStringFromMetadata(DownloadPluginInfo.Username));
                form.Add("password", authenticationmetadata.GetStringFromMetadata(DownloadPluginInfo.Password));
                form.Add("keepLogin", "on");



                WebStream ws = await WebStream.Post("https://www.daisuki.net/bin/SignInServlet.html/input", form, null, LibSet[UserAgentS], null, null, SocketTimeout, true, "http://www.daisuki.net/", _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        session.Status       = ResponseStatus.InvalidLogin;
                        session.ErrorMessage = "Invalid Account Information";
                        session.cookies      = new Dictionary <string, string>();
                    }
                    else
                    {
                        session.cookies = ws.Cookies.ToDictionary();
                        session.Status  = ResponseStatus.Ok;
                    }
                }
                else
                {
                    SetWebError(session);
                }
                ws?.Dispose();
            }
            catch (Exception e)
            {
                session.Status       = ResponseStatus.SystemError;
                session.ErrorMessage = e.ToString();
            }
            return(session);
        }
        private async Task <CookieCollection> SetLocale(string locale, CookieCollection cookies)
        {
            Dictionary <string, string> form = new Dictionary <string, string>();

            form.Add("req", "RpcApiTranslation_SetLang");
            form.Add("locale", "enUS");

            WebStream ws = await WebStream.Post("http://www.crunchyroll.com/ajax/", form, null, LibSet[UserAgentS], null, cookies, SocketTimeout, false, null, _info.ProxyFromGlobalRequirements(_global));

            if (ws != null && ws.StatusCode == HttpStatusCode.OK)
            {
                return(ws.Cookies);
            }
            return(new CookieCollection());
        }
Beispiel #13
0
        private async Task <bool> ErrorCallback(WebStream w, object p)
        {
            SeekableWebParameters swb = (SeekableWebParameters)p;

            if (w.StatusCode == HttpStatusCode.Unauthorized)
            {
                await MayRefreshToken(true);

                NameValueCollection nm = new NameValueCollection();
                nm.Add("Authorization", "Bearer " + Token.AccessToken);
                swb.Headers = nm;
                return(true);
            }
            return(false);
        }
    //////////////////////////////////////////////
    ///          Display Image                 ///
    //////////////////////////////////////////////
    public bool DisplayImage(byte[] RecievedImageByte, byte[] completeImageByte, string inputStream)
    {
        Buffer.BlockCopy(RecievedImageByte, inputStream.IndexOf("FFD8"), completeImageByte, 0, inputStream.Length / 2);
        Image = GameObject.Find("RawImage");       //We have to use GameObject.Find unless we instantiate the a prefab I'll add it later
        WebStream webStream     = Image.GetComponent <WebStream>();
        RawImage  screenDisplay = webStream.frame;

        JPEGsize = inputStream.Length / 2;
        camTexture.LoadImage(completeImageByte);
        Connected = true;
        //Debug.Log("inputStream length: " + count);   //length of bytes of the JPEG being loaded
        screenDisplay.color   = Color.white;
        screenDisplay.texture = camTexture;

        return(true);
    }
        public const string FFmpegLibraryPath_Linux   = @"/usr/bin";                             //linux location

        public static async Task <string> YoutubeAudioToMP3(string audioLink, string audioFormat, TimeSpan audioDuration, string filePath)
        {
            //Save file to the same location with changed extension
            string outputFilePath = Path.ChangeExtension(filePath, ".mp3");

            outputFilePath = MusicTagging.ReplaceInvalidChars(outputFilePath);         //replace any invalid chars in filePath with valid
            outputFilePath = MusicTagging.UpdateFileNameForDuplicates(outputFilePath); //add "copy" to filename if file exists


            //------------ Set library directory --------------
            MusicConverting.setFFMPEGPath();

            //----- Get youtube video audio stream -----------------
            IStream audioStream = new WebStream(new Uri(audioLink), audioFormat, audioDuration);

            //--- do the conversion ----------------
            await convertAudio(audioStream, outputFilePath);

            return(outputFilePath);
        }
Beispiel #16
0
        /// <summary>
        /// FriendTimelineを取得する
        /// </summary>
        /// <returns>取得したFriendTimelineのステータス情報</returns>
        public StatusInfomation[] FriendTimeline()
        {
            WebStream st = null;

            StatusInfomation[] statuses;

            try
            {
                st       = TwitterAwayUtility.GetWebStream(new Uri(TwitterAwayInfo.TwitterFriendsTimelineXml), userName, password);
                statuses = PaeseStatuses(st);
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
            }

            return(statuses);
        }
Beispiel #17
0
        /// <summary>
        /// PublicTimelineを取得する
        /// </summary>
        /// <returns>取得したPublicTimelineのステータス情報</returns>
        public StatusInfomation[] PublicTimeline()
        {
            WebStream st = null;

            StatusInfomation[] statuses;

            try
            {
                st       = TwitterAwayUtility.GetWebStream(new Uri(TwitterAwayInfo.TwitterPublicTimelineXml));
                statuses = PaeseStatuses(st);
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
            }

            return(statuses);
        }
Beispiel #18
0
        /// <summary>
        /// Web上のストリームを返す
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="requestMethod">HTTPリクエストメソッド</param>
        /// <param name="userName">Web認証のユーザー名</param>
        /// <param name="password">Web認証のパスワード</param>
        /// <returns>Web上のストリーム</returns>
        public static WebStream GetWebStream(Uri url, string requestMethod, string userName, string password)
        {
            WebStream ws;

            if (userName != null && userName != string.Empty)
            {
                ws = new WebStream(url, userName, password);
            }
            else
            {
                ws = new WebStream(url);
            }

            if (requestMethod != null && requestMethod != string.Empty)
            {
                ws.Method = requestMethod;
            }

            if (TwitterAway.UserSetting.ProxyUse == UserSetting.ProxyConnects.Unuse)
            {
                ws.ProxyUse = WebStream.ProxyConnect.Unuse;
            }
            else if (TwitterAway.UserSetting.ProxyUse == UserSetting.ProxyConnects.OsSetting)
            {
                ws.ProxyUse = WebStream.ProxyConnect.OsSetting;
            }
            else if (TwitterAway.UserSetting.ProxyUse == UserSetting.ProxyConnects.OriginalSetting)
            {
                ws.ProxyUse = WebStream.ProxyConnect.OriginalSetting;
            }
            ws.ProxyServer = TwitterAway.UserSetting.ProxyServer;
            ws.ProxyPort   = TwitterAway.UserSetting.ProxyPort;
            ws.TimeOut     = TwitterAwayInfo.WebRequestTimeoutMillSec;
            ws.UserAgent   = TwitterAwayInfo.UserAgent;
            ws.AddHeader("X-Twitter-Client", TwitterAwayInfo.ApplicationName);
            ws.AddHeader("X-Twitter-Client-Version", TwitterAwayInfo.VersionNumber);
            ws.CreateWebStream();

            return(ws);
        }
Beispiel #19
0
        [TestCase(256, 1)]     //1で1Mbyte
        //[TestCase(1000000, 2000)] //1で1Mbyte 自作cat.exeでは200MByteまでしか対応できない
        public void StartTest(int block, int count)
        {
            var srcDir = string.Format("{0}\\WebServerTest", TestUtil.ProjectDirectory());

            //こちらの自作cat.exeでは、200Mbyteまでしか対応できていない
            var execProcess = new ExecProcess(string.Format("{0}\\cat.exe", srcDir), "", srcDir, null);

            var buf = new byte[block];

            for (var b = 0; b < block; b++)
            {
                buf[b] = (byte)b;
            }
            var inputStream = new WebStream(block * count);

            for (var i = 0; i < count; i++)
            {
                inputStream.Add(buf);
            }
            WebStream outputStream;

            execProcess.Start(inputStream, out outputStream);

            for (var i = 0; i < count; i++)
            {
                var len = outputStream.Read(buf, 0, buf.Length);
                Assert.AreEqual(len, block);
                if (i == 0)
                {
                    Assert.AreEqual(buf[0], 0);
                    Assert.AreEqual(buf[1], 1);
                    Assert.AreEqual(buf[2], 2);
                }
            }

            outputStream.Dispose();
            inputStream.Dispose();
        }
        private async Task <CrunchySubtitleInfo> GetSubtitle(CrunchySession token, int subid)
        {
            Dictionary <string, string> form = new Dictionary <string, string>();

            form.Add("req", "RpcApiSubtitle_GetXml");
            form.Add("subtitle_script_id", subid.ToString());
            WebStream ws = await WebStream.Post("http://www.crunchyroll.com/xml/", form, null, LibSet[UserAgentS], null, token.cookies.ToCookieCollection(), SocketTimeout, true, "http://www.crunchyroll.com/swf/StandardVideoPlayer.swf", _info.ProxyFromGlobalRequirements(_global));

            string dta = null;

            if (ws.StatusCode == HttpStatusCode.OK)
            {
                XmlSerializer       ser = new XmlSerializer(typeof(Subtitle));
                Subtitle            s   = (Subtitle)ser.Deserialize(ws);
                CrunchySubtitleInfo si  = new CrunchySubtitleInfo();
                DecodeSubtitle(int.Parse(s.Id), s.Iv, s.Data, ref si);
                si.Language = ADBaseLibrary.Subtitles.Languages.CodeFromOriginalLanguage(si.Title);
                ws.Dispose();
                return(si);
            }
            ws?.Dispose();
            return(null);
        }
Beispiel #21
0
        private async Task <WebStream> GetStream(string url)
        {
            int cnt = 0;

            do
            {
                WebStream ws = await WebStream.Get(url, null, uagent, headers, cookies, timeout, true, referer, proxy);

                if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                {
                    ws?.Dispose();
                    cnt++;
                    if (cnt == retries)
                    {
                        return(ws);
                    }
                }
                else
                {
                    return(ws);
                }
            } while (true);
        }
Beispiel #22
0
        /// <summary>
        /// メッセージをUpdateする
        /// </summary>
        /// <param name="message">メッセージ</param>
        public void Update(string message)
        {
            string sendMessage = string.Empty;

            // 送信メッセージをUTF-8化してバイト列に入れる
            byte[] messageBytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, Encoding.Unicode.GetBytes(message));

            // URLエンコード
            foreach (byte b in messageBytes)
            {
                sendMessage += "%" + b.ToString("X2");
            }

            WebStream st = null;

            try
            {
                string send = TwitterAwayInfo.TwitterUpdateXml + "?status=" + sendMessage;
                st = TwitterAwayUtility.GetWebStream(new Uri(send), "POST", userName, password);
            }
            catch (WebException)
            {
                throw;
            }
            catch (UriFormatException)
            {
                throw;
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// ヘッドラインをネットから取得する
        /// </summary>
        public virtual void FetchHeadline()
        {
            if (setting.RssUrl == null)
            {
                return;
            }

            // 時刻をセットする
            lastCheckTime = DateTime.Now;

            WebStream     st     = null;
            XmlTextReader reader = null;

            try
            {
                // 番組のリスト
                ArrayList alChannels = new ArrayList();

                // チャンネル
                Channel channel = null;
                // itemタグの中にいるか
                bool inItemFlag = false;

                // Enclosureの一時リスト
                ArrayList alTempEnclosure = new ArrayList();

                st = PocketLadioUtility.GetWebStream(setting.RssUrl);

                reader = new XmlTextReader(st);

                // 解析したヘッドラインの個数
                int analyzedCount = 0;

                OnHeadlineAnalyze(new HeadlineAnalyzeEventArgs(0, HeadlineAnalyzeEventArgs.UNKNOWN_WHOLE_COUNT));

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.LocalName == "item")
                        {
                            inItemFlag = true;
                            channel    = new Channel(this);
                        } // End of item
                        // itemタグの中にいる場合
                        else if (inItemFlag == true)
                        {
                            if (reader.LocalName == "title")
                            {
                                channel.Title = reader.ReadString();
                            } // End of title
                            else if (reader.LocalName == "description")
                            {
                                channel.Description = reader.ReadString();
                            } // End of description
                            else if (reader.LocalName == "link")
                            {
                                try
                                {
                                    channel.Link = new Uri(reader.ReadString());
                                }
                                catch (UriFormatException)
                                {
                                    ;
                                }
                            } // End of link
                            else if (reader.LocalName == "pubDate")
                            {
                                channel.SetDate(reader.ReadString());
                            } // End of pubDate
                            else if (reader.LocalName == "category")
                            {
                                channel.Category = reader.ReadString();
                            } // End of category
                            else if (reader.LocalName == "author")
                            {
                                channel.Author = reader.ReadString();
                            } // End of author
                            else if (reader.LocalName == "guid")
                            {
                                try
                                {
                                    channel.Link = new Uri(reader.ReadString());
                                }
                                catch (UriFormatException)
                                {
                                    ;
                                }
                            } // End of guid
                            else if (reader.LocalName == "enclosure")
                            {
                                Uri    enclosureUrl    = null;
                                string enclosureLength = string.Empty;
                                string enclosureType   = string.Empty;

                                try
                                {
                                    if (reader.MoveToFirstAttribute())
                                    {
                                        enclosureUrl    = new Uri(reader.GetAttribute("url"));
                                        enclosureLength = reader.GetAttribute("length");
                                        enclosureType   = reader.GetAttribute("type");
                                    }

                                    if (enclosureLength == null)
                                    {
                                        enclosureLength = string.Empty;
                                    }
                                    if (enclosureType == null)
                                    {
                                        enclosureType = string.Empty;
                                    }

                                    // Enclosureタグの数だけ、 Enclosure一時リストにEnclosureの内容を追加していく
                                    Enclosure enclosure = new Enclosure(enclosureUrl, enclosureLength, enclosureType);
                                    if (enclosure.IsPodcast() == true)
                                    {
                                        alTempEnclosure.Add(enclosure);
                                    }
                                }
                                catch (UriFormatException)
                                {
                                    ;
                                }
                            } // End of enclosure
                        }     // End of itemタグの中にいる場合
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        if (reader.LocalName == "item")
                        {
                            inItemFlag = false;
                            // Enclosureの要素の数だけ、Channelの複製を作る
                            if (alTempEnclosure.Count != 0)
                            {
                                foreach (Enclosure enclosure in alTempEnclosure)
                                {
                                    Channel clonedChannel = (Channel)channel.Clone(this);
                                    clonedChannel.Url    = enclosure.Url;
                                    clonedChannel.Length = enclosure.Length;
                                    clonedChannel.Type   = enclosure.Type;
                                    alChannels.Add(clonedChannel);
                                    OnHeadlineAnalyzing(new HeadlineAnalyzeEventArgs(++analyzedCount, HeadlineAnalyzeEventArgs.UNKNOWN_WHOLE_COUNT));
                                }
                            }

                            // Enclosure一時リストをクリア
                            alTempEnclosure.Clear();
                        }
                    }
                }

                OnHeadlineAnalyzed(new HeadlineAnalyzeEventArgs(analyzedCount, analyzedCount));

                channels = (Channel[])alChannels.ToArray(typeof(Channel));
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Beispiel #24
0
        public static async Task <Response> VerifyGlobalRequirements(this DownloadPluginInfo pinfo, Dictionary <string, object> globalmetadata)
        {
            Response r = VerifyRequiredKeys(globalmetadata, pinfo.GlobalRequirements);

            if (r.Status != ResponseStatus.Ok)
            {
                return(r);
            }
            if (VerifyRequirementsList(pinfo.GlobalRequirements, DownloadPluginInfo.ProxyEnabled, DownloadPluginInfo.ProxyAddress, DownloadPluginInfo.ProxyPort, DownloadPluginInfo.ProxyUsername, DownloadPluginInfo.ProxyPassword))
            {
                bool?enabled = globalmetadata.GetBoolFromMetadata(DownloadPluginInfo.ProxyEnabled);
                if (enabled.HasValue && enabled.Value)
                {
                    string address = globalmetadata.GetStringFromMetadata(DownloadPluginInfo.ProxyAddress);

                    if (string.IsNullOrEmpty(address))
                    {
                        return new Response {
                                   ErrorMessage = "'" + DownloadPluginInfo.ProxyAddress + "' is invalid", Status = ResponseStatus.MissingRequirement
                        }
                    }
                    ;
                    int?port = globalmetadata.GetIntFromMetadata(DownloadPluginInfo.ProxyPort);
                    if (!port.HasValue)
                    {
                        return new Response {
                                   ErrorMessage = "'" + DownloadPluginInfo.ProxyPort + "' is invalid", Status = ResponseStatus.MissingRequirement
                        }
                    }
                    ;
                    if (port.Value < 1 || port.Value > 65534)
                    {
                        return new Response {
                                   ErrorMessage = "'" + DownloadPluginInfo.ProxyPort + "' is invalid", Status = ResponseStatus.InvalidArgument
                        }
                    }
                    ;
                    IpInfo    ipnfo = null;
                    IWebProxy proxy = pinfo.ProxyFromGlobalRequirements(globalmetadata);
                    if (proxy == null)
                    {
                        return new Response {
                                   ErrorMessage = "Unable to create proxy", Status = ResponseStatus.InvalidArgument
                        }
                    }
                    ;
                    WebStream s = await WebStream.Get("http://ipinfo.io/json", null, null, null, null, 10000, false, null, proxy);

                    if (s != null && s.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader reader = new StreamReader(s, Encoding.UTF8);

                        string json = reader.ReadToEnd();
                        ipnfo = JsonConvert.DeserializeObject <IpInfo>(json);
                        reader.Dispose();
                    }
                    s?.Dispose();
                    if ((s == null) || (s.StatusCode != HttpStatusCode.OK))
                    {
                        return new Response {
                                   ErrorMessage = "Unable to Connect", Status = ResponseStatus.InvalidArgument
                        }
                    }
                    ;
                    r.ErrorMessage = "IP: " + ipnfo.ip + " " + ipnfo.city + "/" + ipnfo.country;
                }
            }
            return(r);
        }
Beispiel #25
0
        /// <summary>
        /// ヘッドラインをネットから取得する(XML使用)
        /// </summary>
        private void FetchHeadlineXml()
        {
            WebStream     st     = null;
            XmlTextReader reader = null;

            try
            {
                // 番組のリスト
                ArrayList alChannels = new ArrayList();

                st = PocketLadioUtility.GetWebStream(setting.HeadlineXmlUrl);

                reader = new XmlTextReader(st);

                // チャンネル
                Channel channel = new Channel(this);
                // sourceタグの中にいるか
                bool inSourceFlag = false;

                // 解析したヘッドラインの個数
                int analyzedCount = 0;

                OnHeadlineAnalyze(new HeadlineAnalyzeEventArgs(0, HeadlineAnalyzeEventArgs.UNKNOWN_WHOLE_COUNT));

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.LocalName == "source")
                        {
                            inSourceFlag = true;
                            channel      = new Channel(this);
                        } // End of source
                        // sourceタグの中にいる場合
                        else if (inSourceFlag == true)
                        {
                            if (reader.LocalName == "url")
                            {
                                try
                                {
                                    string url = reader.ReadString();
                                    if (url != string.Empty)
                                    {
                                        channel.Url = new Uri(url);
                                    }
                                }
                                catch (UriFormatException)
                                {
                                    ;
                                }
                            } // End of url
                            else if (reader.LocalName == "gnl")
                            {
                                channel.Gnl = reader.ReadString();
                            } // End of gnl
                            else if (reader.LocalName == "nam")
                            {
                                channel.Nam = reader.ReadString();
                            } // End of nam
                            else if (reader.LocalName == "tit")
                            {
                                channel.Tit = reader.ReadString();
                            } // End of tit
                            else if (reader.LocalName == "mnt")
                            {
                                channel.Mnt = reader.ReadString();
                            } // End of mnt
                            else if (reader.LocalName == "tim")
                            {
                                channel.SetTim(reader.ReadString());
                            } // End of tim
                            else if (reader.LocalName == "tims")
                            {
                                channel.SetTims(reader.ReadString());
                            } // End of tims
                            else if (reader.LocalName == "cln")
                            {
                                try
                                {
                                    channel.Cln = int.Parse(reader.ReadString());
                                }
                                catch (ArgumentException)
                                {
                                    ;
                                }
                                catch (FormatException)
                                {
                                    ;
                                }
                                catch (OverflowException)
                                {
                                    ;
                                }
                            } // End of cln
                            else if (reader.LocalName == "clns")
                            {
                                try
                                {
                                    channel.Clns = int.Parse(reader.ReadString());
                                }
                                catch (ArgumentException)
                                {
                                    ;
                                }
                                catch (FormatException)
                                {
                                    ;
                                }
                                catch (OverflowException)
                                {
                                    ;
                                }
                            } // End of clns
                            else if (reader.LocalName == "srv")
                            {
                                channel.Srv = reader.ReadString();
                            } // End of srv
                            else if (reader.LocalName == "prt")
                            {
                                channel.Prt = reader.ReadString();
                            } // End of prt
                            else if (reader.LocalName == "typ")
                            {
                                channel.Typ = reader.ReadString();
                            } // End of typ
                            else if (reader.LocalName == "bit")
                            {
                                try
                                {
                                    channel.Bit = int.Parse(reader.ReadString());
                                }
                                catch (ArgumentException)
                                {
                                    ;
                                }
                                catch (FormatException)
                                {
                                    ;
                                }
                                catch (OverflowException)
                                {
                                    ;
                                }
                            } // End of bit
                        }     // End of sourceタグの中にいる場合
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        if (reader.LocalName == "source")
                        {
                            inSourceFlag = false;
                            alChannels.Add(channel);
                            OnHeadlineAnalyzing(new HeadlineAnalyzeEventArgs(++analyzedCount, HeadlineAnalyzeEventArgs.UNKNOWN_WHOLE_COUNT));
                        }
                    }
                }

                OnHeadlineAnalyzed(new HeadlineAnalyzeEventArgs(analyzedCount, analyzedCount));

                channels = (Channel[])alChannels.ToArray(typeof(Channel));
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Beispiel #26
0
        /// <summary>
        /// ヘッドラインをネットから取得する(DAT v2使用)
        /// </summary>
        private void FetchHeadlineDatV2()
        {
            WebStream st = null;

            string[] channelsDat;
            // チャンネルのリスト
            ArrayList alChannels = new ArrayList();

            try
            {
                st = PocketLadioUtility.GetWebStream(setting.HeadlineDatV2Url);
                WebTextFetch fetch = new WebTextFetch(st, Encoding.GetEncoding("shift-jis"));
                if (HeadlineFetch != null)
                {
                    fetch.Fetch += HeadlineFetch;
                }
                if (HeadlineFetching != null)
                {
                    fetch.Fetching += HeadlineFetching;
                }
                if (HeadlineFetched != null)
                {
                    fetch.Fetched += HeadlineFetched;
                }
                string httpString = fetch.ReadToEnd();
                channelsDat = httpString.Split('\n');
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
            }

            // 番組の総数を数える
            int channelLength = 0;

            for (int i = 0; i < channelsDat.Length; ++i)
            {
                // 空行の場合
                if (channelsDat[i] == string.Empty)
                {
                    ++channelLength;
                }
            }

            OnHeadlineAnalyze(new HeadlineAnalyzeEventArgs(0, channelLength));

            Channel channel = null;
            // 解析済みの番組数
            int channelAnalyzed = 0;

            for (int count = 0; count < channelsDat.Length; ++count)
            {
                // Url取得
                Match urlMatch = urlRegex.Match(channelsDat[count]);
                if (urlMatch.Success)
                {
                    try
                    {
                        if (urlMatch.Groups[1].Value != string.Empty)
                        {
                            if (channel == null)
                            {
                                channel = new Channel(this);
                            }
                            channel.Url = new Uri(urlMatch.Groups[1].Value);
                        }
                    }
                    catch (UriFormatException)
                    {
                        ;
                    }

                    continue;
                }

                // Gnl取得
                Match gnlMatch = gnlRegex.Match(channelsDat[count]);
                if (gnlMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    channel.Gnl = gnlMatch.Groups[1].Value;

                    continue;
                }

                Match namMatch = namRegex.Match(channelsDat[count]);
                if (namMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    channel.Nam = namMatch.Groups[1].Value;

                    continue;
                }

                Match mntMatch = mntRegex.Match(channelsDat[count]);
                if (mntMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    channel.Mnt = mntMatch.Groups[1].Value;

                    continue;
                }

                Match timsMatch = timsRegex.Match(channelsDat[count]);
                if (timsMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    channel.SetTims(timsMatch.Groups[1].Value);

                    continue;
                }

                // Cln取得
                Match clnMatch = clnRegex.Match(channelsDat[count]);
                if (clnMatch.Success)
                {
                    try
                    {
                        if (channel == null)
                        {
                            channel = new Channel(this);
                        }

                        channel.Cln = int.Parse(clnMatch.Groups[1].Value);
                    }
                    catch (ArgumentException)
                    {
                        ;
                    }
                    catch (FormatException)
                    {
                        ;
                    }
                    catch (OverflowException)
                    {
                        ;
                    }

                    continue;
                }

                // Clns取得
                Match clnsMatch = clnsRegex.Match(channelsDat[count]);
                if (clnsMatch.Success)
                {
                    try
                    {
                        if (channel == null)
                        {
                            channel = new Channel(this);
                        }

                        channel.Clns = int.Parse(clnsMatch.Groups[1].Value);
                    }
                    catch (ArgumentException)
                    {
                        ;
                    }
                    catch (FormatException)
                    {
                        ;
                    }
                    catch (OverflowException)
                    {
                        ;
                    }

                    continue;
                }

                Match maxMatch = maxRegex.Match(channelsDat[count]);
                if (maxMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    continue;
                }

                Match srvMatch = srvRegex.Match(channelsDat[count]);
                if (srvMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    channel.Srv = srvMatch.Groups[1].Value;

                    continue;
                }

                Match prtMatch = prtRegex.Match(channelsDat[count]);
                if (prtMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    channel.Prt = prtMatch.Groups[1].Value;

                    continue;
                }

                Match bitMatch = bitRegex.Match(channelsDat[count]);
                if (bitMatch.Success)
                {
                    try
                    {
                        if (channel == null)
                        {
                            channel = new Channel(this);
                        }

                        channel.Bit = int.Parse(bitMatch.Groups[1].Value);
                    }
                    catch (ArgumentException)
                    {
                        ;
                    }
                    catch (FormatException)
                    {
                        ;
                    }
                    catch (OverflowException)
                    {
                        ;
                    }

                    continue;
                }

                Match songMatch = songRegex.Match(channelsDat[count]);
                if (prtMatch.Success)
                {
                    if (channel == null)
                    {
                        channel = new Channel(this);
                    }

                    channel.Tit = songMatch.Groups[1].Value;

                    continue;
                }

                if (channelsDat[count] == string.Empty)
                {
                    if (channel != null)
                    {
                        alChannels.Add(channel);
                        OnHeadlineAnalyzing(new HeadlineAnalyzeEventArgs(++channelAnalyzed, channelLength));
                        channel = null;
                    }
                }
            }

            OnHeadlineAnalyzed(new HeadlineAnalyzeEventArgs(channelLength, channelLength));

            channels = (Channel[])alChannels.ToArray(typeof(Channel));
        }
        public async Task <Episodes> Episodes(ISession session, Show show)
        {
            try
            {
                DaiSukiSession s = session as DaiSukiSession;
                if (s == null)
                {
                    return new Episodes {
                               ErrorMessage = "Invalid Session", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                if (!show.PluginMetadata.ContainsKey("Url"))
                {
                    return new Episodes {
                               ErrorMessage = "Invalid Show", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                Episodes ret = new Episodes();
                ret.Items = new List <Episode>();

                WebStream ws = await WebStream.Get(show.PluginMetadata["Url"], null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, null, _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        SetLoginError(ret);
                    }
                    else
                    {
                        StreamReader rd  = new StreamReader(ws);
                        string       dta = rd.ReadToEnd();
                        rd.Dispose();
                        ret.Status   = ResponseStatus.Ok;
                        ret.Items    = new List <Episode>();
                        ret.ImageUri = new Uri(LibSet[ImageServerS] + "/img/series/" + show.Id + "/340_506.jpg");
                        Match sm = showregex.Match(dta);
                        if (sm.Success)
                        {
                            ret.Items.Add(GetEpisode(show, sm));
                        }
                        MatchCollection scol = show2regex.Matches(dta);
                        foreach (Match sma in scol)
                        {
                            if (sma.Success)
                            {
                                ret.Items.Add(GetEpisode(show, sma));
                            }
                        }
                        ret.Items = ret.Items.OrderBy(a => a.EpisodeNumeric).ToList();
                        for (int x = 0; x < ret.Items.Count; x++)
                        {
                            ret.Items[x].Index = x + 1;
                        }
                    }
                }
                else
                {
                    SetWebError(ret);
                }
                ws?.Dispose();
                return(ret);
            }
            catch (Exception e)
            {
                return(new Episodes {
                    ErrorMessage = e.ToString(), Status = ResponseStatus.SystemError
                });
            }
        }
        public async Task <Response> Download(ISession session, Episode episode, string template, string downloadpath, Quality quality, Format formats,
                                              CancellationToken token, IProgress <DownloadInfo> progress)
        {
            try
            {
                string         deflangcode = "jpn";
                string         deflang     = "日本語";
                Response       ret         = new Response();
                DaiSukiSession s           = session as DaiSukiSession;
                if (s == null)
                {
                    return new Response {
                               ErrorMessage = "Invalid Session", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                if (!episode.PluginMetadata.ContainsKey("Url"))
                {
                    return new Response {
                               ErrorMessage = "Invalid Episode", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                DownloadInfo dp = new DownloadInfo {
                    FileName = TemplateParser.FilenameFromEpisode(episode, quality, template), Format = formats, Percent = 0, Quality = quality
                };
                token.ThrowIfCancellationRequested();
                dp.Languages = new List <string>();
                dp.Percent   = 1;
                dp.Status    = "Getting Metadata";
                progress.Report(dp);
                List <string> todeleteFiles = new List <string>();

                WebStream ws = await WebStream.Get(episode.PluginMetadata["Url"], null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, null, _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        SetLoginError(ret);
                    }
                    else
                    {
                        StreamReader rd  = new StreamReader(ws);
                        string       dta = rd.ReadToEnd();
                        rd.Dispose();
                        ws.Dispose();
                        Match bgn = bgnWrapper.Match(dta);
                        if (!bgn.Success)
                        {
                            ret.ErrorMessage = "Unable to find Daisuki public key";
                            ret.Status       = ResponseStatus.WebError;
                            return(ret);
                        }
                        Match flash = flashVars.Match(dta);
                        if (!flash.Success)
                        {
                            ret.ErrorMessage = "Seems this Episode is a YouTube video, unable to download";
                            ret.Status       = ResponseStatus.WebError;
                            return(ret);
                        }
                        MatchCollection             col  = flash2Vars.Matches(flash.Groups["vars"].Value);
                        Dictionary <string, string> vars = new Dictionary <string, string>();
                        foreach (Match m in col)
                        {
                            if (m.Success)
                            {
                                vars.Add(m.Groups["name"].Value, m.Groups["value"].Value);
                            }
                        }
                        if (!vars.ContainsKey("s") || !vars.ContainsKey("country") || !vars.ContainsKey("init"))
                        {
                            ret.ErrorMessage = "Some of Daisuki startup variables are missing";
                            ret.Status       = ResponseStatus.WebError;
                            return(ret);
                        }
                        token.ThrowIfCancellationRequested();
                        ws = await WebStream.Get(LibSet[BaseHostS] + bgn.Groups["wrapper"].Value, null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, null, _info.ProxyFromGlobalRequirements(_global));

                        if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                        {
                            ret.ErrorMessage = "Unable to find Daisuki public key";
                            ret.Status       = ResponseStatus.WebError;
                            ws?.Dispose();
                            return(ret);
                        }
                        rd  = new StreamReader(ws);
                        dta = rd.ReadToEnd();
                        rd.Dispose();
                        ws.Dispose();
                        Match mm = publicKey.Match(dta);
                        if (!mm.Success)
                        {
                            ret.ErrorMessage = "Unable to find Daisuki public key";
                            ret.Status       = ResponseStatus.WebError;
                            return(ret);
                        }
                        string bld = mm.Groups["key"].Value.Replace("\\n", "");

                        token.ThrowIfCancellationRequested();
                        dp.Percent = 2;
                        progress.Report(dp);

                        ws = await WebStream.Get(LibSet[BaseHostS] + vars["country"] + "?cashPath=" + (long)((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds), null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, episode.PluginMetadata["Url"], _info.ProxyFromGlobalRequirements(_global));

                        Country c;
                        if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                        {
                            ret.ErrorMessage = "Unable to find Daisuki Country Code";
                            ret.Status       = ResponseStatus.WebError;
                            ws?.Dispose();
                            return(ret);
                        }
                        try
                        {
                            XmlSerializer ser = new XmlSerializer(typeof(Country));
                            c = (Country)ser.Deserialize(ws);
                            ws.Dispose();
                        }
                        catch (Exception)
                        {
                            ret.ErrorMessage = "Unable to find Daisuki Country Code";
                            ret.Status       = ResponseStatus.WebError;
                            ws.Dispose();
                            return(ret);
                        }
                        Dictionary <string, string> form = new Dictionary <string, string>();
                        Api api = new Api();
                        if (vars.ContainsKey("ss_id"))
                        {
                            api.SS_Id = vars["ss_id"];
                        }
                        if (vars.ContainsKey("mv_id"))
                        {
                            api.MV_Id = vars["mv_id"];
                        }
                        if (vars.ContainsKey("device_cd"))
                        {
                            api.Device_CD = vars["device_cd"];
                        }
                        if (vars.ContainsKey("ss1_prm"))
                        {
                            api.SS1_PRM = vars["ss1_prm"];
                        }
                        if (vars.ContainsKey("ss2_prm"))
                        {
                            api.SS2_PRM = vars["ss2_prm"];
                        }
                        if (vars.ContainsKey("ss3_prm"))
                        {
                            api.SS3_PRM = vars["ss3_prm"];
                        }
                        RSACryptoServiceProvider prov = ProviderFromPEM(bld);
                        AesManaged aes = new AesManaged();
                        aes.GenerateKey();
                        aes.Mode = CipherMode.CBC;
                        int blocksize = aes.BlockSize / 8;
                        aes.IV      = new byte[blocksize];
                        aes.KeySize = 256;
                        aes.Padding = PaddingMode.Zeros;
                        aes.GenerateKey();
                        byte[] apidata = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(api));
                        int    nsize   = ((apidata.Length + (blocksize - 1)) / blocksize) * blocksize;
                        if (nsize != apidata.Length)
                        {
                            Array.Resize(ref apidata, nsize);
                        }
                        ICryptoTransform t   = aes.CreateEncryptor();
                        byte[]           enc = t.TransformFinalBlock(apidata, 0, nsize);
                        byte[]           key = prov.Encrypt(aes.Key, false);
                        form.Add("s", vars["s"]);
                        form.Add("c", c.CountryCode);
                        form.Add("e", episode.PluginMetadata["Url"]);
                        form.Add("d", Convert.ToBase64String(enc));
                        form.Add("a", Convert.ToBase64String(key));
                        token.ThrowIfCancellationRequested();
                        string n = form.PostFromDictionary();

                        ws = await WebStream.Get(LibSet[BaseHostS] + vars["init"] + "?" + n, null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, episode.PluginMetadata["Url"], _info.ProxyFromGlobalRequirements(_global));

                        if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                        {
                            ret.ErrorMessage = "Unable to retrieve metadata";
                            ret.Status       = ResponseStatus.WebError;
                            ws?.Dispose();
                            return(ret);
                        }
                        rd  = new StreamReader(ws);
                        dta = rd.ReadToEnd();
                        rd.Dispose();
                        ws.Dispose();
                        MetaEncrypt menc = JsonConvert.DeserializeObject <MetaEncrypt>(dta);
                        if (menc == null || menc.Status != "00")
                        {
                            ret.ErrorMessage = "Unable to retrieve metadata";
                            ret.Status       = ResponseStatus.WebError;
                            return(ret);
                        }
                        t = aes.CreateDecryptor();
                        byte[] indata = Convert.FromBase64String(menc.EncryptedData);
                        nsize = ((indata.Length + (blocksize - 1)) / blocksize) * blocksize;
                        if (nsize != indata.Length)
                        {
                            Array.Resize(ref indata, nsize);
                        }

                        byte[] outdata = t.TransformFinalBlock(indata, 0, indata.Length);
                        int    start   = outdata.Length;
                        while (outdata[start - 1] == 0)
                        {
                            start--;
                        }
                        if (start != outdata.Length)
                        {
                            Array.Resize(ref outdata, start);
                        }
                        string final = Encoding.UTF8.GetString(outdata);
                        Data   ldta  = JsonConvert.DeserializeObject <Data>(final);
                        NameValueCollection headers = new NameValueCollection();
                        headers.Add("Accept", "*/*");
                        headers.Add("Accept-Language", "en-US");
                        headers.Add("x-flash-version", "18,0,0,232");
                        string guid    = GenGUID(12);
                        string playurl = ldta.play_url + "&g=" + guid + "&hdcore=3.2.0";
                        token.ThrowIfCancellationRequested();
                        dp.Percent = 3;
                        dp.Status  = "Gettings subtitles";
                        progress.Report(dp);
                        dp.Languages = new List <string>();
                        Dictionary <string, string> subtitles = new Dictionary <string, string>();

                        if (string.IsNullOrEmpty(ldta.caption_url))
                        {
                            dp.Languages.Add("Hardcoded");
                        }
                        else
                        {
                            ws = await WebStream.Get(ldta.caption_url + "?cashPath=" + (long)((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds), null, LibSet[UserAgentS], headers, null, SocketTimeout, true, "http://img.daisuki.net/common2/pages/anime/swf/bngn_player_001.swf", _info.ProxyFromGlobalRequirements(_global));

                            if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                            {
                                ret.ErrorMessage = "Unable to retrieve subtitles";
                                ret.Status       = ResponseStatus.WebError;
                                ws?.Dispose();
                                return(ret);
                            }
                            TTML subs = new TTML(ws);
                            subtitles = subs.ToAss();
                            ws.Dispose();
                        }
                        dp.Percent = 4;
                        dp.Status  = "Downloading video";
                        progress.Report(dp);
                        token.ThrowIfCancellationRequested();
                        ws = await WebStream.Get(playurl, null, LibSet[UserAgentS], headers, null, SocketTimeout, true, "http://img.daisuki.net/common2/pages/anime/swf/bngn_player_001.swf", _info.ProxyFromGlobalRequirements(_global));

                        int    idx     = playurl.LastIndexOf(".smil/", StringComparison.InvariantCulture);
                        string baseurl = string.Empty;
                        if (idx > 0)
                        {
                            baseurl = playurl.Substring(0, idx + 6);
                        }
                        if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                        {
                            ret.ErrorMessage = "Unable to retrieve metadata";
                            ret.Status       = ResponseStatus.WebError;
                            ws?.Dispose();
                            return(ret);
                        }
                        XmlSerializer serm = new XmlSerializer(typeof(Manifest));
                        //Stream ms = File.OpenRead(@"C:\users\mpiva\Downloads\s.manifest");
                        //Manifest manifest = (Manifest)serm.Deserialize(ms);
                        Manifest manifest = (Manifest)serm.Deserialize(ws);


                        rd.Dispose();
                        ws.Dispose();
                        manifest.Init();
                        KeyValuePair <Media, Quality>?kv = BestMediaFromManifest(manifest, quality);
                        if (kv == null)
                        {
                            ret.ErrorMessage = "Unable to find the best media";
                            ret.Status       = ResponseStatus.WebError;
                            return(ret);
                        }
                        dp.Quality = kv.Value.Value;
                        Media  media  = kv.Value.Key;
                        string inputs = string.Empty;
                        string maps   = String.Empty;
                        int    pp     = 0;
                        foreach (string k in subtitles.Keys)
                        {
                            string pth = Path.GetTempFileName() + ".ass";
                            todeleteFiles.Add(pth);
                            File.WriteAllText(pth, subtitles[k]);
                            inputs += "-i \"" + pth + "\" ";
                            dp.Languages.Add(Languages.TranslateToOriginalLanguage(k));
                            maps += GetFFMPEGSubtitleArguments(pp + 1, pp, Languages.CodeFromLanguage(k), Languages.TranslateToOriginalLanguage(k));
                            pp++;
                        }
                        dp.Percent  = 4;
                        dp.FileName = TemplateParser.FilenameFromEpisode(episode, dp.Quality, template);
                        dp.FullPath = Path.Combine(downloadpath, dp.FileName);
                        token.ThrowIfCancellationRequested();
                        progress.Report(dp);
                        string intermediatefile = dp.FullPath + ".tm1";

                        /* http://www.daisuki.net/etc/designs/daisuki/swf/bngn_player_002.swf*/
                        headers["X-Requested-With"] = "ShockwaveFlash/20.0.0.267";
                        FragmentProcessor  frag = new FragmentProcessor(ws.Cookies, headers, LibSet[UserAgentS], SocketTimeout, episode.PluginMetadata["Url"], _info.ProxyFromGlobalRequirements(_global), 2, 5, intermediatefile);
                        double             dbl  = 91;
                        IProgress <double> d    = new Progress <double>((val) =>
                        {
                            dp.Percent = (val * dbl / 100) + 4;
                            progress.Report(dp);
                        });

                        todeleteFiles.Add(intermediatefile);
                        await frag.Start(baseurl, guid, manifest, media, token, d);

                        dp.Size = await ReMux(intermediatefile, inputs, maps, formats, deflangcode, deflang, 96, 4, dp, progress, token);

                        dp.Percent = 100;
                        dp.Status  = "Finished";
                        progress.Report(dp);
                        foreach (string del in todeleteFiles)
                        {
                            try
                            {
                                File.Delete(del);
                            }
                            catch (Exception)
                            {
                            }
                        }
                        ret.Status = ResponseStatus.Ok;
                    }
                }
                else
                {
                    SetWebError(ret);
                }
                ws?.Dispose();
                return(ret);
            }
            catch (Exception e)
            {
                if (e is OperationCanceledException)
                {
                    return new Response {
                               ErrorMessage = "Canceled", Status = ResponseStatus.Canceled
                    }
                }
                ;
                return(new Shows {
                    ErrorMessage = e.ToString(), Status = ResponseStatus.SystemError
                });
            }
        }
Beispiel #29
0
        /// <summary>
        /// ヘッドラインをネットから取得する
        /// </summary>
        public virtual void FetchHeadline()
        {
            // 時刻をセットする
            lastCheckTime = DateTime.Now;

            WebStream st = null;

            try
            {
                // チャンネルのリスト
                ArrayList alChannels = new ArrayList();
                Channel   channel    = null;

                string searchWord = ((setting.SearchWord.Length != 0) ? "&s=" + setting.SearchWord : string.Empty);
                // 半角スペースと全角スペースを+に置き換える SHOUTcast上のURLでAND検索のスペースが+に置き換えられるため
                searchWord = searchWord.Replace(' ', '+').Replace(" ", "+");

                string perView = ((setting.PerView.ToString().Length != 0) ? "&numresult=" + setting.PerView : string.Empty);
                Uri    url     = new Uri(Headline.SHOUTCAST_URL + "/?" + searchWord + perView);

                st = PocketLadioUtility.GetWebStream(url);
                WebTextFetch fetch = new WebTextFetch(st, Encoding.GetEncoding("Windows-1252"));
                if (HeadlineFetch != null)
                {
                    fetch.Fetch += HeadlineFetch;
                }
                if (HeadlineFetching != null)
                {
                    fetch.Fetching += HeadlineFetching;
                }
                if (HeadlineFetched != null)
                {
                    fetch.Fetched += HeadlineFetched;
                }
                string httpString = fetch.ReadToEnd();

#if SHOUTCAST_HTTP_LOG
                // ShoutcastのHTTPのログを書き出す
                StreamWriter sw = null;
                try
                {
                    sw = new StreamWriter(
                        AssemblyUtility.GetExecutablePath() + @"\" + PocketLadioInfo.ShoutcastHttpLog,
                        false,
                        Encoding.GetEncoding("Windows-1252"));
                    sw.Write(httpString);
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Close();
                    }
                }
#endif

                // タグの後に改行を入れる(Willcom高速化サービス対応のため)
                httpString = httpString.Replace(">", ">\n");

                string[] lines = httpString.Split('\n');

                #region HTML解析

                // 順位らしき行
                string maybeRankLine = string.Empty;

                // 1〜指定行目まではHTMLを解析しない
                int analyzeHtmlFirstTo = setting.IgnoreHtmlAnalyzeFirstTo;
                // 指定行目から行末まではHTMLを解析しない
                int analyzeHtmlLast = lines.Length - setting.IgnoreHtmlAnalyzeEndFrom;

                OnHeadlineAnalyze(new HeadlineAnalyzeEventArgs(0, -1));

                // 解析したヘッドラインの個数
                int analyzedCount = 0;

                // HTML解析
                for (int lineNumber = analyzeHtmlFirstTo; lineNumber < analyzeHtmlLast && lineNumber < lines.Length; ++lineNumber)
                {
                    /*** playlist.plsを検索 ***/
                    Match pathMatch = pathRegex.Match(lines[lineNumber]);

                    // playlist.plsが見つかった場合
                    if (pathMatch.Success)
                    {
                        channel = new Channel(this);

                        channel.Path = pathMatch.Groups[1].Value;

                        /*** Rankを検索 ***/
                        Match rankMatch = rankRegex.Match(maybeRankLine);

                        // Rankが見つかった場合
                        if (rankMatch.Success)
                        {
                            channel.Rank = rankMatch.Groups[1].Value;
                        }

                        /*** Categoryを検索 ***/
                        Match categoryMatch;

                        // Categoryが見つからない場合は行を読み飛ばして検索する
                        for (++lineNumber; lineNumber < analyzeHtmlLast; ++lineNumber)
                        {
                            categoryMatch = categoryRegex.Match(lines[lineNumber]);

                            // Categoryが見つかった場合
                            if (categoryMatch.Success)
                            {
                                channel.Category = categoryMatch.Groups[1].Value;
                                break;
                            }
                        }

                        /*** ClusterUrlを検索 ***/
                        Match clusterUrlMatch;

                        // ClusterUrlが見つからない場合は行を読み飛ばして検索する
                        for (; lineNumber < analyzeHtmlLast; ++lineNumber)
                        {
                            clusterUrlMatch = clusterUrlRegex.Match(lines[lineNumber]);

                            // Categoryが見つかった場合
                            if (clusterUrlMatch.Success)
                            {
                                try
                                {
                                    channel.ClusterUrl = new Uri(clusterUrlMatch.Groups[1].Value);
                                }
                                catch (UriFormatException)
                                {
                                    channel.ClusterUrl = null;
                                }
                                break;
                            }
                        }

                        /*** Titleを検索 ***/
                        Match titleMatch;

                        // Titleが見つからない場合は行を読み飛ばして検索する
                        for (; lineNumber < analyzeHtmlLast; ++lineNumber)
                        {
                            titleMatch = titleRegex.Match(lines[lineNumber]);

                            // Titleが見つかった場合
                            if (titleMatch.Success)
                            {
                                channel.Title = titleMatch.Groups[1].Value;
                                break;
                            }
                        }

                        /*** Listenerを検索 ***/
                        Match listenerMatch = listenerRegex.Match(lines[lineNumber]);
                        for (; lineNumber < analyzeHtmlLast; ++lineNumber)
                        {
                            listenerMatch = listenerRegex.Match(lines[lineNumber]);

                            if (listenerMatch.Success)
                            {
                                break;
                            }

                            // Now Playing:は存在しない場合があるのでリスナー数検出の中でチェックを行う
                            Match playingNowMatch = playingNowRegex.Match(lines[lineNumber]);
                            if (playingNowMatch.Success)
                            {
                                Match playingMatch = playingRegex.Match(playingNowMatch.Groups[1].Value);
                                if (playingMatch.Success)
                                {
                                    channel.Playing = playingMatch.Groups[1].Value;
                                }
                            }
                        }
                        try
                        {
                            channel.Listener      = int.Parse(listenerMatch.Groups[1].Value);
                            channel.ListenerTotal = int.Parse(listenerMatch.Groups[2].Value);
                        }
                        catch (ArgumentException)
                        {
                            ;
                        }
                        catch (FormatException)
                        {
                            ;
                        }
                        catch (OverflowException)
                        {
                            ;
                        }

                        /*** Bitrateを検索 ***/
                        Match bitrateMatch;

                        // Bitrateが見つからない場合は行を読み飛ばして検索する
                        for (++lineNumber; lineNumber < analyzeHtmlLast; ++lineNumber)
                        {
                            bitrateMatch = bitRateRegex.Match(lines[lineNumber]);

                            // Bitrateが見つかった場合
                            if (bitrateMatch.Success)
                            {
                                try
                                {
                                    channel.BitRate = int.Parse(bitrateMatch.Groups[1].Value);
                                    break;
                                }
                                catch (ArgumentException)
                                {
                                    ;
                                }
                                catch (FormatException)
                                {
                                    ;
                                }
                                catch (OverflowException)
                                {
                                    ;
                                }
                            }
                        }
                        alChannels.Add(channel);
                        OnHeadlineAnalyzing(new HeadlineAnalyzeEventArgs(++analyzedCount, -1));
                    }

                    /*** Rankらしき行を保存する ***/
                    Match maybeRankLineMatch = maybeRankLineRegex.Match(lines[lineNumber]);

                    if (maybeRankLineMatch.Success)
                    {
                        maybeRankLine = lines[lineNumber];
                    }
                }

                OnHeadlineAnalyzed(new HeadlineAnalyzeEventArgs(analyzedCount, analyzedCount));

                channels = (Channel[])alChannels.ToArray(typeof(Channel));

                #endregion
            }
            finally
            {
                if (st != null)
                {
                    st.Close();
                }
            }
        }
        private async Task <Shows> Shows(ISession session, bool order)
        {
            try
            {
                DaiSukiSession s = session as DaiSukiSession;
                if (s == null)
                {
                    return new Shows {
                               ErrorMessage = "Invalid Session", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                Shows ret = new Shows();
                ret.Items = new List <Show>();
                WebStream ws = await WebStream.Get("http://www.daisuki.net/bin/wcm/searchAnimeAPI?api=anime_list&searchOptions=&currentPath=%2Fcontent%2Fdaisuki%2Fus%2Fen", null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, null, _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        SetLoginError(ret);
                    }
                    else
                    {
                        StreamReader         rd     = new StreamReader(ws);
                        string               dta    = rd.ReadToEnd();
                        BaseResponse <Anime> animes = JsonConvert.DeserializeObject <BaseResponse <Anime> >(dta);
                        rd.Dispose();
                        if (animes.Response == null || animes.Response.Count == 0)
                        {
                            if (animes.Error != null)
                            {
                                ret.ErrorMessage = animes.Error;
                                ret.Status       = ResponseStatus.WebError;
                                return(ret);
                            }
                            SetWebError(ret);
                            ws?.Dispose();
                            return(ret);
                        }
                        foreach (Anime a in animes.Response)
                        {
                            Show cs = new Show();
                            cs.PluginName  = DaiSukiPluginInfo.PluginName;
                            cs.Id          = a.Id.ToString();
                            cs.Type        = ShowType.Anime;
                            cs.Description = a.Synopsis;
                            cs.Name        = a.Title;
                            cs.PluginMetadata.Add("Url", new Uri("http://www.daisuki.net/anime/detail/" + a.AdId).ToString());
                            ret.Items.Add(cs);
                        }
                        if (order)
                        {
                            ret.Items = ret.Items.OrderBy(a => a.Name).ToList();
                        }
                        ret.Status = ResponseStatus.Ok;
                    }
                }
                else
                {
                    SetWebError(ret);
                }
                ws?.Dispose();
                return(ret);
            }
            catch (Exception e)
            {
                return(new Shows {
                    ErrorMessage = e.ToString(), Status = ResponseStatus.SystemError
                });
            }
        }