Пример #1
0
    private static bool BuildBundle(Hashtable bundle, string parent, BundleOptions options)
    {
        BuildPipeline.PushAssetDependencies();
        EditorUtility.UnloadUnusedAssetsImmediate();

        string type = EB.Dot.String("type", bundle, "standard");

        bool result = false;

        switch (type)
        {
        case "standard":
        {
            result = BuildStandardBundle(bundle, parent, options);
        }
        break;

        case "single":
        {
            result = BuildSingleBundle(bundle, parent, options);
        }
        break;

        case "folder":
        {
            result = BuildFolderBundle(bundle, parent, options);
        }
        break;

        case "copy":
        {
            result = BuildCopyBundle(bundle, parent, options);
        }
        break;

        case "ogg":
        {
            result = BuildOggBundle(bundle, parent, options);
        }
        break;

        case "scenes":
        {
            if ((options & BundleOptions.SkipScenes) == 0)
            {
                result = BuildScenesBundle(bundle, parent, options);
            }
        }
        break;

        default:
            Debug.LogError("unknown bundle type: " + type);
            break;
        }

        parent = EB.Dot.String("id", bundle, string.Empty);

        // if we built, make sure to force children updates
        if (result)
        {
            options |= Bundler.BundleOptions.Force;
        }

        // build the dependents
        foreach (Hashtable child in EB.Dot.Array("deps", bundle, new ArrayList()))
        {
            BuildBundle(child, parent, options);
        }

        BuildPipeline.PopAssetDependencies();

        return(result);
    }
Пример #2
0
 public static HtmlString BundleJs(this HtmlHelper html, BundleOptions options) => ViewUtils.BundleJs(
     nameof(BundleJs), HostContext.VirtualFileSources, HostContext.VirtualFiles, Minifiers.JavaScript, options).ToHtmlString();
Пример #3
0
        public static MvcHtmlString Link(this HtmlHelper html, string rel, string href, object htmlAttributes = null, BundleOptions options = BundleOptions.Normal)
        {
            if (string.IsNullOrEmpty(href))
            {
                return(MvcHtmlString.Empty);
            }

            if (href.StartsWith("~/"))
            {
                href = href.Replace("~/", VirtualPathUtility.ToAbsolute("~"));
            }

            var tag = new TagBuilder("link");

            tag.MergeAttribute("rel", rel);

            tag.MergeAttribute("href", href.RewriteUrl(options));

            if (htmlAttributes != null)
            {
                tag.MergeAttributes(htmlAttributes.ToRouteValueDictionary());
            }

            return(tag.ToString(TagRenderMode.SelfClosing).ToMvcHtmlString());
        }
Пример #4
0
        public static MvcHtmlString RenderCssBundle(this HtmlHelper html, string bundlePath, BundleOptions options = BundleOptions.Minified, string media = null)
        {
            if (string.IsNullOrEmpty(bundlePath))
            {
                return(MvcHtmlString.Empty);
            }

            if (!CachePaths())
            {
                BundleCache.SafeClear();
            }

            return(BundleCache.GetOrAdd(bundlePath, str =>
            {
                var filePath = HostingEnvironment.MapPath(bundlePath);

                var baseUrl = VirtualPathUtility.GetDirectory(bundlePath);

                if (options == BundleOptions.Combined)
                {
                    return html.Css(bundlePath.Replace(".bundle", ""), media, options);
                }
                if (options == BundleOptions.MinifiedAndCombined)
                {
                    return html.Css(bundlePath.Replace(".css.bundle", ".min.css"), media, options);
                }

                var cssFiles = File.ReadAllLines(filePath);

                var styles = new StringBuilder();
                foreach (var file in cssFiles)
                {
                    if (file.StartsWith("#"))
                    {
                        continue;
                    }

                    var cssFile = file.Trim()
                                  .Replace(".less", ".css")
                                  .Replace(".sass", ".css")
                                  .Replace(".scss", ".css")
                                  .Replace(".styl", ".css");
                    var cssSrc = Path.Combine(baseUrl, cssFile);

                    styles.AppendLine(
                        html.Css(cssSrc, media, options).ToString()
                        );
                }

                return styles.ToString().ToMvcHtmlString();
            }));
        }
Пример #5
0
 /// <summary>
 /// 停止插件工作者
 /// </summary>
 /// <param name="options"></param>
 protected override void StopWorker(BundleOptions option)
 {
     throw new NotImplementedException();
 }
Пример #6
0
        private void Bundle_Extraction_To_Relative_Path_Succeeds(string relativePath, BundleOptions bundleOptions)
        {
            // As we don't modify user defined environment variables, we will not convert
            // any forward slashes to the standard Windows dir separator ('\'), thus
            // failing to create directory trees for bundle extraction that use Unix
            // style dir separator in Windows.
            if (relativePath == "foo/bar" && OperatingSystem.IsWindows())
            {
                return;
            }

            var fixture = sharedTestState.TestFixture.Copy();
            var bundler = BundleSelfContainedApp(fixture, out var singleFile, bundleOptions);

            // Run the bundled app (extract files to <path>)
            var cmd = Command.Create(singleFile);

            cmd.WorkingDirectory(Path.GetDirectoryName(singleFile))
            .CaptureStdErr()
            .CaptureStdOut()
            .EnvironmentVariable(BundleHelper.DotnetBundleExtractBaseEnvVariable, relativePath)
            .Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining("Hello World");

            var extractedFiles = BundleHelper.GetExtractedFiles(fixture, bundleOptions);
            var extractedDir   = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(singleFile),
                                                                relativePath,
                                                                fixture.TestProject.ProjectName,
                                                                bundler.BundleManifest.BundleID));

            extractedDir.Should().HaveFiles(extractedFiles);
        }
Пример #7
0
 /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
 public WatchedFile(IWebFile webFile, IFileInfo fileInfo, BundleOptions bundleOptions)
 {
     WebFile       = webFile;
     FileInfo      = fileInfo;
     BundleOptions = bundleOptions;
 }
Пример #8
0
 public static HtmlString BundleHtml(this IHtmlHelper html, BundleOptions options) => ViewUtils.BundleHtml(
     nameof(BundleHtml), HostContext.VirtualFileSources, HostContext.VirtualFiles, Minifiers.Html, options).ToHtmlString();
Пример #9
0
    public static List <string> GetBundleConfigs(string directory = BuildSettings.BundlerConfigFolder, BundleOptions options = (Bundler.BundleOptions.None | Bundler.BundleOptions.Extended))
    {
        if ((options & BundleOptions.Force) != 0)
        {
            GeneralUtils.DeleteDirectory(BuildSettings.BuildFolder, true);
        }

        List <string> bundles = new List <string>();

        var baseFiles = new List <string>(Directory.GetFiles(directory, "*.txt", SearchOption.TopDirectoryOnly));

        var recursive = (options & BundleOptions.Extended) != 0;
        var files     = Directory.GetFiles(directory, "*.txt", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

        foreach (string file in files)
        {
            if (baseFiles.Contains(file) && (options & BundleOptions.SkipBase) != 0)
            {
                continue;
            }
            bundles.Add(file);
        }

        return(bundles);
    }
Пример #10
0
    public async Task BundleAsync(string directory, bool forceBuild)
    {
        var projectFiles = Directory.GetFiles(directory, "*.csproj");

        if (!projectFiles.Any())
        {
            throw new BundlingException(
                      "No project file found in the directory. The working directory must have a Blazor project file.");
        }

        var projectFilePath = projectFiles[0];

        CheckProjectIsSupportedType(projectFilePath);

        var config       = ConfigReader.Read(PathHelper.GetWwwRootPath(directory));
        var bundleConfig = config.Bundle;

        if (forceBuild)
        {
            var projects = new List <DotNetProjectInfo>()
            {
                new DotNetProjectInfo(string.Empty, projectFilePath, true)
            };

            DotNetProjectBuilder.BuildProjects(projects, string.Empty);
        }

        var frameworkVersion = GetTargetFrameworkVersion(projectFilePath);
        var projectName      = Path.GetFileNameWithoutExtension(projectFilePath);
        var assemblyFilePath = PathHelper.GetAssemblyFilePath(directory, frameworkVersion, projectName);
        var startupModule    = GetStartupModule(assemblyFilePath);

        var bundleDefinitions = new List <BundleTypeDefinition>();

        FindBundleContributorsRecursively(startupModule, 0, bundleDefinitions);
        bundleDefinitions = bundleDefinitions.OrderByDescending(t => t.Level).ToList();

        var    styleContext  = GetStyleContext(bundleDefinitions, bundleConfig.Parameters);
        var    scriptContext = GetScriptContext(bundleDefinitions, bundleConfig.Parameters);
        string styleDefinitions;
        string scriptDefinitions;

        if (bundleConfig.Mode is BundlingMode.Bundle || bundleConfig.Mode is BundlingMode.BundleAndMinify)
        {
            var options = new BundleOptions
            {
                Directory        = directory,
                FrameworkVersion = frameworkVersion,
                ProjectFileName  = projectName,
                BundleName       = bundleConfig.Name.IsNullOrEmpty() ? "global" : bundleConfig.Name,
                Minify           = bundleConfig.Mode == BundlingMode.BundleAndMinify
            };

            Logger.LogInformation("Generating style bundle...");
            styleDefinitions = StyleBundler.Bundle(options, styleContext);
            Logger.LogInformation($"Style bundle has been generated successfully.");

            Logger.LogInformation("Generating script bundle...");
            scriptDefinitions = ScriptBundler.Bundle(options, scriptContext);
            Logger.LogInformation($"Script bundle has been generated successfully.");
        }
        else
        {
            Logger.LogInformation("Generating style references...");
            styleDefinitions = GenerateStyleDefinitions(styleContext);
            Logger.LogInformation("Generating script references...");
            scriptDefinitions = GenerateScriptDefinitions(scriptContext);
        }

        await UpdateDependenciesInHtmlFileAsync(directory, styleDefinitions, scriptDefinitions);

        Logger.LogInformation("Script and style references in the index.html file have been updated.");
    }
Пример #11
0
    public static bool BuildStandardBundle(string id, string folder, string pathRoot, string filter, string prefix, bool recursive, bool shortNames, string parent, BundleOptions options)
    {
        string targetFolder = _outFolder;

        if (!Directory.Exists(targetFolder))
        {
            try
            {
                Directory.CreateDirectory(targetFolder);
            }
            catch (System.Exception e)
            {
                Debug.Log(e.ToString());
                throw;
            }
        }

        List <Object> objectList = new List <Object>();
        List <string> nameList   = new List <string>();
        List <string> pathList   = new List <string>();

        string[] items = {};

        if (System.IO.File.Exists(folder))
        {
            items = new string[] { folder };
        }
        else if (System.IO.Directory.Exists(folder))
        {
            // Interrogate ALL found objects in the source path and all sub-directories
            items = Directory.GetFiles(folder, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
        }

        string path = Path.Combine(_outFolder, string.Format("{0}.assetbundle", id));           //e.g. "/Users/User/perforce/ff7/main/Unity/android/download/audio.assetbundle"

        BuildAssetBundleOptions buildAssetBundleOptions = _bundleOptions | ((options & BundleOptions.Uncompressed) != 0 ? BuildAssetBundleOptions.UncompressedAssetBundle : 0);

        Debug.Log("Target - " + BuildSettings.Target + ", AssetBundleOptions - " + buildAssetBundleOptions);

        int bundleRelPathLength = folder.ToLower().IndexOf("bundles/");                 // e.g. folder: "Assets/Resources/Bundles/audio"

        if (bundleRelPathLength < 0)
        {
            bundleRelPathLength = 0;
        }

        // Let's see what we've got
        foreach (string s in items)
        {
            if (!string.IsNullOrEmpty(filter))
            {
                if (s.Contains(filter) == false)
                {
                    continue;                     // skip asset
                }
            }

            UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(s);
            if (obj != null && obj.GetType() == typeof(UnityEngine.Object))
            {
                var tmp = AssetDatabase.LoadAllAssetsAtPath(s);
                obj = null;
                for (int i = 0; i < tmp.Length; ++i)
                {
                    if (tmp[i] != null && tmp[i].GetType() != typeof(UnityEngine.Object) && !string.IsNullOrEmpty(tmp[i].name) && s.Contains(tmp[i].name))
                    {
                        Debug.Log("Loading " + s + " option type: " + (tmp[i] != null ? tmp[i].GetType().ToString() : "NULL OBJ"));
                    }
                }

                for (int i = 0; i < tmp.Length; ++i)
                {
                    if (tmp[i] != null && tmp[i].GetType() != typeof(UnityEngine.Object) && !string.IsNullOrEmpty(tmp[i].name) && s.Contains(tmp[i].name))
                    {
                        Debug.Log("Loaded " + s + " type: " + (tmp[i].GetType() != null ? tmp[i].GetType().ToString() : "NULL OBJ"));
                        obj = tmp[i];
                        break;
                    }
                }

                if (obj == null)
                {
                    Debug.Log("No asset loaded for " + s);
                }
            }
            else if (obj != null)
            {
                Debug.Log("Loaded " + s + " type: " + obj.GetType().ToString());
            }


            if (obj == null || (obj is MonoScript))
            {
                if (obj && obj is MonoScript)
                {
                    Debug.Log("SKIPPING MONOSCRIPT: " + s);
                }
                continue;
            }

            string p   = s.Substring(pathRoot.Length + 1);
            int    ext = p.LastIndexOf('.');
            if (ext > 0)
            {
                p = p.Substring(0, ext);
            }
            p = prefix + p.ToLower();

            if (shortNames)
            {
                p = Path.GetFileNameWithoutExtension(p);
            }

            nameList.Add(AssetName(p));
            pathList.Add(PathName(p));
            objectList.Add(obj);
        }

        if (objectList.Count == 0)
        {
            Debug.Log("Skipping empty bundle, id: " + id);
            return(false);
        }

        if ((options & BundleOptions.Force) != 0 || CheckDependancies(path, objectList.ToArray()))
        {
            // build
            bool result = BuildPipeline.BuildAssetBundleExplicitAssetNames(objectList.ToArray(), nameList.ToArray(), path, buildAssetBundleOptions, BuildSettings.Target);
            Debug.Log("BuildPipeline.BuildAssetBundleExplicitAssetNames : BundleID: " + id + " : " + (result ? "SUCCESSFUL " : "FAILED"));
        }

        // build the toc
        Hashtable toc = new Hashtable();
        FileInfo  fi  = new FileInfo(path);

        toc["paths"]  = pathList.ToArray();
        toc["parent"] = parent;
        toc["size"]   = fi.Length;
        toc["ts"]     = fi.LastWriteTime.Ticks;

#if UNITY_ANDROID
        toc["hash"] = CalculateFileHash(fi);
#endif

        _bundles[id] = toc;

        return(true);
    }
Пример #12
0
    private static bool BuildCopyBundle(Hashtable bundle, string parent, BundleOptions options)
    {
        string id        = EB.Dot.String("id", bundle, string.Empty);
        string folder    = EB.Dot.String("folder", bundle, string.Empty);
        string pathRoot  = EB.Dot.String("relpath", bundle, folder);
        string filter    = EB.Dot.String("filter", bundle, string.Empty);
        bool   recursive = EB.Dot.Bool("recursive", bundle, true);

        string targetFolder = Path.Combine(_outFolder, id);

        if (!Directory.Exists(targetFolder))
        {
            Directory.CreateDirectory(targetFolder);
        }

        // Interrogate ALL found objects in the source path and all sub-directories
        List <string> paths = new List <string>();

        string[] items = {};
        if (Directory.Exists(folder))
        {
            items = Directory.GetFiles(folder, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
        }
        else
        {
            Debug.LogWarning("BuildCopyBundle folder does not exist: " + folder);
        }

        int processedItems = 0;

        foreach (string item in items)
        {
            // never copy anything but
            if (!(item.EndsWith(".png") || item.EndsWith(".jpg") || item.EndsWith(".ogg") || item.EndsWith(".mp3") || item.EndsWith(".mp4")))
            {
                continue;
            }

            if (!string.IsNullOrEmpty(filter))
            {
                if (item.Contains(filter) == false)
                {
                    continue;                     // skip asset
                }
            }

            // Unload unused assets after a few items. CheckNPOT is pretty memory heavy because it loads images
            if (processedItems >= 10)
            {
                processedItems = 0;
                EditorUtility.UnloadUnusedAssetsImmediate();
                #region 强制回收GC
                System.GC.Collect(System.GC.MaxGeneration, System.GCCollectionMode.Forced);
                System.GC.WaitForPendingFinalizers();
                System.GC.Collect();
                #endregion
            }

            CheckNPOT(item);

            string path = item.Substring(pathRoot.Length + 1);
            paths.Add(Path.Combine(id, path).Replace("\\", "/"));

            string dest = Path.Combine(targetFolder, path);
            string dir  = Path.GetDirectoryName(dest);


            if (File.Exists(dest) && File.GetLastWriteTime(dest) > File.GetLastWriteTime(item))
            {
                // skip this file it's already been handled.
                continue;
            }

            Directory.CreateDirectory(dir);

            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                CommandLineUtils.RunWindowsSyncCommand("attrib.exe", "-R " + dest);
            }
            else if (Application.platform == RuntimePlatform.OSXEditor)
            {
                CommandLineUtils.Run("chmod", "777 " + dest);
            }

            File.Copy(item, dest, true);

            processedItems++;
        }

        _folders.Add(id, paths.ToArray());

        return(false);
    }
Пример #13
0
    private static bool BuildScenesBundle(Hashtable bundle, string parent, BundleOptions options)
    {
        string folder    = EB.Dot.String("folder", bundle, string.Empty);
        string filter    = EB.Dot.String("filter", bundle, string.Empty);
        string id        = EB.Dot.String("id", bundle, string.Empty);
        bool   recursive = EB.Dot.Bool("recursive", bundle, true);

        bool result = false;

        string[] buildScenes     = BuildSettings.GetScenesFromEditorSettings();
        var      tmp             = new List <string>(buildScenes);
        var      buildSceneNames = EB.ArrayUtils.Map <string, string>(tmp, Path.GetFileNameWithoutExtension);

        if (!System.IO.Directory.Exists(folder))
        {
            Debug.LogWarning("BuildScenesBundle - Folder does not exist : " + folder);
            return(result);
        }

        string[] items = Directory.GetFiles(folder, "*.unity", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

        List <string> devLevels = new List <string>((string[])BuildSettings.DevelopmentLevelsBuild.ToArray(typeof(string)));

        devLevels = EB.ArrayUtils.Map <string, string>(devLevels,
                                                       delegate(string path)
        {
            string sceneName = Path.GetFileNameWithoutExtension(path).ToLower();
            foreach (string testName in BuildSettings.PlayerBuiltInScenes)
            {
                if (sceneName.Contains(testName))
                {
                    return(null);
                }
            }
            return(sceneName);
        });

        var filtered  = new List <string>();
        var arrayList = new ArrayList();

        foreach (string item in items)
        {
            Debug.Log("item: " + item + " " + (BuildSettings.IsDevelopmentBuild ? "YES" : "NO"));
            if (!string.IsNullOrEmpty(filter))
            {
                if (item.Contains(filter) == false)
                {
                    Debug.Log("Skipping scene because its in the build settings " + item);
                    continue;
                }
            }

            string sceneName      = Path.GetFileNameWithoutExtension(item);
            string sceneNameLower = sceneName.ToLower();

            if (BuildSettings.IsDevelopmentBuild && (BuildSettings.DevBundleMode == EB.Assets.DevBundleType.BundleServer) &&
                (BuildSettings.Target == BuildTarget.Android || BuildSettings.Target == BuildTarget.iOS))                       // build everything except the basic transition scenes as separate bundles for faster turn around when authoring/debugging.
            {
                if (!devLevels.Contains(sceneNameLower))
                {
                    continue;
                }
            }
            else if (buildSceneNames.Contains(sceneName))
            {
                Debug.Log("Skipping scene because its in the build settings " + item);
                continue;
            }

            filtered.Add(item);
            arrayList.Add(sceneName);
        }

        if (EB.Dot.Bool("single_bundle", bundle, false))
        {
            var bundle_name = string.Format("scene_{0}.assetbundle", id);
            var bundle_path = Path.Combine(_outFolder, bundle_name);

            var deps = AssetDatabase.GetDependencies(items);
            if ((options & BundleOptions.Force) != 0 || CheckDependancies(bundle_path, deps))
            {
                // build
                Debug.Log("Building " + items.Length + " scenes in one");
                BuildPipeline.PushAssetDependencies();
                BuildPipeline.BuildStreamedSceneAssetBundle(filtered.ToArray(), bundle_path, BuildSettings.Target);
                BuildPipeline.PopAssetDependencies();
                result = true;
            }
            long      ts            = File.GetLastWriteTime(bundle_path).Ticks;
            Hashtable sceneTSLookup = new Hashtable();
            foreach (string scene in arrayList)
            {
                sceneTSLookup[scene] = ts;
            }
            _scenes[id] = sceneTSLookup;
        }
        else
        {
            int itemsCount = filtered.Count;
            for (int i = 0; i < itemsCount; i++)
            {
                string shortname = (string)arrayList[i];
                string item      = filtered[i];

                var bundle_name = string.Format("scene_{0}.assetbundle", shortname);
                var bundle_path = Path.Combine(_outFolder, bundle_name);

                var deps = AssetDatabase.GetDependencies(new string[] { item });

                // check dependancies
                if ((options & BundleOptions.Force) != 0 || CheckDependancies(bundle_path, deps))
                {
                    // build
                    Debug.Log("Building scene " + shortname + " " + bundle_path);
                    BuildPipeline.PushAssetDependencies();

                    string error = null;
                    error = BuildPipeline.BuildStreamedSceneAssetBundle(new string[] { item }, bundle_path, BuildSettings.Target);

                    if (!string.IsNullOrEmpty(error))
                    {
                        Debug.LogError("Error during BuildPipeline.BuildStreamedSceneAssetBundle " + item + " error: " + error);
                    }
                    else if (!File.Exists(bundle_path))
                    {
                        Debug.LogError("No Error returned, but no bundle created: " + bundle_path);
                    }
                    BuildPipeline.PopAssetDependencies();
                    EditorUtility.UnloadUnusedAssetsImmediate();

                    result = true;
                }

                long ts = File.GetLastWriteTime(bundle_path).Ticks;

                Hashtable sceneTSLookup = new Hashtable();
                sceneTSLookup[shortname] = ts;
                _scenes[shortname]       = sceneTSLookup;
            }
        }

        return(result);
    }
Пример #14
0
        public static MvcHtmlString RenderJsBundle(this HtmlHelper html, string bundlePath, BundleOptions options = BundleOptions.Minified)
        {
            if (string.IsNullOrEmpty(bundlePath))
            {
                return(MvcHtmlString.Empty);
            }

            if (!CachePaths())
            {
                BundleCache.SafeClear();
            }

            return(BundleCache.GetOrAdd(bundlePath, str => {
                var filePath = HostingEnvironment.MapPath(bundlePath);

                var baseUrl = VirtualPathUtility.GetDirectory(bundlePath);

                if (options == BundleOptions.Combined)
                {
                    return html.Js(bundlePath.Replace(".bundle", ""), options);
                }
                if (options == BundleOptions.MinifiedAndCombined)
                {
                    return html.Js(bundlePath.Replace(".js.bundle", ".min.js"), options);
                }

                var jsFiles = File.ReadAllLines(filePath);

                var scripts = new StringBuilder();
                foreach (var file in jsFiles)
                {
                    var jsFile = file.Trim().Replace(".coffee", ".js");
                    var jsSrc = Path.Combine(baseUrl, jsFile);

                    scripts.AppendLine(
                        html.Js(jsSrc, options).ToString()
                        );
                }

                return scripts.ToString().ToMvcHtmlString();
            }));
        }
Пример #15
0
        static void ParseArgs(string[] args)
        {
            int i = 0;
            Func <string, string> NextArg = (string option) =>
            {
                if (++i >= args.Length)
                {
                    throw new ArgumentException("Argument missing for" + option);
                }
                return(args[i]);
            };

            string os        = "win";
            string framework = "net5";

            for (; i < args.Length; i++)
            {
                string arg = args[i];
                switch (arg.ToLower())
                {
                case "-?":
                case "-h":
                case "--help":
                    NeedHelp = true;
                    break;

                case "-d":
                case "--diagnostics":
                    Diagnostics = true;
                    break;

                case "--pdb":
                    Options |= BundleOptions.BundleSymbolFiles;
                    break;

                case "--native":
                    Options |= BundleOptions.BundleNativeBinaries;
                    break;

                case "--content":
                    Options |= BundleOptions.BundleAllContent;
                    break;

                case "--host":
                    Host = NextArg(arg);
                    break;

                case "--app":
                    App = NextArg(arg);
                    break;

                case "--template":
                    CreateHost = true;
                    Template   = NextArg(arg);
                    break;

                case "--source":
                    SourceDir = NextArg(arg);
                    break;

                case "-o":
                case "--output":
                    OutputDir = NextArg(arg);
                    break;

                case "--os":
                    os = NextArg(arg).ToLower();
                    break;

                case "--framework":
                    framework = NextArg(arg);
                    break;

                case "--skip-excluded":
                    CopyExcluded = false;
                    break;

                case "--no-bundle":
                    CreateBundle = false;
                    break;

                default:
                    throw new ArgumentException("Invalid option: " + arg);
                }
            }

            switch (os)
            {
            case "win":
                OS = OSPlatform.Windows;
                break;

            case "linux":
                OS = OSPlatform.Linux;
                break;

            case "osx":
                OS = OSPlatform.OSX;
                break;

            default:
                throw new ArgumentException("Unknown OS");
            }

            switch (framework)
            {
            case "netcoreapp3.0":
                Framework = new Version(3, 0);
                break;

            case "netcoreapp3.1":
                Framework = new Version(3, 1);
                break;

            case "net5":
                Framework = new Version(5, 0);
                break;

            default:
                throw new ArgumentException("Unknown Framework");
            }

            if (SourceDir == null)
            {
                throw new ArgumentException("Missing argument: --source");
            }

            if (Host == null)
            {
                throw new ArgumentException("Missing argument: --host");
            }

            if (CreateHost)
            {
                if (Template == null)
                {
                    throw new ArgumentException("Missing argument: --template");
                }

                if (App == null)
                {
                    App = Path.GetFileNameWithoutExtension(Host) + ".dll";
                }
            }

            if (OutputDir == null)
            {
                OutputDir = Environment.CurrentDirectory;
            }
        }
Пример #16
0
 /// <summary>
 /// 内部停止插件的工作者
 /// </summary>
 /// <param name="option"></param>
 protected abstract void StopWorker(BundleOptions option);
Пример #17
0
        public static IServiceCollection AddBTCPayServer(this IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>((provider, o) =>
            {
                var factory = provider.GetRequiredService <ApplicationDbContextFactory>();
                factory.ConfigureBuilder(o);
            });
            services.TryAddSingleton <SettingsRepository>();
            services.TryAddSingleton <InvoicePaymentNotification>();
            services.TryAddSingleton <BTCPayServerOptions>(o => o.GetRequiredService <IOptions <BTCPayServerOptions> >().Value);
            services.TryAddSingleton <InvoiceRepository>(o =>
            {
                var opts      = o.GetRequiredService <BTCPayServerOptions>();
                var dbContext = o.GetRequiredService <ApplicationDbContextFactory>();
                var dbpath    = Path.Combine(opts.DataDir, "InvoiceDB");
                if (!Directory.Exists(dbpath))
                {
                    Directory.CreateDirectory(dbpath);
                }
                return(new InvoiceRepository(dbContext, dbpath));
            });
            services.AddSingleton <BTCPayServerEnvironment>();
            services.TryAddSingleton <TokenRepository>();
            services.TryAddSingleton <EventAggregator>();
            services.TryAddSingleton <CoinAverageSettings>();
            services.TryAddSingleton <ApplicationDbContextFactory>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                ApplicationDbContextFactory dbContext = null;
                if (opts.PostgresConnectionString == null)
                {
                    var connStr = "Data Source=" + Path.Combine(opts.DataDir, "sqllite.db");
                    Logs.Configuration.LogInformation($"SQLite DB used ({connStr})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Sqlite, connStr);
                }
                else
                {
                    Logs.Configuration.LogInformation($"Postgres DB used ({opts.PostgresConnectionString})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Postgres, opts.PostgresConnectionString);
                }
                return(dbContext);
            });
            services.TryAddSingleton <Payments.Lightning.LightningClientFactory>();

            services.TryAddSingleton <BTCPayNetworkProvider>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                return(opts.NetworkProvider);
            });

            services.TryAddSingleton <LanguageService>();
            services.TryAddSingleton <NBXplorerDashboard>();
            services.TryAddSingleton <StoreRepository>();
            services.TryAddSingleton <BTCPayWalletProvider>();
            services.TryAddSingleton <CurrencyNameTable>();
            services.TryAddSingleton <IFeeProviderFactory>(o => new NBXplorerFeeProviderFactory(o.GetRequiredService <ExplorerClientProvider>())
            {
                Fallback    = new FeeRate(100, 1),
                BlockTarget = 20
            });

            services.AddSingleton <CssThemeManager>();
            services.AddSingleton <IHostedService, CssThemeManagerHostedService>();

            services.AddSingleton <Payments.IPaymentMethodHandler <DerivationStrategy>, Payments.Bitcoin.BitcoinLikePaymentHandler>();
            services.AddSingleton <IHostedService, Payments.Bitcoin.NBXplorerListener>();

            services.AddSingleton <Payments.IPaymentMethodHandler <Payments.Lightning.LightningSupportedPaymentMethod>, Payments.Lightning.LightningLikePaymentHandler>();
            services.AddSingleton <IHostedService, Payments.Lightning.LightningListener>();

            services.AddSingleton <IHostedService, NBXplorerWaiters>();
            services.AddSingleton <IHostedService, InvoiceNotificationManager>();
            services.AddSingleton <IHostedService, InvoiceWatcher>();
            services.AddSingleton <IHostedService, RatesHostedService>();
            services.AddTransient <IConfigureOptions <MvcOptions>, BTCPayClaimsFilter>();

            services.TryAddSingleton <ExplorerClientProvider>();
            services.TryAddSingleton <Bitpay>(o =>
            {
                if (o.GetRequiredService <BTCPayServerOptions>().NetworkType == NetworkType.Mainnet)
                {
                    return(new Bitpay(new Key(), new Uri("https://bitpay.com/")));
                }
                else
                {
                    return(new Bitpay(new Key(), new Uri("https://test.bitpay.com/")));
                }
            });
            services.TryAddSingleton <BTCPayRateProviderFactory>();

            services.TryAddScoped <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <AccessTokenController>();
            services.AddTransient <InvoiceController>();
            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();
            // bundling

            services.AddAuthorization(o => Policies.AddBTCPayPolicies(o));
            BitpayAuthentication.AddAuthentication(services);

            services.AddBundles();
            services.AddTransient <BundleOptions>(provider =>
            {
                var opts   = provider.GetRequiredService <BTCPayServerOptions>();
                var bundle = new BundleOptions();
                bundle.UseMinifiedFiles = opts.BundleJsCss;
                bundle.AppendVersion    = true;
                return(bundle);
            });

            return(services);
        }
Пример #18
0
        public static IServiceCollection AddBTCPayServer(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSingleton <MvcNewtonsoftJsonOptions>(o => o.GetRequiredService <IOptions <MvcNewtonsoftJsonOptions> >().Value);
            services.AddDbContext <ApplicationDbContext>((provider, o) =>
            {
                var factory = provider.GetRequiredService <ApplicationDbContextFactory>();
                factory.ConfigureBuilder(o);
            });
            services.AddHttpClient();
            services.AddHttpClient(nameof(ExplorerClientProvider), httpClient =>
            {
                httpClient.Timeout = Timeout.InfiniteTimeSpan;
            });

            services.AddSingleton <BTCPayNetworkJsonSerializerSettings>();
            services.RegisterJsonConverter(n => new ClaimDestinationJsonConverter(n));

            services.AddPayJoinServices();
            services.AddMoneroLike();
            services.TryAddSingleton <SettingsRepository>();
            services.TryAddSingleton <LabelFactory>();
            services.TryAddSingleton <TorServices>();
            services.TryAddSingleton <SocketFactory>();
            services.TryAddSingleton <LightningClientFactoryService>();
            services.TryAddSingleton <InvoicePaymentNotification>();
            services.TryAddSingleton <BTCPayServerOptions>(o =>
                                                           o.GetRequiredService <IOptions <BTCPayServerOptions> >().Value);
            services.AddStartupTask <MigrationStartupTask>();
            services.TryAddSingleton <InvoiceRepository>(o =>
            {
                var opts      = o.GetRequiredService <BTCPayServerOptions>();
                var dbContext = o.GetRequiredService <ApplicationDbContextFactory>();
                var dbpath    = Path.Combine(opts.DataDir, "InvoiceDB");
                if (!Directory.Exists(dbpath))
                {
                    Directory.CreateDirectory(dbpath);
                }
                return(new InvoiceRepository(dbContext, dbpath, o.GetRequiredService <BTCPayNetworkProvider>()));
            });
            services.AddSingleton <BTCPayServerEnvironment>();
            services.TryAddSingleton <TokenRepository>();
            services.TryAddSingleton <WalletRepository>();
            services.TryAddSingleton <EventAggregator>();
            services.TryAddSingleton <PaymentRequestService>();
            services.TryAddSingleton <U2FService>();
            services.TryAddSingleton <ApplicationDbContextFactory>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                ApplicationDbContextFactory dbContext = null;
                if (!String.IsNullOrEmpty(opts.PostgresConnectionString))
                {
                    Logs.Configuration.LogInformation($"Postgres DB used ({opts.PostgresConnectionString})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Postgres, opts.PostgresConnectionString);
                }
                else if (!String.IsNullOrEmpty(opts.MySQLConnectionString))
                {
                    Logs.Configuration.LogInformation($"MySQL DB used ({opts.MySQLConnectionString})");
                    Logs.Configuration.LogWarning("MySQL is not widely tested and should be considered experimental, we advise you to use postgres instead.");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.MySQL, opts.MySQLConnectionString);
                }
                else
                {
                    var connStr = "Data Source=" + Path.Combine(opts.DataDir, "sqllite.db");
                    Logs.Configuration.LogInformation($"SQLite DB used ({connStr})");
                    Logs.Configuration.LogWarning("MySQL is not widely tested and should be considered experimental, we advise you to use postgres instead.");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Sqlite, connStr);
                }

                return(dbContext);
            });

            services.TryAddSingleton <BTCPayNetworkProvider>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                return(opts.NetworkProvider);
            });

            services.TryAddSingleton <AppService>();
            services.TryAddTransient <Safe>();
            services.TryAddSingleton <Ganss.XSS.HtmlSanitizer>(o =>
            {
                var htmlSanitizer = new Ganss.XSS.HtmlSanitizer();


                htmlSanitizer.RemovingAtRule += (sender, args) =>
                {
                };
                htmlSanitizer.RemovingTag += (sender, args) =>
                {
                    if (args.Tag.TagName.Equals("img", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (!args.Tag.ClassList.Contains("img-fluid"))
                        {
                            args.Tag.ClassList.Add("img-fluid");
                        }

                        args.Cancel = true;
                    }
                };

                htmlSanitizer.RemovingAttribute += (sender, args) =>
                {
                    if (args.Tag.TagName.Equals("img", StringComparison.InvariantCultureIgnoreCase) &&
                        args.Attribute.Name.Equals("src", StringComparison.InvariantCultureIgnoreCase) &&
                        args.Reason == Ganss.XSS.RemoveReason.NotAllowedUrlValue)
                    {
                        args.Cancel = true;
                    }
                };
                htmlSanitizer.RemovingStyle += (sender, args) => { args.Cancel = true; };
                htmlSanitizer.AllowedAttributes.Add("class");
                htmlSanitizer.AllowedTags.Add("iframe");
                htmlSanitizer.AllowedTags.Remove("img");
                htmlSanitizer.AllowedAttributes.Add("webkitallowfullscreen");
                htmlSanitizer.AllowedAttributes.Add("allowfullscreen");
                return(htmlSanitizer);
            });

            services.TryAddSingleton <LightningConfigurationProvider>();
            services.TryAddSingleton <LanguageService>();
            services.TryAddSingleton <NBXplorerDashboard>();
            services.TryAddSingleton <StoreRepository>();
            services.TryAddSingleton <PaymentRequestRepository>();
            services.TryAddSingleton <BTCPayWalletProvider>();
            services.TryAddSingleton <WalletReceiveStateService>();
            services.TryAddSingleton <CurrencyNameTable>(CurrencyNameTable.Instance);
            services.TryAddSingleton <IFeeProviderFactory>(o => new NBXplorerFeeProviderFactory(o.GetRequiredService <ExplorerClientProvider>())
            {
                Fallback = new FeeRate(100L, 1)
            });

            services.AddSingleton <CssThemeManager>();
            services.Configure <MvcOptions>((o) => {
                o.Filters.Add(new ContentSecurityPolicyCssThemeManager());
                o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(WalletId)));
                o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(DerivationStrategyBase)));
            });
            services.AddSingleton <IHostedService, CssThemeManagerHostedService>();

            services.AddSingleton <HostedServices.CheckConfigurationHostedService>();
            services.AddSingleton <IHostedService, HostedServices.CheckConfigurationHostedService>(o => o.GetRequiredService <CheckConfigurationHostedService>());

            services.AddSingleton <HostedServices.PullPaymentHostedService>();
            services.AddSingleton <IHostedService, HostedServices.PullPaymentHostedService>(o => o.GetRequiredService <PullPaymentHostedService>());

            services.AddSingleton <BitcoinLikePaymentHandler>();
            services.AddSingleton <IPaymentMethodHandler>(provider => provider.GetService <BitcoinLikePaymentHandler>());
            services.AddSingleton <IHostedService, NBXplorerListener>();

            services.AddSingleton <LightningLikePaymentHandler>();
            services.AddSingleton <IPaymentMethodHandler>(provider => provider.GetService <LightningLikePaymentHandler>());
            services.AddSingleton <IHostedService, LightningListener>();

            services.AddSingleton <PaymentMethodHandlerDictionary>();

            services.AddSingleton <ChangellyClientProvider>();

            services.AddSingleton <NotificationManager>();
            services.AddScoped <NotificationSender>();

            services.AddSingleton <IHostedService, NBXplorerWaiters>();
            services.AddSingleton <IHostedService, InvoiceNotificationManager>();
            services.AddSingleton <IHostedService, InvoiceWatcher>();
            services.AddSingleton <IHostedService, RatesHostedService>();
            services.AddSingleton <IHostedService, BackgroundJobSchedulerHostedService>();
            services.AddSingleton <IHostedService, AppHubStreamer>();
            services.AddSingleton <IHostedService, AppInventoryUpdaterHostedService>();
            services.AddSingleton <IHostedService, TransactionLabelMarkerHostedService>();
            services.AddSingleton <IHostedService, UserEventHostedService>();
            services.AddSingleton <IHostedService, DynamicDnsHostedService>();
            services.AddSingleton <IHostedService, TorServicesHostedService>();
            services.AddSingleton <IHostedService, PaymentRequestStreamer>();
            services.AddSingleton <IHostedService, WalletReceiveCacheUpdater>();
            services.AddSingleton <IBackgroundJobClient, BackgroundJobClient>();
            services.AddScoped <IAuthorizationHandler, CookieAuthorizationHandler>();
            services.AddScoped <IAuthorizationHandler, BitpayAuthorizationHandler>();
            services.AddSingleton <INotificationHandler, NewVersionNotification.Handler>();
            services.AddSingleton <INotificationHandler, InvoiceEventNotification.Handler>();
            services.AddSingleton <INotificationHandler, PayoutNotification.Handler>();

            services.TryAddSingleton <ExplorerClientProvider>();
            services.TryAddSingleton <Bitpay>(o =>
            {
                if (o.GetRequiredService <BTCPayServerOptions>().NetworkType == NetworkType.Mainnet)
                {
                    return(new Bitpay(new Key(), new Uri("https://bitpay.com/")));
                }
                else
                {
                    return(new Bitpay(new Key(), new Uri("https://test.bitpay.com/")));
                }
            });
            services.TryAddSingleton <RateProviderFactory>();
            services.TryAddSingleton <RateFetcher>();

            services.TryAddScoped <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <AccessTokenController>();
            services.AddTransient <InvoiceController>();
            services.AddTransient <AppsPublicController>();
            services.AddTransient <PaymentRequestController>();
            // Add application services.
            services.AddSingleton <EmailSenderFactory>();

            services.AddAPIKeyAuthentication();
            services.AddBtcPayServerAuthenticationSchemes();
            services.AddAuthorization(o => o.AddBTCPayPolicies());
            // bundling
            services.AddSingleton <IBundleProvider, ResourceBundleProvider>();
            services.AddTransient <BundleOptions>(provider =>
            {
                var opts             = provider.GetRequiredService <BTCPayServerOptions>();
                var bundle           = new BundleOptions();
                bundle.UseBundles    = opts.BundleJsCss;
                bundle.AppendVersion = true;
                return(bundle);
            });

            services.AddCors(options =>
            {
                options.AddPolicy(CorsPolicies.All, p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            });
            services.AddSingleton(provider =>
            {
                var btcPayEnv  = provider.GetService <BTCPayServerEnvironment>();
                var rateLimits = new RateLimitService();
                if (btcPayEnv.IsDevelopping)
                {
                    rateLimits.SetZone($"zone={ZoneLimits.Login} rate=1000r/min burst=100 nodelay");
                    rateLimits.SetZone($"zone={ZoneLimits.Register} rate=1000r/min burst=100 nodelay");
                    rateLimits.SetZone($"zone={ZoneLimits.PayJoin} rate=1000r/min burst=100 nodelay");
                }
                else
                {
                    rateLimits.SetZone($"zone={ZoneLimits.Login} rate=5r/min burst=3 nodelay");
                    rateLimits.SetZone($"zone={ZoneLimits.Register} rate=2r/min burst=2 nodelay");
                    rateLimits.SetZone($"zone={ZoneLimits.PayJoin} rate=5r/min burst=3 nodelay");
                }
                return(rateLimits);
            });
            services.AddLogging(logBuilder =>
            {
                var debugLogFile = BTCPayServerOptions.GetDebugLog(configuration);
                if (!string.IsNullOrEmpty(debugLogFile))
                {
                    Serilog.Log.Logger = new LoggerConfiguration()
                                         .Enrich.FromLogContext()
                                         .MinimumLevel.Is(BTCPayServerOptions.GetDebugLogLevel(configuration))
                                         .WriteTo.File(debugLogFile, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: MAX_DEBUG_LOG_FILE_SIZE, rollOnFileSizeLimit: true, retainedFileCountLimit: 1)
                                         .CreateLogger();
                    logBuilder.AddProvider(new Serilog.Extensions.Logging.SerilogLoggerProvider(Log.Logger));
                }
            });
            return(services);
        }
Пример #19
0
        private static void Main(string[] args)
        {
            var options        = new Options();
            var isOptionsValid = Parser.Default.ParseArguments(args, options);

            if (!isOptionsValid)
            {
                var helpText = HelpText.AutoBuild(options);
                HelpText.DefaultParsingErrorsHandler(options, helpText);
                Console.WriteLine(helpText);
                return;
            }

            options.SongID = Math.Abs(options.SongID) % 10000;
            if (string.IsNullOrEmpty(options.ImageFileName) && !File.Exists(options.ImageFileName))
            {
                Console.WriteLine($"ERROR: image file '{options.ImageFileName}' is not found.");
                return;
            }
            var fullDirectoryName = (new DirectoryInfo(options.OutputDirectory)).FullName;

            if (!Directory.Exists(fullDirectoryName))
            {
                try {
                    Directory.CreateDirectory(fullDirectoryName);
                } catch (Exception ex) {
                    Console.WriteLine($"ERROR: Tried to create directory '{fullDirectoryName}' but failed.\n{ex.Message}");
                    return;
                }
            }

            Bitmap bitmap;

            try {
                bitmap = (Bitmap)Image.FromFile(options.ImageFileName);
            } catch (Exception ex) {
                Console.WriteLine($"ERROR: Cannot read image file '{options.ImageFileName}'.\n{ex.Message}");
                return;
            }

            // Magic begins!
            byte[] pvr, dds;
            using (var smallImage = new Bitmap(bitmap, BundleOptions.SmallImageSize, BundleOptions.SmallImageSize)) {
                pvr = PvrUtilities.GetPvrTextureFromImage(smallImage);
            }
            using (var mediumImage = new Bitmap(bitmap, BundleOptions.MediumImageSize, BundleOptions.MediumImageSize)) {
                dds = DdsUtilities.GetDdsTextureFromImage(mediumImage);
            }
            bitmap.Dispose();

            var bundleOptions = new BundleOptions();

            bundleOptions.PvrImage  = pvr;
            bundleOptions.DdsImage  = dds;
            bundleOptions.PvrPathID = options.PvrPathID;
            bundleOptions.DdsPathID = options.DdsPathID;

            var fileName = Path.Combine(fullDirectoryName, $"jacket_{options.SongID}_android.unity3d");

            using (var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write)) {
                bundleOptions.Platform = UnityPlatformID.Android;
                JacketBundle.Serialize(bundleOptions, fileStream);
            }
            fileName = Path.Combine(fullDirectoryName, $"jacket_{options.SongID}_ios.unity3d");
            using (var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write)) {
                bundleOptions.Platform = UnityPlatformID.iOS;
                JacketBundle.Serialize(bundleOptions, fileStream);
            }
            Console.WriteLine($"Building complete. Files are written to '{fullDirectoryName}', song ID = {options.SongID}.");
        }
        public static IServiceCollection AddBTCPayServer(this IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>((provider, o) =>
            {
                var factory = provider.GetRequiredService <ApplicationDbContextFactory>();
                factory.ConfigureBuilder(o);
            });
            services.AddHttpClient();
            services.TryAddSingleton <SettingsRepository>();
            services.TryAddSingleton <InvoicePaymentNotification>();
            services.TryAddSingleton <BTCPayServerOptions>(o => o.GetRequiredService <IOptions <BTCPayServerOptions> >().Value);
            services.TryAddSingleton <InvoiceRepository>(o =>
            {
                var opts      = o.GetRequiredService <BTCPayServerOptions>();
                var dbContext = o.GetRequiredService <ApplicationDbContextFactory>();
                var dbpath    = Path.Combine(opts.DataDir, "InvoiceDB");
                if (!Directory.Exists(dbpath))
                {
                    Directory.CreateDirectory(dbpath);
                }
                return(new InvoiceRepository(dbContext, dbpath));
            });
            services.AddSingleton <BTCPayServerEnvironment>();
            services.TryAddSingleton <TokenRepository>();
            services.TryAddSingleton <EventAggregator>();
            services.TryAddSingleton <CoinAverageSettings>();
            services.TryAddSingleton <ApplicationDbContextFactory>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                ApplicationDbContextFactory dbContext = null;
                if (!String.IsNullOrEmpty(opts.PostgresConnectionString))
                {
                    Logs.Configuration.LogInformation($"Postgres DB used ({opts.PostgresConnectionString})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Postgres, opts.PostgresConnectionString);
                }
                else if (!String.IsNullOrEmpty(opts.MySQLConnectionString))
                {
                    Logs.Configuration.LogInformation($"MySQL DB used ({opts.MySQLConnectionString})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.MySQL, opts.MySQLConnectionString);
                }
                else
                {
                    var connStr = "Data Source=" + Path.Combine(opts.DataDir, "sqllite.db");
                    Logs.Configuration.LogInformation($"SQLite DB used ({connStr})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Sqlite, connStr);
                }

                return(dbContext);
            });

            services.TryAddSingleton <BTCPayNetworkProvider>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                return(opts.NetworkProvider);
            });

            services.TryAddSingleton <AppsHelper>();

            services.TryAddSingleton <LightningConfigurationProvider>();
            services.TryAddSingleton <LanguageService>();
            services.TryAddSingleton <NBXplorerDashboard>();
            services.TryAddSingleton <StoreRepository>();
            services.TryAddSingleton <BTCPayWalletProvider>();
            services.TryAddSingleton <CurrencyNameTable>();
            services.TryAddSingleton <IFeeProviderFactory>(o => new NBXplorerFeeProviderFactory(o.GetRequiredService <ExplorerClientProvider>())
            {
                Fallback    = new FeeRate(100, 1),
                BlockTarget = 20
            });

            services.AddSingleton <CssThemeManager>();
            services.Configure <MvcOptions>((o) => {
                o.Filters.Add(new ContentSecurityPolicyCssThemeManager());
                o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(WalletId)));
                o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(DerivationStrategyBase)));
            });
            services.AddSingleton <IHostedService, CssThemeManagerHostedService>();
            services.AddSingleton <IHostedService, MigratorHostedService>();

            services.AddSingleton <Payments.IPaymentMethodHandler <DerivationStrategy>, Payments.Bitcoin.BitcoinLikePaymentHandler>();
            services.AddSingleton <IHostedService, Payments.Bitcoin.NBXplorerListener>();

            services.AddSingleton <IHostedService, HostedServices.CheckConfigurationHostedService>();

            services.AddSingleton <Payments.IPaymentMethodHandler <Payments.Lightning.LightningSupportedPaymentMethod>, Payments.Lightning.LightningLikePaymentHandler>();
            services.AddSingleton <LightningLikePaymentHandler>();
            services.AddSingleton <IHostedService, Payments.Lightning.LightningListener>();

            services.AddSingleton <ChangellyClientProvider>();

            services.AddSingleton <IHostedService, NBXplorerWaiters>();
            services.AddSingleton <IHostedService, InvoiceNotificationManager>();
            services.AddSingleton <IHostedService, InvoiceWatcher>();
            services.AddSingleton <IHostedService, RatesHostedService>();
            services.AddTransient <IConfigureOptions <MvcOptions>, BTCPayClaimsFilter>();

            services.TryAddSingleton <ExplorerClientProvider>();
            services.TryAddSingleton <Bitpay>(o =>
            {
                if (o.GetRequiredService <BTCPayServerOptions>().NetworkType == NetworkType.Mainnet)
                {
                    return(new Bitpay(new Key(), new Uri("https://bitpay.com/")));
                }
                else
                {
                    return(new Bitpay(new Key(), new Uri("https://test.bitpay.com/")));
                }
            });
            services.TryAddSingleton <RateProviderFactory>();
            services.TryAddSingleton <RateFetcher>();

            services.TryAddScoped <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <AccessTokenController>();
            services.AddTransient <InvoiceController>();
            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();
            // bundling

            services.AddAuthorization(o => Policies.AddBTCPayPolicies(o));
            BitpayAuthentication.AddAuthentication(services);

            services.AddBundles();
            services.AddTransient <BundleOptions>(provider =>
            {
                var opts             = provider.GetRequiredService <BTCPayServerOptions>();
                var bundle           = new BundleOptions();
                bundle.UseBundles    = opts.BundleJsCss;
                bundle.AppendVersion = true;
                return(bundle);
            });

            services.AddCors(options =>
            {
                options.AddPolicy(CorsPolicies.All, p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            });

            var rateLimits = new RateLimitService();

            rateLimits.SetZone($"zone={ZoneLimits.Login} rate=5r/min burst=3 nodelay");
            services.AddSingleton(rateLimits);
            return(services);
        }
Пример #21
0
        public static Bundler Bundle(TestProjectFixture fixture, BundleOptions options = BundleOptions.None)
        {
            string singleFile;

            return(BundleApp(fixture, out singleFile, options, copyExcludedFiles: false));
        }
Пример #22
0
        public static IServiceCollection AddBTCPayServer(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext <ApplicationDbContext>((provider, o) =>
            {
                var factory = provider.GetRequiredService <ApplicationDbContextFactory>();
                factory.ConfigureBuilder(o);
                o.UseOpenIddict <BTCPayOpenIdClient, BTCPayOpenIdAuthorization, OpenIddictScope <string>, BTCPayOpenIdToken, string>();
            });
            services.AddHttpClient();
            services.AddHttpClient(nameof(ExplorerClientProvider), httpClient =>
            {
                httpClient.Timeout = Timeout.InfiniteTimeSpan;
            });
            services.TryAddSingleton <SettingsRepository>();
            services.TryAddSingleton <TorServices>();
            services.TryAddSingleton <SocketFactory>();
            services.TryAddSingleton <LightningClientFactoryService>();
            services.TryAddSingleton <InvoicePaymentNotification>();
            services.TryAddSingleton <BTCPayServerOptions>(o =>
                                                           o.GetRequiredService <IOptions <BTCPayServerOptions> >().Value);
            services.AddStartupTask <MigrationStartupTask>();
            services.TryAddSingleton <InvoiceRepository>(o =>
            {
                var opts      = o.GetRequiredService <BTCPayServerOptions>();
                var dbContext = o.GetRequiredService <ApplicationDbContextFactory>();
                var dbpath    = Path.Combine(opts.DataDir, "InvoiceDB");
                if (!Directory.Exists(dbpath))
                {
                    Directory.CreateDirectory(dbpath);
                }
                return(new InvoiceRepository(dbContext, dbpath, o.GetRequiredService <BTCPayNetworkProvider>()));
            });
            services.AddSingleton <BTCPayServerEnvironment>();
            services.TryAddSingleton <TokenRepository>();
            services.TryAddSingleton <WalletRepository>();
            services.TryAddSingleton <EventAggregator>();
            services.TryAddSingleton <PaymentRequestService>();
            services.TryAddSingleton <U2FService>();
            services.TryAddSingleton <CoinAverageSettings>();
            services.TryAddSingleton <ApplicationDbContextFactory>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                ApplicationDbContextFactory dbContext = null;
                if (!String.IsNullOrEmpty(opts.PostgresConnectionString))
                {
                    Logs.Configuration.LogInformation($"Postgres DB used ({opts.PostgresConnectionString})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Postgres, opts.PostgresConnectionString);
                }
                else if (!String.IsNullOrEmpty(opts.MySQLConnectionString))
                {
                    Logs.Configuration.LogInformation($"MySQL DB used ({opts.MySQLConnectionString})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.MySQL, opts.MySQLConnectionString);
                }
                else
                {
                    var connStr = "Data Source=" + Path.Combine(opts.DataDir, "sqllite.db");
                    Logs.Configuration.LogInformation($"SQLite DB used ({connStr})");
                    dbContext = new ApplicationDbContextFactory(DatabaseType.Sqlite, connStr);
                }

                return(dbContext);
            });

            services.TryAddSingleton <BTCPayNetworkProvider>(o =>
            {
                var opts = o.GetRequiredService <BTCPayServerOptions>();
                return(opts.NetworkProvider);
            });

            services.TryAddSingleton <AppService>();
            services.TryAddTransient <Safe>();
            services.TryAddSingleton <Ganss.XSS.HtmlSanitizer>(o =>
            {
                var htmlSanitizer = new Ganss.XSS.HtmlSanitizer();


                htmlSanitizer.RemovingAtRule += (sender, args) =>
                {
                };
                htmlSanitizer.RemovingTag += (sender, args) =>
                {
                    if (args.Tag.TagName.Equals("img", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (!args.Tag.ClassList.Contains("img-fluid"))
                        {
                            args.Tag.ClassList.Add("img-fluid");
                        }

                        args.Cancel = true;
                    }
                };

                htmlSanitizer.RemovingAttribute += (sender, args) =>
                {
                    if (args.Tag.TagName.Equals("img", StringComparison.InvariantCultureIgnoreCase) &&
                        args.Attribute.Name.Equals("src", StringComparison.InvariantCultureIgnoreCase) &&
                        args.Reason == Ganss.XSS.RemoveReason.NotAllowedUrlValue)
                    {
                        args.Cancel = true;
                    }
                };
                htmlSanitizer.RemovingStyle += (sender, args) => { args.Cancel = true; };
                htmlSanitizer.AllowedAttributes.Add("class");
                htmlSanitizer.AllowedTags.Add("iframe");
                htmlSanitizer.AllowedTags.Remove("img");
                htmlSanitizer.AllowedAttributes.Add("webkitallowfullscreen");
                htmlSanitizer.AllowedAttributes.Add("allowfullscreen");
                return(htmlSanitizer);
            });

            services.TryAddSingleton <LightningConfigurationProvider>();
            services.TryAddSingleton <LanguageService>();
            services.TryAddSingleton <NBXplorerDashboard>();
            services.TryAddSingleton <StoreRepository>();
            services.TryAddSingleton <PaymentRequestRepository>();
            services.TryAddSingleton <BTCPayWalletProvider>();
            services.TryAddSingleton <CurrencyNameTable>();
            services.TryAddSingleton <IFeeProviderFactory>(o => new NBXplorerFeeProviderFactory(o.GetRequiredService <ExplorerClientProvider>())
            {
                Fallback    = new FeeRate(100L, 1),
                BlockTarget = 20
            });

            services.AddSingleton <CssThemeManager>();
            services.Configure <MvcOptions>((o) => {
                o.Filters.Add(new ContentSecurityPolicyCssThemeManager());
                o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(WalletId)));
                o.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(DerivationStrategyBase)));
            });
            services.AddSingleton <IHostedService, CssThemeManagerHostedService>();

            services.AddSingleton <HostedServices.CheckConfigurationHostedService>();
            services.AddSingleton <IHostedService, HostedServices.CheckConfigurationHostedService>(o => o.GetRequiredService <CheckConfigurationHostedService>());

            services.AddSingleton <BitcoinLikePaymentHandler>();
            services.AddSingleton <IPaymentMethodHandler>(provider => provider.GetService <BitcoinLikePaymentHandler>());
            services.AddSingleton <IHostedService, NBXplorerListener>();

            services.AddSingleton <LightningLikePaymentHandler>();
            services.AddSingleton <IPaymentMethodHandler>(provider => provider.GetService <LightningLikePaymentHandler>());
            services.AddSingleton <IHostedService, LightningListener>();

            services.AddSingleton <PaymentMethodHandlerDictionary>();

            services.AddSingleton <ChangellyClientProvider>();

            services.AddSingleton <IHostedService, NBXplorerWaiters>();
            services.AddSingleton <IHostedService, InvoiceNotificationManager>();
            services.AddSingleton <IHostedService, InvoiceWatcher>();
            services.AddSingleton <IHostedService, RatesHostedService>();
            services.AddSingleton <IHostedService, BackgroundJobSchedulerHostedService>();
            services.AddSingleton <IHostedService, AppHubStreamer>();
            services.AddSingleton <IHostedService, DynamicDnsHostedService>();
            services.AddSingleton <IHostedService, TorServicesHostedService>();
            services.AddSingleton <IHostedService, PaymentRequestStreamer>();
            services.AddSingleton <IBackgroundJobClient, BackgroundJobClient>();
            services.AddTransient <IConfigureOptions <MvcOptions>, BTCPayClaimsFilter>();

            services.TryAddSingleton <ExplorerClientProvider>();
            services.TryAddSingleton <Bitpay>(o =>
            {
                if (o.GetRequiredService <BTCPayServerOptions>().NetworkType == NetworkType.Mainnet)
                {
                    return(new Bitpay(new Key(), new Uri("https://bitpay.com/")));
                }
                else
                {
                    return(new Bitpay(new Key(), new Uri("https://test.bitpay.com/")));
                }
            });
            services.TryAddSingleton <RateProviderFactory>();
            services.TryAddSingleton <RateFetcher>();

            services.TryAddScoped <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <AccessTokenController>();
            services.AddTransient <InvoiceController>();
            services.AddTransient <AppsPublicController>();
            services.AddTransient <PaymentRequestController>();
            // Add application services.
            services.AddSingleton <EmailSenderFactory>();
            // bundling

            services.AddAuthorization(o => Policies.AddBTCPayPolicies(o));
            services.AddBtcPayServerAuthenticationSchemes(configuration);

            services.AddSingleton <IBundleProvider, ResourceBundleProvider>();
            services.AddTransient <BundleOptions>(provider =>
            {
                var opts             = provider.GetRequiredService <BTCPayServerOptions>();
                var bundle           = new BundleOptions();
                bundle.UseBundles    = opts.BundleJsCss;
                bundle.AppendVersion = true;
                return(bundle);
            });

            services.AddCors(options =>
            {
                options.AddPolicy(CorsPolicies.All, p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            });

            var rateLimits = new RateLimitService();

            rateLimits.SetZone($"zone={ZoneLimits.Login} rate=5r/min burst=3 nodelay");
            services.AddSingleton(rateLimits);
            return(services);
        }
Пример #23
0
        public static MvcHtmlString RenderCssBundle(this HtmlHelper html, string bundlePath, BundleOptions options = BundleOptions.Minified)
        {
            if (string.IsNullOrEmpty(bundlePath))
            {
                return(MvcHtmlString.Empty);
            }

            if (!CachePaths())
            {
                BundleCache.Clear();
            }

            return(BundleCache.GetOrAdd(bundlePath, str => {
                var filePath = HttpContext.Current.Server.MapPath(bundlePath);

                var baseUrl = VirtualPathUtility.GetDirectory(bundlePath);

                if (options == BundleOptions.Combined)
                {
                    return html.Css(bundlePath.Replace(".bundle", ""), null, options);
                }
                if (options == BundleOptions.MinifiedAndCombined)
                {
                    return html.Css(bundlePath.Replace(".css.bundle", ".min.css"), null, options);
                }

                var cssFiles = File.ReadAllLines(filePath);

                var styles = new StringBuilder();
                foreach (var file in cssFiles)
                {
                    var cssFile = file.Trim().Replace(".less", ".css");
                    var cssSrc = Path.Combine(baseUrl, cssFile);

                    styles.AppendLine(
                        html.Css(cssSrc, null, options).ToString()
                        );
                }

                return styles.ToString().ToMvcHtmlString();
            }));
        }
Пример #24
0
 public static MvcHtmlString Css(this HtmlHelper html, string href, string media = null, BundleOptions options = BundleOptions.Minified)
 {
     return(media != null
            ? html.Link("stylesheet", href, new { media }, options)
            : html.Link("stylesheet", href, null, options));
 }
Пример #25
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.Name = "kpm";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);

            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return(2);
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot   = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                                         CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                                                 "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                                        CommandOptionType.SingleValue);
                var optNoCache       = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet         = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                                                CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                                                      "Ignore failed remote sources if there are local packages meeting version requirements",
                                                      CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async() =>
                {
                    var command     = new RestoreCommand(_environment);
                    command.Reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    command.RestoreDirectory    = argRoot.Value;
                    command.Sources             = optSource.Values;
                    command.FallbackSources     = optFallbackSource.Values;
                    command.NoCache             = optNoCache.HasValue();
                    command.PackageFolder       = optPackageFolder.Value();
                    command.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var success = await command.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            app.Command("bundle", c =>
            {
                c.Description = "Bundle application for deployment";

                var argProject          = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut           = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})",
                                                   CommandOptionType.SingleValue);
                var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders",
                                               CommandOptionType.NoValue);
                var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages",
                                              CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include",
                                             CommandOptionType.MultipleValue);
                var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
                                            CommandOptionType.NoValue);
                var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
                                             CommandOptionType.SingleValue);
                var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
                                                "Name of public folder in the bundle, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
                                                CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of bundled files",
                                           CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new BundleOptions
                    {
                        OutputDir              = optionOut.Value(),
                        ProjectDir             = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration          = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.RuntimeFramework,
                        WwwRoot    = optionWwwRoot.Value(),
                        WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
                        Overwrite  = optionOverwrite.HasValue(),
                        NoSource   = optionNoSource.HasValue(),
                        Runtimes   = optionRuntime.HasValue() ?
                                     string.Join(";", optionRuntime.Values).
                                     Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                                     new string[0],
                        Native  = optionNative.HasValue(),
                        Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue())
                    };

                    var manager = new BundleManager(_hostServices, options);
                    if (!manager.Bundle())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework     = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut           = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionDependencies  = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var optionQuiet         = c.Option("--quiet", "Do not show output such as source/destination of nupkgs",
                                                   CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions              = new BuildOptions();
                    buildOptions.OutputDir        = optionOut.Value();
                    buildOptions.ProjectDir       = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations   = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = true;
                    buildOptions.Reports          = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Produce assemblies for the project in given directory";

                var optionFramework     = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut           = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionQuiet         = c.Option("--quiet", "Do not show output such as dependencies in use",
                                                   CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions              = new BuildOptions();
                    buildOptions.OutputDir        = optionOut.Value();
                    buildOptions.ProjectDir       = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations   = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = false;
                    buildOptions.Reports          = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("add", c =>
            {
                c.Description = "Add a dependency into dependencies section of project.json";

                var argName    = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command        = new AddCommand();
                    command.Reports    = reports;
                    command.Name       = argName.Value;
                    command.Version    = argVersion.Value;
                    command.ProjectDir = argProject.Value;

                    var success = command.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            app.Command("install", c =>
            {
                c.Description = "Install the given dependency";

                var argName    = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version.");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optSource  = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                                          CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                                                 "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                                        CommandOptionType.SingleValue);
                var optNoCache       = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet         = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                                                CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                                                      "Ignore failed remote sources if there are local packages meeting version requirements",
                                                      CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    var addCmd        = new AddCommand();
                    addCmd.Reports    = reports;
                    addCmd.Name       = argName.Value;
                    addCmd.Version    = argVersion.Value;
                    addCmd.ProjectDir = argProject.Value;

                    var restoreCmd     = new RestoreCommand(_environment);
                    restoreCmd.Reports = reports;

                    restoreCmd.RestoreDirectory    = argProject.Value;
                    restoreCmd.Sources             = optSource.Values;
                    restoreCmd.FallbackSources     = optFallbackSource.Values;
                    restoreCmd.NoCache             = optNoCache.HasValue();
                    restoreCmd.PackageFolder       = optPackageFolder.Value();
                    restoreCmd.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var installCmd     = new InstallCommand(addCmd, restoreCmd);
                    installCmd.Reports = reports;

                    var success = await installCmd.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            app.Command("packages", packagesCommand =>
            {
                packagesCommand.Description = "Commands related to managing local and remote packages folders";
                packagesCommand.HelpOption("-?|-h|--help");
                packagesCommand.OnExecute(() =>
                {
                    packagesCommand.ShowHelp();
                    return(2);
                });

                packagesCommand.Command("add", c =>
                {
                    c.Description = "Add a NuGet package to the specified packages folder";
                    var argNupkg  = c.Argument("[nupkg]", "Path to a NuGet package");
                    var argSource = c.Argument("[source]", "Path to packages folder");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async() =>
                    {
                        var options = new AddOptions
                        {
                            Reports        = CreateReports(optionVerbose.HasValue(), quiet: false),
                            SourcePackages = argSource.Value,
                            NuGetPackage   = argNupkg.Value
                        };
                        var command = new Packages.AddCommand(options);
                        var success = await command.Execute();
                        return(success ? 0 : 1);
                    });
                });

                packagesCommand.Command("push", c =>
                {
                    c.Description = "Incremental copy of files from local packages to remote location";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                                               "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        // Implicitly commit changes before push
                        var commitOptions = new CommitOptions
                        {
                            Reports        = reports,
                            SourcePackages = argSource.Value
                        };
                        var commitCommand = new CommitCommand(commitOptions);
                        var success       = commitCommand.Execute();
                        if (!success)
                        {
                            return(1);
                        }

                        var pushOptions = new PushOptions
                        {
                            Reports        = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pushCommand = new PushCommand(pushOptions);
                        success         = pushCommand.Execute();
                        return(success ? 0 : 1);
                    });
                });

                packagesCommand.Command("pull", c =>
                {
                    c.Description = "Incremental copy of files from remote location to local packages";
                    var argRemote = c.Argument("[remote]", "Path to remote packages folder");
                    var argSource = c.Argument("[source]",
                                               "Path to source packages folder, default is current directory");
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        bool success;
                        if (Directory.Exists(argSource.Value))
                        {
                            // Implicitly commit changes before pull
                            var commitOptions = new CommitOptions
                            {
                                Reports        = reports,
                                SourcePackages = argSource.Value
                            };
                            var commitCommand = new CommitCommand(commitOptions);
                            success           = commitCommand.Execute();
                            if (!success)
                            {
                                return(1);
                            }
                        }

                        var pullOptions = new PullOptions
                        {
                            Reports        = reports,
                            SourcePackages = argSource.Value,
                            RemotePackages = argRemote.Value
                        };
                        var pullCommand = new PullCommand(pullOptions);
                        success         = pullCommand.Execute();
                        return(success ? 0 : 1);
                    });
                });
            });

            app.Command("list", c =>
            {
                c.Description      = "Print the dependencies of a given project.";
                var showAssemblies = c.Option("-a|--assemblies",
                                              "Show the assembly files that are depended on by given project.",
                                              CommandOptionType.NoValue);
                var framework = c.Option("--framework",
                                         "Show dependencies for only the given framework.",
                                         CommandOptionType.SingleValue);
                var runtimeFolder = c.Option("--runtime",
                                             "The folder containing all available framework assemblies.",
                                             CommandOptionType.SingleValue);
                var argProject = c.Argument("[project]", "The path to project. If omitted, the command will use the project in the current directory.");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject, framework)
                    {
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder  = runtimeFolder.Value(),
                    };

                    if (!options.Valid)
                    {
                        if (options.Project == null)
                        {
                            options.Reports.Error.WriteLine(string.Format("A project could not be found in {0}.", options.Path).Red());
                            return(1);
                        }
                        else
                        {
                            options.Reports.Error.WriteLine("Invalid options.".Red());
                            return(2);
                        }
                    }

                    var command = new DependencyListCommand(options);
                    return(command.Execute());
                });
            });

            // "kpm wrap" invokes MSBuild, which is not available on *nix
            if (!PlatformHelper.IsMono)
            {
                app.Command("wrap", c =>
                {
                    c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files";

                    var argPath          = c.Argument("[path]", "Path to csproj to be wrapped");
                    var optConfiguration = c.Option("--configuration <CONFIGURATION>",
                                                    "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue);
                    var optMsBuildPath = c.Option("--msbuild <PATH>",
                                                  @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'",
                                                  CommandOptionType.SingleValue);
                    var optInPlace = c.Option("-i|--in-place",
                                              "Generate or update project.json files in project directories of csprojs",
                                              CommandOptionType.NoValue);
                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                        var command           = new WrapCommand();
                        command.Reports       = reports;
                        command.CsProjectPath = argPath.Value;
                        command.Configuration = optConfiguration.Value();
                        command.MsBuildPath   = optMsBuildPath.Value();
                        command.InPlace       = optInPlace.HasValue();

                        var success = command.ExecuteCommand();

                        return(success ? 0 : 1);
                    });
                });
            }

            return(app.Execute(args));
        }
Пример #26
0
 private static string RewriteUrl(this string relativePath, BundleOptions options = BundleOptions.Normal)
 {
     return(DefaultUrlFilter(relativePath, options));
 }
Пример #27
0
 /// <summary>
 /// 停止插件
 /// </summary>
 public override void Stop(BundleOptions option)
 {
     // Nothing to do
 }