/// <summary>
        ///
        /// </summary>
        /// <param name="session"></param>
        /// <param name="objectToRename"></param>
        /// <param name="newName"></param>
        public static void RenameFileSystemEntry(IStorageProviderSession session, ICloudFileSystemEntry objectToRename, String newName)
        {
            // rename the fsentry
            BaseFileEntry fentry = objectToRename as BaseFileEntry;

            fentry.Name = newName;
        }
        public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long uploadSize)
        {
            // get the full path
            String uriPath = GetResourceUrl(session, fileSystemEntry, null);
            Uri    uri     = new Uri(uriPath);

            // set the new size
            BaseFileEntry f = fileSystemEntry as BaseFileEntry;

            f.Length = uploadSize;

            // create the file if not exists
            FileStream fs = null;

            if (!File.Exists(uri.LocalPath))
            {
                fs = File.Create(uri.LocalPath);
            }
            else
            {
                fs = File.OpenWrite(uri.LocalPath);
            }

            // go ahead
            return(fs);
        }
        public void CommitUploadStream(params object[] arg)
        {
            // convert the args
            DavService     svc             = arg[0] as DavService;
            HttpWebRequest uploadRequest   = arg[1] as HttpWebRequest;
            BaseFileEntry  fileSystemEntry = arg[2] as BaseFileEntry;

#if !WINDOWS_PHONE && !MONODROID
            WebRequestStream requestStream = arg[3] as WebRequestStream;

            // check if all data was written into stream
            if (requestStream.WrittenBytes != uploadRequest.ContentLength)
            {
                // nothing todo request was aborted
                return;
            }
#endif

            // 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
#if !WINDOWS_PHONE && !MONODROID
            fileSystemEntry.Length = uploadRequest.ContentLength;
#endif
        }
예제 #4
0
        public void CommitUploadStream(params object[] arg)
        {
            // convert the args
            // FtpService svc = arg[0] as FtpService;
            FtpWebRequest uploadRequest   = arg[1] as FtpWebRequest;
            BaseFileEntry fileSystemEntry = arg[2] as BaseFileEntry;

#if !WINDOWS_PHONE && !ANDROID
            WebRequestStream requestStream = arg[3] as WebRequestStream;

            // close the stream
            requestStream.Close();

            // close conncetion
            uploadRequest.Abort();

            // check if all data was written into stream
            if (requestStream.WrittenBytes != uploadRequest.ContentLength)
            {
                // nothing todo request was aborted
                return;
            }
#endif
            // adjust the lengt
#if !WINDOWS_PHONE && !ANDROID
            fileSystemEntry.Length = uploadRequest.ContentLength;
#endif
        }
예제 #5
0
        private static Boolean BuildFileEntry(BaseFileEntry fileEntry, JsonHelper jh)
        {
            /*
             *  "revision": 29251,
             *  "thumb_exists": false,
             *  "bytes": 37941660,
             *  "modified": "Tue, 01 Jun 2010 14:45:09 +0000",
             *  "path": "/Public/2010_06_01 15_53_48_336.nvl",
             *  "is_dir": false,
             *  "icon": "page_white",
             *  "mime_type": "application/octet-stream",
             *  "size": "36.2MB"
             * */

            // set the size
            fileEntry.Length = Convert.ToInt64(jh.GetProperty("bytes"));

            // set the modified time
            fileEntry.Modified = jh.GetDateTimeProperty("modified");

            // build the displayname
            var DropBoxPath = jh.GetProperty("path");
            var arr         = DropBoxPath.Split('/');

            fileEntry.Name = arr.Length > 0 ? arr[arr.Length - 1] : DropBoxPath;

            if (DropBoxPath.Equals("/"))
            {
                fileEntry.Id       = "/";
                fileEntry.ParentID = null;
            }
            else
            {
                fileEntry.Id       = DropBoxPath.Trim('/');
                fileEntry.ParentID = DropBoxResourceIDHelpers.GetParentID(DropBoxPath);
            }


            // set the hash property if possible
            var hashValue = jh.GetProperty("hash");

            if (hashValue.Length > 0)
            {
                fileEntry.SetPropertyValue("hash", hashValue);
            }

            // set the path property
            fileEntry.SetPropertyValue("path", DropBoxPath.Equals("/") ? "" : DropBoxPath);

            // set the revision value if possible
            var revValue = jh.GetProperty("rev");

            if (revValue.Length > 0)
            {
                fileEntry.SetPropertyValue("rev", revValue);
            }

            // go ahead
            return(true);
        }
예제 #6
0
        public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, string newName)
        {
            // get credentials
            ICredentials creds = ((GenericNetworkCredentials)session.SessionToken).GetCredential(null, null);

            // get old name uri
            String uriPath = GetResourceUrl(session, fsentry.Parent, fsentry.Name);

            // get the new path
            String TargetPath = PathHelper.Combine(GenericHelper.GetResourcePath(fsentry.Parent), newName);

            // do it
            if (!_ftpService.FtpRename(uriPath, TargetPath, creds))
            {
                return(false);
            }

            // rename the entry
            BaseFileEntry fentry = fsentry as BaseFileEntry;

            fentry.Name = newName;

            // go ahead
            return(true);
        }
        private bool MoveOrRenameOrCopyItem(DropBoxStorageProviderSession session, BaseFileEntry orgEntry, String toPath, bool copy)
        {
            // build the path for resource
            var resourcePath = DropBoxResourceIDHelpers.GetResourcePath(orgEntry);

            // request the json object via oauth
            var parameters = new Dictionary <string, string>
            {
                { "from_path", resourcePath },
                { "root", GetRootToken(session) },
                { "to_path", toPath }
            };

            try
            {
                // move or rename the entry
                int code;
                var res = DropBoxRequestParser.RequestResourceByUrl(GetUrlString(copy ? DropBoxCopyItem : DropBoxMoveItem, session.ServiceConfiguration), parameters, this, session, out code);

                // update the entry
                DropBoxRequestParser.UpdateObjectFromJsonString(res, orgEntry, this, session);
            }
            catch (Exception)
            {
                return(false);
            }

            orgEntry.Id = toPath;
            return(true);
        }
        private void RefreshChildsOfDirectory(IStorageProviderSession session, BaseDirectoryEntry dir)
        {
            // get the location
            String reslocation = GetResourceUrl(session, dir as ICloudFileSystemEntry, null);

            // ensure that we have a trailing slash
            reslocation = reslocation.TrimEnd('/');
            reslocation = reslocation + "/";

            // build the uri
            Uri resUri = new Uri(reslocation);

            // convert BaseDir to DirInfo
            DirectoryInfo dInfo = new DirectoryInfo(resUri.LocalPath);

            // clear childs
            dir.ClearChilds();

            // get all childs
            foreach (FileSystemInfo fInfo in dInfo.GetFileSystemInfos())
            {
                BaseFileEntry f = CreateEntryByFileSystemInfo(fInfo, session, dir);
                dir.AddChild(f);
            }
        }
예제 #9
0
        private static Boolean BuildDirectyEntry(BaseDirectoryEntry dirEntry, JsonHelper jh, IStorageProviderService service, IStorageProviderSession session)
        {
            // build the file entry part
            if (!BuildFileEntry(dirEntry, jh))
            {
                return(false);
            }

            // now take the content
            var content = jh.GetListProperty("contents");

            if (content.Count == 0)
            {
                return(true);
            }

            // remove all childs
            dirEntry.ClearChilds();

            // add the childs
            foreach (var jsonContent in content)
            {
                // parse the item
                var jc = new JsonHelper();
                if (!jc.ParseJsonMessage(jsonContent))
                {
                    continue;
                }

                // check if we have a directory
                var isDir = jc.GetBooleanProperty("is_dir");

                BaseFileEntry fentry;

                if (isDir)
                {
                    fentry = new BaseDirectoryEntry("Name", 0, DateTime.Now, service, session);
                }
                else
                {
                    fentry = new BaseFileEntry("Name", 0, DateTime.Now, service, session);
                }

                // build the file attributes
                BuildFileEntry(fentry, jc);

                // establish parent child realtionship
                dirEntry.AddChild(fentry);
            }

            // set the length
            dirEntry.Length = dirEntry.Count;

            // go ahead
            return(true);
        }
예제 #10
0
        protected BaseFileEntry(BaseFileEntry other)
        {
            if (other == null)
            {
                throw new System.ArgumentNullException((other).ToString(), "BaseFileEntry cannot be null");
            }

            Path = other.Path;
            Add  = other.Add;
            SetFileName();
        }
예제 #11
0
        public static ICloudFileSystemEntry ParseSingleEntry(IStorageProviderSession session, String json, JsonHelper parser)
        {
            if (parser == null)
            {
                parser = CreateParser(json);
            }

            ContainsError(json, true, parser);

            BaseFileEntry entry;

            String type = parser.GetProperty("type");

            if (!IsFolderType(type) && !IsFileType(type))
            {
                throw new SkyDriveParserException("Can not retrieve entry type while parsing single entry");
            }

            String   id             = parser.GetProperty("id");
            String   name           = parser.GetProperty("name");
            String   parentID       = parser.GetProperty("parent_id");
            String   uploadLocation = parser.GetProperty("upload_location");
            DateTime updatedTime    = Convert.ToDateTime(parser.GetProperty("updated_time"));

            if (IsFolderType(type))
            {
                int count = parser.GetPropertyInt("count");
                entry = new BaseDirectoryEntry(name, count, updatedTime, session.Service, session)
                {
                    Id = id
                };
            }
            else
            {
                int size = parser.GetPropertyInt("size");
                entry = new BaseFileEntry(name, size, updatedTime, session.Service, session)
                {
                    Id = id
                };
            }
            entry[SkyDriveConstants.UploadLocationKey] = uploadLocation;

            if (!String.IsNullOrEmpty(parentID))
            {
                entry.ParentID = parentID;
            }
            else
            {
                entry.Name = "/";
            }

            return(entry);
        }
        public bool RenameResourceEx(IStorageProviderSession session, ICloudFileSystemEntry fsentry, String newFullPath)
        {
            // get the uri
            String uriPath = GetResourceUrl(session, fsentry, null);
            Uri    srUri   = new Uri(uriPath);

            // get new name uri
            Uri tgUri = new Uri(newFullPath);

            // rename
            FileSystemInfo f = null;

            if (File.Exists(srUri.LocalPath))
            {
                f = new FileInfo(srUri.LocalPath);
                ((FileInfo)f).MoveTo(tgUri.LocalPath);
            }
            else if (Directory.Exists(srUri.LocalPath))
            {
                f = new DirectoryInfo(srUri.LocalPath);
                ((DirectoryInfo)f).MoveTo(tgUri.LocalPath);
            }
            else
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorFileNotFound);
            }

            // reload file info
            if (File.Exists(tgUri.LocalPath))
            {
                f = new FileInfo(tgUri.LocalPath);
            }
            else if (Directory.Exists(tgUri.LocalPath))
            {
                f = new DirectoryInfo(tgUri.LocalPath);
            }
            else
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorFileNotFound);
            }

            // update fsEntry
            BaseFileEntry fs = fsentry as BaseFileEntry;

            fs.Name     = Path.GetFileName(tgUri.LocalPath);
            fs.Length   = (f is FileInfo ? (f as FileInfo).Length : 0);
            fs.Modified = f.LastWriteTimeUtc;

            // go ahead
            return(true);
        }
        /// <summary>
        /// This method creates a filesystem entry
        /// </summary>
        /// <param name="session"></param>
        /// <param name="Name"></param>
        /// <param name="modified"></param>
        /// <param name="fileSize"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static ICloudFileSystemEntry CreateFileSystemEntry(IStorageProviderSession session, string Name, DateTime modified, long fileSize, ICloudDirectoryEntry parent)
        {
            // build up query url
            var newObj = new BaseFileEntry(Name, fileSize, modified, session.Service, session);

            // case the parent if possible
            if (parent != null)
            {
                var objparent = parent as BaseDirectoryEntry;
                objparent.AddChild(newObj);
            }

            return(newObj);
        }
        /// <summary>
        /// This method request information about a resource
        /// </summary>
        /// <param name="session"></param>
        /// <param name="Name"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, string Name, ICloudDirectoryEntry parent)
        {
            // build url
            String uriString = GetResourceUrl(session, parent, null);

            uriString = PathHelper.Combine(uriString, Name);

            // get the data
            List <BaseFileEntry> childs          = null;
            BaseFileEntry        requestResource = RequestResourceFromWebDavShare(session, uriString, out childs);

            // check errors
            if (requestResource == null)
            {
                return(null);
            }

            // rename the root
            if (Name.Equals("/"))
            {
                requestResource.Name = "/";
            }

            // init parent child relation
            if (parent != null)
            {
                BaseDirectoryEntry parentDir = parent as BaseDirectoryEntry;
                parentDir.AddChild(requestResource);
            }

            // check if we have to add childs
            if (!(requestResource is BaseDirectoryEntry))
            {
                return(requestResource);
            }
            else
            {
                BaseDirectoryEntry requestedDir = requestResource as BaseDirectoryEntry;

                // add the childs
                foreach (BaseFileEntry child in childs)
                {
                    requestedDir.AddChild(child);
                }
            }

            // go ahead
            return(requestResource);
        }
예제 #15
0
        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);
        }
        /// <summary>
        /// Renames a webdave file or folder
        /// </summary>
        /// <param name="session"></param>
        /// <param name="fsentry"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, string newName)
        {
            // build the targte url
            String uriStringTarget = this.GetResourceUrl(session, fsentry.Parent, null);

            uriStringTarget = PathHelper.Combine(uriStringTarget, newName);

            if (MoveResource(session, fsentry, uriStringTarget))
            {
                // rename the fsentry
                BaseFileEntry fentry = fsentry as BaseFileEntry;
                fentry.Name = newName;

                // go ahead
                return(true);
            }
            else
            {
                // go ahead
                return(false);
            }
        }
        public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, string name, ICloudDirectoryEntry parent)
        {
            // build path
            String path;

            if (name.Equals("/"))
            {
                path = session.ServiceConfiguration.ServiceLocator.LocalPath;
            }
            else if (parent == null)
            {
                path = Path.Combine(session.ServiceConfiguration.ServiceLocator.LocalPath, name);
            }
            else
            {
                path = new Uri(GetResourceUrl(session, parent, name)).LocalPath;
            }

            // check if file exists
            if (File.Exists(path))
            {
                // create the fileinfo
                var fInfo = new FileInfo(path);

                var bf = new BaseFileEntry(fInfo.Name, fInfo.Length, fInfo.LastWriteTimeUtc, this, session)
                {
                    Parent = parent
                };

                // add to parent
                if (parent != null)
                {
                    (parent as BaseDirectoryEntry).AddChild(bf);
                }

                // go ahead
                return(bf);
            }
            // check if directory exists
            if (Directory.Exists(path))
            {
                // build directory info
                var dInfo = new DirectoryInfo(path);

                // build bas dir
                var dir = CreateEntryByFileSystemInfo(dInfo, session) as BaseDirectoryEntry;
                if (name.Equals("/"))
                {
                    dir.Name = "/";
                }

                // add to parent
                if (parent != null)
                {
                    (parent as BaseDirectoryEntry).AddChild(dir);
                }

                // refresh the childs
                RefreshChildsOfDirectory(session, dir);

                // go ahead
                return(dir);
            }

            return(null);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fsentry"></param>
        /// <param name="newLength"></param>
        public static void ModifyFileSystemEntryLength(ICloudFileSystemEntry fsentry, long newLength)
        {
            BaseFileEntry fs = (BaseFileEntry)fsentry;

            fs.Length = newLength;
        }
 private bool CopyItem(DropBoxStorageProviderSession session, BaseFileEntry orgEntry, String toPath)
 {
     return(MoveOrRenameOrCopyItem(session, orgEntry, toPath, true));
 }
예제 #20
0
        private static ICloudFileSystemEntry ParseSingleEntry(IStorageProviderSession session, String json, JsonHelper parser)
        {
            if (json == null)
            {
                return(null);
            }

            if (parser == null)
            {
                parser = CreateParser(json);
            }

            if (ContainsError(json, false, parser))
            {
                return(null);
            }

            BaseFileEntry entry;

            var type = parser.GetProperty("type");

            if (!IsFolderType(type) && !IsFileType(type))
            {
                return(null);
            }

            var id             = parser.GetProperty("id");
            var name           = parser.GetProperty("name");
            var parentID       = parser.GetProperty("parent_id");
            var uploadLocation = parser.GetProperty("upload_location");
            var updatedTime    = Convert.ToDateTime(parser.GetProperty("updated_time")).ToUniversalTime();

            if (IsFolderType(type))
            {
                int count = parser.GetPropertyInt("count");
                entry = new BaseDirectoryEntry(name, count, updatedTime, session.Service, session)
                {
                    Id = id
                };
            }
            else
            {
                var size = Convert.ToInt64(parser.GetProperty("size"));
                entry = new BaseFileEntry(name, size, updatedTime, session.Service, session)
                {
                    Id = id
                };
            }
            entry[SkyDriveConstants.UploadLocationKey] = uploadLocation;

            if (!String.IsNullOrEmpty(parentID))
            {
                entry.ParentID = SkyDriveConstants.RootIDRegex.IsMatch(parentID) ? "/" : parentID;
            }
            else
            {
                entry.Name = "/";
                entry.Id   = "/";
            }

            entry[SkyDriveConstants.InnerIDKey]   = id;
            entry[SkyDriveConstants.TimestampKey] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);

            return(entry);
        }
예제 #21
0
        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);
        }
예제 #22
0
        public static BaseFileEntry UpdateObjectFromJsonString(String jsonMessage, BaseFileEntry objectToUpdate, IStorageProviderService service, IStorageProviderSession session)
        {
            // verify if we have a directory or a file
            var jc = new JsonHelper();

            if (!jc.ParseJsonMessage(jsonMessage))
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidFileOrDirectoryName);
            }

            var isDir = jc.GetBooleanProperty("is_dir");

            // create the entry
            BaseFileEntry dbentry;
            Boolean       bEntryOk;

            if (isDir)
            {
                if (objectToUpdate == null)
                {
                    dbentry = new BaseDirectoryEntry("Name", 0, DateTime.Now, service, session);
                }
                else
                {
                    dbentry = objectToUpdate as BaseDirectoryEntry;
                }

                bEntryOk = BuildDirectyEntry(dbentry as BaseDirectoryEntry, jc, service, session);
            }
            else
            {
                if (objectToUpdate == null)
                {
                    dbentry = new BaseFileEntry("Name", 0, DateTime.Now, service, session);
                }
                else
                {
                    dbentry = objectToUpdate;
                }

                bEntryOk = BuildFileEntry(dbentry, jc);
            }

            // parse the childs and fill the entry as self
            if (!bEntryOk)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotContactStorageService);
            }

            // set the is deleted flag
            try
            {
                // try to read the is_deleted property
                dbentry.IsDeleted = jc.GetBooleanProperty("is_deleted");
            }
            catch (Exception)
            {
                // the is_deleted proprty is missing (so it's not a deleted file or folder)
                dbentry.IsDeleted = false;
            }

            // return the child
            return(dbentry);
        }
예제 #23
0
        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);

            var s = new StreamReader(data).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)
            {
                bool     isHidden      = false;
                bool     isDirectory   = false;
                DateTime 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.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 += "/";
                }

                bool isSelf = nameBaseForSelfCheck.Equals(decodedTargetUrl);

                var ph           = new PathHelper(nameBase);
                var resourceName = HttpUtility.UrlDecode(ph.GetFileName());

                BaseFileEntry 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);
        }
예제 #24
0
        public static IEnumerable <BaseFileEntry> ParseEntriesXml(IStorageProviderSession session, String xml)
        {
            var doc = XDocument.Load(new StringReader(xml));

            var entries = doc.Descendants(XName.Get("entry", GoogleDocsConstants.AtomNamespace));

            var fsEntries = new List <BaseFileEntry>();

            foreach (var entry in entries)
            {
                var resourceId = entry.Element(XName.Get("resourceId", GoogleDocsConstants.GdNamespace)).ValueOrEmpty().Replace(':', '_');
                var title      = entry.Element(XName.Get("title", GoogleDocsConstants.AtomNamespace)).ValueOrEmpty();
                var updated    = entry.Element(XName.Get("updated", GoogleDocsConstants.AtomNamespace)).ValueOrEmpty();
                var etag       = entry.Attribute(XName.Get("etag", GoogleDocsConstants.GdNamespace)).ValueOrEmpty();
                var kind       = entry.Elements(XName.Get("category", GoogleDocsConstants.AtomNamespace)).Single(x => x.Attribute("scheme").ValueOrEmpty().Equals(GoogleDocsConstants.SchemeKind)).Attribute("label").ValueOrEmpty();

                BaseFileEntry fsEntry = kind.Equals("folder")
                                            ? new BaseDirectoryEntry(title, 0, Convert.ToDateTime(updated).ToUniversalTime(), session.Service, session)
                                            : new BaseFileEntry(title, 0, Convert.ToDateTime(updated).ToUniversalTime(), session.Service, session);

                fsEntry.Id = resourceId;
                fsEntry.SetPropertyValue(GoogleDocsConstants.EtagProperty, etag);
                fsEntry.SetPropertyValue(GoogleDocsConstants.KindProperty, kind);
                if (kind.Equals("folder"))
                {
                    var uploadUrl = entry.Elements(XName.Get("link", GoogleDocsConstants.AtomNamespace)).FirstOrDefault(x => x.Attribute("rel").ValueOrEmpty().Equals(GoogleDocsConstants.SchemeResCreateMedia)).AttributeOrNull("href").ValueOrEmpty();
                    fsEntry.SetPropertyValue(GoogleDocsConstants.ResCreateMediaProperty, uploadUrl);
                }
                else
                {
                    var length      = entry.Element(XName.Get("quotaBytesUsed", GoogleDocsConstants.GdNamespace)).ValueOrEmpty();
                    var downloadUrl = entry.Elements(XName.Get("content", GoogleDocsConstants.AtomNamespace)).FirstOrDefault().AttributeOrNull("src").ValueOrEmpty();
                    var editUrl     = entry.Elements(XName.Get("link", GoogleDocsConstants.AtomNamespace)).FirstOrDefault(x => x.Attribute("rel").ValueOrEmpty().Equals(GoogleDocsConstants.SchemeResEditMedia)).AttributeOrNull("href").ValueOrEmpty();

                    fsEntry.Length = Convert.ToInt64(length);
                    fsEntry.SetPropertyValue(GoogleDocsConstants.DownloadUrlProperty, downloadUrl);
                    if (!String.IsNullOrEmpty(editUrl))
                    {
                        fsEntry.SetPropertyValue(GoogleDocsConstants.ResEditMediaProperty, editUrl);
                    }

                    var ext = GoogleDocsResourceHelper.GetExtensionByKind(kind);
                    if (!String.IsNullOrEmpty(ext))
                    {
                        fsEntry.Name += '.' + ext;
                    }
                }

                //var parents = entry.Elements(XName.Get("link", GoogleDocsConstants.AtomNamespace))
                //    .Where(x => x.AttributeOrNull("rel").ValueOrEmpty().Equals(GoogleDocsConstants.SchemeParent))
                //    .Select(x =>
                //        {
                //            var parentUrl = x.ValueOrEmpty();
                //            var index = parentUrl.LastIndexOf('/');
                //            return parentUrl.Substring(index).Replace(':', '_').Replace("%3A", "_");
                //        });

                //fsEntry.SetPropertyValue(GoogleDocsConstants.ParentsProperty, String.Join(",", parents.ToArray()));

                fsEntries.Add(fsEntry);
            }

            return(fsEntries);
        }