/// <summary> /// Remove the file on server. /// </summary> /// <param name="file">File info.</param> /// <param name="removeShareDescription">Also remove share description file (.share.wdmrc)</param> /// <returns>True or false operation result.</returns> public virtual async Task <bool> Remove(File file, bool removeShareDescription = true) //, bool doInvalidateCache = true) { // remove all parts if file splitted var qry = file.Files .AsParallel() .WithDegreeOfParallelism(Math.Min(MaxInnerParallelRequests, file.Files.Count)) .Select(async pfile => { var removed = await Remove(pfile.FullPath); return(removed); }); bool res = (await Task.WhenAll(qry)).All(r => r); if (res) { if (file.Name.EndsWith(PublishInfo.SharedFilePostfix)) //unshare master item { var mpath = WebDavPath.Clean(file.FullPath.Substring(0, file.FullPath.Length - PublishInfo.SharedFilePostfix.Length)); var item = await GetItemAsync(mpath); if (item is Folder folder) { await Unpublish(folder.GetPublicLinks(this).First().Uri, folder.FullPath); } else if (item is File ifile) { await Unpublish(ifile); } } else { if (removeShareDescription) //remove share description (.wdmrc.share) { if (await GetItemAsync(file.FullPath + PublishInfo.SharedFilePostfix) is File sharefile) { await Remove(sharefile, false); } } } } //if (doInvalidateCache) // _itemCache.Invalidate(file.Path, file.FullPath); return(res); }
private static File ToFile(this FolderInfoProps item, string nameReplacement = null) { var path = string.IsNullOrEmpty(nameReplacement) ? item.home : WebDavPath.Combine(WebDavPath.Parent(item.home), nameReplacement); var file = new File(path ?? item.name, item.size, item.hash) { PublicLink = string.IsNullOrEmpty(item.weblink) ? "" : ConstSettings.PublishFileLink + item.weblink, CreationTimeUtc = UnixTimeStampToDateTime(item.mtime), LastAccessTimeUtc = UnixTimeStampToDateTime(item.mtime), LastWriteTimeUtc = UnixTimeStampToDateTime(item.mtime), }; return(file); }
public Link(ItemLink rootLink, string fullPath, string href) : this(href) { _rootLink = rootLink; FullPath = fullPath; IsRoot = WebDavPath.PathEquals(WebDavPath.Parent(FullPath), _rootLink.MapTo); ItemType = IsRoot ? rootLink.IsFile ? Cloud.ItemType.File : Cloud.ItemType.Folder : Cloud.ItemType.Unknown; Size = IsRoot ? rootLink.Size : 0; CreationTimeUtc = rootLink.CreationDate ?? DateTime.Now; }
public Task <StoreCollectionResult> CreateCollectionAsync(string name, bool overwrite, IHttpContext httpContext) { if (!IsWritable) { return(Task.FromResult(new StoreCollectionResult(DavStatusCode.PreconditionFailed))); } var destinationPath = WebDavPath.Combine(FullPath, name); var cmdFabric = new SpecialCommandFabric(); var cmd = cmdFabric.Build(CloudManager.Instance(httpContext.Session.Principal.Identity), destinationPath); if (cmd != null) { var res = cmd.Execute().Result; return(Task.FromResult(new StoreCollectionResult(res.IsSuccess ? DavStatusCode.Created : DavStatusCode.PreconditionFailed))); } DavStatusCode result; if (name != string.Empty && FindSubItem(name) != null) { if (!overwrite) { return(Task.FromResult(new StoreCollectionResult(DavStatusCode.PreconditionFailed))); } result = DavStatusCode.NoContent; } else { result = DavStatusCode.Created; } try { CloudManager.Instance(httpContext.Session.Principal.Identity).CreateFolder(name, FullPath); } catch (Exception exc) { Logger.Log(LogLevel.Error, () => $"Unable to create '{destinationPath}' directory.", exc); return(null); } return(Task.FromResult(new StoreCollectionResult(result, new MailruStoreCollection(httpContext, LockingManager, new Folder(destinationPath), IsWritable)))); }
public async Task <PublishInfo> Publish(Folder folder, bool makeShareFile = true) { var url = await Publish(folder.FullPath); folder.PublicLinks.Clear(); folder.PublicLinks.Add(new PublicLinkInfo(url)); var info = folder.ToPublishInfo(); if (makeShareFile) { string path = WebDavPath.Combine(folder.FullPath, PublishInfo.SharedFilePostfix); UploadFileJson(path, info) .ThrowIf(r => !r, r => new Exception($"Cannot upload JSON file, path = {path}")); } return(info); }
private void FillWithULinks(Folder folder) { if (!folder.IsChildsLoaded) { return; } var flinks = _linkManager.GetItems(folder.FullPath); if (flinks.Any()) { foreach (var flink in flinks) { string linkpath = WebDavPath.Combine(folder.FullPath, flink.Name); if (!flink.IsFile) { folder.Folders.Add(new Folder(0, linkpath) { CreationTimeUtc = flink.CreationDate ?? DateTime.MinValue }); } else { if (folder.Files.All(inf => inf.FullPath != linkpath)) { var newfile = new File(linkpath, flink.Size); { newfile.PublicLinks.Add(new PublicLinkInfo(flink.Href)); } if (flink.CreationDate != null) { newfile.LastWriteTimeUtc = flink.CreationDate.Value; } folder.Files.Add(newfile); } } } } foreach (var childFolder in folder.Folders) { FillWithULinks(childFolder); } }
public override IEnumerable <KeyValuePair <string, string> > ToKvp(int index) { foreach (var pair in base.ToKvp(index)) { yield return(pair); } yield return(new KeyValuePair <string, string>($"idContext.{index}", WebDavPath.Combine(_pathPrefix, Path))); yield return(new KeyValuePair <string, string>($"order.{index}", Order.ToString())); yield return(new KeyValuePair <string, string>($"sort.{index}", SortBy)); yield return(new KeyValuePair <string, string>($"offset.{index}", Offset.ToString())); yield return(new KeyValuePair <string, string>($"amount.{index}", Amount.ToString())); }
public override IEnumerable <KeyValuePair <string, string> > ToKvp(int index) { foreach (var pair in base.ToKvp(index)) { yield return(pair); } yield return(new KeyValuePair <string, string>($"dst.{index}", WebDavPath.Combine("/disk", Destination))); yield return(new KeyValuePair <string, string>($"force.{index}", Force ? "1" : "0")); yield return(new KeyValuePair <string, string>($"size.{index}", Size.ToString())); yield return(new KeyValuePair <string, string>($"md5.{index}", Md5)); yield return(new KeyValuePair <string, string>($"sha256.{index}", Sha256)); }
public async Task <RenameResult> Rename(string fullPath, string newName) { string destPath = WebDavPath.Parent(fullPath); destPath = WebDavPath.Combine(destPath, newName); //var req = await new YadMoveRequest(HttpSettings, (YadWebAuth)Authent, fullPath, destPath).MakeRequestAsync(); await new YaDCommonRequest(HttpSettings, (YadWebAuth)Authent) .With(new YadMovePostModel(fullPath, destPath), out YadResponceModel <YadMoveRequestData, YadMoveRequestParams> itemInfo) .MakeRequestAsync(); var res = itemInfo.ToRenameResult(); return(res); }
/// <summary> /// Перемещение ссылки из одного каталога в другой /// </summary> /// <param name="link"></param> /// <param name="destinationPath"></param> /// <param name="doSave">Сохранить изменения в файл в облаке</param> /// <returns></returns> /// <remarks> /// Корневую ссылку просто перенесем /// /// Если это вложенная ссылка, то перенести ее нельзя, а можно /// 1. сделать новую ссылку на эту вложенность /// 2. скопировать содержимое /// если следовать логике, что при копировании мы копируем содержимое ссылок, а при перемещении - перемещаем ссылки, то надо делать новую ссылку /// /// Логика хороша, но /// некоторые клиенты сначала делают структуру каталогов, а потом по одному переносят файлы, например, TotalCommander c плагином WebDAV v.2.9 /// в таких условиях на каждый файл получится свой собственный линк, если делать правильно, т.е. в итоге расплодится миллин линков /// поэтому делаем неправильно - копируем содержимое линков /// </remarks> public async Task <bool> RemapLink(Link link, string destinationPath, bool doSave = true) { if (WebDavPath.PathEquals(link.MapPath, destinationPath)) { return(true); } if (link.IsRoot) { var rootlink = _itemList.Items.FirstOrDefault(it => WebDavPath.PathEquals(it.MapTo, link.MapPath) && it.Name == link.Name); if (rootlink != null) { string oldmap = rootlink.MapTo; rootlink.MapTo = destinationPath; Save(); _itemCache.Invalidate(link.FullPath, oldmap, destinationPath); return(true); } return(false); } // it's a link on inner item of root link, creating new link if (!link.IsResolved) { await ResolveLink(link); } var res = await Add( link.Href, destinationPath, link.Name, link.ItemType == MailRuCloud.ItemType.File, link.Size, DateTime.Now); if (res) { if (doSave) { Save(); } _itemCache.Invalidate(destinationPath); } return(res); }
/// <summary> /// Убрать все привязки на мёртвые ссылки /// </summary> /// <param name="doWriteHistory"></param> public async Task <int> RemoveDeadLinks(bool doWriteHistory) { var z = _cloud.GetItem(@"/__enc/3/_linked_test", MailRuCloud.ItemType.Folder, false).Result; var removes = _itemList.Items .AsParallel() .WithDegreeOfParallelism(5) .Select(it => GetItemLink(WebDavPath.Combine(it.MapTo, it.Name)).Result) .Where(itl => itl.IsBad || _cloud.GetItem(itl.MapPath, MailRuCloud.ItemType.Folder, false).Result == null) .ToList(); if (removes.Count == 0) { return(0); } _itemList.Items.RemoveAll(it => removes.Any(rem => WebDavPath.PathEquals(rem.MapPath, it.MapTo) && rem.Name == it.Name)); if (removes.Any()) { if (doWriteHistory) { foreach (var link in removes) { _itemCache.Invalidate(link.FullPath, link.MapPath); } string path = WebDavPath.Combine(WebDavPath.Root, HistoryContainerName); string res = await _cloud.DownloadFileAsString(path); var history = new StringBuilder(res ?? string.Empty); foreach (var link in removes) { history.Append($"{DateTime.Now} REMOVE: {link.Href} {link.Name}\r\n"); } _cloud.UploadFile(path, history.ToString()); } Save(); return(removes.Count); } return(0); }
public Task <IStoreItem> GetItemAsync(Uri uri, IHttpContext httpContext) { //TODO: Refact var path = GetPathFromUri(uri); //TODO: clean this trash try { var item = Cloud.Instance(httpContext).GetItems(path).Result; if (item != null) { if (item.FullPath == path) { var dir = new Folder(item.NumberOfFolders, item.NumberOfFiles, item.Size, path); return(Task.FromResult <IStoreItem>(new MailruStoreCollection(httpContext, LockingManager, dir, IsWritable))); } var fa = item.Files.FirstOrDefault(k => k.FullPath == path); if (fa != null) { return(Task.FromResult <IStoreItem>(new MailruStoreItem(LockingManager, fa, IsWritable))); } string parentPath = WebDavPath.Parent(path); item = Cloud.Instance(httpContext).GetItems(parentPath).Result; if (item != null) { var f = item.Files.FirstOrDefault(k => k.FullPath == path); return(null != f ? Task.FromResult <IStoreItem>(new MailruStoreItem(LockingManager, f, IsWritable)) : null); } } } catch (AggregateException e) { var we = e.InnerExceptions.OfType <WebException>().FirstOrDefault(); if (we == null || we.Status != WebExceptionStatus.ProtocolError) { throw; } } return(Task.FromResult <IStoreItem>(null)); }
public override async Task <SpecialCommandResult> Execute() { string source = WebDavPath.Clean(Parames.Count == 1 ? Path : Parames[0]); string target = WebDavPath.Clean(Parames.Count == 1 ? Parames[0] : Parames[1]); var sourceEntry = await Cloud.GetItem(source); if (null == sourceEntry) { return(SpecialCommandResult.Fail); } var res = await Cloud.Move(sourceEntry, target); return(new SpecialCommandResult { IsSuccess = res }); }
public override IEnumerable <KeyValuePair <string, string> > ToKvp(int index) { foreach (var pair in base.ToKvp(index)) { yield return(pair); } yield return(new KeyValuePair <string, string>($"id.{index}", WebDavPath.Combine(_prefix, Path))); //if (Path == "/Camera") //{ // yield return new KeyValuePair<string, string>($"id.{index}", "/photounlim/"); //} //else //{ // yield return new KeyValuePair<string, string>($"id.{index}", WebDavPath.Combine("/disk/", Path)); //} }
public async Task <IEntry> FolderInfo(string path, Link ulink, int offset = 0, int limit = Int32.MaxValue) { if (_creds.IsAnonymous) { return(await AnonymousRepo.FolderInfo(path, ulink, offset, limit)); } FolderInfoResult datares; try { datares = await new FolderInfoRequest(HttpSettings, Authent, ulink != null ? ulink.Href : path, ulink != null, offset, limit).MakeRequestAsync(); } catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound) { return(null); } MailRuCloud.ItemType itemType; //TODO: subject to refact, bad-bad-bad if (null == ulink || ulink.ItemType == MailRuCloud.ItemType.Unknown) { itemType = datares.body.home == path || WebDavPath.PathEquals("/" + datares.body.weblink, path) ? MailRuCloud.ItemType.Folder : MailRuCloud.ItemType.File; } else { itemType = ulink.ItemType; } var entry = itemType == MailRuCloud.ItemType.File ? (IEntry)datares.ToFile( home: WebDavPath.Parent(path), ulink: ulink, filename: ulink == null ? WebDavPath.Name(path) : ulink.OriginalName, nameReplacement: ulink?.IsLinkedToFileSystem ?? true ? WebDavPath.Name(path) : null) : datares.ToFolder(path, ulink); return(entry); }
///// <summary> ///// Проверка доступности ссылки ///// </summary> ///// <param name="link"></param> ///// <returns></returns> //private bool IsLinkAlive(ItemLink link) //{ // string path = WebDavPath.Combine(link.MapTo, link.Name); // try // { // var entry = _cloud.GetItem(path).Result; // return entry != null; // } // catch (AggregateException e) // when ( // let's check if there really no file or just other network error // e.InnerException is WebException we && // (we.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound // ) // { // return false; // } //} /// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="doResolveType">Resolving file/folder type requires addition request to cloud</param> /// <returns></returns> public async Task <Link> GetItemLink(string path, bool doResolveType = true) { var cached = _itemCache.Get(path); if (null != cached) { return((Link)cached); } //TODO: subject to refact string parent = path; ItemLink wp; string right = string.Empty; do { string name = WebDavPath.Name(parent); parent = WebDavPath.Parent(parent); wp = _itemList.Items.FirstOrDefault(ip => parent == ip.MapTo && name == ip.Name); if (null == wp) { right = WebDavPath.Combine(name, right); } } while (parent != WebDavPath.Root && null == wp); if (null == wp) { return(null); } string addhref = string.IsNullOrEmpty(right) ? string.Empty : '/' + Uri.EscapeDataString(right.TrimStart('/')); var link = new Link(wp, path, wp.Href + addhref); //resolve additional link properties, e.g. OriginalName, ItemType, Size if (doResolveType) { await ResolveLink(link); } _itemCache.Add(link.FullPath, link); return(link); }
/// <summary> /// Сохранить в файл в облаке список ссылок /// </summary> public void Save() { lock (_lockContainer) { Logger.Info($"Saving links to {LinkContainerName}"); string content = JsonConvert.SerializeObject(_itemList, Formatting.Indented); string path = WebDavPath.Combine(WebDavPath.Root, LinkContainerName); try { _cloud.FileUploaded -= OnFileUploaded; _cloud.UploadFile(path, content); } finally { _cloud.FileUploaded += OnFileUploaded; } } }
/// <summary> /// Убрать ссылку /// </summary> /// <param name="path"></param> /// <param name="doSave">Save container after removing</param> public bool RemoveLink(string path, bool doSave = true) { var name = WebDavPath.Name(path); var parent = WebDavPath.Parent(path); var z = _itemList.Items.FirstOrDefault(f => f.MapTo == parent && f.Name == name); if (z != null) { _itemList.Items.Remove(z); _itemCache.Invalidate(path, parent); if (doSave) { Save(); } return(true); } return(false); }
public async Task <PublishInfo> Publish(File file, bool makeShareFile = true, bool generateDirectVideoLink = false, bool makeM3UFile = false, SharedVideoResolution videoResolution = SharedVideoResolution.All) { if (file.Files.Count > 1 && (generateDirectVideoLink || makeM3UFile)) { throw new ArgumentException($"Cannot generate direct video link for splitted file {file.FullPath}"); } foreach (var innerFile in file.Files) { var url = await Publish(innerFile.FullPath); innerFile.PublicLinks.Clear(); innerFile.PublicLinks.Add(new PublicLinkInfo(url)); } var info = file.ToPublishInfo(this, generateDirectVideoLink, videoResolution); if (makeShareFile) { string path = $"{file.FullPath}{PublishInfo.SharedFilePostfix}"; UploadFileJson(path, info) .ThrowIf(r => !r, r => new Exception($"Cannot upload JSON file, path = {path}")); } if (makeM3UFile) { string path = $"{file.FullPath}{PublishInfo.PlaylistFilePostfix}"; var content = new StringBuilder(); { content.Append("#EXTM3U\r\n"); foreach (var item in info.Items) { content.Append($"#EXTINF:-1,{WebDavPath.Name(item.Path)}\r\n"); content.Append($"{item.PlaylistUrl}\r\n"); } } UploadFile(path, content.ToString()) .ThrowIf(r => !r, r => new Exception($"Cannot upload JSON file, path = {path}")); } return(info); }
public static File ToFile(this FolderInfoResult data, string home = null, Link ulink = null, string filename = null, string nameReplacement = null) { if (string.IsNullOrEmpty(filename)) { return(new File(WebDavPath.Combine(data.body.home ?? "", data.body.name), data.body.size)); } PatchEntryPath(data, home, ulink); var z = data.body.list? .Where(it => it.kind == "file") .Select(it => filename != null && it.name == filename ? it.ToFile(nameReplacement) : it.ToFile()) .ToList(); var groupedFile = z.ToGroupedFiles() .First(it => it.Name == (string.IsNullOrEmpty(nameReplacement) ? filename : nameReplacement)); return(groupedFile); }
public void ProcessRename(string fullPath, string newName) { string newPath = WebDavPath.Combine(WebDavPath.Parent(fullPath), newName); bool changed = false; foreach (var link in _itemList.Items) { if (WebDavPath.IsParentOrSame(fullPath, link.MapTo)) { link.MapTo = WebDavPath.ModifyParent(link.MapTo, fullPath, newPath); changed = true; } } if (changed) { _itemCache.Invalidate(fullPath, newPath); Save(); } }
public override async Task <SpecialCommandResult> Execute() { string path; string param = Parames.Count == 0 ? string.Empty : Parames[0].Replace("\\", WebDavPath.Separator); SharedVideoResolution videoResolution = Parames.Count < 2 ? Cloud.Settings.DefaultSharedVideoResolution : EnumExtensions.ParseEnumMemberValue <SharedVideoResolution>(Parames[1]); if (Parames.Count == 0) { path = Path; } else if (param.StartsWith(WebDavPath.Separator)) { path = param; } else { path = WebDavPath.Combine(Path, param); } var entry = await Cloud.GetItemAsync(path); if (null == entry) { return(SpecialCommandResult.Fail); } try { await Cloud.Publish(entry, true, _generateDirectVideoLink, _makeM3UFile, videoResolution); } catch (Exception e) { return(new SpecialCommandResult(false, e.Message)); } return(SpecialCommandResult.Success); }
/// <summary> /// Загрузить из файла в облаке список ссылок /// </summary> public void Load() { if (!_cloud.Account.IsAnonymous) { Logger.Info($"Loading links from {LinkContainerName}"); try { lock (_lockContainer) { //throw new Exception("temp"); string filepath = WebDavPath.Combine(WebDavPath.Root, LinkContainerName); var file = (File)_cloud.GetItem(filepath, Cloud.ItemType.File, false); if (file != null && file.Size > 3) //some clients put one/two/three-byte file before original file { _itemList = _cloud.DownloadFileAsJson <ItemList>(file); } } } catch (Exception e) { Logger.Warn("Cannot load links", e); } } if (null == _itemList) { _itemList = new ItemList(); } foreach (var f in _itemList.Items) { f.MapTo = WebDavPath.Clean(f.MapTo); if (!f.Href.IsAbsoluteUri) { f.Href = new Uri(_cloud.Repo.PublicBaseUrlDefault + f.Href); } } }
/// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="offset"></param> /// <param name="limit"></param> /// <param name="depth">Not applicable here, always = 1</param> /// <returns></returns> public async Task <IEntry> FolderInfo(RemotePath path, int offset = 0, int limit = Int32.MaxValue, int depth = 1) { FolderInfoResult datares; try { datares = await new FolderInfoRequest(HttpSettings, Authent, path, offset, limit).MakeRequestAsync(); } catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound) { return(null); } Cloud.ItemType itemType; if (null == path.Link || path.Link.ItemType == Cloud.ItemType.Unknown) { itemType = datares.Body.Home == path.Path || WebDavPath.PathEquals("/" + datares.Body.Weblink, path.Path) //datares.body.list.Any(fi => "/" + fi.weblink == path) ? Cloud.ItemType.Folder : Cloud.ItemType.File; } else { itemType = path.Link.ItemType; } var entry = itemType == Cloud.ItemType.File ? (IEntry)datares.ToFile( PublicBaseUrlDefault, home: WebDavPath.Parent(path.Path ?? string.Empty), ulink: path.Link, filename: path.Link == null ? WebDavPath.Name(path.Path) : path.Link.OriginalName, nameReplacement: path.Link?.IsLinkedToFileSystem ?? true ? WebDavPath.Name(path.Path) : null) : datares.ToFolder(PublicBaseUrlDefault, path.Path, path.Link); return(entry); }
public override async Task <SpecialCommandResult> Execute() { var res = await Task.Run(async() => { var sourceFileInfo = new FileInfo(Parames[0]); string name = sourceFileInfo.Name; string targetPath = WebDavPath.Combine(Path, name); Logger.Info($"COMMAND:COPY:{Parames[0]}"); using (var source = System.IO.File.Open(Parames[0], FileMode.Open, FileAccess.Read, FileShare.Read)) using (var target = await Cloud.GetFileUploadStream(targetPath, sourceFileInfo.Length).ConfigureAwait(false)) { source.CopyTo(target); } return(SpecialCommandResult.Success); }); return(res); }
/// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="ulink"></param> /// <param name="offset"></param> /// <param name="limit"></param> /// <param name="depth">Not applicable here, always = 1</param> /// <returns></returns> public async Task <IEntry> FolderInfo(string path, Link ulink, int offset = 0, int limit = Int32.MaxValue) { FolderInfoResult datares; try { datares = await new FolderInfoRequest(HttpSettings, Authent, ulink != null ? ulink.Href : path, ulink != null, offset, limit).MakeRequestAsync(); } catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound) { return(null); } MailRuCloud.ItemType itemType; if (null == ulink) { itemType = datares.body.home == path ? MailRuCloud.ItemType.Folder : MailRuCloud.ItemType.File; } else { itemType = ulink.ItemType; } var entry = itemType == MailRuCloud.ItemType.File ? (IEntry)datares.ToFile( home: WebDavPath.Parent(path), ulink: ulink, filename: ulink == null ? WebDavPath.Name(path) : ulink.OriginalName, nameReplacement: WebDavPath.Name(path)) : datares.ToFolder(path, ulink); return(entry); //var res = req; //return res; }
private async Task <IEntry> FolderInfo(string path, int depth = 1) { ListRequest.Result datares; try { datares = await new ListRequest(HttpSettings, Authent, ShardManager.MetaServer.Url, path, depth) .MakeRequestAsync(); // если файл разбит или зашифрован - то надо взять все куски // в протоколе V2 на запрос к файлу сразу приходит листинг каталога, в котором он лежит // здесь (протокол Bin) приходит информация именно по указанному файлу // поэтому вот такой костыль с двойным запросом //TODO: переделать двойной запрос к файлу if (datares.Item is FsFile fsfile && fsfile.Size < 2048) { string name = WebDavPath.Name(path); path = WebDavPath.Parent(path); datares = await new ListRequest(HttpSettings, Authent, ShardManager.MetaServer.Url, path, 1) .MakeRequestAsync(); var zz = datares.ToFolder(); return(zz.Files.First(f => f.Name == name)); } } catch (RequestException re) when(re.StatusCode == HttpStatusCode.NotFound) { return(null); } catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound) { return(null); } var z = datares.ToEntry(); return(z); }
public override async Task <SpecialCommandResult> Execute() { string name = Parames.Count > 0 && !string.IsNullOrWhiteSpace(Parames[0]) ? Parames[0] : ".wdmrc.list.lst"; string target = WebDavPath.Combine(Path, name); var data = await Cloud.Account.RequestRepo.FolderInfo(Path, null); var sb = new StringBuilder(); foreach (var e in Flat(data)) { string hash = (e as File)?.Hash ?? "-"; string link = string.IsNullOrWhiteSpace(e.PublicLink) ? "-" : e.PublicLink; sb.AppendLine( $"{e.FullPath}\t{e.Size.DefaultValue}\t{e.CreationTimeUtc:yyyy.MM.dd HH:mm:ss}\t{hash}\t{link}"); } Cloud.UploadFile(target, sb.ToString()); return(SpecialCommandResult.Success); }
public bool RenameLink(Link link, string newName) { // can't rename items within linked folder if (!link.IsRoot) { return(false); } var ilink = _itemList.Items.FirstOrDefault(it => WebDavPath.PathEquals(it.MapTo, link.MapPath) && it.Name == link.Name); if (null == ilink) { return(false); } if (ilink.Name == newName) { return(true); } ilink.Name = newName; Save(); _itemCache.Invalidate(link.MapPath); return(true); }
/// <summary> /// Привязать ссылку к облаку /// </summary> /// <param name="url">Ссылка</param> /// <param name="path">Путь в облаке, в который поместить ссылку</param> /// <param name="name">Имя для ссылки</param> /// <param name="isFile">Признак, что ссылка ведёт на файл, иначе - на папку</param> /// <param name="size">Размер данных по ссылке</param> /// <param name="creationDate">Дата создания</param> public async Task <bool> Add(string url, string path, string name, bool isFile, long size, DateTime?creationDate) { path = WebDavPath.Clean(path); var folder = (Folder)await _cloud.GetItemAsync(path); if (folder.Entries.Any(entry => entry.Name == name)) { return(false); } url = GetRelaLink(url); path = WebDavPath.Clean(path); if (folder.Entries.Any(entry => entry.Name == name)) { return(false); } if (_itemList.Items.Any(it => WebDavPath.PathEquals(it.MapTo, path) && it.Name == name)) { return(false); } _itemList.Items.Add(new ItemLink { Href = url, MapTo = path, Name = name, IsFile = isFile, Size = size, CreationDate = creationDate }); _itemCache.Invalidate(path); return(true); }