예제 #1
0
        void Start()
        {
            try
            {
                if (!Directory.Exists(DefaultPath))
                {
                    Directory.CreateDirectory(DefaultPath);
                }
                if (!Directory.Exists(LoggingPath))
                {
                    Directory.CreateDirectory(LoggingPath);
                }
                if (!Directory.Exists(PluginPath))
                {
                    Directory.CreateDirectory(PluginPath);
                }

                ExtensionLoader.Load();

                DataStore.GetInstance().Save();
                PluginCollector.GetCollector();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(string.Format("[Error] Failed to load Redox, Error: {0}", ex));
            }
        }
예제 #2
0
 public void UnloadPlugin(string name, PluginContainer pc = null)
 {
     if (Plugins.TryGetValue(name, out CSPlugin plugin))
     {
         PluginCollector.GetCollector().GetContainer(name).Disable();
         Plugins.Remove(name);
         logger.LogInfo("[CSharp] Succesfully unloaded plugin " + plugin.Title);
     }
 }
예제 #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
            var pt = new PluginTable();

            services.AddSingleton <PluginTable>(pt);
            services.AddSingleton <PluginServiceCollection>();
            var plugin = new PluginCollector(pt);
        }
예제 #4
0
        public void CheckCalcOfYValuesOfDataPoints()
        {
            PluginCollector           coll  = new PluginCollector();
            MonitoringPluginPageModel model = new MonitoringPluginPageModel(coll);

            model.BloodSugarDataPoints.Add(new ChartDataPoint(new DateTime(2016, 6, 12, 10, 0, 0), 50));
            model.BloodSugarDataPoints.Add(new ChartDataPoint(new DateTime(2016, 6, 12, 14, 0, 0), 150));
            //model.BloodSugarDataPoints.Add(new ChartDataPoint(new DateTime(2016, 6, 12, 10, 0, 0), 50));

            var result1 = model.calcDataPointsYValue(new ChartDataPoint(new DateTime(2016, 6, 12, 11, 0, 0), 0));
            var result2 = model.calcDataPointsYValue(new ChartDataPoint(new DateTime(2016, 6, 12, 12, 0, 0), 0));
            var result3 = model.calcDataPointsYValue(new ChartDataPoint(new DateTime(2016, 6, 12, 13, 0, 0), 0));


            Assert.True(result1 == 75 && result2 == 100 && result3 == 125);
        }
예제 #5
0
        public static void LoadPlugin(string dir)
        {
            FileInfo info = null;

            try
            {
                foreach (var file in Directory.GetFiles(dir, Expression))
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    info = new FileInfo(file);
                    string   name = info.Name.Replace(".dll", string.Empty);
                    Assembly assembly;

                    if (!Plugins.TryGetValue(name, out assembly))
                    {
                        assembly = Assembly.Load(File.ReadAllBytes(file));
                        Plugins.Add(name, assembly);
                    }
                    foreach (Type type in assembly.GetExportedTypes())
                    {
                        if (type.IsSubclassOf(typeof(RedoxPlugin)) && type.IsPublic && !type.IsAbstract)
                        {
                            object          instance  = Activator.CreateInstance(type);
                            RedoxPlugin     plugin    = (RedoxPlugin)instance;
                            PluginContainer container = new PluginContainer(plugin, instance);
                            PluginCollector.GetCollector().AddPlugin(container);

                            container.Plugin.Path = Path.GetDirectoryName(info.Directory.FullName);

                            logger.LogInfo(string.Format("[Redox] Succesfully loaded plugin {0}, {1}, Author {2} ({3}", plugin.Title, plugin.Version, plugin.Author, plugin.Description));
                        }
                    }
                    sw.Stop();
                    int time = sw.Elapsed.Milliseconds;

                    if (time > 500)
                    {
                        logger.LogSpeed(string.Format("[Redox] Plugin {0} took {1} milliseconds to load", name, time));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("An exception has thrown while trying to load plugin {0}, Error: {1}", info.FullName, ex));
            }
        }
예제 #6
0
 public static void StartAll()
 {
     foreach (var engine in _engines)
     {
         var instance = (IPluginEngine)Activator.CreateInstance(engine);
         if (!_instances.Contains(instance))
         {
             Logger.LogInfo(string.Format("[Redox] Loading {0} Engine..", instance.Language));
             _instances.Add(instance);
             instance.LoadPlugins();
         }
         else
         {
             Logger.LogWarning(string.Format("[Redox] Skipping engine {0} because its already loaded!", engine.Name));
         }
     }
     Logger.LogInfo($"[Redox] Succesfully loaded {PluginCollector.GetCollector().GetPlugins().Count} Plugins");
 }
예제 #7
0
        public void CheckAddBloodSugarDataPoint()
        {
            PluginCollector           coll  = new PluginCollector();
            MonitoringPluginPageModel model = new MonitoringPluginPageModel(coll);

            model.AddDatapoints(DataPoints.BloodSugar);

            AddBloodSugarPageModel bmodel = new AddBloodSugarPageModel(coll);

            bmodel.BloodSugarValue = 40;
            DateTime tmpDate = DateTime.Now;

            bmodel.Date = tmpDate;
            var x = bmodel.AddDataPoint;

            model.LoadData();
            ChartDataPoint bsPoint = (from ChartDataPoint poi in model.BloodSugarDataPoints where (DateTime)poi.XValue == tmpDate select poi).ToList().FirstOrDefault();

            Assert.True((DateTime)bsPoint.XValue == tmpDate);
        }
예제 #8
0
        public static void LoadPlugin(string dir)
        {
            foreach (var file in Directory.GetFiles(dir, Expression))
            {
                FileInfo info = new FileInfo(file);
                string   name = info.Name.Replace(".dll", string.Empty);
                Assembly assembly;

                if (!Plugins.TryGetValue(name, out assembly))
                {
                    assembly = Assembly.Load(File.ReadAllBytes(file));
                    Plugins.Add(name, assembly);
                }

                if (ValidPlugin(assembly))
                {
                    foreach (Type type in assembly.GetExportedTypes())
                    {
                        if (type.IsSubclassOf(typeof(RedoxPlugin)) && type.IsPublic && !type.IsAbstract)
                        {
                            RedoxPlugin     plugin    = (RedoxPlugin)Activator.CreateInstance(type);
                            PluginContainer container = new PluginContainer(plugin);

                            PluginCollector.GetCollector().AddPlugin(container);

                            foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                            {
                                container.Methods.Add(method.Name, method);
                            }

                            Debug.Log(string.Format("[Redox] Succesfully loaded plugin {0}, {1}, {2} ({3})", plugin.Title, plugin.Author, plugin.Version, plugin.Description));
                        }
                    }
                }
                else
                {
                    Debug.LogWarning(string.Format("[Redox] Denied plugin {0} because of forbidden references", assembly.FullName));
                }
            }
        }
예제 #9
0
        private static int Plugins(PluginsOptions pluginsOptions)
        {
            var action = pluginsOptions.Action.ToLower();

            if (action == "list")
            {
                using (var collector = new PluginCollector())
                {
                    _logger.Info($"Plugins found: { collector.Plugins.Count }");

                    foreach (var plugin in collector.Plugins)
                    {
                        _logger.Info($"- { plugin.Name } v.{ plugin.Version }: { plugin.Description }");
                    }
                }
            }
            else if (action == "help")
            {
                using (var collector = new PluginCollector())
                {
                    var plugin = collector.Plugins.SingleOrDefault((p) => p.Name.Equals(pluginsOptions.PluginName, StringComparison.InvariantCultureIgnoreCase));
                    if (plugin != null)
                    {
                        plugin.Initialize(_logger.Factory);

                        _logger.Info($"{ plugin.Name } v.{ plugin.Version }");
                        _logger.Info($"by { plugin.Author }");
                        _logger.Info(plugin.Description);
                        _logger.Info(plugin.Help);

                        plugin.Shutdown();
                    }
                }
            }

            return(0);
        }
예제 #10
0
        public void LoadPlugin(string dir)
        {
            FileInfo info = null;

            foreach (var file in Directory.GetFiles(dir, Pattern))
            {
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    info = new FileInfo(file);
                    string name = Path.GetFileNameWithoutExtension(info.Name);
                    if (Plugins.TryGetValue(name, out CSPlugin p))
                    {
                        if (p.Container.Running)
                        {
                            logger.LogWarning(string.Format("[CSharp] Failed to load {0} because its already initialized", p.Title));
                            break;
                        }
                        logger.LogInfo(string.Format("[CSharp] Succesfully loaded plugin {0}, {1}, Author {2} ({3})", p.Title, p.Version, p.Author, p.Description));
                        p.Container.Start();
                        break;
                    }
                    if (!Assemblies.TryGetValue(name, out Assembly assembly))
                    {
                        assembly = Assembly.Load(File.ReadAllBytes(file));
                        Assemblies.Add(name, assembly);
                    }


                    if (this.IsSecure(assembly, out ViolationType violationType))
                    {
                        foreach (Type type in assembly.GetExportedTypes())
                        {
                            if (type.IsSubclassOf(typeof(CSPlugin)) && type.IsPublic && !type.IsAbstract)
                            {
                                object   instance = Activator.CreateInstance(type);
                                CSPlugin plugin   = (CSPlugin)instance;

                                if (name != plugin.Title)
                                {
                                    logger.LogWarning($"[CSharp] Failed to load plugin {plugin.Title} because the file name is not the same as the title");
                                    return;
                                }
                                if (((plugin.CoreVersion.ToString() == "0.0.0.0") || (plugin.CoreVersion >= Redox.Version)) || Bootstrap.RedoxMod.Config.LoadIncompitablePlugins)
                                {
                                    plugin.FileInfo = info;
                                    PluginContainer container = new PluginContainer(plugin, instance, Language);
                                    PluginCollector.GetCollector().AddPlugin(container);
                                    Plugins.Add(plugin.Title, plugin);
                                    logger.LogInfo(string.Format("[CSharp] Succesfully loaded plugin {0}, {1}, Author {2} ({3})", plugin.Title, plugin.Version, plugin.Author, plugin.Description));
                                }
                                else
                                {
                                    logger.LogWarning($"[Redox] Plugin \"{plugin.Title}\" is not compitable with the current redox version!");
                                }
                            }
                        }
                        sw.Stop();
                        int time = sw.Elapsed.Milliseconds;

                        if (time > 500)
                        {
                            logger.LogSpeed(string.Format("[CSharp] Plugin {0} took {1} milliseconds to load", name, time));
                        }
                    }
                    else
                    {
                        logger.LogWarning(string.Format("[CSharp] {0} has been blocked due security violation: {1}", assembly.GetName().Name, violationType));
                    }
                }


                catch (Exception ex)
                {
                    logger.LogError(string.Format("[CSharp] Failed to load {0}, Error: {1}", info.Name, ex));
                }
            }
        }
예제 #11
0
        /// <summary>
        /// Syntax $$Run-Plugin::PluginName['arg1', 'arg2', 'argN']
        /// </summary>
        public static JObject ResolvePluginExpressions(this JObject json, ref int warnings)
        {
            var expressionRegex = new Regex(@"(?<expression>\$\$Run-Plugin::(?<name>[^\[]*)\[(?<arguments>[^\]]*)\])", RegexOptions.Compiled);

            var pluginExpressions = expressionRegex.Matches(json.ToString()).Cast <Match>()
                                    .Select((m) => new
            {
                Expression = m.Groups["expression"].Value,
                Name       = m.Groups["name"].Value,
                Arguments  = Regex.Unescape(m.Groups["arguments"].Value)
                             .Split(',') // do not use StringSplitOptions.RemoveEmptyEntries
                             .Select((a) => a.Trim(new[] { ' ', '\'' }))
                             .ToArray()
            })
                                    .Distinct()
                                    .ToList();

            #region Print debug expressions

            _logger.Debug($"Plugin expressions found '{ pluginExpressions.Count }'");

            foreach (var plugin in pluginExpressions)
            {
                _logger.Debug($"\tExpression '{ plugin.Expression }'");
                _logger.Debug($"\t\tPlugin '{ plugin.Name }'");

                foreach (var argument in plugin.Arguments)
                {
                    _logger.Debug($"\t\tArgument '{ argument }'");
                }
            }

            #endregion

            _logger.Info("Collecting plugins");

            using (var collector = new PluginCollector())
            {
                _logger.Info($"Plugins found '{ collector.Plugins.Count }'");

                foreach (var plugin in collector.Plugins)
                {
                    _logger.Debug($"\tPlugin '{ plugin.Name }' - '{ plugin.Version }' - '{ plugin.Description }'");
                }

                string resolvedJson = json.ToString();

                foreach (var expression in pluginExpressions)
                {
                    var plugin = collector.Plugins.SingleOrDefault((p) => p.Name.Equals(expression.Name, StringComparison.InvariantCultureIgnoreCase));
                    if (plugin == null)
                    {
                        _logger.Warn($"Plugin not found for expression '{ expression.Expression }'");
                        warnings++;
                        continue;
                    }

                    dynamic pluginResult;

                    #region Execute plugin

                    _logger.Info($"Executing plugin '{ plugin.Name }' - '{ plugin.Version }' - '{ plugin.Description }'");

                    plugin.Initialize(_logger.Factory);
                    try
                    {
                        if (plugin is IMetadataCompilerPlugin)
                        {
                            pluginResult = (plugin as IMetadataCompilerPlugin).Compile(expression.Arguments);
                        }

                        /*
                         * else if (plugin is I<MyCustom>CompilerPlugin)
                         * {
                         *      pluginResult = (plugin as I<MyCustom>CompilerPlugin).Compile(expression.Arguments);
                         * }
                         */
                        else
                        {
                            throw new ApplicationException($"Invalid plugin type in expression '{ expression.Expression }'");
                        }
                    }
                    finally
                    {
                        plugin.Shutdown();
                    }

                    #endregion

                    _logger.Debug($"Resolved plugin expression type is '{ pluginResult.Get‌​Type() }' => '{ pluginResult }'");

                    var replaceExpression = expression.Expression;
                    // Add beginning and trailing quotes, since we're replacing a json value fragment with raw string json object.
                    if (!(pluginResult is JValue))
                    {
                        replaceExpression = "\"" + expression.Expression + "\"";
                    }

                    resolvedJson = resolvedJson.Replace(replaceExpression, pluginResult.ToString());
                }

                _logger.Info("Parsing resolved plugin metadata");
                _logger.Debug(resolvedJson);

                return(JObject.Parse(resolvedJson));
            }
        }
예제 #12
0
        public async void Initialize()
        {
            try
            {
                if (!string.IsNullOrEmpty(CustomPath))
                {
                    RootPath = CustomPath;
                }
                else
                {
                    RootPath = Directory.GetCurrentDirectory() + "\\Redox\\";
                }

                PluginPath     = Path.Combine(RootPath, "Plugins\\");
                ExtensionPath  = Path.Combine(RootPath, "Extensions\\");
                DependencyPath = Path.Combine(RootPath, "Dependencies\\");
                DataPath       = Path.Combine(RootPath, "Data\\");
                LoggingPath    = Path.Combine(RootPath, "Logs\\");
                AssemblePath   = Path.GetDirectoryName(assembly.Location);



                if (!Directory.Exists(RootPath))
                {
                    Directory.CreateDirectory(RootPath);
                }
                if (!Directory.Exists(LoggingPath))
                {
                    Directory.CreateDirectory(LoggingPath);
                }
                if (!Directory.Exists(ExtensionPath))
                {
                    Directory.CreateDirectory(ExtensionPath);
                }
                if (!Directory.Exists(DependencyPath))
                {
                    Directory.CreateDirectory(DependencyPath);
                }
                if (!Directory.Exists(PluginPath))
                {
                    Directory.CreateDirectory(PluginPath);
                }
                if (!Directory.Exists(DataPath))
                {
                    Directory.CreateDirectory(DataPath);
                }

                Config = new RedoxConfig();
                string path = Path.Combine(RootPath, "Redox.json");
                if (File.Exists(path))
                {
                    Config = Utility.Json.FromFile <RedoxConfig>(path);
                }
                else
                {
                    Utility.Json.ToFile(path, Config.Init());
                }

                this.EnableCertificates();
                this.LoadDependencies();
                ExtensionLoader.Load();
                this.Container = ContainerConfig.Configure();
                this.BuildContainer();
                Logger = Container.Resolve <ILogger>();
                Logger.LogInfo("[Redox] Initializing RedoxMod..");
                PluginEngineManager.Register <CSPluginEngine>();
                Logger.LogInfo("[Redox] Loading data...");

                await PermissionManager.LoadAsync();

                await GroupManager.LoadAsync();

                await RoleManager.LoadAsync();

                await RoleManager.CreateRoleAsync(new Role("default", "default role", 0, false));

                await GroupManager.CreateGroupAsync(new Group("default", "default group for players.", "default", 0, true, false));

                await RoleManager.AddGroupAsync("default", "default");

                Logger.LogInfo("[Redox] Loading standard library..");
                LocalStorage.Load();
                PluginCollector.GetCollector();
                Logger.LogInfo($"[Redox] RedoxMod V{Version} has been initialized.");
            }
            catch (Exception ex)
            {
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(string.Format("[Error] Failed to load Redox, Error: {0}", ex));
            }
            LifeTimeWatch   = Stopwatch.StartNew();
            WebRequestTimer = Timers.Create(5, TimerType.Repeat, WebRequestUpdate);
        }