Esempio n. 1
0
        private async void installClientButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult messageBoxResult;

            if (!ValheimPlusInstalledClient)
            {
                messageBoxResult = MessageBox.Show("Are you sure you wish to install ValheimPlus?", "Confirm", MessageBoxButton.YesNo);
            }
            else
            {
                messageBoxResult = MessageBox
                                   .Show("Are you sure you wish to reinstall ValheimPlus?", "Confirm", MessageBoxButton.YesNo);
            }

            if (messageBoxResult == MessageBoxResult.Yes)
            {
                try
                {
                    bool success = await UpdateManager.DownloadValheimPlusUpdateAsync(Settings.ValheimPlusServerClientVersion, true, true);

                    if (success)
                    {
                        ValheimPlusInstalledClient = ValidationManager.CheckInstallationStatus(Settings.ClientInstallationPath);
                        if (ValheimPlusInstalledClient)
                        {
                            Settings = SettingsDAL.GetSettings();
                            statusLabel.Foreground       = Brushes.Green;
                            clientInstalledLabel.Content = String.Format("ValheimPlus {0} installed on client", Settings.ValheimPlusGameClientVersion);
                            statusSnackBar.MessageQueue.Enqueue(String.Format("Success! ValheimPlus {0} installed on client", Settings.ValheimPlusGameClientVersion));
                            installClientUpdateButton.IsEnabled = false;
                            UISettingsInit();
                        }
                    }
                }
                catch (Exception)
                {
                    statusSnackBar.MessageQueue.Enqueue("An error occured, report it to the devs!");
                }
            }
        }
Esempio n. 2
0
        private void setServerPathButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new Microsoft.Win32.OpenFileDialog
            {
                Filter = "Executeable|valheim_server.exe"
            };

            if (dialog.ShowDialog() == true)
            {
                var    fullPath      = dialog.FileName;
                string formattedPath = String.Format("{0}\\", System.IO.Path.GetDirectoryName(fullPath));
                string uriPath       = new Uri(formattedPath).AbsolutePath.ToString();
                uriPath = Uri.UnescapeDataString(uriPath);
                Settings.ServerInstallationPath = uriPath;

                SettingsDAL.UpdateSettings(Settings, false);

                FetchSettings();

                statusSnackBar.MessageQueue.Enqueue("Path for server client set");
            }
        }
Esempio n. 3
0
        public void FetchSettings()
        {
            try
            {
                // Fetching path settings
                Settings = SettingsDAL.GetSettings();

                // Fetch current versions and update settings if needed
                bool success = UpdateManager.CheckCurrentVersion(Settings);

                if (success)
                {
                    // Checking paths and installation status
                    UISettingsInit();
                }
            }
            catch (Exception)
            {
                statusLabel.Foreground = Brushes.Red;
                statusLabel.Content    = "Error! Settings file not found, reinstall manager.";
            }
        }
Esempio n. 4
0
        private async void installServerUpdateButton_Click(object sender, RoutedEventArgs e)
        {
            installServerUpdateButton.IsEnabled = false;
            installServerUpdateButton.Content   = "Installing update ...";

            ValheimPlusUpdate valheimPlusUpdate = await UpdateManager.CheckForValheimPlusUpdatesAsync(Settings.ValheimPlusServerClientVersion);

            if (valheimPlusUpdate.NewVersion)
            {
                bool success = await UpdateManager.DownloadValheimPlusUpdateAsync(Settings.ValheimPlusServerClientVersion, false, false);

                if (success)
                {
                    Settings = SettingsDAL.GetSettings();
                    serverInstalledLabel.Content = String.Format("ValheimPlus {0} installed on server", Settings.ValheimPlusServerClientVersion);
                    statusSnackBar.MessageQueue.Enqueue("Success! Server client updated to latest version");
                    installServerUpdateButton.Content   = "Update installed!";
                    installServerUpdateButton.IsEnabled = false;
                    statusLabel.Visibility = Visibility.Hidden;
                }
            }
        }
        public static bool CheckCurrentVersion(Settings settings)
        {
            try
            {
                System.Diagnostics.FileVersionInfo serverClientVersion =
                    System.Diagnostics.FileVersionInfo.GetVersionInfo(String.Format("{0}BepInEx/plugins/ValheimPlus.dll", settings.ServerInstallationPath));

                if (serverClientVersion.FileVersion != settings.ValheimPlusServerClientVersion)
                {
                    settings.ValheimPlusServerClientVersion = serverClientVersion.FileVersion;
                    bool success = SettingsDAL.UpdateSettings(settings, false);
                }
            }
            catch (Exception)
            {
                //
            }

            try
            {
                System.Diagnostics.FileVersionInfo gameClientVersion =
                    System.Diagnostics.FileVersionInfo.GetVersionInfo(String.Format("{0}BepInEx/plugins/ValheimPlus.dll", settings.ClientInstallationPath));

                if (gameClientVersion.FileVersion != settings.ValheimPlusGameClientVersion)
                {
                    settings.ValheimPlusGameClientVersion = gameClientVersion.FileVersion;
                    bool success = SettingsDAL.UpdateSettings(settings, true);
                }
            }
            catch (Exception)
            {
                //
            }

            return(true);
        }
Esempio n. 6
0
        public static void CheckOrionProductTeamBlog()
        {
            HttpWebResponse httpWebResponse = WebRequestHelper.SendHttpWebRequest(BusinessLayerSettings.Instance.OrionProductTeamBlogUrl);

            if (httpWebResponse == null)
            {
                return;
            }
            using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                BlogItemDAL.StoreBlogItems(ProductBlogSvcWrapper.GetBlogItems((RssBlogItems) new XmlSerializer(typeof(RssBlogItems)).Deserialize((TextReader)streamReader)), Convert.ToInt32(SettingsDAL.Get("ProductsBlog-StoredPostsCount")));
        }
Esempio n. 7
0
 public SettingsBLL(string connection)
 {
     _connection = connection;
     DAL         = new SettingsDAL(connection);
 }
Esempio n. 8
0
 public SettingsLogic(LocaleDAL localeDAL, SettingsDAL settingsDAL)
 {
     _LocaleDAL   = localeDAL;
     _SettingsDAL = settingsDAL;
 }
Esempio n. 9
0
 public void GetSettingsTest()
 {
     Assert.IsNotNull(SettingsDAL.GetSettings());
 }
        public ScheduledJob CreateDiscoveryJob(
            DiscoveryConfiguration configuration,
            IDiscoveryPluginFactory pluginFactory)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            Engine engine = this.engineDAL.GetEngine(((DiscoveryConfigurationBase)configuration).get_EngineId());
            DiscoveryPollingEngineType?pollingEngineType = OrionDiscoveryJobFactory.GetDiscoveryPollingEngineType(configuration.get_EngineID(), this.engineDAL);
            int result;

            if (!int.TryParse(SettingsDAL.Get("SWNetPerfMon-Settings-SNMP MaxReps"), out result))
            {
                result = 5;
            }
            OrionDiscoveryJobDescription discoveryJobDescription1 = new OrionDiscoveryJobDescription();

            discoveryJobDescription1.set_ProfileId(((DiscoveryConfigurationBase)configuration).get_ProfileId());
            discoveryJobDescription1.set_EngineId(((DiscoveryConfigurationBase)configuration).get_EngineId());
            discoveryJobDescription1.set_HopCount(configuration.get_HopCount());
            discoveryJobDescription1.set_IcmpTimeout(configuration.get_SearchTimeout());
            DiscoveryCommonSnmpConfiguration snmpConfiguration = new DiscoveryCommonSnmpConfiguration();

            snmpConfiguration.set_MaxSnmpReplies(result);
            snmpConfiguration.set_SnmpRetries(configuration.get_SnmpRetries());
            snmpConfiguration.set_SnmpTimeout(configuration.get_SnmpTimeout());
            snmpConfiguration.set_SnmpPort(configuration.get_SnmpPort());
            snmpConfiguration.set_PreferredSnmpVersion(configuration.get_PreferredSnmpVersion());
            discoveryJobDescription1.set_SnmpConfiguration(snmpConfiguration);
            discoveryJobDescription1.set_DisableICMP(configuration.get_DisableICMP());
            discoveryJobDescription1.set_PreferredPollingMethod(((CoreDiscoveryPluginConfiguration)((DiscoveryConfigurationBase)configuration).GetDiscoveryPluginConfiguration <CoreDiscoveryPluginConfiguration>()).get_PreferredPollingMethod());
            discoveryJobDescription1.set_VulnerabilityCheckDisabled(SettingsDAL.GetCurrentInt("SWNetPerfMon-Settings-VulnerabilityCheckDisabled", 0) == 1);
            discoveryJobDescription1.set_MaxThreadsInDetectionPhase(SettingsDAL.GetCurrentInt("Discovery-MaxThreadsInDetectionPhase", 5));
            discoveryJobDescription1.set_MaxThreadsInInventoryPhase(SettingsDAL.GetCurrentInt("Discovery-MaxThreadsInInventoryPhase", 5));
            discoveryJobDescription1.set_PreferredDnsAddressFamily(SettingsDAL.GetCurrentInt("SWNetPerfMon-Settings-Default Preferred AddressFamily DHCP", 4));
            discoveryJobDescription1.set_TagFilter(configuration.get_TagFilter());
            discoveryJobDescription1.set_DefaultProbes(configuration.get_DefaultProbes());
            OrionDiscoveryJobDescription discoveryJobDescription2 = discoveryJobDescription1;
            List <DiscoveryPluginInfo>   discoveryPluginInfos     = DiscoveryPluginFactory.GetDiscoveryPluginInfos();
            IList <IDiscoveryPlugin>     plugins     = pluginFactory.GetPlugins((IList <DiscoveryPluginInfo>)discoveryPluginInfos);
            List <DiscoveryPluginInfo>   pluginInfos = new List <DiscoveryPluginInfo>();
            IDictionary <IDiscoveryPlugin, DiscoveryPluginInfo> pairsPluginAndInfo = DiscoveryPluginHelper.CreatePairsPluginAndInfo((IEnumerable <IDiscoveryPlugin>)plugins, (IEnumerable <DiscoveryPluginInfo>)discoveryPluginInfos);
            bool flag1 = RegistrySettings.IsFreePoller();

            using (IEnumerator <IDiscoveryPlugin> enumerator = ((IEnumerable <IDiscoveryPlugin>)plugins).GetEnumerator())
            {
                while (((IEnumerator)enumerator).MoveNext())
                {
                    IDiscoveryPlugin current = enumerator.Current;
                    if (flag1 && !(current is ISupportFreeEngine))
                    {
                        OrionDiscoveryJobFactory.log.DebugFormat("Discovery plugin {0} is not supported on FPE machine", (object)current);
                    }
                    else if (!((DiscoveryConfigurationBase)configuration).get_ProfileId().HasValue&& !(current is IOneTimeJobSupport))
                    {
                        OrionDiscoveryJobFactory.log.DebugFormat("Plugin {0} is not supporting one time job and it's description woun't be added.", (object)((object)current).GetType().FullName);
                    }
                    else
                    {
                        if (configuration.get_TagFilter() != null && configuration.get_TagFilter().Any <string>())
                        {
                            if (!(current is IDiscoveryPluginTags idiscoveryPluginTags))
                            {
                                OrionDiscoveryJobFactory.log.DebugFormat("Discovery job for tags requested, however plugin {0} doesn't support tags, skipping.", (object)current);
                                continue;
                            }
                            if (!configuration.get_TagFilter().Intersect <string>(idiscoveryPluginTags.get_Tags() ?? Enumerable.Empty <string>(), (IEqualityComparer <string>)StringComparer.InvariantCultureIgnoreCase).Any <string>())
                            {
                                OrionDiscoveryJobFactory.log.DebugFormat("Discovery job for tags [{0}], however plugin {1} doesn't support any of the tags requested, skipping.", (object)string.Join(",", (IEnumerable <string>)configuration.get_TagFilter()), (object)current);
                                continue;
                            }
                        }
                        if (configuration.get_IsAgentJob() && (!(current is IAgentPluginJobSupport pluginJobSupport) || !((IEnumerable <string>)configuration.get_AgentPlugins()).Contains <string>(pluginJobSupport.get_PluginId())))
                        {
                            OrionDiscoveryJobFactory.log.DebugFormat("Plugin {0} is not contained in supported agent plugins and will not be used.", (object)((object)current).GetType().FullName);
                        }
        // Token: 0x0600037A RID: 890 RVA: 0x00015B20 File Offset: 0x00013D20
        public ScheduledJob CreateDiscoveryJob(DiscoveryConfiguration configuration, IDiscoveryPluginFactory pluginFactory)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }
            Engine engine = this.engineDAL.GetEngine(configuration.EngineId);
            DiscoveryPollingEngineType?discoveryPollingEngineType = OrionDiscoveryJobFactory.GetDiscoveryPollingEngineType(configuration.EngineID, this.engineDAL);
            int maxSnmpReplies;

            if (!int.TryParse(SettingsDAL.Get("SWNetPerfMon-Settings-SNMP MaxReps"), out maxSnmpReplies))
            {
                maxSnmpReplies = 5;
            }
            OrionDiscoveryJobDescription orionDiscoveryJobDescription = new OrionDiscoveryJobDescription
            {
                ProfileId         = configuration.ProfileId,
                EngineId          = configuration.EngineId,
                HopCount          = configuration.HopCount,
                IcmpTimeout       = configuration.SearchTimeout,
                SnmpConfiguration = new DiscoveryCommonSnmpConfiguration
                {
                    MaxSnmpReplies       = maxSnmpReplies,
                    SnmpRetries          = configuration.SnmpRetries,
                    SnmpTimeout          = configuration.SnmpTimeout,
                    SnmpPort             = configuration.SnmpPort,
                    PreferredSnmpVersion = configuration.PreferredSnmpVersion
                },
                DisableICMP                = configuration.DisableICMP,
                PreferredPollingMethod     = configuration.GetDiscoveryPluginConfiguration <CoreDiscoveryPluginConfiguration>().PreferredPollingMethod,
                VulnerabilityCheckDisabled = (SettingsDAL.GetCurrentInt("SWNetPerfMon-Settings-VulnerabilityCheckDisabled", 0) == 1),
                MaxThreadsInDetectionPhase = SettingsDAL.GetCurrentInt("Discovery-MaxThreadsInDetectionPhase", 5),
                MaxThreadsInInventoryPhase = SettingsDAL.GetCurrentInt("Discovery-MaxThreadsInInventoryPhase", 5),
                PreferredDnsAddressFamily  = SettingsDAL.GetCurrentInt("SWNetPerfMon-Settings-Default Preferred AddressFamily DHCP", 4),
                TagFilter     = configuration.TagFilter,
                DefaultProbes = configuration.DefaultProbes
            };
            List <DiscoveryPluginInfo> discoveryPluginInfos = DiscoveryPluginFactory.GetDiscoveryPluginInfos();
            IList <IDiscoveryPlugin>   plugins = pluginFactory.GetPlugins(discoveryPluginInfos);
            List <DiscoveryPluginInfo> list    = new List <DiscoveryPluginInfo>();
            IDictionary <IDiscoveryPlugin, DiscoveryPluginInfo> dictionary = DiscoveryPluginHelper.CreatePairsPluginAndInfo(plugins, discoveryPluginInfos);
            bool flag = RegistrySettings.IsFreePoller();

            foreach (IDiscoveryPlugin discoveryPlugin in plugins)
            {
                if (flag && !(discoveryPlugin is ISupportFreeEngine))
                {
                    OrionDiscoveryJobFactory.log.DebugFormat("Discovery plugin {0} is not supported on FPE machine", discoveryPlugin);
                }
                else if (configuration.ProfileId == null && !(discoveryPlugin is IOneTimeJobSupport))
                {
                    OrionDiscoveryJobFactory.log.DebugFormat("Plugin {0} is not supporting one time job and it's description woun't be added.", discoveryPlugin.GetType().FullName);
                }
                else
                {
                    if (configuration.TagFilter != null && configuration.TagFilter.Any <string>())
                    {
                        IDiscoveryPluginTags discoveryPluginTags = discoveryPlugin as IDiscoveryPluginTags;
                        if (discoveryPluginTags == null)
                        {
                            OrionDiscoveryJobFactory.log.DebugFormat("Discovery job for tags requested, however plugin {0} doesn't support tags, skipping.", discoveryPlugin);
                            continue;
                        }
                        if (!configuration.TagFilter.Intersect(discoveryPluginTags.Tags ?? Enumerable.Empty <string>(), StringComparer.InvariantCultureIgnoreCase).Any <string>())
                        {
                            OrionDiscoveryJobFactory.log.DebugFormat("Discovery job for tags [{0}], however plugin {1} doesn't support any of the tags requested, skipping.", string.Join(",", configuration.TagFilter), discoveryPlugin);
                            continue;
                        }
                    }
                    if (configuration.IsAgentJob)
                    {
                        IAgentPluginJobSupport agentPluginJobSupport = discoveryPlugin as IAgentPluginJobSupport;
                        if (agentPluginJobSupport == null || !configuration.AgentPlugins.Contains(agentPluginJobSupport.PluginId))
                        {
                            OrionDiscoveryJobFactory.log.DebugFormat("Plugin {0} is not contained in supported agent plugins and will not be used.", discoveryPlugin.GetType().FullName);
                            continue;
                        }
                    }
                    if (discoveryPollingEngineType != null && !OrionDiscoveryJobFactory.IsDiscoveryPluginSupportedForDiscoveryPollingEngineType(discoveryPlugin, discoveryPollingEngineType.Value, dictionary))
                    {
                        if (OrionDiscoveryJobFactory.log.IsDebugEnabled)
                        {
                            OrionDiscoveryJobFactory.log.DebugFormat(string.Format("Plugin {0} is not supported for polling engine {1}", discoveryPlugin.GetType().FullName, configuration.EngineID), Array.Empty <object>());
                        }
                    }
                    else
                    {
                        DiscoveryPluginJobDescriptionBase discoveryPluginJobDescriptionBase = null;
                        Exception ex = null;
                        try
                        {
                            discoveryPluginJobDescriptionBase = discoveryPlugin.GetJobDescription(configuration);
                        }
                        catch (Exception ex2)
                        {
                            discoveryPluginJobDescriptionBase = null;
                            ex = ex2;
                        }
                        if (discoveryPluginJobDescriptionBase == null)
                        {
                            string text = "Plugin " + discoveryPlugin.GetType().FullName + " was not able found valid job description.";
                            if (ex != null)
                            {
                                OrionDiscoveryJobFactory.log.Warn(text, ex);
                            }
                            else
                            {
                                OrionDiscoveryJobFactory.log.Warn(text);
                            }
                        }
                        else
                        {
                            orionDiscoveryJobDescription.DiscoveryPluginJobDescriptions.Add(discoveryPluginJobDescriptionBase);
                            DiscoveryPluginInfo item = dictionary[discoveryPlugin];
                            list.Add(item);
                        }
                    }
                }
            }
            JobDescription jobDescription = new JobDescription
            {
                TypeName = typeof(OrionDiscoveryJob).AssemblyQualifiedName,
                JobDetailConfiguration = this.GetOrionDiscoveryJobDescriptionString(orionDiscoveryJobDescription, list, configuration.UseJsonFormat),
                JobNamespace           = "orion",
                ResultTTL       = TimeSpan.FromMinutes(10.0),
                TargetNode      = new HostAddress(IPAddressHelper.ToStringIp(engine.IP), 4),
                LegacyEngine    = engine.ServerName.ToLowerInvariant(),
                EndpointAddress = (configuration.IsAgentJob ? configuration.AgentAddress : null),
                SupportedRoles  = 7
            };

            jobDescription.Timeout = OrionDiscoveryJobFactory.GetDiscoveryJobTimeout(configuration);
            ScheduledJob scheduledJob;

            if (configuration.CronSchedule != null)
            {
                bool   flag2 = false;
                string text2 = configuration.CronSchedule.CronExpression;
                if (string.IsNullOrWhiteSpace(text2))
                {
                    DateTime t = configuration.CronSchedule.StartTime.ToLocalTime();
                    if (t < DateTime.Now)
                    {
                        OrionDiscoveryJobFactory.log.InfoFormat("Profile (ID={0}) with past Once(Cron) schedule. We should not create job for it.", configuration.ProfileID);
                        return(null);
                    }
                    text2 = string.Format("{0} {1} {2} {3} *", new object[]
                    {
                        t.Minute,
                        t.Hour,
                        t.Day,
                        t.Month
                    });
                    flag2 = true;
                }
                scheduledJob              = new ScheduledJob(jobDescription, text2, "net.pipe://localhost/orion/core/scheduleddiscoveryjobsevents2", configuration.ProfileID.ToString());
                scheduledJob.RunOnce      = flag2;
                scheduledJob.TimeZoneInfo = TimeZoneInfo.Local;
                if (!flag2)
                {
                    scheduledJob.Start = configuration.CronSchedule.StartTime.ToUniversalTime();
                    DateTime?endTime  = configuration.CronSchedule.EndTime;
                    DateTime maxValue = DateTime.MaxValue;
                    if ((endTime == null || (endTime != null && endTime.GetValueOrDefault() != maxValue)) && configuration.CronSchedule.EndTime != null)
                    {
                        scheduledJob.End = configuration.CronSchedule.EndTime.Value.ToUniversalTime();
                    }
                }
            }
            else if (!configuration.ScheduleRunAtTime.Equals(DateTime.MinValue))
            {
                scheduledJob = new ScheduledJob(jobDescription, configuration.ScheduleRunAtTime, "net.pipe://localhost/orion/core/scheduleddiscoveryjobsevents2", configuration.ProfileID.ToString());
            }
            else
            {
                scheduledJob = new ScheduledJob(jobDescription, configuration.ScheduleRunFrequency, "net.pipe://localhost/orion/core/scheduleddiscoveryjobsevents2", configuration.ProfileID.ToString());
            }
            return(scheduledJob);
        }
Esempio n. 12
0
        public static async Task <(string name, List <AvModel> av)> GetPossibleAvNameAndInfo(string fileName)
        {
            (string name, List <AvModel> av)ret = new();

            var    imgFolder = SettingService.GetSetting().Result.JavLibraryImageFolder;
            string name      = "";
            var    fi        = new FileInfo(fileName);

            var allPrefix             = new SettingsDAL().GetPrefix().Result.OrderByDescending(x => x.Length).ToList();
            var fileNameWithoutFormat = fi.Name.Replace(fi.Extension, "");

            foreach (var prefix in allPrefix)
            {
                if (fileNameWithoutFormat.Contains(prefix, StringComparison.OrdinalIgnoreCase))
                {
                    var pattern    = prefix + "{1}-?\\d{1,5}";
                    var possibleId = Regex.Match(fileNameWithoutFormat, pattern, RegexOptions.IgnoreCase).Value;

                    if (possibleId.Contains("-"))
                    {
                        name = possibleId;
                    }
                    else
                    {
                        bool          isFirst = true;
                        StringBuilder sb      = new StringBuilder();

                        foreach (var c in possibleId)
                        {
                            if (c >= '0' && c <= '9')
                            {
                                if (isFirst)
                                {
                                    sb.Append("-");
                                    isFirst = false;
                                }
                            }
                            sb.Append(c);
                        }

                        name = sb.ToString();
                    }

                    break;
                }
            }

            ret.name = name.ToUpper();

            if (!string.IsNullOrWhiteSpace(name))
            {
                var avs = await new JavLibraryDAL().GetAvModelByWhere($" AND AvId='{name}'");

                if (avs != null && avs.Any())
                {
                    //foreach (var av in avs)
                    //{
                    //    av.PicUrl = "file://" + (imgFolder + av.AvId + "-" + av.Name + ".jpg").Replace("\\", "/");
                    //}
                    ret.av = avs;
                }
                else
                {
                    ret.av = new List <AvModel>();
                }
            }
            else
            {
                ret.av = new List <AvModel>();
            }

            return(ret);
        }
Esempio n. 13
0
        public static async Task Rename(string folder, IProgress <string> progress)
        {
            List <string> allPrefix = new List <string>();
            Dictionary <FileInfo, List <AvModel> > ret = new Dictionary <FileInfo, List <AvModel> >();
            Dictionary <string, int> moveReocrd        = new Dictionary <string, int>();

            var moveSubFolder = @"\tempFin\";
            var moveFolder    = folder + moveSubFolder;
            int found         = 0;
            int notFound      = 0;

            progress.Report($"初始化移动目录 {moveFolder}");

            if (!Directory.Exists(moveFolder))
            {
                Directory.CreateDirectory(moveFolder);
            }
            else
            {
                var alreadyFiles = new DirectoryInfo(moveFolder).GetFiles();

                foreach (var f in alreadyFiles)
                {
                    moveReocrd.Add(f.Name.ToUpper(), 1);
                }
            }

            progress.Report("开始加载缓存");

            var avs = await new JavLibraryDAL().GetAvModelByWhere("");

            progress.Report($"共加载 {avs.Count} 条缓存并开始处理前缀");

            allPrefix = new SettingsDAL().GetPrefix().Result.OrderByDescending(x => x.Length).ToList();

            progress.Report($"共加载 {allPrefix.Count} 条前缀");

            progress.Report($"开始获取目录 {folder} 下的文件");

            var files = Directory.GetFiles(folder);

            progress.Report($"共获取 {files.Length} 个文件");

            foreach (var f in files)
            {
                progress.Report($"开始处理文件 {f}");

                bool           findMatch   = false;
                string         pi          = "";
                FileInfo       fi          = new FileInfo(f);
                List <AvModel> fiMatchList = new List <AvModel>();

                var fileNameWithoutFormat = fi.Name.Replace(fi.Extension, "");

                ret.Add(fi, fiMatchList);

                foreach (var prefix in allPrefix)
                {
                    if (fileNameWithoutFormat.Contains(prefix, StringComparison.OrdinalIgnoreCase))
                    {
                        progress.Report($"\t找到匹配前缀 {prefix}");

                        var pattern    = prefix + "{1}-?\\d{1,7}";
                        var possibleId = Regex.Match(fileNameWithoutFormat, pattern, RegexOptions.IgnoreCase).Value;

                        if (possibleId.Contains("-"))
                        {
                            pi = possibleId;
                        }
                        else
                        {
                            bool          isFirst = true;
                            StringBuilder sb      = new StringBuilder();

                            foreach (var c in possibleId)
                            {
                                if (c >= '0' && c <= '9')
                                {
                                    if (isFirst)
                                    {
                                        sb.Append("-");
                                        isFirst = false;
                                    }
                                }
                                sb.Append(c);
                            }

                            pi = sb.ToString();
                        }

                        if (!string.IsNullOrEmpty(pi))
                        {
                            progress.Report($"\t找到适配的番号 {pi}");

                            var possibleAv = avs.Where(x => x.AvId.Equals(pi, StringComparison.OrdinalIgnoreCase)).ToList();

                            if (possibleAv == null || possibleAv.Count <= 0)
                            {
                                var prefixPart = pi.Split('-')[0];
                                var numberPart = pi.Split('-')[1];

                                if (numberPart.StartsWith("00"))
                                {
                                    numberPart = numberPart.Substring(2);

                                    pi = prefixPart + "-" + numberPart;

                                    possibleAv = avs.Where(x => x.AvId.Equals(pi, StringComparison.OrdinalIgnoreCase)).ToList();
                                }
                            }

                            findMatch = true;
                            foreach (var av in possibleAv)
                            {
                                fiMatchList.AddRange(possibleAv);
                            }

                            progress.Report($"\t找到适配的AV {fiMatchList.Count} 条");

                            break;
                        }
                    }
                }

                if (findMatch)
                {
                    found++;
                }
                else
                {
                    notFound++;
                }
            }

            foreach (var item in ret)
            {
                if (item.Value.Count == 0)
                {
                    progress.Report($"文件 {item.Key.Name} 没有找到匹配");
                }
                else if (item.Value.Count > 1)
                {
                    foreach (var subItem in item.Value)
                    {
                        progress.Report($"文件 {item.Key.Name} 找到多条匹配,暂不处理");
                    }
                }
                else if (item.Value.Count == 1)
                {
                    progress.Report($"文件 {item.Key.Name} 找到1条匹配,开始处理");

                    var chinese = "";

                    if (item.Key.Name.Replace(item.Value.FirstOrDefault().AvId, "").Replace(item.Value.FirstOrDefault().Name, "").Contains("-C", StringComparison.OrdinalIgnoreCase) || item.Key.Name.Replace(item.Value.FirstOrDefault().AvId, "").Replace(item.Value.FirstOrDefault().Name, "").Contains("ch", StringComparison.OrdinalIgnoreCase))
                    {
                        chinese = "-C";
                    }

                    var tempFileName = item.Value.FirstOrDefault().AvId + "-" + item.Value.FirstOrDefault().Name + chinese + item.Key.Extension;
                    tempFileName = tempFileName.ToUpper();

                    if (moveReocrd.ContainsKey(tempFileName))
                    {
                        moveReocrd[tempFileName]++;

                        progress.Report($"\t存在移动记录,文件名后缀+1 -> {moveReocrd[tempFileName]}");

                        if (moveReocrd[tempFileName] == 2)
                        {
                            var oldFileMove = item.Value.FirstOrDefault().AvId + "-" + item.Value.FirstOrDefault().Name + "-1" + item.Key.Extension;
                            File.Move(moveFolder + tempFileName, moveFolder + oldFileMove.ToUpper());
                        }

                        tempFileName = item.Value.FirstOrDefault().AvId + "-" + item.Value.FirstOrDefault().Name + "-" + moveReocrd[tempFileName] + item.Key.Extension;
                    }
                    else
                    {
                        moveReocrd.Add(tempFileName, 1);
                    }

                    try
                    {
                        File.Move(item.Key.FullName, moveFolder + tempFileName);

                        progress.Report($"\t移动文件 -> {item.Key.FullName} 到 -> {moveFolder + tempFileName}");
                    }
                    catch (Exception ee)
                    {
                        progress.Report("异常 " + ee.ToString());
                    }
                }
            }

            progress.Report($"找到匹配 --> {found} 未找到匹配 --> {notFound}");
        }
Esempio n. 14
0
        public string GetCustomFields(int propID)
        {
            SettingsDAL setDAL = new SettingsDAL();

            return(setDAL.GetCustomFields(propID));
        }