示例#1
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;
            }
        }
示例#2
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();
        }
示例#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();
        }
示例#4
0
        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);
        }
示例#5
0
        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);
        }
示例#6
0
        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);
        }
示例#7
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();
        }
示例#8
0
        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);
        }
示例#9
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);
        }
示例#10
0
        private async Task <Episode> GetEpisodeUpdate(CrunchySession s, Episode placeholder, string datetime)
        {
            try
            {
                WebStream ws = await WebStream.Get(placeholder.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))
                    {
                        ws?.Dispose();
                        return(null);
                    }
                    StreamReader rd  = new StreamReader(ws);
                    string       dta = rd.ReadToEnd();
                    rd.Dispose();
                    Episodes eps = new Episodes();
                    eps.Items = new List <Episode>();
                    Show show = new Show();
                    show.PluginName = placeholder.PluginName;
                    show.Id         = placeholder.ShowId;

                    MatchCollection scol      = seasonregex.Matches(dta);
                    int             seasonnum = scol.Count;
                    if (scol.Count == 0)
                    {
                        AddEpisodes(eps, show, dta, String.Empty, 1, true);
                    }
                    else
                    {
                        Match sma = scol[0];
                        if (sma.Success)
                        {
                            string data      = sma.Value;
                            string seasoname = sma.Groups["season"].Value;
                            AddEpisodes(eps, show, data, seasoname, seasonnum, true);
                        }
                    }
                    if (eps.Items.Count == 0)
                    {
                        ws?.Dispose();
                        return(null);
                    }
                    Episode ep = eps.Items[0];
                    placeholder.PluginMetadata["Url"] = ep.PluginMetadata["Url"];
                    placeholder.ImageUri       = ep.ImageUri;
                    placeholder.Description    = ep.Description;
                    placeholder.EpisodeAlpha   = ep.EpisodeAlpha;
                    placeholder.EpisodeNumeric = ep.EpisodeNumeric;
                    placeholder.Id             = ep.Id;
                    placeholder.SeasonAlpha    = ep.SeasonAlpha;
                    placeholder.SeasonNumeric  = ep.SeasonNumeric;
                    placeholder.Name           = ep.Name;
                    placeholder.DateTime       = datetime;
                    UpdateHistory.Add(placeholder.UniqueTag, JsonConvert.SerializeObject(placeholder));
                    ws?.Dispose();
                    return(placeholder);
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(null);
        }
示例#11
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);
        }
示例#12
0
        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
                });
            }
        }
示例#13
0
        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
                });
            }
        }
示例#14
0
        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
                });
            }
        }
示例#15
0
        public async Task <Tag> GetNextTag(Stream stream)
        {
            Tag t = new Tag();

            byte[] header    = new byte[11];
            byte[] remainder = new byte[4];
            stream.Read(header, 0, 11);
            t.Type       = header[0];
            t.PacketSize = header[1] << 16 | header[2] << 8 | header[3] & 255;
            t.TimeStamp  = (header[7] << 24 | header[4] << 16 | header[5] << 8 | header[6] & 255) & 0x7FFFFFFF;
            t.Remainder  = new byte[3];
            Array.Copy(header, 8, t.Remainder, 0, 3);
            byte[] data = new byte[t.PacketSize];
            stream.Read(data, 0, t.PacketSize);
            stream.Read(remainder, 0, 4);
            Array.Reverse(remainder);
            t.TotalSize      = BitConverter.ToInt32(remainder, 0);
            t.NeedDecryption = false;

            if (t.Type == 10 || t.Type == 11)
            {
                t.Type -= 2;
                byte tp  = data[12];
                int  pos = 13;
                if ((tp & 2) > 0)
                {
                    pos += 16;
                }
                if ((tp & 4) > 0)
                {
                    StringBuilder bld = new StringBuilder();
                    byte          b   = data[pos++];
                    while (b != 0)
                    {
                        bld.Append((char)b);
                        b = data[pos++];
                    }
                    string nurl = bld.ToString();
                    if (nurl != KeyUrl)
                    {
                        Uri bas = new Uri(baseurl);

                        string url = string.Format(FormatKey, bas.Scheme + "://" + bas.Host + nurl, guid, manifest.Pv20.Substring(1) + "&hdcore=3.2.0");
                        int    idx = nurl.IndexOf("_");
                        keydata = nurl.Substring(idx);
                        WebStream ws = await GetStream(url);

                        if (ws == null || ws.StatusCode != HttpStatusCode.OK)
                        {
                            ws?.Dispose();
                            throw new IOException("Error " + ws.StatusCode + " trying to download fragment");
                        }
                        KeyData = new byte[ws.ContentLength];
                        await ws.ReadAsync(KeyData, 0, (int)ws.ContentLength);

                        ws.Dispose();
                        KeyUrl = nurl;
                    }
                }
                t.NeedDecryption = true;
                t.Key            = KeyData;
            }
            t.Packet     = data;
            t.PacketSize = data.Length;
            return(t);
        }
示例#16
0
        public async Task <Shows> Shows(ISession session, ShowType type)
        {
            try
            {
                CrunchySession s = session as CrunchySession;
                if (s == null)
                {
                    return new Shows {
                               ErrorMessage = "Invalid Session", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                Shows ret = new Shows();
                ret.Items = new List <Show>();
                string    url = string.Format(LibSet[ShowUrlS], ShowFromType(type));
                WebStream ws  = await WebStream.Get(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();
                        MatchCollection           col = showregex.Matches(dta);
                        Dictionary <string, Show> ls  = new Dictionary <string, Show>();
                        foreach (Match m in col)
                        {
                            if (m.Success)
                            {
                                Show cs = new Show();

                                cs.Id = int.Parse(m.Groups["id"].Value).ToString();
                                if (!ls.ContainsKey(cs.Id))
                                {
                                    cs.Name       = m.Groups["title"].Value;
                                    cs.Type       = type;
                                    cs.PluginName = CrunchyPluginInfo.PluginName;
                                    cs.PluginMetadata.Add("Url",
                                                          new Uri("http://www.crunchyroll.com" + m.Groups["url"].Value).ToString());
                                    ls.Add(cs.Id, cs);
                                }
                            }
                        }
                        col = show2regex.Matches(dta);
                        foreach (Match m in col)
                        {
                            if (m.Success)
                            {
                                string id  = int.Parse(m.Groups["id"].Value).ToString();
                                Show   ccd = ls[id];
                                ccd.Description = Regex.Unescape(m.Groups["desc"].Value);
                            }
                        }
                        ret.Items  = ls.Values.OrderBy(a => a.Name).Cast <Show>().ToList();
                        ret.Status = ResponseStatus.Ok;
                    }
                }
                else
                {
                    SetWebError(ret);
                }
                ws?.Dispose();
                return(ret);
            }
            catch (Exception e)
            {
                return(new Shows {
                    ErrorMessage = e.ToString(), Status = ResponseStatus.SystemError
                });
            }
        }
示例#17
0
        private async Task <UpdateResponse> Updates(CrunchySession s, ShowType t)
        {
            int            startpage = 0;
            UpdateResponse ret       = new UpdateResponse();
            bool           end       = false;

            do
            {
                string    url = string.Format(LibSet[UpdateUrlS], ShowFromType(t), startpage);
                WebStream ws  = await WebStream.Get(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))
                    {
                        ws.Dispose();
                        SetLoginError(ret);
                        return(ret);
                    }
                    StreamReader rd  = new StreamReader(ws);
                    string       dta = rd.ReadToEnd();
                    rd.Dispose();
                    MatchCollection scol = updregex.Matches(dta);
                    if (scol.Count == 0)
                    {
                        end = true;
                    }
                    foreach (Match m in scol)
                    {
                        string show  = m.Groups["show"].Value;
                        string image = m.Groups["image"].Value;
                        string title = WebUtility.HtmlDecode(m.Groups["title"].Value);
                        string ep    = m.Groups["ep"].Value;
                        Uri    ur    = new Uri("http://www.crunchyroll.com" + m.Groups["url"].Value);
                        int    a     = ep.IndexOf("&ndash;", StringComparison.InvariantCulture);
                        if (a >= 0)
                        {
                            ep = ep.Substring(0, a).Trim();
                            string tag = CrunchyPluginInfo.PluginName + "|" + show + "|" + ep;
                            if (UpdateHistory.Exists(tag))
                            {
                                Episode c = JsonConvert.DeserializeObject <Episode>(UpdateHistory.Get(tag));
                                ret.Found.Add(c);
                            }
                            else
                            {
                                Episode p = new Episode();
                                p.PluginMetadata.Add("Url", ur.ToString());
                                p.ShowName   = title;
                                p.ShowId     = show;
                                p.PluginName = CrunchyPluginInfo.PluginName;
                                p.UniqueTag  = tag;
                                p.ImageUri   = new Uri(image);
                                p.Type       = t;
                                ret.NotFound.Add(p);
                            }
                        }
                    }
                }
                else
                {
                    ws?.Dispose();
                    SetWebError(ret);
                    return(ret);
                }
                ws?.Dispose();
                startpage++;
            } while (!end);
            return(ret);
        }
示例#18
0
        public async Task <Episodes> Episodes(ISession session, Show show)
        {
            try
            {
                CrunchySession s = session as CrunchySession;
                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>();
                        Match sm = epsshowimage.Match(dta);
                        if (sm.Success)
                        {
                            ret.ImageUri = new Uri(sm.Groups["image"].Value);
                        }
                        MatchCollection scol      = seasonregex.Matches(dta);
                        int             seasonnum = scol.Count;
                        if (scol.Count == 0)
                        {
                            AddEpisodes(ret, show, dta, String.Empty, 1);
                        }
                        else
                        {
                            foreach (Match sma in scol)
                            {
                                if (sma.Success)
                                {
                                    string data      = sma.Value;
                                    string seasoname = sma.Groups["season"].Value;
                                    AddEpisodes(ret, show, data, seasoname, seasonnum);
                                }
                                seasonnum--;
                            }
                        }
                        int index = ret.Items.Count;
                        for (int x = 0; x < ret.Items.Count; x++)
                        {
                            ret.Items[x].Index = index;
                            index--;
                        }
                        ret.Items.Reverse();
                    }
                }
                else
                {
                    SetWebError(ret);
                }
                ws?.Dispose();
                return(ret);
            }
            catch (Exception e)
            {
                return(new Episodes {
                    ErrorMessage = e.ToString(), Status = ResponseStatus.SystemError
                });
            }
        }