public async Task <IScriptType> GetScriptType(IList <string> modFiles)
        {
            CurrentScriptTypeRegistry = await ScriptTypeRegistry.DiscoverScriptTypes(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            IScriptType FoundScriptType = null;

            await Task.Run(() =>
            {
                foreach (IScriptType scriptType in CurrentScriptTypeRegistry.Types)
                {
                    bool HasFoundScriptType = false;
                    if (scriptType.FileNames != null)
                    {
                        foreach (string scriptFile in scriptType.FileNames)
                        {
                            // ??? Need to check for Fomod/Omod/Whatever before this part
                            string FileToFind = Path.Combine(FomodRoot, scriptFile);
                            string Match      = modFiles.Where(x => Path.GetFileName(x).Contains(scriptFile, StringComparison.OrdinalIgnoreCase) && Path.GetFileName(Path.GetDirectoryName(x)).Contains(FomodRoot, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                            if (!string.IsNullOrEmpty(Match))
                            {
                                HasFoundScriptType = true;
                                FoundScriptType    = scriptType;
                            }
                        }
                    }

                    if (HasFoundScriptType)
                    {
                        break;
                    }
                }
            });

            return(FoundScriptType);
        }
        public async Task <IScriptType> GetScriptType(IList <string> modFiles, string extractedFilePath = null)
        {
            CurrentScriptTypeRegistry = await ScriptTypeRegistry.DiscoverScriptTypes(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            IScriptType FoundScriptType = null;

            string omodMatch = modFiles.Where(x => x.Equals("script") || x.Equals("script.txt")).FirstOrDefault();

            await Task.Run(() =>
            {
                foreach (IScriptType scriptType in CurrentScriptTypeRegistry.Types)
                {
                    bool HasFoundScriptType = false;
                    if (scriptType.FileNames != null)
                    {
                        foreach (string scriptFile in scriptType.FileNames)
                        {
                            string scriptDataString = "";
                            if (!string.IsNullOrEmpty(omodMatch))
                            {
                                byte[] scriptData = File.ReadAllBytes(Path.Combine(extractedFilePath, omodMatch));
                                scriptDataString  = System.Text.Encoding.Default.GetString(scriptData);
                            }

                            if (!string.IsNullOrEmpty(omodMatch) && scriptType.ValidateScript(scriptType.LoadScript(scriptDataString)))
                            {
                                HasFoundScriptType = true;
                                FoundScriptType    = scriptType;
                            }
                            else
                            {
                                string fomodMatch = modFiles.Where(x => scriptMatch(x, scriptFile)).FirstOrDefault();
                                if (!string.IsNullOrEmpty(fomodMatch))
                                {
                                    HasFoundScriptType = true;
                                    FoundScriptType    = scriptType;
                                }
                            }
                        }
                    }

                    if (HasFoundScriptType)
                    {
                        break;
                    }
                }
            });

            return(FoundScriptType);
        }
        public async Task <IList <string> > GetRequirements(IList <string> modFiles, bool includeAssets)
        {
            CurrentScriptTypeRegistry = await ScriptTypeRegistry.DiscoverScriptTypes(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            // TODO: I don't think there is a good way to determine which image files are referenced by the installer script without
            //   unpacking it first, right?
            IList <string> RequiredFiles = includeAssets
                ? modFiles.Where(path => RequiredExtensions.Contains(Path.GetExtension(path))).ToList()
                : new List <string>();

            return(await Task.Run(() =>
            {
                bool HasFoundScriptType = false;
                foreach (IScriptType scriptType in CurrentScriptTypeRegistry.Types)
                {
                    if (scriptType.FileNames != null)
                    {
                        foreach (string scriptFile in scriptType.FileNames)
                        {
                            // ??? Need to check for Fomod/Omod/Whatever before this part
                            string FileToFind = Path.Combine(FomodRoot, scriptFile);
                            string Match = modFiles.Where(x => Path.GetFileName(x).Contains(scriptFile, StringComparison.OrdinalIgnoreCase) && Path.GetFileName(Path.GetDirectoryName(x)).Contains(FomodRoot, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                            if (!string.IsNullOrEmpty(Match))
                            {
                                HasFoundScriptType = true;
                                RequiredFiles.Add(Match);
                            }
                        }
                    }

                    if (HasFoundScriptType)
                    {
                        break;
                    }
                }

                if (!HasFoundScriptType)
                {
                    throw new UnsupportedException();
                }

                return RequiredFiles;
            }));
        }
        public async Task <IList <string> > GetRequirements(IList <string> modFiles, bool includeAssets, IList <string> allowedTypes)
        {
            CurrentScriptTypeRegistry = await ScriptTypeRegistry.DiscoverScriptTypes(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            // TODO: I don't think there is a good way to determine which image files are referenced by the installer script without
            //   unpacking it first, right?
            IList <string> RequiredFiles = includeAssets
                ? modFiles.Where(path => RequiredExtensions.Contains(Path.GetExtension(path))).ToList()
                : new List <string>();

            return(await Task.Run(() =>
            {
                bool HasFoundScriptType = false;
                foreach (IScriptType scriptType in CurrentScriptTypeRegistry.Types)
                {
                    if ((allowedTypes != null) && !allowedTypes.Contains(scriptType.TypeId))
                    {
                        continue;
                    }

                    if (scriptType.FileNames != null)
                    {
                        foreach (string scriptFile in scriptType.FileNames)
                        {
                            string omodMatch = modFiles.Where(x => x.Equals("script") || x.Equals("script.txt")).FirstOrDefault();
                            bool isOmod = false;
                            try
                            {
                                isOmod = (!string.IsNullOrEmpty(omodMatch) && scriptType.ValidateScript(scriptType.LoadScript(omodMatch)));
                            } catch (Exception) {
                                // don't care
                            }

                            if (isOmod)
                            {
                                HasFoundScriptType = true;
                                RequiredFiles.Add(omodMatch);
                            }
                            else
                            {
                                string fomodMatch = modFiles.Where(x => scriptMatch(x, scriptFile)).FirstOrDefault();
                                if (!string.IsNullOrEmpty(fomodMatch))
                                {
                                    HasFoundScriptType = true;
                                    RequiredFiles.Add(fomodMatch);
                                }
                            }
                        }
                    }

                    if (HasFoundScriptType)
                    {
                        break;
                    }
                }

                if (!HasFoundScriptType)
                {
                    throw new UnsupportedException();
                }

                return RequiredFiles;
            }));
        }
Пример #5
0
        static int DoInstall(string game, string filename, string installationPath, string profilePath, string gamePath,
                             List <string> additionalSearchPaths, string seVersion, ref string errorString)
        {
            if (game == null)
            {
                errorString = "no game specified";
                return(1);
            }
            if (filename == null)
            {
                errorString = "no file specified";
                return(1);
            }
            if (profilePath == null)
            {
                errorString = "no profile path specified";
                return(1);
            }
            if (gamePath == null)
            {
                errorString = "no game path specified";
                return(1);
            }
            try
            {
                EnvironmentInfo environmentInfo = new EnvironmentInfo(Properties.Settings.Default);

                string   exeLocation = Assembly.GetExecutingAssembly().Location;
                string   exePath     = System.IO.Path.GetDirectoryName(exeLocation);
                string[] gameModes   = Directory.GetFiles(Path.Combine(exePath, "GameModes"), String.Format("{0}.dll", game));
                if (gameModes.Count() == 0)
                {
                    errorString = "unknown game";
                    return(1);
                }

                Assembly         gameAssembly    = Assembly.LoadFrom(gameModes[0]);
                IGameModeFactory gameModeFactory = null;
                Type[]           exportedTypes   = gameAssembly.GetExportedTypes();
                foreach (Type type in exportedTypes)
                {
                    if (typeof(IGameModeFactory).IsAssignableFrom(type) && !type.IsAbstract)
                    {
                        ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(EnvironmentInfo) });
                        gameModeFactory = (IGameModeFactory)constructor.Invoke(new Object[] { environmentInfo });
                    }
                }
                if (gameModeFactory == null)
                {
                    errorString = "invalid game";
                    return(1);
                }

                string str7zPath = Path.Combine(environmentInfo.ProgrammeInfoDirectory, environmentInfo.Is64BitProcess ? "7z-64bit.dll" : "7z-32bit.dll");
                SevenZipCompressor.SetLibraryPath(str7zPath);

                FileUtil fileUtil = new NexusFileUtil(environmentInfo);

                environmentInfo.Settings.InstallationPaths[gameModeFactory.GameModeDescriptor.ModeId] = installationPath;
                environmentInfo.Settings.ModFolder[gameModeFactory.GameModeDescriptor.ModeId]         = installationPath;
//                environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = environmentInfo.TemporaryPath;
                environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = Path.Combine(installationPath, "temp");
                if (environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] == null)
                {
                    environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] = new KeyedSettings <string>();
                }
                if (environmentInfo.Settings.DelayedSettings["ALL"] == null)
                {
                    environmentInfo.Settings.DelayedSettings["ALL"] = new KeyedSettings <string>();
                }

                ViewMessage warning = null;

                IGameMode gameMode = gameModeFactory.BuildGameMode(fileUtil, out warning);

                IModCacheManager cacheManager = new NexusModCacheManager(environmentInfo.TemporaryPath, gameMode.GameModeEnvironmentInfo.ModDirectory, fileUtil);

                IScriptTypeRegistry scriptTypeRegistry = ScriptTypeRegistry.DiscoverScriptTypes(Path.Combine(Path.GetDirectoryName(exeLocation), "ScriptTypes"), gameMode, new List <string>());
                if (scriptTypeRegistry.Types.Count == 0)
                {
                    errorString = "No script types were found.";
                    return(2);
                }

                // use a proxy so we can intercept accesses to the IGameMode interface. This allows us to make the additional search paths accessible from
                // the sandbox and feed in the script extender version even though the nmm lib won't find it.
                // This has to happen after DiscoverScriptTypes becaus that function tries to localize the assembly which fails for the dynamic assembly
                // of the proxy. Fortunately DiscoverScriptTypes has no side-effects on the gameMode.
                // This recreates the gamemode object so it's important no code above modifies gameMode
                ProxyGenerator      generator   = new ProxyGenerator();
                GameModeInterceptor interceptor = new GameModeInterceptor(additionalSearchPaths, seVersion != null ? new Version(seVersion) : null);

                gameMode = (IGameMode)generator.CreateClassProxy(gameMode.GetType(), new object[] { environmentInfo, fileUtil }, new IInterceptor[] { interceptor });

                IModFormatRegistry formatRegistry = ModFormatRegistry.DiscoverFormats(cacheManager, gameMode.SupportedFormats, scriptTypeRegistry, Path.Combine(Path.GetDirectoryName(exeLocation), "ModFormats"));
                if (formatRegistry.Formats.Count == 0)
                {
                    errorString = "No formats were found.";
                    return(2);
                }

                // we install the mod from the temporary path. Unfortunately this requires the archive to be copied, otherwise the sandbox will
                // prevent the installer script from accessing the archive in its original location
                string fileNameTemporary = Path.Combine(environmentInfo.TemporaryPath, Path.GetFileName(filename));
                File.Copy(filename, fileNameTemporary);
                IMod mod = CreateMod(fileNameTemporary, formatRegistry, gameMode);
                if (mod == null)
                {
                    errorString = "failed to initialize mod";
                    return(3);
                }

                System.IO.File.WriteAllText(installationPath + "/__installInfo.txt", mod.ModName + "\n" + mod.HumanReadableVersion + "\n" + mod.Id);

                if (mod.HasInstallScript)
                {
                    DummyDataFileUtilFactory dummyFactory = null;
                    IDataFileUtil            dataFileUtility;
                    Logger.Info("Detected C# script that relies on files in the actual data folder");

                    string modlistFile = Path.Combine(profilePath, "modlist.txt");
                    // ASSUMED mods path is the parent directory of the gameMode.InstallationPath
                    string modsPath = Directory.GetParent(gameMode.InstallationPath).FullName;
                    // Prepare dummy data directory
                    dummyFactory    = new DummyDataFileUtilFactory(gameMode.GameModeEnvironmentInfo.InstallationPath, modlistFile, modsPath, gamePath, additionalSearchPaths);
                    dataFileUtility = dummyFactory.CreateDummyDataFileUtil();

                    TxFileManager  fileManager     = new TxFileManager();
                    IInstallLog    installLog      = new DummyInstallLog();
                    IIniInstaller  iniIniInstaller = new IniInstaller(mod, installLog, fileManager, delegate { return(OverwriteResult.No); });
                    IPluginManager pluginManager   = new DummyPluginManager(Path.Combine(profilePath, "plugins.txt"), gameMode, mod);
                    IGameSpecificValueInstaller gameSpecificValueInstaller = gameMode.GetGameSpecificValueInstaller(mod, installLog, fileManager, new NexusFileUtil(environmentInfo), delegate { return(OverwriteResult.No); });
                    IModFileInstaller           fileInstaller = new ModFileInstaller(gameMode.GameModeEnvironmentInfo, mod, installLog, pluginManager, dataFileUtility, fileManager, delegate { return(OverwriteResult.No); }, false);
                    InstallerGroup       installers           = new InstallerGroup(dataFileUtility, fileInstaller, iniIniInstaller, gameSpecificValueInstaller, pluginManager);
                    IVirtualModActivator modActivator         = new DummyVirtualModActivator(gameMode, environmentInfo);
                    IScriptExecutor      executor             = mod.InstallScript.Type.CreateExecutor(mod, gameMode, environmentInfo, modActivator, installers, SynchronizationContext.Current);
                    // run the script in a second thread and start the main loop in the main thread to ensure we can handle message boxes and the like
                    ScriptRunner runner = new ScriptRunner(executor, mod.InstallScript);

                    runner.Execute();
                    runner.TaskEnded += delegate
                    {
                        iniIniInstaller.FinalizeInstall();
                        gameSpecificValueInstaller.FinalizeInstall();
                        mod.EndReadOnlyTransaction();

                        Application.Exit();
                    };

                    Application.Run();
                    switch (runner.Status)
                    {
                    case BackgroundTasks.TaskStatus.Cancelled: return(11);

                    case BackgroundTasks.TaskStatus.Error: return(6);

                    case BackgroundTasks.TaskStatus.Incomplete: return(10);

                    default: return(0);
                    }
                }
                else
                {
                    errorString = "no install script";
                    return(4);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("exception: " + e.Message);
                MessageBox.Show(e.Message, "Installation failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(5);
            }
        }