Пример #1
0
        public void download(string options)
        {
            DownloadOptions downloadOptions = null;
            HttpWebRequest webRequest = null;

            try
            {
                downloadOptions = JSON.JsonHelper.Deserialize<DownloadOptions>(options);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
            }
        }
Пример #2
0
        public void cancel(string options)
        {
            Debug.WriteLine("cancel :: " + options);
            string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);
            string   id            = optionStrings[0];
            string   callbackId    = optionStrings[1];

            if (InProcDownloads.ContainsKey(id))
            {
                DownloadRequestState state = InProcDownloads[id];
                if (!state.isCancelled)
                { // prevent multiple callbacks for the same cancel
                    state.isCancelled = true;
                    if (!state.request.HaveResponse)
                    {
                        state.request.Abort();
                        InProcDownloads.Remove(id);
                        //callbackId = state.options.CallbackId;
                        //state = null;
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                               new SyncError(Sync.AbortError)),
                                              state.options.CallbackId);
                    }
                }
            }
            else
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception?
            }
        }
        private string GetStatusText(DownloadRequestState status)
        {
            switch (status)
            {
            case DownloadRequestState.Initialized:
                return(AppResources.Page_Downloads_Status_Initialized);

            case DownloadRequestState.Downloading:
                return(AppResources.Page_Downloads_Status_Downloading);

            case DownloadRequestState.Paused:
                return(AppResources.Page_Downloads_Status_Paused);

            case DownloadRequestState.Copying:
                return(AppResources.Page_Downloads_Status_Copying);

            case DownloadRequestState.Removing:
                return(AppResources.Page_Downloads_Status_Removing);

            case DownloadRequestState.Completed:
                return(AppResources.Page_Downloads_Status_Completed);

            case DownloadRequestState.Error:
                return(AppResources.Page_Downloads_Status_Error);

            default:
                return(status.ToString());
            }
        }
Пример #4
0
        public void download(string options)
        {
            DownloadOptions downloadOptions = null;
            HttpWebRequest  webRequest      = null;

            try
            {
                downloadOptions = JSON.JsonHelper.Deserialize <DownloadOptions>(options);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
            }
        }
Пример #5
0
        /// <summary>
        /// Reads response into FileUploadResult
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;

            try
            {
                HttpWebRequest webRequest = reqState.request;
                string         callbackId = reqState.options.CallbackId;

                if (InProcDownloads.ContainsKey(reqState.options.Id))
                {
                    InProcDownloads.Remove(reqState.options.Id);
                }

                using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
                {
                    using (Stream streamResponse = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(streamResponse))
                        {
                            string responseString = streamReader.ReadToEnd();
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileUploadResult(bytesSent, (long)response.StatusCode, responseString)));
                            });
                        }
                    }
                }
            }
            catch (WebException webex)
            {
                // TODO: probably need better work here to properly respond with all http status codes back to JS
                // Right now am jumping through hoops just to detect 404.
                if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound) ||
                    webex.Status == WebExceptionStatus.UnknownError)
                {
                    int statusCode            = (int)((HttpWebResponse)webex.Response).StatusCode;
                    FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), reqState.options.CallbackId);
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                           new FileTransferError(ConnectionError)),
                                          reqState.options.CallbackId);
                }
            }
            catch (Exception ex)
            {
                FileTransferError transferError = new FileTransferError(ConnectionError, reqState.options.Server, reqState.options.FilePath, 403);
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, transferError), reqState.options.CallbackId);
            }
        }
Пример #6
0
        public void abort(string options)
        {
            string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);
            string   id            = optionStrings[0];
            string   callbackId    = optionStrings[1];

            if (InProcDownloads.ContainsKey(id))
            {
                DownloadRequestState state = InProcDownloads[id];
                state.request.Abort();
                state.request = null;

                callbackId = state.options.CallbackId;
                InProcDownloads.Remove(id);
                state = null;
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileTransfer.AbortError)),
                                      callbackId);
            }
            else
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception?
            }
        }
Пример #7
0
        public void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest  webRequest      = null;
            string          callbackId;

            try
            {
                string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);

                downloadOptions          = new TransferOptions();
                downloadOptions.Url      = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2], out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id         = optionStrings[3];
                downloadOptions.Headers    = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
            }
            //catch (WebException webEx)
            //{

            //}
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
            }
        }
Пример #8
0
        /// <summary>
        /// sends a file to a server
        /// </summary>
        /// <param name="options">Upload options</param>
        /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
        public void upload(string options)
        {
            options = options.Replace("{}", ""); // empty objects screw up the Deserializer
            string callbackId = "";

            TransferOptions uploadOptions = null;
            HttpWebRequest  webRequest    = null;

            try
            {
                try
                {
                    string[] args = JSON.JsonHelper.Deserialize <string[]>(options);
                    uploadOptions          = new TransferOptions();
                    uploadOptions.FilePath = args[0];
                    uploadOptions.Server   = args[1];
                    uploadOptions.FileKey  = args[2];
                    uploadOptions.FileName = args[3];
                    uploadOptions.MimeType = args[4];
                    uploadOptions.Params   = args[5];


                    bool trustAll = false;
                    bool.TryParse(args[6], out trustAll);
                    uploadOptions.TrustAllHosts = trustAll;

                    bool doChunked = false;
                    bool.TryParse(args[7], out doChunked);
                    uploadOptions.ChunkedMode = doChunked;

                    //8 : Headers
                    //9 : id
                    //10: method

                    uploadOptions.Headers = args[8];
                    uploadOptions.Id      = args[9];
                    uploadOptions.Method  = args[10];

                    uploadOptions.CallbackId = callbackId = args[11];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Uri serverUri;
                try
                {
                    serverUri = new Uri(uploadOptions.Server);
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
                    return;
                }
                webRequest             = (HttpWebRequest)WebRequest.Create(serverUri);
                webRequest.ContentType = "multipart/form-data;boundary=" + Boundary;
                webRequest.Method      = uploadOptions.Method;

                if (!string.IsNullOrEmpty(uploadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(uploadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                DownloadRequestState reqState = new DownloadRequestState();
                reqState.options = uploadOptions;
                reqState.request = webRequest;

                InProcDownloads[uploadOptions.Id] = reqState;


                webRequest.BeginGetRequestStream(WriteCallback, reqState);
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
            }
        }
Пример #9
0
        public void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest webRequest = null;
            string callbackId;

            try
            {
                // source, target, trustAllHosts, this._id, headers
                string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);

                downloadOptions = new TransferOptions();
                downloadOptions.Url = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2],out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id = optionStrings[3];
                downloadOptions.Headers = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//","");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int bytesRead = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
                    if (entry != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                      new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    // eat it
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
Пример #10
0
        /// <summary>
        /// sends a file to a server
        /// </summary>
        /// <param name="options">Upload options</param>
        /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
        public void upload(string options)
        {
            options = options.Replace("{}", ""); // empty objects screw up the Deserializer
            string callbackId = "";

            TransferOptions uploadOptions = null;
            HttpWebRequest  webRequest    = null;

            try
            {
                try
                {
                    string[] args = JSON.JsonHelper.Deserialize <string[]>(options);
                    uploadOptions          = new TransferOptions();
                    uploadOptions.FilePath = args[0];
                    uploadOptions.Server   = args[1];
                    uploadOptions.FileKey  = args[2];
                    uploadOptions.FileName = args[3];
                    uploadOptions.MimeType = args[4];
                    uploadOptions.Params   = args[5];

                    bool trustAll = false;
                    bool.TryParse(args[6], out trustAll);
                    uploadOptions.TrustAllHosts = trustAll;

                    bool doChunked = false;
                    bool.TryParse(args[7], out doChunked);
                    uploadOptions.ChunkedMode = doChunked;

                    //8 : Headers
                    //9 : id
                    //10: method

                    uploadOptions.Headers = args[8];
                    uploadOptions.Id      = args[9];
                    uploadOptions.Method  = args[10];

                    uploadOptions.Cookies    = args[11];
                    uploadOptions.CallbackId = callbackId = args[12];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Uri serverUri;
                try
                {
                    serverUri = new Uri(uploadOptions.Server);
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
                    return;
                }
                webRequest             = (HttpWebRequest)WebRequest.Create(serverUri);
                webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
                webRequest.Method      = uploadOptions.Method;
                var cookies       = (uploadOptions.Cookies ?? "").Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                var cookiesHeader = "";
                if (cookies.Length > 0)
                {
                    foreach (var c in cookies)
                    {
                        var cookie = (c ?? "").Split(new[] { ';' }, StringSplitOptions.None);
                        if (cookie.Length >= 4)
                        {
                            //if (webRequest.CookieContainer == null)
                            //{
                            //    webRequest.CookieContainer = new CookieContainer();
                            //}
                            //var cookieItem = new Cookie(cookie[0], cookie[1], cookie[2], cookie[3]);
                            //cookieItem.Expires = new DateTime(2100, 1, 1);
                            //webRequest.CookieContainer.Add(serverUri, cookieItem);
                            cookiesHeader = (string.IsNullOrEmpty(cookiesHeader) ? "" : "; ")
                                            + cookie[0] + "=" + cookie[1];
                        }
                    }
                }
                if (!string.IsNullOrEmpty(cookiesHeader))
                {
                    webRequest.Headers["Cookie"] = cookiesHeader;
                }

                if (!string.IsNullOrEmpty(uploadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(uploadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                DownloadRequestState reqState = new DownloadRequestState();
                reqState.options = uploadOptions;
                reqState.request = webRequest;

                InProcDownloads[uploadOptions.Id] = reqState;

                webRequest.BeginGetRequestStream(uploadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void downloadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       request  = reqState.request;

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // create the file if not exists
                    if (!isoFile.FileExists(reqState.options.FilePath))
                    {
                        var file = isoFile.CreateFile(reqState.options.FilePath);
                        file.Close();
                    }

                    using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                    {
                        long totalBytes = response.ContentLength;
                        int  bytesRead  = 0;
                        using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            using (BinaryWriter writer = new BinaryWriter(fileStream))
                            {
                                int    BUFFER_SIZE = 1024;
                                byte[] buffer;

                                while (true)
                                {
                                    buffer = reader.ReadBytes(BUFFER_SIZE);
                                    // fire a progress event ?
                                    bytesRead += buffer.Length;
                                    if (buffer.Length > 0)
                                    {
                                        writer.Write(buffer);
                                    }
                                    else
                                    {
                                        writer.Close();
                                        reader.Close();
                                        fileStream.Close();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                WPCordovaClassLib.Cordova.Commands.File.FileEntry entry = new WPCordovaClassLib.Cordova.Commands.File.FileEntry(reqState.options.FilePath);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
            }
            catch (IsolatedStorageException)
            {
                // Trying to write the file somewhere within the IsoStorage.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)));
            }
            catch (SecurityException)
            {
                // Trying to write the file somewhere not allowed.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)));
            }
            catch (WebException webex)
            {
                // TODO: probably need better work here to properly respond with all http status codes back to JS
                // Right now am jumping through hoops just to detect 404.
                if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound) || webex.Status == WebExceptionStatus.UnknownError)
                {
                    // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!!
                    // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
                    // FACEPALM
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError, null, null, 404)));
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)));
                }
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)));
            }
        }
Пример #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void downloadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       request  = reqState.request;

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // create the file if not exists
                    if (!isoFile.FileExists(reqState.options.FilePath))
                    {
                        var file = isoFile.CreateFile(reqState.options.FilePath);
                        file.Close();
                    }

                    using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                    {
                        long totalBytes = response.ContentLength;
                        int  bytesRead  = 0;
                        using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            using (BinaryWriter writer = new BinaryWriter(fileStream))
                            {
                                int    BUFFER_SIZE = 1024;
                                byte[] buffer;

                                while (true)
                                {
                                    buffer = reader.ReadBytes(BUFFER_SIZE);
                                    // fire a progress event ?
                                    bytesRead += buffer.Length;
                                    if (buffer.Length > 0)
                                    {
                                        writer.Write(buffer);
                                    }
                                    else
                                    {
                                        writer.Close();
                                        reader.Close();
                                        fileStream.Close();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                WP7CordovaClassLib.Cordova.Commands.File.FileEntry entry = new WP7CordovaClassLib.Cordova.Commands.File.FileEntry(reqState.options.FilePath);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
            }
            catch (IsolatedStorageException)
            {
                // DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(INVALID_MODIFICATION_ERR)));
            }
            catch (SecurityException)
            {
                //DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(SECURITY_ERR)));
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new File.ErrorCode(File.NOT_FOUND_ERR)));
            }
        }
Пример #13
0
        /// <summary>
        /// sends a file to a server
        /// </summary>
        /// <param name="options">Upload options</param>
        /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
        public void upload(string options)
        {
            options = options.Replace("{}", ""); // empty objects screw up the Deserializer
            string callbackId = "";

            TransferOptions uploadOptions = null;
            HttpWebRequest  webRequest    = null;

            try
            {
                try
                {
                    string[] args = JSON.JsonHelper.Deserialize <string[]>(options);
                    uploadOptions          = new TransferOptions();
                    uploadOptions.FilePath = args[0];
                    uploadOptions.Server   = args[1];
                    uploadOptions.FileKey  = args[2];
                    uploadOptions.FileName = args[3];
                    uploadOptions.MimeType = args[4];
                    uploadOptions.Params   = args[5];

                    bool trustAll = false;
                    bool.TryParse(args[6], out trustAll);
                    uploadOptions.TrustAllHosts = trustAll;

                    bool doChunked = false;
                    bool.TryParse(args[7], out doChunked);
                    uploadOptions.ChunkedMode = doChunked;

                    //8 : Headers
                    //9 : id
                    //10: method

                    uploadOptions.Headers = args[8];
                    uploadOptions.Id      = args[9];
                    uploadOptions.Method  = args[10];

                    uploadOptions.CallbackId = callbackId = args[11];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Uri serverUri;
                try
                {
                    serverUri = new Uri(uploadOptions.Server);
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
                    return;
                }
                webRequest             = (HttpWebRequest)WebRequest.Create(serverUri);
                webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
                webRequest.Method      = uploadOptions.Method;

                DownloadRequestState reqState = new DownloadRequestState();
                InProcDownloads[uploadOptions.Id] = reqState;
                reqState.options = uploadOptions;
                reqState.request = webRequest;

                try
                {
                    // Associate cookies with the request
                    // This is an async call, so we need to await it in order to preserve proper control flow
                    Task cookieTask = CopyCookiesFromWebBrowser(webRequest);
                    cookieTask.Wait();
                }
                catch (AggregateException ae)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                           new FileTransferError(FileTransfer.ConnectionError, uploadOptions.FilePath, uploadOptions.Server, 0, ae.InnerException.Message)));
                    return;
                }

                if (!string.IsNullOrEmpty(uploadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(uploadOptions.Headers);
                    if (headers != null)
                    {
                        foreach (string key in headers.Keys)
                        {
                            webRequest.Headers[key] = headers[key];
                        }
                    }
                }

                webRequest.BeginGetRequestStream(uploadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
            }
        }
Пример #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private async void downloadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       request  = reqState.request;
            string filepath = reqState.options.FilePath;
            string filename;

            if (String.IsNullOrEmpty(filepath))
            {
                return;
            }

            string[] split = filepath.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
            if (split.Length < 1)
            {
                return;
            }
            else
            {
                filename = split[split.Length - 1];
            }
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                StorageFolder storagefolder = await StorageFolder.GetFolderFromPathAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path);

                await storagefolder.CreateFileAsync(filename);

                StorageFile storagefile = await StorageFile.GetFileFromPathAsync(storagefolder.Path + "\\" + filename);

                Stream fileStream = await storagefile.OpenStreamForWriteAsync();

                long totalBytes = response.ContentLength;
                int  bytesRead  = 0;
                using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                {
                    using (BinaryWriter writer = new BinaryWriter(fileStream))
                    {
                        int    BUFFER_SIZE = 1024;
                        byte[] buffer;

                        while (true)
                        {
                            buffer = reader.ReadBytes(BUFFER_SIZE);
                            // fire a progress event ?
                            bytesRead += buffer.Length;
                            if (buffer.Length > 0)
                            {
                                writer.Write(buffer);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                File.FileEntry entry = new File.FileEntry(true, storagefolder.Path + "\\" + filename);
                DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
            }


            catch (WebException webex)
            {
                // TODO: probably need better work here to properly respond with all http status codes back to JS
                // Right now am jumping through hoops just to detect 404.
                if ((((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound) || (webex.Status == WebExceptionStatus.UnknownError))
                {
                    // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!!
                    // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
                    // FACEPALM
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError, null, null, 404)));
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)));
                }
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)));
            }
        }
Пример #15
0
        public void sync(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest webRequest = null;
            string callbackId;

            try
            {
                // options.src, options.type, options.headers, options.id
                string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);

                downloadOptions = new TransferOptions();
                downloadOptions.Url = optionStrings[0];

                downloadOptions.Id = optionStrings[1];

                downloadOptions.FilePath = "content_sync/downloads/" + downloadOptions.Id;

                if (String.Equals(optionStrings[2], "replace"))
                {
                    downloadOptions.Type = Replace;
                }
                else
                {
                    downloadOptions.Type = Merge;
                }

                downloadOptions.Headers = optionStrings[3];

                bool copyCordovaAssets = false;
                bool.TryParse(optionStrings[4], out copyCordovaAssets);
                downloadOptions.CopyCordovaAssets = copyCordovaAssets;

                bool copyRootApp = false;
                bool.TryParse(optionStrings[5], out copyRootApp);
                downloadOptions.CopyRootApp = copyRootApp;

                downloadOptions.Timeout = Convert.ToInt32(optionStrings[6]);

                bool trustAll = false;
                bool.TryParse(optionStrings[7], out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Manifest = optionStrings[8];

                downloadOptions.CallbackId = callbackId = optionStrings[optionStrings.Length-1];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // not sure if we still need this
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//","");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Create, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int bytesRead = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchSyncProgress(bytesRead, totalBytes, 1, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    string result = "{ \"localPath\": \"" + downloadOptions.FilePath + "\" , \"Id\" : \"" + downloadOptions.Id + "\"}";
                    if (result != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, 0), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                      new SyncError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                      new SyncError(InvalidUrlError, downloadOptions.Url, null, 0)));
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new SyncProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private async void downloadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       request  = reqState.request;

            string callbackId = reqState.options.CallbackId;

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                // send a progress change event
                DispatchFileTransferProgress(0, response.ContentLength, callbackId);
                StorageFile storageFile1;
                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // create any directories in the path that do not exist
                    string directoryName = getDirectoryName(reqState.options.FilePath);
                    if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                    {
                        isoFile.CreateDirectory(directoryName);
                    }

                    // create the file if not exists
                    if (!isoFile.FileExists(reqState.options.FilePath))
                    {
                        var file = isoFile.CreateFile(reqState.options.FilePath);
                        file.Close();
                    }

                    using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.OpenOrCreate, FileAccess.Write, isoFile))
                    {
                        long totalBytes = response.ContentLength;
                        int  bytesRead  = 0;

                        using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            using (BinaryWriter writer = new BinaryWriter(fileStream))
                            {
                                int    BUFFER_SIZE = 1024;
                                byte[] buffer;

                                while (true)
                                {
                                    buffer = reader.ReadBytes(BUFFER_SIZE);
                                    // fire a progress event ?
                                    bytesRead += buffer.Length;
                                    if (buffer.Length > 0 && !reqState.isCancelled)
                                    {
                                        writer.Write(buffer);
                                        DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
                                        System.Threading.Thread.Sleep(1);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                writer.Close();
                                reader.Close();
                                fileStream.Close();
                                StorageFolder installedLocation = Package.Current.InstalledLocation;
                                StorageFile   storageFile       = await installedLocation.CreateFileAsync(Path.GetFileName(reqState.options.FilePath), CreationCollisionOption.OpenIfExists);

                                storageFile1 = storageFile;
                                Stream stream = await storageFile1.OpenStreamForWriteAsync();

                                try
                                {
                                    stream.Write(buffer, 0, (int)buffer.Length);
                                }
                                finally
                                {
                                    if (stream != null)
                                    {
                                        stream.Dispose();
                                    }
                                }

                                StorageFolder local      = Windows.Storage.ApplicationData.Current.LocalFolder;
                                StorageFile   storedFile = await local.GetFileAsync(Path.GetFileName(reqState.options.FilePath));

                                Deployment.Current.Dispatcher.BeginInvoke(async() =>
                                {
                                    {
                                        await Windows.System.Launcher.LaunchFileAsync(storedFile);
                                    }
                                });

                                var options = new Windows.System.LauncherOptions();
                                options.DisplayApplicationPicker = true;
                            }
                        }
                    }
                    if (reqState.isCancelled)
                    {
                        isoFile.DeleteFile(reqState.options.FilePath);
                    }
                }

                if (reqState.isCancelled)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)),
                                          callbackId);
                }
                else
                {
                    File.FileEntry entry = new File.FileEntry(reqState.options.FilePath);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
                }
            }
            catch (IsolatedStorageException)
            {
                // Trying to write the file somewhere within the IsoStorage.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
                                      callbackId);
            }
            catch (SecurityException)
            {
                // Trying to write the file somewhere not allowed.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
                                      callbackId);
            }
            catch (WebException webex)
            {
                // TODO: probably need better work here to properly respond with all http status codes back to JS
                // Right now am jumping through hoops just to detect 404.
                HttpWebResponse response = (HttpWebResponse)webex.Response;
                if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) ||
                    webex.Status == WebExceptionStatus.UnknownError)
                {
                    // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!!
                    // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
                    // FACEPALM
                    // Or just cast it to an int, whiner ... -jm
                    int    statusCode = (int)response.StatusCode;
                    string body       = "";

                    using (Stream streamResponse = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(streamResponse))
                        {
                            body = streamReader.ReadToEnd();
                        }
                    }
                    FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError),
                                          callbackId);
                }
                else
                {
                    lock (reqState)
                    {
                        if (!reqState.isCancelled)
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                                   new FileTransferError(ConnectionError)),
                                                  callbackId);
                        }
                        else
                        {
                            Debug.WriteLine("It happened");
                        }
                    }
                }
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new FileTransferError(FileNotFoundError)),
                                      callbackId);
            }

            System.Threading.Thread.Sleep(1000);
            if (InProcDownloads.ContainsKey(reqState.options.Id))
            {
                InProcDownloads.Remove(reqState.options.Id);
            }
        }
Пример #17
0
        /// <summary>
        /// Read file from Isolated Storage and sends it to server
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void WriteCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState   = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       webRequest = reqState.request;
            string callbackId = reqState.options.CallbackId;

            try
            {
                using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult)))
                {
                    string lineStart        = "--";
                    string lineEnd          = Environment.NewLine;
                    byte[] boundaryBytes    = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd);
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd;

                    if (!string.IsNullOrEmpty(reqState.options.Params))
                    {
                        Dictionary <string, string> paramMap = parseHeaders(reqState.options.Params);
                        foreach (string key in paramMap.Keys)
                        {
                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                            string formItem      = string.Format(formdataTemplate, key, paramMap[key]);
                            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
                            requestStream.Write(formItemBytes, 0, formItemBytes.Length);
                        }
                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    }
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isoFile.FileExists(reqState.options.FilePath))
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0)));
                            return;
                        }

                        using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile))
                        {
                            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd;
                            string header         = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType);
                            byte[] headerBytes    = System.Text.Encoding.UTF8.GetBytes(header);
                            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                            requestStream.Write(headerBytes, 0, headerBytes.Length);
                            byte[] buffer    = new byte[4096];
                            int    bytesRead = 0;

                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                // TODO: Progress event
                                requestStream.Write(buffer, 0, bytesRead);
                                bytesSent += bytesRead;
                            }
                        }
                        byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd);
                        requestStream.Write(endRequest, 0, endRequest.Length);
                    }
                }
                // webRequest

                webRequest.BeginGetResponse(ReadCallback, reqState);
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
            }
        }
Пример #18
0
        public void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest webRequest = null;
            string callbackId;

            try
            {
                string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);

                downloadOptions = new TransferOptions();
                downloadOptions.Url = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2],out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id = optionStrings[3];
                downloadOptions.Headers = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];

            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
            }
            //catch (WebException webEx)
            //{

            //}
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
            }
        }
Пример #19
0
        public void sync(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest  webRequest      = null;
            string          callbackId;

            try
            {
                // options.src, options.type, options.headers, options.id
                string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);

                downloadOptions     = new TransferOptions();
                downloadOptions.Url = optionStrings[0];

                downloadOptions.Id = optionStrings[1];

                downloadOptions.FilePath = "content_sync/downloads/" + downloadOptions.Id;

                if (String.Equals(optionStrings[2], "replace"))
                {
                    downloadOptions.Type = Replace;
                }
                else
                {
                    downloadOptions.Type = Merge;
                }

                downloadOptions.Headers = optionStrings[3];

                bool copyCordovaAssets = false;
                bool.TryParse(optionStrings[4], out copyCordovaAssets);
                downloadOptions.CopyCordovaAssets = copyCordovaAssets;

                bool copyRootApp = false;
                bool.TryParse(optionStrings[5], out copyRootApp);
                downloadOptions.CopyRootApp = copyRootApp;

                downloadOptions.Timeout = Convert.ToInt32(optionStrings[6]);

                bool trustAll = false;
                bool.TryParse(optionStrings[7], out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Manifest = optionStrings[8];

                downloadOptions.CallbackId = callbackId = optionStrings[optionStrings.Length - 1];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // not sure if we still need this
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", "");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri      = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Create, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int  bytesRead  = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int    BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchSyncProgress(bytesRead, totalBytes, 1, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    string result = "{ \"localPath\": \"" + downloadOptions.FilePath + "\" , \"Id\" : \"" + downloadOptions.Id + "\"}";
                    if (result != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, 0), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new SyncError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                           new SyncError(InvalidUrlError, downloadOptions.Url, null, 0)));
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new SyncProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId   = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
        public async void download(string options)
        {
            TransferOptions downloadOptions = null;
            HttpWebRequest  webRequest      = null;
            string          callbackId;

            try
            {
                // source, target, trustAllHosts, this._id, headers
                string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options);

                downloadOptions          = new TransferOptions();
                downloadOptions.Url      = optionStrings[0];
                downloadOptions.FilePath = optionStrings[1];

                bool trustAll = false;
                bool.TryParse(optionStrings[2], out trustAll);
                downloadOptions.TrustAllHosts = trustAll;

                downloadOptions.Id         = optionStrings[3];
                downloadOptions.Headers    = optionStrings[4];
                downloadOptions.CallbackId = callbackId = optionStrings[5];
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                // is the URL a local app file?
                if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
                {
                    using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", "");

                        // pre-emptively create any directories in the FilePath that do not exist
                        string directoryName = getDirectoryName(downloadOptions.FilePath);
                        if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                        {
                            isoFile.CreateDirectory(directoryName);
                        }

                        // just copy from one area of iso-store to another ...
                        if (isoFile.FileExists(downloadOptions.Url))
                        {
                            isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
                        }
                        else
                        {
                            // need to unpack resource from the dll
                            Uri uri      = new Uri(cleanUrl, UriKind.Relative);
                            var resource = Application.GetResourceStream(uri);

                            if (resource != null)
                            {
                                // create the file destination
                                if (!isoFile.FileExists(downloadOptions.FilePath))
                                {
                                    var destFile = isoFile.CreateFile(downloadOptions.FilePath);
                                    destFile.Close();
                                }

                                using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                                {
                                    long totalBytes = resource.Stream.Length;
                                    int  bytesRead  = 0;
                                    using (BinaryReader reader = new BinaryReader(resource.Stream))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            int    BUFFER_SIZE = 1024;
                                            byte[] buffer;

                                            while (true)
                                            {
                                                buffer = reader.ReadBytes(BUFFER_SIZE);
                                                // fire a progress event ?
                                                bytesRead += buffer.Length;
                                                if (buffer.Length > 0)
                                                {
                                                    writer.Write(buffer);
                                                    DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
                                                }
                                                else
                                                {
                                                    writer.Close();
                                                    reader.Close();
                                                    fileStream.Close();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
                    if (entry != null)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
                    }

                    return;
                }
                else
                {
                    // otherwise it is web-bound, we will actually download it
                    //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
                    webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
                }
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
                return;
            }

            if (downloadOptions != null && webRequest != null)
            {
                DownloadRequestState state = new DownloadRequestState();
                state.options = downloadOptions;
                state.request = webRequest;
                InProcDownloads[downloadOptions.Id] = state;

                // Associate cookies with the request
                // This is an async call, so we need to await it in order to preserve proper control flow
                await CopyCookiesFromWebBrowser(webRequest);

                if (!string.IsNullOrEmpty(downloadOptions.Headers))
                {
                    Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                try
                {
                    webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
                }
                catch (WebException)
                {
                    // eat it
                }
                // dispatch an event for progress ( 0 )
                lock (state)
                {
                    if (!state.isCancelled)
                    {
                        var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
                        plugRes.KeepCallback = true;
                        plugRes.CallbackId   = callbackId;
                        DispatchCommandResult(plugRes, callbackId);
                    }
                }
            }
        }
Пример #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void downloadCallback(IAsyncResult asynchronousResult)
        {
            DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
            HttpWebRequest       request  = reqState.request;

            string callbackId = reqState.options.CallbackId;

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                // send a progress change event
                DispatchSyncProgress(0, response.ContentLength, 0, callbackId);

                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // create any directories in the path that do not exist
                    string directoryName = getDirectoryName(reqState.options.FilePath);
                    if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
                    {
                        isoFile.CreateDirectory(directoryName);
                    }

                    // make sure we delete the file if it exists
                    if (isoFile.FileExists(reqState.options.FilePath))
                    {
                        isoFile.DeleteFile(reqState.options.FilePath);
                    }

                    if (!isoFile.FileExists(reqState.options.FilePath))
                    {
                        var file = isoFile.CreateFile(reqState.options.FilePath);
                        file.Close();
                    }

                    using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile))
                    {
                        long totalBytes = response.ContentLength;
                        int  bytesRead  = 0;
                        using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            using (BinaryWriter writer = new BinaryWriter(fileStream))
                            {
                                int    BUFFER_SIZE = 1024;
                                byte[] buffer;

                                while (true)
                                {
                                    buffer = reader.ReadBytes(BUFFER_SIZE);
                                    // fire a progress event ?
                                    bytesRead += buffer.Length;
                                    if (buffer.Length > 0 && !reqState.isCancelled)
                                    {
                                        writer.Write(buffer);
                                        DispatchSyncProgress(bytesRead, totalBytes, 1, callbackId);
                                    }
                                    else
                                    {
                                        writer.Close();
                                        reader.Close();
                                        fileStream.Close();
                                        break;
                                    }
                                    System.Threading.Thread.Sleep(1);
                                }
                            }
                        }
                    }
                    if (reqState.isCancelled)
                    {
                        isoFile.DeleteFile(reqState.options.FilePath);
                    }
                }

                if (reqState.isCancelled)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new SyncError(AbortError)),
                                          callbackId);
                }
                else
                {
                    UnZip  unzipper     = new UnZip();
                    string destFilePath = "www/" + reqState.options.FilePath;
                    // at this point, bytesLoaded = bytesTotal so we'll just put the as '1'
                    DispatchSyncProgress(1, 1, 2, callbackId);
                    unzipper.unzip(reqState.options.FilePath, destFilePath, reqState.options.Type);

                    if (reqState.options.CopyCordovaAssets)
                    {
                        copyCordovaAssets(destFilePath);
                    }

                    DispatchSyncProgress(1, 1, 3, callbackId);
                    string result = "{ \"localPath\": \"" + reqState.options.FilePath + "\" , \"Id\" : \"" + reqState.options.Id + "\"}";
                    DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId);
                }
            }
            catch (IsolatedStorageException)
            {
                // Trying to write the file somewhere within the IsoStorage.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new SyncError(UnzipError)),
                                      callbackId);
            }
            catch (SecurityException)
            {
                // Trying to write the file somewhere not allowed.
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new SyncError(UnzipError)),
                                      callbackId);
            }
            catch (WebException webex)
            {
                // TODO: probably need better work here to properly respond with all http status codes back to JS
                // Right now am jumping through hoops just to detect 404.
                HttpWebResponse response = (HttpWebResponse)webex.Response;
                if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) ||
                    webex.Status == WebExceptionStatus.UnknownError)
                {
                    // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!!
                    // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
                    // FACEPALM
                    // Or just cast it to an int, whiner ... -jm
                    int    statusCode = (int)response.StatusCode;
                    string body       = "";

                    using (Stream streamResponse = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(streamResponse))
                        {
                            body = streamReader.ReadToEnd();
                        }
                    }
                    SyncError ftError = new SyncError(ConnectionError, null, null, statusCode, body);
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError),
                                          callbackId);
                }
                else
                {
                    lock (reqState)
                    {
                        if (!reqState.isCancelled)
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                                   new SyncError(ConnectionError)),
                                                  callbackId);
                        }
                        else
                        {
                            Debug.WriteLine("It happened");
                        }
                    }
                }
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
                                                       new SyncError(UnzipError)),
                                      callbackId);
            }

            //System.Threading.Thread.Sleep(1000);
            if (InProcDownloads.ContainsKey(reqState.options.Id))
            {
                InProcDownloads.Remove(reqState.options.Id);
            }
        }
Пример #22
0
        /// <summary>
        /// sends a file to a server
        /// </summary>
        /// <param name="options">Upload options</param>
        /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
        public void upload(string options)
        {
            options = options.Replace("{}", ""); // empty objects screw up the Deserializer
            string callbackId = "";

            TransferOptions uploadOptions = null;
            HttpWebRequest webRequest = null;

            try
            {
                try
                {
                    string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
                    uploadOptions = new TransferOptions();
                    uploadOptions.FilePath = args[0];
                    uploadOptions.Server = args[1];
                    uploadOptions.FileKey = args[2];
                    uploadOptions.FileName = args[3];
                    uploadOptions.MimeType = args[4];
                    uploadOptions.Params = args[5];

                    bool trustAll = false;
                    bool.TryParse(args[6],out trustAll);
                    uploadOptions.TrustAllHosts = trustAll;

                    bool doChunked = false;
                    bool.TryParse(args[7], out doChunked);
                    uploadOptions.ChunkedMode = doChunked;

                    //8 : Headers
                    //9 : id
                    //10: method

                    uploadOptions.Headers = args[8];
                    uploadOptions.Id = args[9];
                    uploadOptions.Method = args[10];

                    uploadOptions.CallbackId = callbackId = args[11];
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                    return;
                }

                Uri serverUri;
                try
                {
                    serverUri = new Uri(uploadOptions.Server);
                }
                catch (Exception)
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
                    return;
                }
                webRequest = (HttpWebRequest)WebRequest.Create(serverUri);
                webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
                webRequest.Method = uploadOptions.Method;

                if (!string.IsNullOrEmpty(uploadOptions.Headers))
                {
                    Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers);
                    foreach (string key in headers.Keys)
                    {
                        webRequest.Headers[key] = headers[key];
                    }
                }

                DownloadRequestState reqState = new DownloadRequestState();
                reqState.options = uploadOptions;
                reqState.request = webRequest;

                InProcDownloads[uploadOptions.Id] = reqState;

                webRequest.BeginGetRequestStream(uploadCallback, reqState);
            }
            catch (Exception /*ex*/)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId);
            }
        }
Пример #23
0
 public EventArgsState(DownloadRequestState state)
 {
     State = state;
 }
Пример #24
0
 private static void Raise(this DownloadStateEventHandler handler, BackgroundTransferRequest request, DownloadRequestState state)
 {
     if (request != null && handler != null)
     {
         handler(request, new EventArgsState(state));
     }
 }