Exemple #1
0
        public Response <Bitmap> Load(Uri uri, bool localCacheOnly)
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.IceCreamSandwich)
            {
                InstallCacheIfNeeded(m_Context);
            }

            URLConnection connection = OpenConnection(uri);

            connection.UseCaches = true;
            if (localCacheOnly)
            {
                connection.SetRequestProperty("Cache-Control", "only-if-cached,max-age=" + int.MaxValue);
            }

            var httpConnection = connection as HttpURLConnection;

            if (httpConnection != null)
            {
                int responseCode = (int)httpConnection.ResponseCode;
                if (responseCode >= 300)
                {
                    httpConnection.Disconnect();
                    throw new ResponseException(responseCode + " " + httpConnection.ResponseMessage);
                }
            }

            long contentLength = connection.GetHeaderFieldInt("Content-Length", -1);
            bool fromCache     = ParseResponseSourceHeader(connection.GetHeaderField(ResponseSource));

            return(new Response <Bitmap>(connection.InputStream, fromCache, contentLength));
        }
 protected internal virtual URLConnection SendRequest(string method, string path,
                                                      IDictionary <string, string> headers, object bodyObj)
 {
     try
     {
         Uri           url  = new Uri("cblite://" + path);
         URLConnection conn = (URLConnection)url.OpenConnection();
         conn.SetDoOutput(true);
         conn.SetRequestMethod(method);
         if (headers != null)
         {
             foreach (string header in headers.Keys)
             {
                 conn.SetRequestProperty(header, headers.Get(header));
             }
         }
         IDictionary <string, IList <string> > allProperties = conn.GetRequestProperties();
         if (bodyObj != null)
         {
             conn.SetDoInput(true);
             ByteArrayInputStream bais = new ByteArrayInputStream(mapper.WriteValueAsBytes(bodyObj
                                                                                           ));
             conn.SetRequestInputStream(bais);
         }
         Couchbase.Lite.Router.Router router = new Couchbase.Lite.Router.Router(manager, conn
                                                                                );
         router.Start();
         return(conn);
     }
     catch (UriFormatException)
     {
         Fail();
     }
     catch (IOException)
     {
         Fail();
     }
     return(null);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="mirrorNames"></param>
        /// <param name="mirrorUrls"></param>
        /// <param name="mirror"></param>
        /// <param name="title"></param>
        /// <param name="path">FULL PATH</param>
        /// <param name="poster"></param>
        /// <param name="fileName"></param>
        /// <param name="beforeTxt"></param>
        /// <param name="openWhenDone"></param>
        /// <param name="showNotificaion"></param>
        /// <param name="showDoneNotificaion"></param>
        /// <param name="showDoneAsToast"></param>
        /// <param name="resumeIntent"></param>
        public static void HandleIntent(int id, List <BasicMirrorInfo> mirrors, int mirror, string title, string path, string poster, string beforeTxt, bool openWhenDone, bool showNotificaion, bool showDoneNotificaion, bool showDoneAsToast, bool resumeIntent)
        {
            const int UPDATE_TIME = 1;

            try {
                isStartProgress[id] = true;
                print("START DLOAD::: " + id);
                if (isPaused.ContainsKey(id))
                {
                    //if (isPaused[id] == 2) {
                    //  isPaused.Remove(id);
                    //    print("YEET DELETED KEEEE");
                    return;
                    //  }
                }
                var context = Application.Context;

                //$"{nameof(id)}={id}|||{nameof(title)}={title}|||{nameof(path)}={path}|||{nameof(poster)}={poster}|||{nameof(fileName)}={fileName}|||{nameof(beforeTxt)}={beforeTxt}|||{nameof(openWhenDone)}={openWhenDone}|||{nameof(showDoneNotificaion)}={showDoneNotificaion}|||{nameof(showDoneAsToast)}={showDoneAsToast}|||");

                int progress = 0;

                int bytesPerSec = 0;

                void UpdateDloadNot(string progressTxt)
                {
                    //poster != ""
                    if (!isPaused.ContainsKey(id))
                    {
                        isPaused[id] = 0;
                    }
                    try {
                        int  isPause  = isPaused[id];
                        bool canPause = isPause == 0;
                        if (isPause != 2)
                        {
                            ShowLocalNot(new LocalNot()
                            {
                                actions = new List <LocalAction>()
                                {
                                    new LocalAction()
                                    {
                                        action = $"handleDownload|||id={id}|||dType={(canPause ? 1 : 0)}|||", name = canPause ? "Pause" : "Resume"
                                    }, new LocalAction()
                                    {
                                        action = $"handleDownload|||id={id}|||dType=2|||", name = "Stop"
                                    }
                                }, mediaStyle = false, bigIcon = poster, title = $"{title} - {ConvertBytesToAny(bytesPerSec / UPDATE_TIME, 2, 2)} MB/s", autoCancel = false, showWhen = false, onGoing = canPause, id = id, smallIcon = PublicNot, progress = progress, body = progressTxt
                            }, context);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   //canPause
                        }
                    }
                    catch (Exception _ex) {
                        print("ERRORLOADING PROGRESS:::" + _ex);
                    }
                }

                void ShowDone(bool succ, string overrideText = null)
                {
                    print("DAAAAAAAAAASHOW DONE" + succ);
                    if (succ)
                    {
                        App.RemoveKey(DOWNLOAD_KEY, id.ToString());
                        App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString());
                    }
                    if (showDoneNotificaion)
                    {
                        print("DAAAAAAAAAASHOW DONE!!!!");
                        Device.BeginInvokeOnMainThread(() => {
                            try {
                                print("DAAAAAAAAAASHOW DONE222");
                                ShowLocalNot(new LocalNot()
                                {
                                    mediaStyle = poster != "", bigIcon = poster, title = title, autoCancel = true, onGoing = false, id = id, smallIcon = PublicNot, body = overrideText ?? (succ ? "Download done!" : "Download Failed")
                                }, context);                                                                                                                                                                                                                                                                    // ((e.Cancelled || e.Error != null) ? "Download Failed!"
                            }
                            catch (Exception _ex) {
                                print("SUPERFATALEX: " + _ex);
                            }
                        });
                        //await Task.Delay(1000); // 100% sure that it is downloaded
                        OnSomeDownloadFinished?.Invoke(null, EventArgs.Empty);
                    }
                    else
                    {
                        print("DONT SHOW WHEN DONE");
                    }
                    // Toast.MakeText(context, "PG DONE!!!", ToastLength.Long).Show();
                }



                void StartT()
                {
                    isStartProgress[id] = true;
                    if (isPaused.ContainsKey(id))
                    {
                        //if (isPaused[id] == 2) {
                        //    isPaused.Remove(id);
                        return;
                        //  }
                    }

                    Thread t = new Thread(() => {
                        print("START:::");
                        string json = JsonConvert.SerializeObject(new DownloadHandleNot()
                        {
                            id = id, mirrors = mirrors, showDoneAsToast = showDoneAsToast, openWhenDone = openWhenDone, showDoneNotificaion = showDoneNotificaion, beforeTxt = beforeTxt, mirror = mirror, path = path, poster = poster, showNotificaion = showNotificaion, title = title
                        });

                        App.SetKey(DOWNLOAD_KEY_INTENT, id.ToString(), json);

                        var mirr = mirrors[mirror];

                        string url     = mirr.mirror;
                        string urlName = mirr.name;
                        string referer = mirr.referer ?? "";
                        bool isM3u8    = url.Contains(".m3u8");

                        if ((int)Android.OS.Build.VERSION.SdkInt > 9)
                        {
                            StrictMode.ThreadPolicy policy = new
                                                             StrictMode.ThreadPolicy.Builder().PermitAll().Build();
                            StrictMode.SetThreadPolicy(policy);
                        }
                        long total     = 0;
                        int fileLength = 0;

                        void UpdateProgress()
                        {
                            UpdateDloadNot($"{beforeTxt.Replace("{name}", urlName)}{progress} % ({ConvertBytesToAny(total, 1, 2)} MB/{ConvertBytesToAny(fileLength, 1, 2)} MB)");
                        }

                        void UpdateFromId(object sender, int _id)
                        {
                            if (_id == id)
                            {
                                UpdateProgress();
                            }
                        }

                        bool removeKeys = true;
                        var rFile       = new Java.IO.File(path);

                        try {
                            // CREATED DIRECTORY IF NEEDED
                            try {
                                Java.IO.File __file = new Java.IO.File(path);
                                __file.Mkdirs();
                            }
                            catch (Exception _ex) {
                                print("FAILED:::" + _ex);
                            }

                            URL _url = new URL(url);

                            URLConnection connection = _url.OpenConnection();

                            print("SET CONNECT ::");
                            if (!rFile.Exists())
                            {
                                print("FILE DOSENT EXITS");
                                rFile.CreateNewFile();
                            }
                            else
                            {
                                if (resumeIntent)
                                {
                                    total = rFile.Length();
                                    connection.SetRequestProperty("Range", "bytes=" + rFile.Length() + "-");
                                }
                                else
                                {
                                    rFile.Delete();
                                    rFile.CreateNewFile();
                                }
                            }
                            print("SET CONNECT ::2");
                            connection.SetRequestProperty("Accept-Encoding", "identity");
                            if (referer != "")
                            {
                                connection.SetRequestProperty("Referer", referer);
                            }
                            int clen = 0;

                            if (isM3u8)
                            {
                                clen = 1;
                            }
                            else
                            {
                                bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(10000), () => {
                                    connection.Connect();
                                    clen = connection.ContentLength;
                                    if (clen < 5000000 && !path.Contains("/YouTube/"))                                       // min of 5 MB
                                    {
                                        clen = 0;
                                    }
                                });
                                if (!Completed)
                                {
                                    print("FAILED MASS");
                                    clen = 0;
                                }
                                print("SET CONNECT ::3");
                            }

                            print("TOTALLLLL::: " + clen);

                            if (clen == 0)
                            {
                                if (isStartProgress.ContainsKey(id))
                                {
                                    isStartProgress.Remove(id);
                                }
                                if (mirror < mirrors.Count - 1 && progress < 2 && rFile.Length() < 1000000)                                   // HAVE MIRRORS LEFT
                                {
                                    mirror++;
                                    removeKeys   = false;
                                    resumeIntent = false;
                                    rFile.Delete();

                                    print("DELETE;;;");
                                }
                                else
                                {
                                    ShowDone(false);
                                }
                            }
                            else
                            {
                                fileLength = clen + (int)total;
                                print("FILELEN:::: " + fileLength);
                                App.SetKey("dlength", "id" + id, fileLength);
                                string fileExtension = MimeTypeMap.GetFileExtensionFromUrl(url);
                                InputStream input    = new BufferedInputStream(connection.InputStream);

                                //long skip = App.GetKey<long>(DOWNLOAD_KEY, id.ToString(), 0);

                                OutputStream output = new FileOutputStream(rFile, true);

                                outputStreams[id] = output;
                                inputStreams[id]  = input;

                                if (isPaused.ContainsKey(id))
                                {
                                    //if (isPaused[id] == 2) {
                                    //    isPaused.Remove(id);
                                    return;
                                    //  }
                                }

                                isPaused[id] = 0;
                                activeIds.Add(id);

                                int m3u8Progress = 0;

                                int cProgress()
                                {
                                    if (isM3u8)
                                    {
                                        return(m3u8Progress);
                                    }
                                    return((int)(total * 100 / fileLength));
                                }
                                progress = cProgress();

                                byte[] data = new byte[1024];
                                // skip;
                                int count;
                                int previousProgress = 0;
                                UpdateDloadNot(total == 0 ? "Download starting" : "Download resuming");

                                System.DateTime lastUpdateTime = System.DateTime.Now;
                                long lastTotal = total;

                                changedPause += UpdateFromId;

                                if (isStartProgress.ContainsKey(id))
                                {
                                    isStartProgress.Remove(id);
                                }
                                bool showDone = true;

                                bool WriteDataUpdate()
                                {
                                    progressDownloads[id] = total;
                                    progress = cProgress();

                                    if (isPaused[id] == 1)
                                    {
                                        print("PAUSEDOWNLOAD");
                                        UpdateProgress();
                                        while (isPaused[id] == 1)
                                        {
                                            Thread.Sleep(100);
                                        }
                                        if (isPaused[id] != 2)
                                        {
                                            UpdateProgress();
                                        }
                                    }
                                    if (isPaused[id] == 2)                                       // DELETE FILE
                                    {
                                        print("DOWNLOAD STOPPED");
                                        ShowDone(false, "Download Stopped");
                                        output.Flush();
                                        output.Close();
                                        input.Close();
                                        outputStreams.Remove(id);
                                        inputStreams.Remove(id);
                                        isPaused.Remove(id);
                                        rFile.Delete();
                                        App.RemoveKey(DOWNLOAD_KEY, id.ToString());
                                        App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString());
                                        App.RemoveKey(App.hasDownloadedFolder, id.ToString());
                                        App.RemoveKey("dlength", "id" + id);
                                        App.RemoveKey("DownloadIds", id.ToString());
                                        changedPause -= UpdateFromId;
                                        activeIds.Remove(id);
                                        removeKeys = true;
                                        OnSomeDownloadFailed?.Invoke(null, EventArgs.Empty);
                                        Thread.Sleep(100);
                                        return(true);
                                    }

                                    if (DateTime.Now.Subtract(lastUpdateTime).TotalSeconds > UPDATE_TIME)
                                    {
                                        lastUpdateTime = DateTime.Now;
                                        long diff      = total - lastTotal;
                                        //  UpdateDloadNot($"{ConvertBytesToAny(diff/UPDATE_TIME, 2,2)}MB/s | {progress}%");
                                        //{ConvertBytesToAny(diff / UPDATE_TIME, 2, 2)}MB/s |
                                        if (progress >= 100)
                                        {
                                            print("DLOADPG DONE!");
                                            ShowDone(true);
                                        }
                                        else
                                        {
                                            UpdateProgress();
                                            // UpdateDloadNot(progress + "%");
                                        }
                                        bytesPerSec = 0;

                                        lastTotal = total;
                                    }

                                    if (progress >= 100 || progress > previousProgress)
                                    {
                                        // Only post progress event if we've made progress.
                                        previousProgress = progress;
                                        if (progress >= 100)
                                        {
                                            print("DLOADPG DONE!");
                                            ShowDone(true);
                                            showDone = false;
                                        }
                                        else
                                        {
                                            // UpdateProgress();
                                            // UpdateDloadNot(progress + "%");
                                        }
                                    }
                                    return(false);
                                }


                                void OnError()
                                {
                                    showDone = false;
                                    ShowDone(false, "Download Failed");
                                }

                                if (isM3u8)
                                {
                                    var links   = ParseM3u8(url, referer);
                                    int counter = 0;
                                    byte[] buffer;
                                    try {
                                        while ((buffer = CloudStreamCore.DownloadByteArrayFromUrl(links[counter], referer)) != null)
                                        {
                                            counter++;
                                            m3u8Progress = counter * 100 / links.Length;
                                            count        = buffer.Length;
                                            total       += count;
                                            bytesPerSec += count;
                                            output.Write(buffer, 0, count);
                                            if (WriteDataUpdate())
                                            {
                                                return;
                                            }
                                        }
                                    }
                                    catch (Exception) {
                                        OnError();
                                    }
                                }
                                else
                                {
                                    try {
                                        while ((count = input.Read(data)) != -1)
                                        {
                                            total       += count;
                                            bytesPerSec += count;

                                            output.Write(data, 0, count);
                                            if (WriteDataUpdate())
                                            {
                                                return;
                                            }
                                        }
                                    }
                                    catch (Exception) {
                                        OnError();
                                    }
                                }

                                if (showDone)
                                {
                                    ShowDone(true);
                                }
                                output.Flush();
                                output.Close();
                                input.Close();
                                outputStreams.Remove(id);
                                inputStreams.Remove(id);
                                activeIds.Remove(id);
                            }
                        }
                        catch (Exception _ex) {
                            print("DOWNLOADURL: " + url);
                            print("DOWNLOAD FAILED BC: " + _ex);
                            if (mirror < mirrors.Count - 1 && progress < 2)                               // HAVE MIRRORS LEFT
                            {
                                mirror++;
                                removeKeys   = false;
                                resumeIntent = false;
                                rFile.Delete();
                            }
                            else
                            {
                                ShowDone(false);
                            }
                        }
                        finally {
                            changedPause -= UpdateFromId;
                            isPaused.Remove(id);
                            if (isStartProgress.ContainsKey(id))
                            {
                                isStartProgress.Remove(id);
                            }
                            if (removeKeys)
                            {
                                //App.RemoveKey(DOWNLOAD_KEY, id.ToString());
                                //App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString());
                            }
                            else
                            {
                                StartT();
                            }
                        }
                    });

                    t.Start();
                }
                StartT();
            }
            catch (Exception) {
            }
        }
Exemple #4
0
        // 1. Create the input
        // 1.1 Create a protocol buffer
        // 1.2 Create the query params
        // 2. Create a connection
        // 3. Do the annotation
        //    This method has two contracts:
        //    1. It should call the two relevant callbacks
        //    2. It must not throw an exception
        /// <summary>Actually try to perform the annotation on the server side.</summary>
        /// <remarks>
        /// Actually try to perform the annotation on the server side.
        /// This is factored out so that we can retry up to 3 times.
        /// </remarks>
        /// <param name="annotation">The annotation we need to fill.</param>
        /// <param name="backend">The backend we are querying against.</param>
        /// <param name="serverURL">The URL of the server we are hitting.</param>
        /// <param name="message">The message we are sending the server (don't need to recompute each retry).</param>
        /// <param name="tries">The number of times we've tried already.</param>
        private void DoAnnotation(Annotation annotation, StanfordCoreNLPClient.Backend backend, URL serverURL, byte[] message, int tries)
        {
            try
            {
                // 1. Set up the connection
                URLConnection connection = serverURL.OpenConnection();
                // 1.1 Set authentication
                if (apiKey != null && apiSecret != null)
                {
                    string userpass  = apiKey + ":" + apiSecret;
                    string basicAuth = "Basic " + Sharpen.Runtime.GetStringForBytes(Base64.GetEncoder().Encode(Sharpen.Runtime.GetBytesForString(userpass)));
                    connection.SetRequestProperty("Authorization", basicAuth);
                }
                // 1.2 Set some protocol-independent properties
                connection.SetDoOutput(true);
                connection.SetRequestProperty("Content-Type", "application/x-protobuf");
                connection.SetRequestProperty("Content-Length", int.ToString(message.Length));
                connection.SetRequestProperty("Accept-Charset", "utf-8");
                connection.SetRequestProperty("User-Agent", typeof(StanfordCoreNLPClient).FullName);
                switch (backend.protocol)
                {
                case "https":
                case "http":
                {
                    // 1.3 Set some protocol-dependent properties
                    ((HttpURLConnection)connection).SetRequestMethod("POST");
                    break;
                }

                default:
                {
                    throw new InvalidOperationException("Haven't implemented protocol: " + backend.protocol);
                }
                }
                // 2. Annotate
                // 2.1. Fire off the request
                connection.Connect();
                connection.GetOutputStream().Write(message);
                connection.GetOutputStream().Flush();
                // 2.2 Await a response
                // -- It might be possible to send more than one message, but we are not going to do that.
                Annotation response = serializer.Read(connection.GetInputStream()).first;
                // 2.3. Copy response over to original annotation
                foreach (Type key in response.KeySet())
                {
                    annotation.Set(key, response.Get(key));
                }
            }
            catch (Exception t)
            {
                // 3. We encountered an error -- retry
                if (tries < 3)
                {
                    log.Warn(t);
                    DoAnnotation(annotation, backend, serverURL, message, tries + 1);
                }
                else
                {
                    throw new Exception(t);
                }
            }
        }