Esempio n. 1
0
        public override void ClearCache()
        {
            _IsReady = false;
            pathlist.Clear();

            var job = JobControler.CreateNewJob();

            job.DisplayName = "Initialize CarotCrypt";
            job.ProgressStr = "Initialize...";
            JobControler.Run(job, async(j) =>
            {
                job.Progress = -1;

                job.ProgressStr = "waiting for base system...";
                while (!RemoteServerFactory.ServerList[_dependService].IsReady)
                {
                    await Task.Delay(1000, j.Ct).ConfigureAwait(false);
                }

                job.ProgressStr = "loading...";
                var host        = await RemoteServerFactory.PathToItem(cryptRootPath, ReloadType.Reload).ConfigureAwait(false);
                if (host == null)
                {
                    return;
                }
                var root = new CarotCryptSystemItem(this, host, null);
                pathlist.AddOrUpdate("", (k) => root, (k, v) => root);
                await EnsureItem("", 1).ConfigureAwait(false);
                _IsReady = true;

                job.Progress    = 1;
                job.ProgressStr = "done.";
            });
        }
Esempio n. 2
0
        private Dictionary <string, IRemoteItem> ExpandPath(string basepath, IRemoteItem items)
        {
            var    total    = new ConcurrentBag <KeyValuePair <string, IRemoteItem> >();
            string filename = items.Name;

            total.Add(new KeyValuePair <string, IRemoteItem>(basepath + filename, items));
            if (items.ItemType == RemoteItemType.Folder)
            {
                var children = RemoteServerFactory.PathToItem(items.FullPath).Result.Children;
                if (children.Count() > 0)
                {
                    Parallel.ForEach(children,
                                     new ParallelOptions {
                        MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0))
                    },
                                     () => new Dictionary <string, IRemoteItem>(), (x, state, local) =>
                    {
                        return(local.Concat(ExpandPath(basepath + filename + "\\", RemoteServerFactory.PathToItem(x.FullPath).Result)).ToDictionary(y => y.Key, y => y.Value));
                    },
                                     (subtotal) =>
                    {
                        foreach (var i in subtotal)
                        {
                            total.Add(i);
                        }
                    });
                }
            }
            return(total.ToDictionary(y => y.Key, y => y.Value));
        }
Esempio n. 3
0
        public ClipboardRemoteDrive(IEnumerable <IRemoteItem> items)
        {
            if ((items?.Count() ?? 0) == 0)
            {
                throw new ArgumentException("no item selected");
            }

            var total = new ConcurrentBag <KeyValuePair <string, IRemoteItem> >();

            Parallel.ForEach(
                items,
                new ParallelOptions {
                MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0))
            },
                () => new Dictionary <string, IRemoteItem>(),
                (x, state, local) =>
            {
                return(local.Concat(ExpandPath("", RemoteServerFactory.PathToItem(x.FullPath).Result)).ToDictionary(y => y.Key, y => y.Value));
            },
                (subtotal) =>
            {
                foreach (var i in subtotal)
                {
                    total.Add(i);
                }
            });
            SortedDictionary <string, IRemoteItem> exItems = new SortedDictionary <string, IRemoteItem>(total.ToDictionary(y => y.Key, y => y.Value));

            selectedItemPaths = exItems.Values.Select(x => x.FullPath).ToArray();
            baseItemPaths     = items.Select(x => x.FullPath).ToArray();

            var flist = new List <FORMATETC>();

            using (var stream = new MemoryStream())
            {
                stream.Write(BitConverter.GetBytes(selectedItemPaths.Count()), 0, sizeof(int));

                int index = 0;
                foreach (var i in exItems)
                {
                    if (i.Value.ItemType == RemoteItemType.Folder)
                    {
                        addfolder(i.Key, stream);
                    }
                    else
                    {
                        addfile(i.Key, stream);
                    }
                    flist.Add(new FORMATETC {
                        cfFormat = CF_FILECONTENTS, dwAspect = DVASPECT.DVASPECT_CONTENT, lindex = index++, ptd = IntPtr.Zero, tymed = TYMED.TYMED_ISTREAM
                    });
                }

                stream.Position           = 0;
                fileGroupDescriptorBuffer = new byte[stream.Length];
                stream.Read(fileGroupDescriptorBuffer, 0, fileGroupDescriptorBuffer.Length);
            }
            formatetc = formatetc.Concat(flist).ToArray();
        }
Esempio n. 4
0
        static IRemoteItem CreateFolders(string path_str, Job controlJob)
        {
            var m = Regex.Match(path_str, @"^(?<server>[^:]+)(://)(?<path>.*)$");

            if (m.Success)
            {
                var servername = m.Groups["server"].Value;
                var server     = RemoteServerFactory.ServerList[servername];

                var paths   = m.Groups["path"].Value;
                var current = server[""];
                m = Regex.Match(paths, @"^(?<current>[^/\\]*)(/|\\)?(?<next>.*)$");
                while (!string.IsNullOrEmpty(m.Groups["current"].Value))
                {
                    controlJob.Ct.ThrowIfCancellationRequested();
                    current = RemoteServerFactory.PathToItem(current.FullPath).Result;

                    var child = current.Children.Where(x => x.PathItemName == m.Groups["current"].Value || x.Name == m.Groups["current"].Value).FirstOrDefault();
                    if (child == null)
                    {
                        current = server.ReloadItem(current.ID).Result;
                        child   = current.Children.Where(x => x.PathItemName == m.Groups["current"].Value || x.Name == m.Groups["current"].Value).FirstOrDefault();
                        if (child == null)
                        {
                            break;
                        }
                    }
                    current = child;
                    paths   = m.Groups["next"].Value;
                    m       = Regex.Match(paths, @"^(?<current>[^/\\]*)(/|\\)?(?<next>.*)$");
                }
                m = Regex.Match(paths, @"^(?<current>[^/\\]*)(/|\\)?(?<next>.*)$");
                while (!string.IsNullOrEmpty(m.Groups["current"].Value))
                {
                    controlJob.Ct.ThrowIfCancellationRequested();
                    var folderjob = current.MakeFolder(Uri.UnescapeDataString(m.Groups["current"].Value), WeekDepend: true, parentJob: controlJob);
                    folderjob.Wait(ct: controlJob.Ct);
                    current = folderjob.Result;
                    if (current == null)
                    {
                        return(null);
                    }
                    paths = m.Groups["next"].Value;
                    m     = Regex.Match(paths, @"^(?<current>[^/\\]*)(/|\\)?(?<next>.*)$");
                }
                return(current);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 5
0
        private IEnumerable <IRemoteItem> GetItems(IRemoteItem rootitem)
        {
            List <IRemoteItem> ret = new List <IRemoteItem>();

            if (rootitem == null)
            {
                return(ret);
            }
            ret.Add(rootitem);

            var target = rootitem.Children;

            if (target == null)
            {
                return(ret);
            }

            Parallel.ForEach(
                target,
                new ParallelOptions {
                MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0))
            },
                () => new List <IRemoteItem>(),
                (x, state, local) =>
            {
                var item = RemoteServerFactory.PathToItem(x.FullPath).Result;
                if (item == null)
                {
                    return(local);
                }
                local.Add(item);
                local.AddRange(GetItems(item));
                return(local);
            },
                (result) =>
            {
                lock (ret)
                    ret.AddRange(result);
            }
                );
            return(ret);
        }
Esempio n. 6
0
 public override void FixChain(IRemoteServer server)
 {
     try
     {
         _server = server;
         var orgItem = RemoteServerFactory.PathToItem(orgpath).Result;
         if (orgItem == null)
         {
             (_server as CarotCryptSystem)?.RemoveItem(ID);
             return;
         }
         decryptedPath = OrgPathToPath(orgItem as RemoteItemBase);
         decryptedName = (_server as CarotCryptSystem).CryptCarot.DecryptFilename(orgItem.Name) ?? "";
     }
     catch
     {
         System.Diagnostics.Debug.WriteLine(ID);
     }
     base.FixChain(server);
 }
Esempio n. 7
0
        private static Job InitServer(Job master)
        {
            var loadJob = JobControler.CreateNewJob(JobClass.Normal, depends: master);

            loadJob.WeekDepend  = true;
            loadJob.DisplayName = "Load server list";
            JobControler.Run(loadJob, (j) =>
            {
                j.Progress    = -1;
                j.ProgressStr = "Loading...";
                RemoteServerFactory.Restore();

                while (!RemoteServerFactory.ServerList.Values.All(x => x.IsReady))
                {
                    loadJob.Ct.ThrowIfCancellationRequested();
                    Task.Delay(500).Wait(loadJob.Ct);
                }

                j.Progress    = 1;
                j.ProgressStr = "Done.";
            });
            return(loadJob);
        }
Esempio n. 8
0
 public void GetData(ref FORMATETC format, out STGMEDIUM medium)
 {
     medium = new STGMEDIUM();
     if (format.dwAspect != DVASPECT.DVASPECT_CONTENT)
     {
         Marshal.ThrowExceptionForHR(DV_E_DVASPECT);
     }
     if (format.cfFormat == CF_CLOUD_DRIVE_ITEMS)
     {
         var mem = new MemoryStream();
         var bf  = new BinaryFormatter();
         bf.Serialize(mem, baseItemPaths); // copy string[] contains "server://path/to/item"
         mem.Position          = 0;
         medium.tymed          = TYMED.TYMED_ISTREAM;
         medium.unionmember    = Marshal.GetComInterfaceForObject(new StreamWrapper(mem), typeof(IStream));
         medium.pUnkForRelease = null;
     }
     else if (format.cfFormat == CF_FILEDESCRIPTORW)
     {
         var hGlobal = Marshal.AllocHGlobal(fileGroupDescriptorBuffer.Length);
         Marshal.Copy(fileGroupDescriptorBuffer, 0, hGlobal, fileGroupDescriptorBuffer.Length);
         medium.tymed          = TYMED.TYMED_HGLOBAL;
         medium.unionmember    = hGlobal;
         medium.pUnkForRelease = null;
     }
     else if (format.cfFormat == CF_FILECONTENTS)
     {
         if (format.lindex >= 0 && format.lindex < selectedItemPaths.Length)
         {
             medium.tymed = TYMED.TYMED_ISTREAM;
             dstream?.Dispose();
             medium.unionmember    = Marshal.GetComInterfaceForObject(new StreamWrapper(dstream = RemoteServerFactory.PathToItem(selectedItemPaths[format.lindex]).Result.DownloadItemRaw()), typeof(IStream));
             medium.pUnkForRelease = null;
         }
         else
         {
             Marshal.ThrowExceptionForHR(DV_E_TYMED);
         }
     }
     else
     {
         Marshal.ThrowExceptionForHR(DV_E_TYMED);
     }
 }
Esempio n. 9
0
 public override void Init()
 {
     RemoteServerFactory.Register(GetServiceName(), typeof(CarotCryptSystem));
 }
Esempio n. 10
0
        private async Task LoadItems(string ID, int depth = 0, bool deep = false)
        {
            if (depth < 0)
            {
                return;
            }
            ID = ID ?? "";

            bool master = true;

            loadinglist.AddOrUpdate(ID, new ManualResetEventSlim(false), (k, v) =>
            {
                if (v.IsSet)
                {
                    return(new ManualResetEventSlim(false));
                }

                master = false;
                return(v);
            });

            if (!master)
            {
                while (loadinglist.TryGetValue(ID, out var tmp) && tmp != null)
                {
                    await Task.Run(() => tmp.Wait()).ConfigureAwait(false);
                }
                return;
            }

            TSviewCloudConfig.Config.Log.LogOut("[LoadItems(CarotCryptSystem)] " + ID);
            try
            {
                var orgID = (string.IsNullOrEmpty(ID)) ? cryptRootPath : ID;
                if (!orgID.StartsWith(cryptRootPath))
                {
                    throw new ArgumentException("ID is not in root path", "ID");
                }
                var orgitem = await RemoteServerFactory.PathToItem(orgID, (deep)?ReloadType.Reload : ReloadType.Cache).ConfigureAwait(false);

                if (orgitem?.Children != null && orgitem.Children?.Count() != 0)
                {
                    var ret = new List <CarotCryptSystemItem>();
                    Parallel.ForEach(
                        orgitem.Children,
                        new ParallelOptions {
                        MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0))
                    },
                        () => new List <CarotCryptSystemItem>(),
                        (x, state, local) =>
                    {
                        if (!x.Name.StartsWith(cryptNameHeader))
                        {
                            return(local);
                        }

                        var child = RemoteServerFactory.PathToItem(x.FullPath, (deep) ? ReloadType.Reload : ReloadType.Cache).Result;
                        if (child == null)
                        {
                            return(local);
                        }

                        var item = new CarotCryptSystemItem(this, child, pathlist[ID]);
                        pathlist.AddOrUpdate(item.ID, (k) => item, (k, v) => item);
                        local.Add(item);
                        return(local);
                    },
                        (result) =>
                    {
                        lock (ret)
                            ret.AddRange(result);
                    }
                        );
                    pathlist[ID].SetChildren(ret);
                }
                else
                {
                    pathlist[ID].SetChildren(null);
                }
            }
            finally
            {
                ManualResetEventSlim tmp2;
                while (!loadinglist.TryRemove(ID, out tmp2))
                {
                    await Task.Delay(10).ConfigureAwait(false);
                }
                tmp2.Set();
            }
            if (depth > 0)
            {
                Parallel.ForEach(pathlist[ID].Children,
                                 new ParallelOptions {
                    MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0))
                },
                                 (x) => { LoadItems(x.ID, depth - 1).ConfigureAwait(false); });
            }
        }
Esempio n. 11
0
        public void OnDeserialized(StreamingContext c)
        {
            TSviewCloudConfig.Config.Log.LogOut("[Restore] CarotCryptSystem {0} as {1}", cryptRootPath, Name);
            CryptCarot = new CryptCarotDAV(cryptNameHeader)
            {
                Password = DrivePassword
            };
            loadinglist = new ConcurrentDictionary <string, ManualResetEventSlim>();

            var job = JobControler.CreateNewJob();

            job.DisplayName = "CryptCarotDAV";
            job.ProgressStr = "waiting parent";

            JobControler.Run(job, async(j) =>
            {
                j.ProgressStr = "Loading...";
                j.Progress    = -1;

                try
                {
                    int waitcount = 500;
                    while (!(RemoteServerFactory.ServerList.Keys.Contains(_dependService) && RemoteServerFactory.ServerList[_dependService].IsReady))
                    {
                        if (RemoteServerFactory.ServerList.Keys.Contains(_dependService))
                        {
                            await Task.Delay(1, job.Ct).ConfigureAwait(false);
                        }
                        else
                        {
                            await Task.Delay(1000, job.Ct).ConfigureAwait(false);
                        }

                        if (waitcount-- == 0)
                        {
                            throw new FileNotFoundException("Depend Service is not ready.", _dependService);
                        }
                    }
                }
                catch
                {
                    RemoteServerFactory.Delete(this);
                    return;
                }

                if (pathlist == null)
                {
                    pathlist = new ConcurrentDictionary <string, CarotCryptSystemItem>();
                    var root = new CarotCryptSystemItem(this, await RemoteServerFactory.PathToItem(cryptRootPath).ConfigureAwait(false), null);
                    pathlist.AddOrUpdate("", (k) => root, (k, v) => root);
                    await EnsureItem("", 1).ConfigureAwait(false);
                }
                else
                {
                    Parallel.ForEach(pathlist.Values.ToArray(),
                                     new ParallelOptions {
                        MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0))
                    },
                                     (x) => x.FixChain(this));
                }

                j.ProgressStr = "Done";
                j.Progress    = 1;

                _IsReady = true;
            });
        }
Esempio n. 12
0
        private void DoSearch()
        {
            if (radioButton_selected.Checked && SelectedItems == null)
            {
                return;
            }

            button_seach.Enabled      = false;
            button_cancel.Enabled     = true;
            button_showresult.Enabled = false;

            var typeAll    = radioButton_typeAll.Checked;
            var typeFolder = radioButton_typeFolder.Checked;
            var typeFile   = radioButton_typeFile.Checked;

            var selectall  = radioButton_SearchAll.Checked;
            var selectitem = radioButton_selected.Checked;
            var selecttree = radioButton_SerachFolder.Checked;
            var treepath   = textBox_SearchFolder.Text;

            var searchStr = comboBox_name.Text;

            var strstarts  = radioButton_startswith.Checked;
            var strends    = radioButton_endswith.Checked;
            var strcontain = radioButton_contain.Checked;

            var strregex = checkBox_regex.Checked;
            var strcase  = checkBox_case.Checked;

            var SizeOver  = checkBox_Over.Checked;
            var SizeUnder = checkBox_Under.Checked;
            var Over      = numericUpDown_over.Value;
            var Under     = numericUpDown_under.Value;

            var modifiedFromEnable = dateTimePicker_modifiedFrom.Checked;
            var modifiedToEnable   = dateTimePicker_modifiedTo.Checked;
            var createdFromEnable  = dateTimePicker_createdFrom.Checked;
            var createdToEnable    = dateTimePicker_createdTo.Checked;
            var modifiedFrom       = dateTimePicker_modifiedFrom.Value;
            var modifiedTo         = dateTimePicker_modifiedTo.Value;
            var createdFrom        = dateTimePicker_createdFrom.Value;
            var createdTo          = dateTimePicker_createdTo.Value;

            progressBar1.Style = ProgressBarStyle.Marquee;
            label_result.Text  = "wait for system...";

            SearchJob?.Cancel();
            SearchJob             = JobControler.CreateNewJob();
            SearchJob.DisplayName = "Search";
            JobControler.Run(SearchJob, (j) =>
            {
                j.ProgressStr = "Create index...";
                j.Progress    = -1;

                TSviewCloudConfig.Config.Log.LogOut("[Search] start");
                var sw = new System.Diagnostics.Stopwatch();
                try
                {
                    List <IRemoteItem> initselection = new List <IRemoteItem>();
                    List <IRemoteItem> selection     = new List <IRemoteItem>();

                    if (selectall)
                    {
                        initselection.AddRange(RemoteServerFactory.ServerList.Values.Select(x => x[""]));
                    }
                    if (selectitem)
                    {
                        initselection.AddRange(SelectedItems);
                    }
                    if (selecttree)
                    {
                        initselection.Add(RemoteServerFactory.PathToItem(treepath).Result);
                    }

                    synchronizationContext.Post((o) =>
                    {
                        label_result.Text = o as string;
                    }, "Prepare items...");

                    TSviewCloudConfig.Config.Log.LogOut("[Search] Create index");
                    sw.Start();

                    Parallel.ForEach(
                        initselection,
                        new ParallelOptions {
                        MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * 0.75) * 1.0))
                    },
                        () => new List <IRemoteItem>(),
                        (x, state, local) =>
                    {
                        if (x == null)
                        {
                            return(local);
                        }
                        var item = RemoteServerFactory.PathToItem(x.FullPath).Result;
                        if (item == null)
                        {
                            return(local);
                        }

                        local.AddRange(GetItems(item));
                        return(local);
                    },
                        (result) =>
                    {
                        lock (selection)
                            selection.AddRange(result);
                    }
                        );

                    synchronizationContext.Post((o) =>
                    {
                        label_result.Text = o as string;
                    }, "Prepare items done.");
                    sw.Stop();
                    var itemsearch_time = sw.Elapsed;



                    var search = selection.AsParallel();

                    if (typeFile)
                    {
                        search = search.Where(x => x.ItemType == RemoteItemType.File);
                    }
                    if (typeFolder)
                    {
                        search = search.Where(x => x.ItemType == RemoteItemType.Folder);
                    }


                    if (strregex)
                    {
                        if (!strcase)
                        {
                            search = search.Where(x => Regex.IsMatch(x.Name ?? "", searchStr));
                        }
                        else
                        {
                            search = search.Where(x => Regex.IsMatch(x.Name ?? "", searchStr, RegexOptions.IgnoreCase));
                        }
                    }
                    else
                    {
                        if (!strcase)
                        {
                            if (strstarts)
                            {
                                search = search.Where(x => (x.Name?.StartsWith(searchStr) ?? searchStr == ""));
                            }
                            if (strends)
                            {
                                search = search.Where(x => (x.Name?.EndsWith(searchStr) ?? searchStr == ""));
                            }
                            if (strcontain)
                            {
                                search = search.Where(x => (x.Name?.IndexOf(searchStr) >= 0));
                            }
                        }
                        else
                        {
                            search = search.Where(x => (
                                                      System.Globalization.CultureInfo.CurrentCulture.CompareInfo.IndexOf(
                                                          x.Name ?? "",
                                                          searchStr,
                                                          System.Globalization.CompareOptions.IgnoreCase | System.Globalization.CompareOptions.IgnoreKanaType | System.Globalization.CompareOptions.IgnoreWidth
                                                          | System.Globalization.CompareOptions.IgnoreNonSpace | System.Globalization.CompareOptions.IgnoreSymbols
                                                          ) >= 0));
                        }
                    }

                    if (SizeOver)
                    {
                        search = search.Where(x => (x.Size ?? 0) > Over);
                    }
                    if (SizeUnder)
                    {
                        search = search.Where(x => (x.Size ?? 0) < Under);
                    }


                    if (modifiedFromEnable)
                    {
                        search = search.Where(x => x.ModifiedDate > modifiedFrom);
                    }
                    if (modifiedToEnable)
                    {
                        search = search.Where(x => x.ModifiedDate < modifiedTo);
                    }

                    if (createdFromEnable)
                    {
                        search = search.Where(x => x.CreatedDate > createdFrom);
                    }
                    if (createdToEnable)
                    {
                        search = search.Where(x => x.CreatedDate < createdTo);
                    }

                    synchronizationContext.Post((o) =>
                    {
                        label_result.Text = o as string;
                    }, "Search...");
                    j.ProgressStr = "Search...";

                    TSviewCloudConfig.Config.Log.LogOut("[Search] Search");
                    sw.Restart();

                    SearchResult = search.ToArray();

                    sw.Stop();
                    var filteritem_time = sw.Elapsed;

                    j.Progress    = 1;
                    j.ProgressStr = "Found : " + SearchResult.Count().ToString();

                    synchronizationContext.Post((o) =>
                    {
                        label_result.Text         = o as string;
                        button_seach.Enabled      = true;
                        button_cancel.Enabled     = false;
                        button_showresult.Enabled = true;
                        progressBar1.Style        = ProgressBarStyle.Continuous;
                        SearchJob = null;
                    }, string.Format("Found : {0}, Index {1} search {2}", SearchResult.Count(), itemsearch_time, filteritem_time));

                    TSviewCloudConfig.Config.Log.LogOut("[Search] found " + SearchResult.Count().ToString());
                }
                catch
                {
                    TSviewCloudConfig.Config.Log.LogOut("[Search] Abort");

                    synchronizationContext.Post((o) =>
                    {
                        label_result.Text     = "abort";
                        button_seach.Enabled  = true;
                        button_cancel.Enabled = false;
                        progressBar1.Style    = ProgressBarStyle.Continuous;
                        SearchJob             = null;
                    }, null);
                }
            });
        }
Esempio n. 13
0
        static IEnumerable <IRemoteItem> FindItems(string path_str, bool recursive = false, IRemoteItem root = null, CancellationToken ct = default(CancellationToken), ReloadType reload = ReloadType.Reload)
        {
            ct.ThrowIfCancellationRequested();
            List <IRemoteItem> ret = new List <IRemoteItem>();

            if (string.IsNullOrEmpty(path_str))
            {
                if (root == null)
                {
                    if (recursive)
                    {
                        ret.AddRange(RemoteServerFactory.ServerList.Values.Select(x => x[""]).Select(x => FindItems("", true, x, ct, reload)).SelectMany(x => x));
                        return(ret);
                    }
                    else
                    {
                        ret.AddRange(RemoteServerFactory.ServerList.Values.Select(x => x[""]));
                        return(ret);
                    }
                }
                else
                {
                    root = RemoteServerFactory.PathToItem(root.FullPath, reload).Result;
                    if (root == null)
                    {
                        return(ret);
                    }
                    ret.Add(root);
                    var children = root.Children;
                    if (recursive)
                    {
                        ret.AddRange(children.Where(x => x.ItemType == RemoteItemType.File));
                        ret.AddRange(children.Where(x => x.ItemType == RemoteItemType.Folder).Select(x => FindItems("", true, x, ct, reload)).SelectMany(x => x));
                    }
                    return(ret);
                }
            }

            var m = Regex.Match(path_str, @"^(?<server>[^:]+)(://)(?<path>.*)$");

            if (m.Success)
            {
                var servername = m.Groups["server"].Value;
                if (servername.IndexOfAny(new[] { '?', '*' }) < 0)
                {
                    var server = RemoteServerFactory.ServerList[servername];
                    return(FindItems(m.Groups["path"].Value, recursive, server[""], ct, reload));
                }
                else
                {
                    var servers = RemoteServerFactory.ServerList.Keys;
                    return(servers.Where(x => Regex.IsMatch(x, "^" + Regex.Escape(servername).Replace("\\*", ".*").Replace("\\?", ".") + "$"))
                           .Select(x => FindItems(m.Groups["path"].Value, recursive, RemoteServerFactory.ServerList[x][""], ct, reload))
                           .SelectMany(x => x));
                }
            }
            else
            {
                if (root == null)
                {
                    return(ret);
                }

                m        = Regex.Match(path_str, @"^(?<current>[^/\\]*)(/|\\)?(?<next>.*)$");
                path_str = m.Groups["next"].Value;

                root = RemoteServerFactory.PathToItem(root.FullPath, reload).Result;
                if (root == null)
                {
                    return(ret);
                }
                var children = root.Children;

                var itemname = m.Groups["current"].Value;
                if (itemname == "**")
                {
                    ret.AddRange(FindItems(path_str, true, root, ct, reload));
                    ret.AddRange(children
                                 .Select(x => FindItems(path_str, true, x, ct, reload))
                                 .SelectMany(x => x));
                    ret.AddRange(children
                                 .Select(x => FindItems("**/" + path_str, true, x, ct, reload))
                                 .SelectMany(x => x));
                    return(ret.Distinct(new RemoteItemEqualityComparer()));
                }
                else if (itemname.IndexOfAny(new[] { '?', '*' }) < 0)
                {
                    return(children.Where(x => x.Name == itemname || x.PathItemName == itemname)
                           .Select(x => FindItems(path_str, recursive, x, ct, reload))
                           .SelectMany(x => x));
                }
                else
                {
                    return(children.Where(x => Regex.IsMatch(x.Name, "^" + Regex.Escape(itemname).Replace("\\*", ".*").Replace("\\?", ".") + "$"))
                           .Select(x => FindItems(path_str, recursive, x, ct, reload))
                           .SelectMany(x => x));
                }
            }
        }
Esempio n. 14
0
        private static int RunUpload(string[] targetArgs, string[] paramArgs)
        {
            string remotePath;
            string localPath;

            if (targetArgs.Length < 3)
            {
                Console.Error.WriteLine("upload needs more 2 arguments.");
                Console.Error.WriteLine("upload (localpath) (remotetarget)");
                return(0);
            }

            remotePath = targetArgs[2];
            remotePath = remotePath.Replace('\\', '/');
            localPath  = targetArgs[1];
            if (!localPath.Contains(':') && !localPath.StartsWith(@"\\"))
            {
                localPath = Path.GetFullPath(localPath);
            }
            if (!localPath.StartsWith(@"\\"))
            {
                localPath = ItemControl.GetLongFilename(localPath);
            }

            Console.Error.WriteLine("upload");
            Console.Error.WriteLine("remote: " + remotePath);
            Console.Error.WriteLine("local: " + ItemControl.GetOrgFilename(localPath));

            bool createFolder = false;

            foreach (var p in paramArgs)
            {
                switch (p)
                {
                case "createfolder":
                    Console.Error.WriteLine("(--createfolder: create folders)");
                    createFolder = true;
                    break;
                }
            }

            var job = JobControler.CreateNewJob(JobClass.ControlMaster);

            job.DisplayName = "Upload";
            JobControler.Run(job, (j) =>
            {
                try
                {
                    var j2 = InitServer(j);
                    j2.Wait(ct: j.Ct);

                    var target         = FindItems(remotePath, ct: j.Ct);
                    IRemoteItem remote = null;

                    if (target.Count() != 1 && !createFolder)
                    {
                        Console.Error.WriteLine("upload needs 1 remote target item.");
                        j.ResultAsObject = 2;
                        return;
                    }
                    if (target.Count() == 0 && createFolder)
                    {
                        Console.Error.WriteLine("Create new folders.");
                        remote = CreateFolders(remotePath, j);
                        if (remote == null)
                        {
                            Console.Error.WriteLine("make folder failed.");
                            j.ResultAsObject = 3;
                            return;
                        }
                    }
                    else
                    {
                        remote = target.First();
                    }

                    ConsoleJobDisp.Run();

                    if (File.Exists(localPath))
                    {
                        ItemControl.UploadFiles(remote, new[] { localPath }, true, j);
                    }
                    else if (Directory.Exists(localPath))
                    {
                        if (!localPath.EndsWith(":\\") && localPath.EndsWith("\\"))
                        {
                            localPath = localPath.TrimEnd('\\');
                        }
                        ItemControl.UploadFolder(remote, localPath, true, j);
                    }
                    else
                    {
                        Console.Error.WriteLine("upload localitem not found.");
                        j.ResultAsObject = 2;
                        return;
                    }

                    while (JobControler.JobTypeCount(JobClass.Upload) > 0)
                    {
                        JobControler.JobList().Where(x => x.JobType == JobClass.Upload).FirstOrDefault()?.Wait(ct: j.Ct);
                    }

                    var SaveConfigJob         = JobControler.CreateNewJob(TSviewCloudPlugin.JobClass.Save);
                    SaveConfigJob.DisplayName = "Save server list";
                    JobControler.Run(SaveConfigJob, (j3) =>
                    {
                        j3.Progress    = -1;
                        j3.ProgressStr = "Save...";

                        TSviewCloudConfig.Config.Save();
                        RemoteServerFactory.Save();

                        j3.Progress    = 1;
                        j3.ProgressStr = "Done.";
                    });
                    SaveConfigJob.Wait();

                    job.ResultAsObject = 0;
                }
                catch (OperationCanceledException)
                {
                    job.ResultAsObject = -1;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("error: " + ex.ToString());
                    job.ResultAsObject = 1;
                }
            });
            try
            {
                job.Wait(ct: job.Ct);
            }
            catch (OperationCanceledException)
            {
            }
            TSviewCloudConfig.Config.ApplicationExit = true;
            Console.Out.Flush();
            return((job.ResultAsObject as int?) ?? -1);
        }
Esempio n. 15
0
        private static int RunDownload(string [] targetArgs, string[] paramArgs)
        {
            string remotePath;
            string localPath;

            if (targetArgs.Length < 3)
            {
                Console.Error.WriteLine("download needs more 2 arguments.");
                Console.Error.WriteLine("download (remotepath) (localpath)");
                return(0);
            }

            remotePath = targetArgs[1];
            remotePath = remotePath.Replace('\\', '/');
            localPath  = targetArgs[2];
            if (!localPath.Contains(':') && !localPath.StartsWith(@"\\"))
            {
                localPath = Path.GetFullPath(localPath);
            }
            if (!localPath.StartsWith(@"\\"))
            {
                localPath = ItemControl.GetLongFilename(localPath);
            }

            Console.Error.WriteLine("download");
            Console.Error.WriteLine("remote: " + remotePath);
            Console.Error.WriteLine("local: " + ItemControl.GetOrgFilename(localPath));

            ReloadType reload = ReloadType.Reload;

            foreach (var p in paramArgs)
            {
                switch (p)
                {
                case "cache":
                    Console.Error.WriteLine("(--cache: no reload)");
                    reload = ReloadType.Cache;
                    break;
                }
            }

            var job = JobControler.CreateNewJob(JobClass.ControlMaster);

            job.DisplayName = "Download";
            JobControler.Run(job, (j) =>
            {
                try
                {
                    var j2 = InitServer(j);
                    j2.Wait(ct: j.Ct);

                    var target = FindItems(remotePath, ct: j.Ct, reload: reload);

                    if (target.Count() < 1)
                    {
                        j.ResultAsObject = 2;
                        return;
                    }

                    string remotePathBase = null;
                    if (remotePath.IndexOfAny(new[] { '*', '?' }) < 0)
                    {
                        remotePathBase = ItemControl.GetCommonPath(target);
                    }
                    else
                    {
                        remotePathBase = GetBasePath(remotePath);
                    }

                    target = RemoveDup(target);

                    ConsoleJobDisp.Run();

                    var j3 = target
                             .Where(x => x.ItemType == RemoteItemType.File)
                             .Select(x => RemoteServerFactory.PathToItem(x.FullPath, ReloadType.Reload).Result)
                             .Select(x => ItemControl.DownloadFile(Path.Combine(localPath, ItemControl.GetLocalFullPath(x.FullPath, remotePathBase)), x, j, true));
                    var j4 = target
                             .Where(x => x.ItemType == RemoteItemType.Folder)
                             .Select(x => RemoteServerFactory.PathToItem(x.FullPath, ReloadType.Reload).Result)
                             .Select(x => ItemControl.DownloadFolder(Path.GetDirectoryName(Path.Combine(localPath, ItemControl.GetLocalFullPath(x.FullPath, remotePathBase))), new[] { x }, j, true));

                    foreach (var jx in j3.Concat(j4).ToArray())
                    {
                        j.Ct.ThrowIfCancellationRequested();
                        jx.Wait(ct: j.Ct);
                    }

                    job.ResultAsObject = 0;
                }
                catch (OperationCanceledException)
                {
                    job.ResultAsObject = -1;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("error: " + ex.ToString());
                    job.ResultAsObject = 1;
                }
            });
            try
            {
                job.Wait(ct: job.Ct);
            }
            catch (OperationCanceledException)
            {
            }
            TSviewCloudConfig.Config.ApplicationExit = true;
            Console.Out.Flush();
            return((job.ResultAsObject as int?) ?? -1);
        }