Exemplo n.º 1
0
        public static string GetExecutable(string directory, EmulatorDefinitionProfile profile, bool relative)
        {
            if (!Directory.Exists(directory))
            {
                throw new Exception($"{directory} not found.");
            }

            var fileEnumerator = new SafeFileEnumerator(directory, "*.*", SearchOption.AllDirectories);

            foreach (var file in fileEnumerator)
            {
                if (file.Attributes.HasFlag(FileAttributes.Directory))
                {
                    continue;
                }

                var relativePath = file.FullName.Replace(Path.GetDirectoryName(file.FullName), "").Trim(Path.DirectorySeparatorChar);
                var regex        = new Regex(profile.StartupExecutable, RegexOptions.IgnoreCase);
                if (regex.IsMatch(relativePath))
                {
                    if (relative)
                    {
                        return(relativePath);
                    }
                    else
                    {
                        return(file.FullName);
                    }
                }
            }

            return(null);
        }
Exemplo n.º 2
0
        public static async Task <List <Program> > GetExecutablesFromFolder(string path, SearchOption searchOption, CancellationTokenSource cancelToken = null)
        {
            return(await Task.Run(() =>
            {
                var execs = new List <Program>();
                var files = new SafeFileEnumerator(path, "*.exe", SearchOption.AllDirectories);

                foreach (var file in files)
                {
                    if (cancelToken?.IsCancellationRequested == true)
                    {
                        return null;
                    }

                    if (file.Attributes.HasFlag(FileAttributes.Directory))
                    {
                        continue;
                    }

                    var versionInfo = FileVersionInfo.GetVersionInfo(file.FullName);
                    var programName = !string.IsNullOrEmpty(versionInfo.ProductName?.Trim()) ? versionInfo.ProductName : new DirectoryInfo(Path.GetDirectoryName(file.FullName)).Name;

                    execs.Add(new Program()
                    {
                        Path = file.FullName,
                        Icon = file.FullName,
                        WorkDir = Path.GetDirectoryName(file.FullName),
                        Name = programName
                    });
                }

                return execs;
            }));
        }
        public void StandardEnumTest()
        {
            var path       = @"c:\Windows\appcompat\";
            var enumerator = new SafeFileEnumerator(path, "*.*", SearchOption.AllDirectories);
            var files      = enumerator.ToList();

            CollectionAssert.IsNotEmpty(files);
        }
Exemplo n.º 4
0
        public static bool GetGameUsesEasyAntiCheat(string installDir)
        {
            if (string.IsNullOrEmpty(installDir) || !Directory.Exists(installDir))
            {
                return false;
            }

            var fileEnumerator = new SafeFileEnumerator(installDir, "EasyAntiCheat*.dll", SearchOption.AllDirectories);
            return fileEnumerator.Any() == true;
        }
Exemplo n.º 5
0
        public static bool GetGameRequiresOrigin(string installDir)
        {
            if (string.IsNullOrEmpty(installDir) || !Directory.Exists(installDir))
            {
                return false;
            }

            var fileEnumerator = new SafeFileEnumerator(installDir, "Activation.*", SearchOption.AllDirectories);
            return fileEnumerator.Any() == true;
        }
Exemplo n.º 6
0
        public static bool GetGameRequiresUplay(Game game)
        {
            if (string.IsNullOrEmpty(game.InstallDirectory) || !Directory.Exists(game.InstallDirectory))
            {
                return(false);
            }

            var fileEnumerator = new SafeFileEnumerator(game.InstallDirectory, "uplay_*_loader*", SearchOption.AllDirectories);

            return(fileEnumerator.Any() == true);
        }
Exemplo n.º 7
0
        public static bool GetGameUsesEasyAntiCheat(Game game)
        {
            if (string.IsNullOrEmpty(game.InstallDirectory) || !Directory.Exists(game.InstallDirectory))
            {
                return(false);
            }

            var fileEnumerator = new SafeFileEnumerator(game.InstallDirectory, "EasyAntiCheat*.dll", SearchOption.AllDirectories);

            return(fileEnumerator.Any() == true);
        }
Exemplo n.º 8
0
        private Task ScanExistingFilesToProcess(CancellationToken ct)
        {
            lock (_scanLock)
            {
                if (_fileScanTask.IsCanceled || _fileScanTask.IsCompleted || _fileScanTask.IsFaulted)
                {
                    _fileScanTask = Task.Run(
                        () =>
                    {
                        foreach (string filePath in SafeFileEnumerator.EnumerateFiles(this.Settings.SourceFolder, this.Settings.Filter, SearchOption.AllDirectories))
                        {
                            if (ct.IsCancellationRequested)
                            {
                                break;
                            }

                            FileInfo sourceInfo;
                            try
                            {
                                sourceInfo = new FileInfo(filePath);
                            }
                            catch (IOException)
                            {
                                continue;
                            }

                            foreach (var folder in this.Settings.DestinationFolders)
                            {
                                // do not stop the processing here in case of cancellation
                                // because we must stay coherent when sending events by file
                                // i.e. we must be careful not to send a partial destination list for a file
                                var destInfo = new FileInfo(GetDestinationFilePath(filePath, folder));

                                if (!IOHelper.AreSameFile(sourceInfo, destInfo))
                                {
                                    var newFileData = new FileTransferData {
                                        MachineName           = Environment.MachineName,
                                        MonitoredFolderPath   = _monitor.Path,
                                        DestinationFolderPath = folder,
                                        FileName   = sourceInfo.Name,
                                        TotalBytes = sourceInfo.Length
                                    };

                                    _fileTransferSubject.OnNext(newFileData);
                                }
                            }
                        }
                    });
                }
            }

            return(_fileScanTask);
        }
        public void OverUnsafeWorksTest()
        {
            var path = @"c:\Windows\appcompat\";

            var dirInfo = new System.IO.DirectoryInfo(path);

            Assert.Throws <UnauthorizedAccessException>(() => dirInfo.GetFiles("*.*", SearchOption.AllDirectories));

            var enumerator = new SafeFileEnumerator(path, "*.*", SearchOption.AllDirectories);

            Assert.DoesNotThrow(() => enumerator.ToList());
        }
Exemplo n.º 10
0
        internal void StartTransferring()
        {
            lock (_transferLock)
            {
                StartMonitoring();

                if (_fileTransferTask.IsCanceled || _fileTransferTask.IsFaulted || _fileTransferTask.IsCompleted)
                {
                    _fileScanCts = new CancellationTokenSource();
                    ScanExistingFilesToProcess(_fileScanCts.Token);

                    _fileTranferLoopCts = new CancellationTokenSource();
                    _fileCopyCts        = new CancellationTokenSource();

                    var fileTransferLoopCt = _fileTranferLoopCts.Token;
                    var fileCopyCt         = _fileCopyCts.Token;

                    _fileTransferTask = Task.Run(
                        async() =>
                    {
                        while (!fileTransferLoopCt.IsCancellationRequested)
                        {
                            foreach (var file in SafeFileEnumerator.EnumerateFiles(this.Settings.SourceFolder, this.Settings.Filter, SearchOption.AllDirectories))
                            {
                                if (fileTransferLoopCt.IsCancellationRequested)
                                {
                                    break;
                                }

                                await TransferFile(file, fileCopyCt).ConfigureAwait(false);
                            }

                            try
                            {
                                // force a resynchronisation every 30 seconds
                                // and wait an additional short delay to let Windows release handles
                                // (e.g. acquired by FileMonitor)
                                if (_newFileEvent.Wait(TimeSpan.FromSeconds(30), fileTransferLoopCt))
                                {
                                    await Task.Delay(TimeSpan.FromMilliseconds(250)).ConfigureAwait(false);
                                }
                            }
                            catch (OperationCanceledException)
                            {
                            }

                            _newFileEvent.Reset();
                        }
                    });
                }
            }
        }
        private IEnumerable <string> GetFiles(CancellationToken token)
        {
            List <string> extensions = new List <string>();

            if (searchInfo.IncludeImages)
            {
                extensions.AddRange(FileHelper.Pics);
            }
            if (searchInfo.IncludeAudios)
            {
                extensions.AddRange(FileHelper.Audio);
            }
            if (searchInfo.IncludeVideos)
            {
                extensions.AddRange(FileHelper.Video);
            }
            if (searchInfo.IncludeDocuments)
            {
                extensions.AddRange(FileHelper.Docs);
            }
            searchInfo.CustomFileTypes = searchInfo.CustomFileTypes ?? Enumerable.Empty <string>();
            extensions.AddRange(searchInfo.CustomFileTypes);
            extensions = extensions.Distinct().ToList();

            var files  = Enumerable.Empty <string>();
            var result = Extensions.GetOptimizedFolders(searchInfo.ScanLocations);

            foreach (var item in result.UniqueFolders.Where(x => x.Include))
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }
                var filter = new FileSearchFilter
                {
                    SearchOption         = item.IncludeSubfolders.HasValue && item.IncludeSubfolders.Value ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly,
                    ExtensionList        = new HashSet <string>(extensions),
                    ExcludedList         = new HashSet <string>(),
                    MinSize              = searchInfo.MinSize,
                    MaxSize              = searchInfo.MaxSize,
                    ModifyAfter          = searchInfo.ModifiedAfter,
                    ModifyBefore         = searchInfo.ModifiedBefore,
                    IncludeHiddenFolders = searchInfo.IncludeHiddenFolders,
                    IncludeSystemFolders = searchInfo.IncludeSystemFolders
                };
                files = files.Concat(SafeFileEnumerator.EnumerateFiles(item.Name, filter, token));
            }
            return(files);
        }
        private void GenerateFileJournal(AcquisitionParameter parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (!Directory.Exists(this.JournalAbsoluteSavePath))
            {
                return;
            }

            var now = DateTimePrecise.Now;

            var fileJournal = new FileJournal();

            fileJournal.JournalHeader.CreationDateTime = now;
            fileJournal.JournalHeader.CreationSource   = this.AgentUniversalName;
            fileJournal.JournalHeader.Id         = parameters.SequenceId;
            fileJournal.JournalHeader.Sequenceur = parameters.SequenceId;
            fileJournal.JournalHeader.Root       = Path.Combine(this.JournalRootPath, parameters.SequenceId);

            var filename            = string.IsNullOrWhiteSpace(this.Configuration.Agent.Journalisation.CharacterizationFileName) ? this.AgentUniversalName : string.Format("{0}.{1}", this.Configuration.Agent.Journalisation.CharacterizationFileName, this.AgentUniversalName);
            var xmlCompleteFileName = Path.Combine(this.JournalAbsoluteSavePath, parameters.SequenceId + "." + filename + this.FileJournalFileExtension);
            int rootLength          = 1 + Path.Combine(this.JournalRootPath, parameters.SequenceId).Length;

            using (var recorder = new JournalBufferedRecorder(xmlCompleteFileName, fileJournal, forceFlush: true))
            {
                try
                {
                    foreach (var file in SafeFileEnumerator.EnumerateFiles(this.JournalAbsoluteSavePath, "*.*", SearchOption.AllDirectories).Where(file => !Path.GetExtension(file).Equals(".fjx", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        fileJournal.Add(new FileJournalEntry {
                            FileName = Path.GetFileName(file), RelativePath = file.Substring(rootLength), DateTime = now
                        });
                    }

                    foreach (var journalEntry in _fileJournalEntries)
                    {
                        fileJournal.Add(journalEntry);
                    }
                }
                finally
                {
                    fileJournal.Close();
                }
            }
        }
Exemplo n.º 13
0
        public void Run(ref Report report, List <Dictionary <string, string> > list)
        {
            foreach (var directory in directories)
            {
                if (!Directory.Exists(directory))
                {
                    continue;
                }

                foreach (var file in SafeFileEnumerator.EnumerateFiles(directory, "*.exe", SearchOption.AllDirectories))
                {
                    if (file.Length > 248)
                    {
                        continue;
                    }

                    var fileDate = FileInspector.GetDate(file);

                    if ((fileDate - DateTime.Now).TotalDays > 14)
                    {
                        continue;
                    }

                    try
                    {
                        list.Add(new Dictionary <string, string>
                        {
                            { "token", "File" },
                            { "hash", "[" + FileInspector.GetHash(file) },
                            { "date", fileDate.ToString("MM-dd-yyyy") + "]" },
                            { "publisher", "(" + FileInspector.GetPublisher(file) + ")" },
                            { "path", file }
                        });
                    }
                    catch (IOException)
                    {
                        list.Add(new Dictionary <string, string>
                        {
                            { "token", "File" },
                            { "date", "[" + fileDate.ToString("MM-dd-yyyy") + "]" },
                            { "path", file }
                        });
                    }
                }
            }

            report.Add(list);
        }
Exemplo n.º 14
0
        public static async Task <List <Game> > SearchForGames(DirectoryInfoBase path, EmulatorProfile profile, CancellationTokenSource cancelToken = null)
        {
            return(await Task.Run(() =>
            {
                logger.Info($"Looking for games in {path}, using {profile.Name} emulator profile.");
                if (!profile.ImageExtensions.HasNonEmptyItems())
                {
                    throw new Exception("Cannot scan for games, emulator doesn't support any file types.");
                }

                var games = new List <Game>();
                var fileEnumerator = new SafeFileEnumerator(path, "*.*", SearchOption.AllDirectories);
                foreach (var file in fileEnumerator)
                {
                    if (cancelToken?.IsCancellationRequested == true)
                    {
                        return null;
                    }

                    if (file.Attributes.HasFlag(FileAttributes.Directory))
                    {
                        continue;
                    }

                    foreach (var extension in profile.ImageExtensions)
                    {
                        if (extension.IsNullOrEmpty())
                        {
                            continue;
                        }

                        if (string.Equals(file.Extension.TrimStart('.'), extension.Trim(), StringComparison.OrdinalIgnoreCase))
                        {
                            var newGame = new Game()
                            {
                                Name = StringExtensions.NormalizeGameName(StringExtensions.GetPathWithoutAllExtensions(Path.GetFileName(file.Name))),
                                GameImagePath = file.FullName,
                                InstallDirectory = Path.GetDirectoryName(file.FullName)
                            };

                            games.Add(newGame);
                        }
                    }
                }

                return games;
            }));
        }
Exemplo n.º 15
0
        public static bool TryGetGameActions(string installDir, out GameAction playAction, out List <GameAction> otherActions)
        {
            var fileEnum = new SafeFileEnumerator(installDir, ".itch.toml", SearchOption.AllDirectories);

            if (fileEnum.Any())
            {
                var strMan   = File.ReadAllText(fileEnum.First().FullName);
                var manifest = Serialization.FromToml <LaunchManifest>(strMan);
                if (manifest.actions?.Any() == true)
                {
                    playAction   = null;
                    otherActions = new List <GameAction>();
                    foreach (var action in manifest.actions)
                    {
                        if (action.name.Equals("play", StringComparison.OrdinalIgnoreCase))
                        {
                            playAction = new GameAction
                            {
                                IsHandledByPlugin = true,
                                Name       = "Play",
                                Path       = action.path,
                                WorkingDir = action.path.IsHttpUrl() ? null : ExpandableVariables.InstallationDirectory,
                                Type       = action.path.IsHttpUrl() ? GameActionType.URL : GameActionType.File,
                                Arguments  = action.args?.Any() == true?string.Join(" ", action.args) : null
                            };
                        }
                        else
                        {
                            otherActions.Add(new GameAction
                            {
                                Name       = action.name,
                                Path       = action.path,
                                WorkingDir = action.path.IsHttpUrl() ? null : ExpandableVariables.InstallationDirectory,
                                Type       = action.path.IsHttpUrl() ? GameActionType.URL : GameActionType.File,
                                Arguments  = action.args?.Any() == true ? string.Join(" ", action.args) : null
                            });
                        }
                    }

                    return(true);
                }
            }

            playAction   = null;
            otherActions = null;
            return(false);
        }
Exemplo n.º 16
0
        public static List <IGame> SearchForGames(DirectoryInfoBase path, EmulatorProfile profile)
        {
            logger.Info($"Looking for games in {path}, using {profile.Name} emulator profile.");
            if (profile.ImageExtensions == null)
            {
                throw new Exception("Cannot scan for games, emulator doesn't support any file types.");
            }

            var games          = new List <IGame>();
            var fileEnumerator = new SafeFileEnumerator(path, "*.*", SearchOption.AllDirectories);

            foreach (var file in fileEnumerator)
            {
                if (file.Attributes.HasFlag(FileAttributes.Directory))
                {
                    continue;
                }

                foreach (var extension in profile.ImageExtensions)
                {
                    if (string.Equals(file.Extension.TrimStart('.'), extension, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var newGame = new Game()
                        {
                            Name             = StringExtensions.NormalizeGameName(Path.GetFileNameWithoutExtension(file.Name)),
                            IsoPath          = file.FullName,
                            InstallDirectory = Path.GetDirectoryName(file.FullName)
                        };

                        games.Add(newGame);
                    }
                }
            }

            return(games);
        }
Exemplo n.º 17
0
    private Dictionary <string, LanguageProfile> BuildFileList(ProgressReporter progressReporter, CancellationToken cancellationToken)
    {
        var files = new Dictionary <string, LanguageProfile>();

        //build extension-profile map
        var profileExtensions = new Dictionary <string, LanguageProfile>();

        foreach (var profile in Profiles)
        {
            foreach (var ext in profile.Extensions.Where(ext => !profileExtensions.ContainsKey(ext.ToUpper())))
            {
                profileExtensions.Add(ext.ToUpper(), profile);
            }
        }

        Func <string, LanguageProfile> getMappedProfile = delegate(string path)
        {
            var             ext     = Path.GetExtension(path);
            LanguageProfile profile = null;

            if (ext != null)
            {
                profileExtensions.TryGetValue(ext.ToUpper(), out profile);
            }

            return(profile);
        };

        Func <string, bool> ignoreFile = delegate(string path)
        {
            var attr = File.GetAttributes(path);

            return(attr.HasFlag(FileAttributes.Hidden) || attr.HasFlag(FileAttributes.System));
        };

        foreach (var path in _pathOptions)
        {
            if (!Directory.Exists(path.Path) && !File.Exists(path.Path))
            {
                continue;
            }

            var attr = File.GetAttributes(path.Path);


            if (attr.HasFlag(FileAttributes.Directory))
            {
                foreach (var file in SafeFileEnumerator.EnumerateFiles(path.Path, "*.*", path.Option))
                {
                    try
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        if (ignoreFile(file))
                        {
                            continue;
                        }

                        var profile = getMappedProfile(file);
                        if (profile != null && !files.ContainsKey(file))
                        {
                            files[file] = profile;
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        _wasCancelled = true;
                        //return empty results on cancellation
                        return(new Dictionary <string, LanguageProfile>());
                    }
                }
            }

            else
            {
                try
                {
                    if (ignoreFile(path.Path))
                    {
                        continue;
                    }

                    var profile = getMappedProfile(path.Path);

                    if (profile != null && !files.ContainsKey(path.Path))
                    {
                        files[path.Path] = profile;
                    }
                }

                catch (UnauthorizedAccessException)
                {
                }
            }
        }

        return(files);
    }
Exemplo n.º 18
0
        public static List <ScannedEmulator> SearchForEmulators(DirectoryInfoBase path, List <EmulatorDefinition> definitions)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();

            logger.Info($"Looking for emulators in {path}, using {definitions.Count} definitions.");
            var emulators = new Dictionary <EmulatorDefinition, List <ScannedEmulatorProfile> >();

            var fileEnumerator = new SafeFileEnumerator(path, "*.exe", SearchOption.AllDirectories);

            foreach (var file in fileEnumerator)
            {
                if (file.Attributes.HasFlag(FileAttributes.Directory))
                {
                    continue;
                }

                foreach (var definition in definitions)
                {
                    foreach (var defProfile in definition.Profiles)
                    {
                        var reqMet = true;
                        var folder = Path.GetDirectoryName(file.FullName);
                        var regex  = new Regex(defProfile.ExecutableLookup, RegexOptions.IgnoreCase);
                        if (regex.IsMatch(file.Name))
                        {
                            if (defProfile.RequiredFiles?.Any() == true)
                            {
                                foreach (var reqFile in defProfile.RequiredFiles)
                                {
                                    if (!File.Exists(Path.Combine(folder, reqFile)))
                                    {
                                        reqMet = false;
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            reqMet = false;
                        }

                        if (reqMet)
                        {
                            var emuProfile = new ScannedEmulatorProfile()
                            {
                                Name              = defProfile.Name,
                                Arguments         = defProfile.DefaultArguments,
                                Executable        = file.FullName,
                                WorkingDirectory  = folder,
                                ImageExtensions   = defProfile.ImageExtensions,
                                ProfileDefinition = defProfile
                            };

                            if (!emulators.ContainsKey(definition))
                            {
                                emulators.Add(definition, new List <ScannedEmulatorProfile>());
                            }

                            emulators[definition].Add(emuProfile);
                        }
                    }
                }
            }

            var result = new List <ScannedEmulator>();

            foreach (var key in emulators.Keys)
            {
                result.Add(new ScannedEmulator(key.Name, emulators[key]));
            }

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds / 1000);

            return(result);
        }
Exemplo n.º 19
0
        public void Search()
        {
            try
            {
                if (!string.IsNullOrEmpty(SearchTerm))
                {
                    IsCheckIOBusy = true;
                    FileCollection.Clear();

                    IsRightPanelVisible = false;
                    if (!isFavoriteView)
                    {
                        IsFavoriteView = false;
                        if (!isSearchInActive)
                        {
                            searchFolder = currentFolder;
                            previousFolderBeforeSearch = previousFolder;
                        }

                        if (lastSearchTerm != searchTerm)
                        {
                            lastSearchTerm = searchTerm;
                            ClearMenu();

                            var clearSearchName = Properties.Resource.lblClearSearchResults;
                            var clearSearchMenu = new TCFile(clearSearchName, searchFolder, previousFolderBeforeSearch, TCFile.TCType.CLEAR, null);
                            clearSearchMenu.FileClickedEvent += MenuItem_FileClickedEvent;
                            FolderMenu.Add(clearSearchMenu);

                            var searchItemName    = Properties.Resource.lblSearchResults;
                            var searchResultsMenu = new TCFile(searchItemName, searchFolder, previousFolderBeforeSearch, TCFile.TCType.SEARCH, null);
                            searchResultsMenu.FileClickedEvent += MenuItem_FileClickedEvent;
                            FolderMenu.Add(searchResultsMenu);
                        }

                        try
                        {
                            List <FileInfo> searchResults           = new List <FileInfo>();
                            var             fileSearchStringResults = SafeFileEnumerator.EnumerateFiles(searchFolder, $"*{SearchTerm}*", SearchOption.AllDirectories);
                            foreach (var filePath in fileSearchStringResults)
                            {
                                FileInfo fileToAdd = new FileInfo(filePath);
                                searchResults.Add(fileToAdd);
                            }
                            isSearchInActive = true;
                            RenderFilesInView(searchResults, true);
                        }
                        catch (UnauthorizedAccessException ue)
                        {
                            Console.WriteLine(ue.Message);
                        }
                        catch (FileNotFoundException fnfe)
                        {
                            Console.WriteLine(fnfe.Message);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }

                        try
                        {
                            List <DirectoryInfo> searchDirResults = new List <DirectoryInfo>();
                            var fileSearchStringResults           = SafeFileEnumerator.EnumerateDirectories(searchFolder, $"*{SearchTerm}*", SearchOption.AllDirectories);
                            foreach (var filePath in fileSearchStringResults)
                            {
                                DirectoryInfo fileToAdd = new DirectoryInfo(filePath);
                                searchDirResults.Add(fileToAdd);
                            }
                            RenderDirectoriesInView(searchDirResults);
                        }
                        catch (UnauthorizedAccessException ue)
                        {
                            Console.WriteLine(ue.Message);
                        }
                        catch (DirectoryNotFoundException dnfe)
                        {
                            Console.WriteLine(dnfe.Message);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                    else
                    {
                        var searchResults = _referenceService.SearchFavorite(SearchTerm);
                        RenderFavorites(searchResults);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Search failed: {0}", e.ToString());
            }
        }
Exemplo n.º 20
0
        public static async Task <List <ScannedEmulator> > SearchForEmulators(DirectoryInfoBase path, List <EmulatorDefinition> definitions, CancellationTokenSource cancelToken = null)
        {
            return(await Task.Run(() =>
            {
                logger.Info($"Looking for emulators in {path}, using {definitions.Count} definitions.");
                var emulators = new Dictionary <EmulatorDefinition, List <ScannedEmulatorProfile> >();

                var fileEnumerator = new SafeFileEnumerator(path, "*.exe", SearchOption.AllDirectories);
                foreach (var file in fileEnumerator)
                {
                    if (cancelToken?.IsCancellationRequested == true)
                    {
                        return null;
                    }

                    if (file.Attributes.HasFlag(FileAttributes.Directory))
                    {
                        continue;
                    }

                    foreach (var definition in definitions)
                    {
                        foreach (var defProfile in definition.Profiles)
                        {
                            var reqMet = true;
                            var folder = Path.GetDirectoryName(file.FullName);
                            var regex = new Regex(defProfile.ExecutableLookup, RegexOptions.IgnoreCase);
                            if (regex.IsMatch(file.Name))
                            {
                                if (defProfile.RequiredFiles?.Any() == true)
                                {
                                    foreach (var reqFile in defProfile.RequiredFiles)
                                    {
                                        if (!File.Exists(Path.Combine(folder, reqFile)))
                                        {
                                            reqMet = false;
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                reqMet = false;
                            }

                            if (reqMet)
                            {
                                var emuProfile = new ScannedEmulatorProfile()
                                {
                                    Name = defProfile.Name,
                                    Arguments = defProfile.DefaultArguments,
                                    Executable = file.FullName,
                                    WorkingDirectory = folder,
                                    ImageExtensions = defProfile.ImageExtensions,
                                    ProfileDefinition = defProfile
                                };

                                if (!emulators.ContainsKey(definition))
                                {
                                    emulators.Add(definition, new List <ScannedEmulatorProfile>());
                                }

                                emulators[definition].Add(emuProfile);
                            }
                        }
                    }
                }

                var result = new List <ScannedEmulator>();
                foreach (var key in emulators.Keys)
                {
                    result.Add(new ScannedEmulator(key.Name, emulators[key]));
                }

                return result;
            }));
        }
Exemplo n.º 21
0
    static void Main(string[] args)
    {
        // DirectoryInfo diTop = new DirectoryInfo(@"e:\");
        var sf = new SafeFileEnumerator(@"e:\Sync\", @"*.NEF");

        long sum = 0;

        try
        {
            foreach (var path  in sf)
            {
                var nefFileInfo   = new FileInfo(path);
                var directoryInfo = nefFileInfo.Directory;
                if (directoryInfo == null)
                {
                    continue;
                }
                //directoryInfo.WriteLine(directoryInfo.FullName);
                if (directoryInfo.Name.ToLower() == "raw" && directoryInfo.Parent != null)
                {
                    var jpgPath = Path.Combine(directoryInfo.Parent.FullName,
                                               Path.GetFileNameWithoutExtension(path) + ".JPG");
                    if (!File.Exists(jpgPath))
                    {
                        Console.WriteLine(nefFileInfo.FullName);
                        sum += nefFileInfo.Length;
                    }
                }
            }
            var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
            nfi.NumberGroupSeparator = " ";
            string formatted = (sum / 1000.0).ToString("#,0.00", nfi); // "1 234 897.11"

            Console.WriteLine(ToByteSize(sum));
//            foreach (var di in diTop.EnumerateDirectories("?aw", SearchOption.AllDirectories))
//            {
//                try
//                {
//                    Console.WriteLine($"{di.FullName}");
//                    Console.WriteLine($"{di.Parent?.FullName}");
//                }
//                catch (UnauthorizedAccessException unAuthTop)
//                {
//                    Console.WriteLine("{0}", unAuthTop.Message);
//                }
//            }

//            foreach (var di in diTop.EnumerateDirectories("*"))
//            {
//                try
//                {
//                    foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
//                    {
//                        try
//                        {
//                            // Display each file over 10 MB;
//                            if (fi.Length > 10000000)
//                            {
//                                Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
//                            }
//                        }
//                        catch (UnauthorizedAccessException UnAuthFile)
//                        {
//                            Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
//                        }
//                    }
//                }
//                catch (UnauthorizedAccessException UnAuthSubDir)
//                {
//                    Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
//                }
//            }
        }
        catch (DirectoryNotFoundException DirNotFound)
        {
            Console.WriteLine("{0}", DirNotFound.Message);
        }
        catch (UnauthorizedAccessException UnAuthDir)
        {
            Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
        }
        catch (PathTooLongException LongPath)
        {
            Console.WriteLine("{0}", LongPath.Message);
        }
    }
Exemplo n.º 22
0
        public override IEnumerable <GameInfo> GetGames()
        {
#if false
            logger.Info($"Looking for games in {path}, using {profile.Name} emulator profile.");
            if (!profile.ImageExtensions.HasNonEmptyItems())
            {
                throw new Exception("Cannot scan for games, emulator doesn't support any file types.");
            }
#endif

            var games = new List <GameInfo>();

            // Hack to exclude anything past disc one for games we're not treating as multi-file / m3u but have multiple discs :|
            var discXpattern = new Regex(@"\(Disc \d", RegexOptions.Compiled);

            settings.Mappings?.Where(m => m.Enabled).ToList().ForEach(mapping =>
            {
                var emulator             = PlayniteAPI.Database.Emulators.First(e => e.Id == mapping.EmulatorId);
                var emuProfile           = emulator.Profiles.First(p => p.Id == mapping.EmulatorProfileId);
                var platform             = PlayniteAPI.Database.Platforms.First(p => p.Id == mapping.PlatformId);
                var imageExtensionsLower = emuProfile.ImageExtensions.Where(ext => !ext.IsNullOrEmpty()).Select(ext => ext.Trim().ToLower());
                var srcPath = mapping.SourcePath;
                var dstPath = mapping.DestinationPathResolved;
                SafeFileEnumerator fileEnumerator;

                if (Directory.Exists(dstPath))
                {
                    #region Import "installed" games
                    fileEnumerator = new SafeFileEnumerator(dstPath, "*.*", SearchOption.TopDirectoryOnly);

                    foreach (var file in fileEnumerator)
                    {
                        if (mapping.GamesUseFolders && file.Attributes.HasFlag(FileAttributes.Directory) && !discXpattern.IsMatch(file.Name))
                        {
                            var rom = new SafeFileEnumerator(file.FullName, "*.*", SearchOption.AllDirectories).FirstOrDefault(f => imageExtensionsLower.Contains(f.Extension.TrimStart('.').ToLower()));
                            if (rom != null)
                            {
                                var newGame = new GameInfo()
                                {
                                    Source           = "EmuLibrary",
                                    Name             = StringExtensions.NormalizeGameName(StringExtensions.GetPathWithoutAllExtensions(Path.GetFileName(file.Name))),
                                    GameImagePath    = PlayniteApi.Paths.IsPortable ? rom.FullName.Replace(PlayniteApi.Paths.ApplicationPath, Playnite.SDK.ExpandableVariables.PlayniteDirectory) : rom.FullName,
                                    InstallDirectory = PlayniteApi.Paths.IsPortable ? file.FullName.Replace(PlayniteApi.Paths.ApplicationPath, Playnite.SDK.ExpandableVariables.PlayniteDirectory) : file.FullName,
                                    IsInstalled      = true,
                                    GameId           = new ELPathInfo(new FileInfo(Path.Combine(new string[] { mapping.SourcePath, file.Name, rom.FullName.Replace(file.FullName, "").TrimStart('\\') })), new DirectoryInfo(Path.Combine(mapping.SourcePath, file.Name))).ToGameId(),
                                    Platform         = platform.Name,
                                    PlayAction       = new GameAction()
                                    {
                                        Type              = GameActionType.Emulator,
                                        EmulatorId        = emulator.Id,
                                        EmulatorProfileId = emuProfile.Id,
                                        IsHandledByPlugin = false, // don't change this. PN will using emulator action
                                    }
                                };

                                games.Add(newGame);
                            }
                        }
                        else if (!mapping.GamesUseFolders)
                        {
                            foreach (var extension in imageExtensionsLower)
                            {
                                if (file.Extension.TrimStart('.') == extension && !discXpattern.IsMatch(file.Name))
                                {
                                    var newGame = new GameInfo()
                                    {
                                        Source           = "EmuLibrary",
                                        Name             = StringExtensions.NormalizeGameName(StringExtensions.GetPathWithoutAllExtensions(Path.GetFileName(file.Name))),
                                        GameImagePath    = PlayniteApi.Paths.IsPortable ? file.FullName.Replace(PlayniteApi.Paths.ApplicationPath, Playnite.SDK.ExpandableVariables.PlayniteDirectory) : file.FullName,
                                        InstallDirectory = PlayniteApi.Paths.IsPortable ? dstPath.Replace(PlayniteApi.Paths.ApplicationPath, Playnite.SDK.ExpandableVariables.PlayniteDirectory) : dstPath,
                                        IsInstalled      = true,
                                        GameId           = new ELPathInfo(new FileInfo(Path.Combine(mapping.SourcePath, file.Name))).ToGameId(),
                                        Platform         = platform.Name,
                                        PlayAction       = new GameAction()
                                        {
                                            Type              = GameActionType.Emulator,
                                            EmulatorId        = emulator.Id,
                                            EmulatorProfileId = emuProfile.Id,
                                            IsHandledByPlugin = false, // don't change this. PN will using emulator action
                                        }
                                    };

                                    games.Add(newGame);
                                }
                            }
                        }
                    }
                }
                #endregion

                #region Import "uninstalled" games
                if (Directory.Exists(srcPath))
                {
                    fileEnumerator = new SafeFileEnumerator(srcPath, "*.*", SearchOption.TopDirectoryOnly);

                    foreach (var file in fileEnumerator)
                    {
                        if (mapping.GamesUseFolders && file.Attributes.HasFlag(FileAttributes.Directory) && !discXpattern.IsMatch(file.Name))
                        {
                            var rom = new SafeFileEnumerator(file.FullName, "*.*", SearchOption.AllDirectories).FirstOrDefault(f => imageExtensionsLower.Contains(f.Extension.TrimStart('.').ToLower()));
                            if (rom != null)
                            {
                                var pathInfo = new ELPathInfo(new FileInfo(rom.FullName), new DirectoryInfo(file.FullName));
                                var equivalentInstalledPath = Path.Combine(dstPath, pathInfo.RelativeRomPath);
                                if (File.Exists(equivalentInstalledPath))
                                {
                                    continue;
                                }

                                var newGame = new GameInfo()
                                {
                                    Source      = "EmuLibrary",
                                    Name        = StringExtensions.NormalizeGameName(StringExtensions.GetPathWithoutAllExtensions(Path.GetFileName(file.Name))),
                                    IsInstalled = false,
                                    GameId      = pathInfo.ToGameId(),
                                    Platform    = platform.Name,
                                    PlayAction  = new GameAction()
                                    {
                                        Type              = GameActionType.Emulator,
                                        EmulatorId        = emulator.Id,
                                        EmulatorProfileId = emuProfile.Id,
                                        IsHandledByPlugin = false, // don't change this. PN will using emulator action
                                    }
                                };

                                games.Add(newGame);
                            }
                        }
                        else if (!mapping.GamesUseFolders)
                        {
                            foreach (var extension in imageExtensionsLower)
                            {
                                if (file.Extension.TrimStart('.') == extension && !discXpattern.IsMatch(file.Name))
                                {
                                    var equivalentInstalledPath = Path.Combine(dstPath, file.Name);
                                    if (File.Exists(equivalentInstalledPath))
                                    {
                                        continue;
                                    }

                                    var newGame = new GameInfo()
                                    {
                                        Source      = "EmuLibrary",
                                        Name        = StringExtensions.NormalizeGameName(StringExtensions.GetPathWithoutAllExtensions(Path.GetFileName(file.Name))),
                                        IsInstalled = false,
                                        GameId      = new ELPathInfo(new FileInfo(file.FullName)).ToGameId(),
                                        Platform    = platform.Name,
                                        PlayAction  = new GameAction()
                                        {
                                            Type              = GameActionType.Emulator,
                                            EmulatorId        = emulator.Id,
                                            EmulatorProfileId = emuProfile.Id,
                                            IsHandledByPlugin = false, // don't change this. PN will using emulator action
                                        }
                                    };

                                    games.Add(newGame);
                                }
                            }
                        }
                    }
                }
            });
            #endregion

            return(games);
        }
Exemplo n.º 23
0
        public static async Task <List <Program> > GetShortcutProgramsFromFolder(string path, CancellationTokenSource cancelToken = null)
        {
            return(await Task.Run(() =>
            {
                var folderExceptions = new string[]
                {
                    @"\Accessibility\",
                    @"\Accessories\",
                    @"\Administrative Tools\",
                    @"\Maintenance\",
                    @"\StartUp\",
                    @"\Windows ",
                    @"\Microsoft ",
                };

                var nameExceptions = new string[]
                {
                    "uninstall",
                    "setup"
                };

                var pathExceptions = new string[]
                {
                    @"\system32\",
                    @"\windows\",
                };

                var shell = new IWshRuntimeLibrary.WshShell();
                var apps = new List <Program>();
                var shortucts = new SafeFileEnumerator(path, "*.lnk", SearchOption.AllDirectories);

                foreach (var shortcut in shortucts)
                {
                    if (cancelToken?.IsCancellationRequested == true)
                    {
                        return null;
                    }

                    if (shortcut.Attributes.HasFlag(FileAttributes.Directory))
                    {
                        continue;
                    }

                    var fileName = shortcut.Name;
                    var Directory = Path.GetDirectoryName(shortcut.FullName);

                    if (folderExceptions.FirstOrDefault(a => shortcut.FullName.IndexOf(a, StringComparison.OrdinalIgnoreCase) >= 0) != null)
                    {
                        continue;
                    }

                    if (nameExceptions.FirstOrDefault(a => shortcut.FullName.IndexOf(a, StringComparison.OrdinalIgnoreCase) >= 0) != null)
                    {
                        continue;
                    }

                    var link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcut.FullName);
                    var target = link.TargetPath;

                    if (pathExceptions.FirstOrDefault(a => target.IndexOf(a, StringComparison.OrdinalIgnoreCase) >= 0) != null)
                    {
                        continue;
                    }

                    // Ignore duplicates
                    if (apps.FirstOrDefault(a => a.Path == target) != null)
                    {
                        continue;
                    }

                    // Ignore non-application links
                    if (Path.GetExtension(target) != ".exe")
                    {
                        continue;
                    }

                    var app = new Program()
                    {
                        Path = target,
                        Icon = link.IconLocation,
                        Name = Path.GetFileNameWithoutExtension(shortcut.Name),
                        WorkDir = link.WorkingDirectory
                    };

                    apps.Add(app);
                }

                return apps;
            }));
        }