public void CommitUploadStream(params object[] arg) { // convert the args var svc = arg[0] as DavService; var uploadRequest = arg[1] as HttpWebRequest; var fileSystemEntry = arg[2] as BaseFileEntry; var requestStream = arg[3] as WebRequestStream; // check if all data was written into stream if (requestStream.WrittenBytes != uploadRequest.ContentLength) { // nothing todo request was aborted return; } // perform the request int code; WebException e; svc.PerformWebRequest(uploadRequest, null, out code, out e); // check the ret value if (!HttpUtilityEx.IsSuccessCode(code)) { SharpBoxException.ThrowSharpBoxExceptionBasedOnHttpErrorCode(uploadRequest, (HttpStatusCode)code, e); } // adjust the lengt fileSystemEntry.Length = uploadRequest.ContentLength; }
public String Format(IHostPwEntry hostPwEntry) { PuttyOptions options = null; bool success = PuttyOptions.TryParse(hostPwEntry.AdditionalOptions, out options); StringBuilder sb = new StringBuilder(String.Format("\"{0}\" scp://{1}", ExecutablePath, hostPwEntry.GetUsername())); if (!success || (success && !options.HasKeyFile())) { // See: https://winscp.net/eng/docs/session_url > Special Characters sb.AppendFormat(":\"{0}\"", HttpUtilityEx.UrlEncodeUpperCase(hostPwEntry.GetPassword())); } sb.AppendFormat("@{0}", hostPwEntry.IPAddress); if (success && options.Port.HasValue) { sb.AppendFormat(":{0}", options.Port); } // Starting with version 5.6 a passphrase for the private key file can be provided. // See: https://winscp.net/eng/docs/faq_passphrase if (success && options.HasKeyFile()) { sb.AppendFormat(" -privatekey=\"{0}\" -passphrase=\"{1}\"", options.KeyFilePath, hostPwEntry.GetPassword()); } return(sb.ToString()); }
/// <summary> /// This method removes a specific resource from a webdav share /// </summary> /// <param name="session"></param> /// <param name="entry"></param> public override Boolean DeleteResource(IStorageProviderSession session, ICloudFileSystemEntry entry) { // get the credentials var creds = session.SessionToken as ICredentials; // build url var uriString = GetResourceUrl(session, entry, null); var uri = new Uri(uriString); // create the service var svc = new DavService(); // create the webrequest int errorCode; WebException e; svc.PerformSimpleWebCall(uri.ToString(), WebRequestMethodsEx.WebDAV.Delete, creds.GetCredential(null, null), null, out errorCode, out e); if (!HttpUtilityEx.IsSuccessCode(errorCode)) { return(false); } // remove from parent var parentDir = entry.Parent as BaseDirectoryEntry; if (parentDir != null) { parentDir.RemoveChildById(entry.Id); } return(true); }
/// <summary> /// This method generates a session to a webdav share via username and password /// </summary> /// <param name="token"></param> /// <param name="configuration"></param> /// <returns></returns> public override IStorageProviderSession CreateSession(ICloudStorageAccessToken token, ICloudStorageConfiguration configuration) { // cast the creds to the right type WebDavConfiguration config = configuration as WebDavConfiguration; // build service DavService svc = new DavService(); // check if url available int status = (int)HttpStatusCode.OK; WebException e = null; svc.PerformSimpleWebCall(config.ServiceLocator.ToString(), WebRequestMethodsEx.WebDAV.Options, (token as ICredentials).GetCredential(null, null), null, out status, out e); if (status == (int)HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else if (HttpUtilityEx.IsSuccessCode(status)) { return(new WebDavStorageProviderSession(token, config, this)); } else { return(null); } }
private static void DavPreparation(WebRequest request, object context) { // cast to http webrequest var hrequest = request as HttpWebRequest; // Set default headers hrequest.Headers["Pragma"] = "no-cache"; hrequest.Headers["Cache-Control"] = "no-cache"; hrequest.ContentType = "text/xml"; hrequest.Accept = "*/*"; // for all meta data calls we allow stream buffering in webdav if (hrequest.Method != WebRequestMethods.Http.Put) { hrequest.AllowWriteStreamBuffering = true; } // set translate mode hrequest.Headers["Translate"] = "f"; // Retrieve only the requested folder switch (hrequest.Method) { case WebRequestMethodsEx.WebDAV.PropFind: hrequest.Headers["Depth"] = "1"; break; case WebRequestMethodsEx.WebDAV.Move: { var targetUri = context as string; if (targetUri == null) { throw new Exception("Not a valid URL"); } targetUri = HttpUtilityEx.GenerateEncodedUriString(new Uri(targetUri)); targetUri = targetUri.Replace(WebDavConfiguration.YaUrl + ":443", WebDavConfiguration.YaUrl); hrequest.Headers["Destination"] = targetUri; } break; case WebRequestMethodsEx.WebDAV.Copy: { var targetUri = context as string; if (targetUri == null) { throw new Exception("Not a valid URL"); } targetUri = HttpUtilityEx.GenerateEncodedUriString(new Uri(targetUri)); targetUri = targetUri.Replace(WebDavConfiguration.YaUrl + ":443", WebDavConfiguration.YaUrl); hrequest.Headers["Destination"] = targetUri; hrequest.Headers["Depth"] = "infinity"; hrequest.Headers["Overwrite"] = "T"; } break; } }
public ActionResult UrlEncode(string str, bool isDecode) { if (str.IsNullOrEmpty()) { return(Content("")); } var res = isDecode ? HttpUtility.UrlDecode(str, Encoding.Default) : HttpUtilityEx.UrlEncode(str, Encoding.Default); return(Content(res)); }
private void DavPreparation(WebRequest request, Object context) { // cast to http webrequest HttpWebRequest hrequest = request as HttpWebRequest; // Set default headers hrequest.Headers["Pragma"] = "no-cache"; hrequest.Headers["Cache-Control"] = "no-cache"; hrequest.ContentType = "text/xml"; hrequest.Accept = "*/*"; #if !WINDOWS_PHONE // for all meta data calls we allow stream buffering in webdav if (hrequest.Method != WebRequestMethods.Http.Put) { hrequest.AllowWriteStreamBuffering = true; } #endif // set translate mode hrequest.Headers["Translate"] = "f"; // Retrieve only the requested folder if (hrequest.Method == WebRequestMethodsEx.WebDAV.PropFind) { hrequest.Headers["Depth"] = "1"; } // set the target in case of move operation else if (hrequest.Method == WebRequestMethodsEx.WebDAV.Move) { String targetUri = context as String; if (targetUri == null) { throw new Exception("Not a valid URL"); } targetUri = HttpUtilityEx.GenerateEncodedUriString(new Uri(targetUri)); hrequest.Headers["Destination"] = targetUri; } else if (hrequest.Method == WebRequestMethodsEx.WebDAV.Copy) { String targetUri = context as String; if (targetUri == null) { throw new Exception("Not a valid URL"); } targetUri = HttpUtilityEx.GenerateEncodedUriString(new Uri(targetUri)); hrequest.Headers["Destination"] = targetUri; hrequest.Headers["Depth"] = "infinity"; hrequest.Headers["Overwrite"] = "T"; } }
public override WebRequest CreateWebRequest(string url, String method, ICredentials credentials, Boolean bAllowStreamBuffering, object context) { // quote the string in the right way String quotedurl = HttpUtilityEx.GenerateEncodedUriString(new Uri(url)); // create base request WebRequest request = base.CreateWebRequest(quotedurl, method, credentials, bAllowStreamBuffering, context, DavPreparation) as HttpWebRequest; // go ahead return(request); }
private static string GetResourceUrlInternal(IStorageProviderSession session, String path) { if (session is DropBoxStorageProviderSession) { var dbSession = session as DropBoxStorageProviderSession; String uri = PathHelper.Combine(dbSession.SandBoxMode ? GetUrlString(DropBoxSandboxRoot, session.ServiceConfiguration) : GetUrlString(DropBoxDropBoxRoot, session.ServiceConfiguration), HttpUtilityEx.UrlEncodeUTF8(path)); return(uri); } return(null); }
public static string GetCommitUploadSessionUrl(IStorageProviderSession session, IResumableUploadSession uploadSession) { var rUploadSession = uploadSession as ResumableUploadSession; if (rUploadSession == null) { throw new ArgumentNullException("uploadSession"); } return(GetUrlString(DropBoxCommitChunkedUpload, session.ServiceConfiguration) + "/" + GetRootToken((DropBoxStorageProviderSession)session) + "/" + HttpUtilityEx.UrlEncodeUTF8(DropBoxResourceIDHelpers.GetResourcePath(null, rUploadSession.FileName, rUploadSession.ParentId))); }
public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, string Name, ICloudDirectoryEntry parent) { // build url String uriString = GetResourceUrlInternal(session, parent); if (!Name.Equals("/") && Name.Length > 0) { uriString = PathHelper.Combine(uriString, HttpUtilityEx.UrlEncodeUTF8(Name)); } // request the data from url int code; var res = DropBoxRequestParser.RequestResourceByUrl(uriString, this, session, out code); // check error if (res.Length == 0) { if (code != (int)HttpStatusCode.OK) { HttpException hex = new HttpException(Convert.ToInt32(code), "HTTP Error"); throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotRetrieveDirectoryList, hex); } else { throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotRetrieveDirectoryList); } } // build the entry and subchilds BaseFileEntry entry = DropBoxRequestParser.CreateObjectsFromJsonString(res, this, session); // check if it was a deleted file if (entry.IsDeleted) { return(null); } // set the parent entry.Parent = parent; // go ahead return(entry); }
public override string GetResourceUrl(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, String additionalPath) { // get the dropbox session DropBoxStorageProviderSession dbSession = session as DropBoxStorageProviderSession; // build the internal url String url = GetResourceUrlInternal(session, fileSystemEntry); // add the optional path if (additionalPath != null) { url = PathHelper.Combine(url, HttpUtilityEx.UrlEncodeUTF8(additionalPath)); } // generate the oauth url OAuthService svc = new OAuthService(); return(svc.GetProtectedResourceUrl(url, dbSession.Context, dbSession.SessionToken as DropBoxToken, null, WebRequestMethodsEx.Http.Get)); }
public static String GetDownloadFileUrlInternal(IStorageProviderSession session, ICloudFileSystemEntry entry) { // cast varibales var dropBoxSession = session as DropBoxStorageProviderSession; // gather information var rootToken = GetRootToken(dropBoxSession); var dropboxPath = DropBoxResourceIDHelpers.GetResourcePath(entry); // add all information to url; var url = GetUrlString(DropBoxUploadDownloadFile, session.ServiceConfiguration) + "/" + rootToken; if (dropboxPath.Length > 0 && dropboxPath[0] != '/') { url += "/"; } url += HttpUtilityEx.UrlEncodeUTF8(dropboxPath); return(url); }
public static WebDavRequestResult CreateObjectsFromNetworkStream(Stream data, string targetUrl, IStorageProviderService service, IStorageProviderSession session, NameBaseFilterCallback callback) { var config = session.ServiceConfiguration as WebDavConfiguration; var results = new WebDavRequestResult(); var queryLessUri = HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator).ToString().TrimEnd('/'); var decodedTargetUrl = HttpUtility.UrlDecode(targetUrl); string s; using (var streamReader = new StreamReader(data)) { s = streamReader.ReadToEnd(); } //todo: var xDoc = XDocument.Load(new StringReader(s.Replace("d:d:", "d:"))); var responses = xDoc.Descendants(XName.Get("response", DavNamespace)); foreach (var response in responses) { var isHidden = false; var isDirectory = false; var lastModified = DateTime.Now; long contentLength = 0; var href = response.Element(XName.Get("href", DavNamespace)).ValueOrEmpty(); var propstats = response.Descendants(XName.Get("propstat", DavNamespace)); foreach (var propstat in propstats) { var prop = propstat.Element(XName.Get("prop", DavNamespace)); var status = propstat.Element(XName.Get("status", DavNamespace)).ValueOrEmpty(); if (!status.Equals(HttpOk) || prop == null) { continue; } var strLastModified = prop.Element(XName.Get("getlastmodified", DavNamespace)).ValueOrEmpty(); var strContentLength = prop.Element(XName.Get("getcontentlength", DavNamespace)).ValueOrEmpty(); var resourceType = prop.Element(XName.Get("resourcetype", DavNamespace)); var strIsHidden = prop.Element(XName.Get("ishidden", DavNamespace)).ValueOrEmpty(); if (!string.IsNullOrEmpty(strIsHidden)) { int code; if (!int.TryParse(strIsHidden, out code)) { code = 0; } isHidden = Convert.ToBoolean(code); } if (resourceType != null && resourceType.Element(XName.Get("collection", DavNamespace)) != null) { isDirectory = true; } if (!string.IsNullOrEmpty(strContentLength)) { contentLength = Convert.ToInt64(strContentLength); } if (!string.IsNullOrEmpty(strLastModified) && DateTime.TryParse(strLastModified, out lastModified)) { lastModified = lastModified.ToUniversalTime(); } } //entry not to be encluded if (isHidden) { continue; } var nameBase = href; if (callback != null) { nameBase = callback(targetUrl, service, session, nameBase); } string nameBaseForSelfCheck; if (nameBase.StartsWith(config.ServiceLocator.ToString())) { nameBaseForSelfCheck = HttpUtility.UrlDecode(nameBase); nameBase = nameBase.Remove(0, config.ServiceLocator.ToString().Length); } else { nameBaseForSelfCheck = queryLessUri + HttpUtilityEx.PathDecodeUTF8(nameBase); } nameBase = nameBase.TrimEnd('/'); nameBaseForSelfCheck = nameBaseForSelfCheck.TrimEnd('/'); if (targetUrl.EndsWith("/")) { nameBaseForSelfCheck += "/"; } var isSelf = nameBaseForSelfCheck.Equals(decodedTargetUrl); var ph = new PathHelper(nameBase); var resourceName = HttpUtility.UrlDecode(ph.GetFileName()); var entry = !isDirectory ? new BaseFileEntry(resourceName, contentLength, lastModified, service, session) : new BaseDirectoryEntry(resourceName, contentLength, lastModified, service, session); if (isSelf) { results.Self = entry; } else { results.Childs.Add(entry); } } return(results); }
public static String GetCommitUploadSessionUrl(IStorageProviderSession session, IResumableUploadSession uploadSession) { return(GetUrlString(DropBoxCommitChunkedUpload, session.ServiceConfiguration) + "/" + GetRootToken((DropBoxStorageProviderSession)session) + "/" + HttpUtilityEx.UrlEncodeUTF8(DropBoxResourceIDHelpers.GetResourcePath(uploadSession.File.Parent, uploadSession.File.Name))); }
private string GetResourceUrlInternal(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry) { // cast varibales DropBoxStorageProviderSession dropBoxSession = session as DropBoxStorageProviderSession; // build the path for resource String resourcePath = GenericHelper.GetResourcePath(fileSystemEntry); // trim heading and trailing slashes resourcePath = resourcePath.TrimStart('/'); resourcePath = resourcePath.TrimEnd('/'); // build the metadata url String getMetaData; // get url if (dropBoxSession.SandBoxMode) { getMetaData = PathHelper.Combine(GetUrlString(DropBoxSandboxRoot, session.ServiceConfiguration), HttpUtilityEx.UrlEncodeUTF8(resourcePath)); } else { getMetaData = PathHelper.Combine(GetUrlString(DropBoxDropBoxRoot, session.ServiceConfiguration), HttpUtilityEx.UrlEncodeUTF8(resourcePath)); } return(getMetaData); }
public static WebDavRequestResult CreateObjectsFromNetworkStream(Stream data, String targetUrl, IStorageProviderService service, IStorageProviderSession session, NameBaseFilterCallback callback) { WebDavConfiguration config = session.ServiceConfiguration as WebDavConfiguration; WebDavRequestResult results = new WebDavRequestResult(); try { String resourceName = String.Empty; long resourceLength = 0; DateTime resourceModificationDate = DateTime.Now; DateTime resourceCreationDate = DateTime.Now; String resourceContentType = String.Empty; Boolean bIsHidden = false; Boolean bIsDirectory = false; Boolean bIsSelf = false; // build queryless uri String queryLessUri = HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator).ToString().TrimEnd('/'); // work with decoded target url String decodedTargetUrl = HttpUtility.UrlDecode(targetUrl); XmlTextReader reader = new XmlTextReader(data); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: { // we are on an element and we have to handle this elements String currentElement = reader.Name; // we found a resource name if (currentElement.Contains(":href")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // get the name String nameBase = reader.Value; // call the filter if needed if (callback != null) { nameBase = callback(targetUrl, service, session, nameBase); } /* * Just for bug fixing * * Console.WriteLine(" SVC Locator: " + config.ServiceLocator.ToString()); * Console.WriteLine("SVC Locator QL: " + HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator)); * Console.WriteLine(" Target Url: " + targetUrl); * Console.WriteLine(" NameBase: " + nameBase); */ // generate namebase for self check String nameBaseForSelfCheck; // remove the base url and build for selfcheck if (nameBase.StartsWith(config.ServiceLocator.ToString())) { nameBaseForSelfCheck = HttpUtility.UrlDecode(nameBase); nameBase = nameBase.Remove(0, config.ServiceLocator.ToString().Length); } else { nameBaseForSelfCheck = queryLessUri + HttpUtilityEx.PathDecodeUTF8(nameBase); } // trim all trailing slashes nameBase = nameBase.TrimEnd('/'); // work with the trailing lsahed nameBaseForSelfCheck = nameBaseForSelfCheck.TrimEnd('/'); if (targetUrl.EndsWith("/")) { nameBaseForSelfCheck += "/"; } // check if we are self if (nameBaseForSelfCheck.Equals(decodedTargetUrl)) { bIsSelf = true; } else { bIsSelf = false; } // get the last file or directory name PathHelper ph = new PathHelper(nameBase); resourceName = ph.GetFileName(); // unquote name resourceName = HttpUtility.UrlDecode(resourceName); } else if (currentElement.Contains(":ishidden")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // try to parse int iIsHidden = 0; if (!int.TryParse(reader.Value, out iIsHidden)) { iIsHidden = 0; } // convert bIsHidden = Convert.ToBoolean(iIsHidden); } else if (currentElement.Contains(":getcontentlength")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // read value if (!long.TryParse(reader.Value, out resourceLength)) { resourceLength = -1; } } else if (currentElement.Contains(":creationdate")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // parse if (!DateTime.TryParse(reader.Value, out resourceCreationDate)) { resourceCreationDate = DateTime.Now; } } else if (currentElement.Contains(":getlastmodified")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // parse if (!DateTime.TryParse(reader.Value, out resourceModificationDate)) { resourceModificationDate = DateTime.Now; } } else if (currentElement.Contains(":getcontenttype")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // parse resourceContentType = reader.Value; } else if (currentElement.Contains(":collection")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // set as directory bIsDirectory = true; } // go ahead break; } case XmlNodeType.EndElement: { // handle the end of an response if (!reader.Name.ToLower().Contains(":response")) { break; } // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(reader.Name, reader)) { continue; } // handle the end of an response, this means // create entry BaseFileEntry entry = null; if (bIsDirectory) { entry = new BaseDirectoryEntry(resourceName, resourceLength, resourceModificationDate, service, session); } else { entry = new BaseFileEntry(resourceName, resourceLength, resourceModificationDate, service, session); } entry.SetPropertyValue("CreationDate", resourceCreationDate); entry.SetPropertyValue("ContentType", resourceContentType); if (!bIsHidden) { if (bIsSelf) { results.Self = entry; } else { results.Childs.Add(entry); } } // reset all state properties resourceName = String.Empty; resourceLength = 0; resourceModificationDate = DateTime.Now; resourceCreationDate = DateTime.Now; resourceContentType = String.Empty; bIsHidden = false; bIsDirectory = false; // go ahead break; } default: { break; } } } ; if (results.Self == null) { throw new Exception("Unknown error in webrequest parser"); } } catch (Exception) { } // go ahead return(results); }