Beispiel #1
0
 /// <summary>加载组件
 /// </summary>
 /// <param name="plugin"></param>
 public static void LoadPlugin(PluginEntity plugin)
 {
     lock (_Plugins)
     {
         if (!_Plugins.Exists(p => p.Id == plugin.Id))
         {
             string webPath = _ApplicationBase + plugin.Name + "\\" + plugin.PVersion + "\\";
             string appPath = webPath + "bin\\";
             try
             {
                 System.IO.File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\bin\\Huber.SandBonDriver.dll", appPath + "Huber.SandBonDriver.dll", true);
                 System.IO.File.Copy(AppDomain.CurrentDomain.BaseDirectory + "Huber.Kernel.dll", appPath + "Huber.Kernel.dll", true);
             }
             catch (Exception)
             {
             }
             var loader = new SandBoxDynamicLoader(
                 appPath,
                 string.Format(_AppdomainName, plugin.Name, plugin.PVersion.ToString()),
                 webPath + "Web.config",
                 plugin.Id);
             loader.LoadAssembly(appPath + plugin.Name + ".dll");
             _LoaderDic.Add(loader.PluginName, loader);
             _Plugins.Add(plugin);
             AddUrls(loader);
             loader.InvokeMothod("Huber.Kernel.Entity.HuberVariable", "SetCurWebDir", webPath, "/Plugins/" + plugin.Name + "/" + plugin.PVersion);
         }
     }
 }
Beispiel #2
0
        /// <summary>添加插件(不启动)
        /// </summary>
        public int AddPlugin(PluginEntity pluginDescriptor)
        {
            const string sql    = "insert into t_plugin (Name,Describe,Author,DefaultController,DefaultAction,PVersion,MenuShow,Icon) values (@Name,@Describe,@Author,@DefaultController,@DefaultAction,@PVersion,@MenuShow,@Icon)";
            int          result = 0;

            SQLiteParameter[] para = new SQLiteParameter[]
            {
                new SQLiteParameter("@Name", pluginDescriptor.Name),
                new SQLiteParameter("@Describe", pluginDescriptor.Describe),
                new SQLiteParameter("@Author", pluginDescriptor.Author),
                new SQLiteParameter("@DefaultController", pluginDescriptor.DefaultController),
                new SQLiteParameter("@DefaultAction", pluginDescriptor.DefaultAction),
                new SQLiteParameter("@PVersion", pluginDescriptor.PVersion),
                new SQLiteParameter("@MenuShow", pluginDescriptor.MenuShow),
                new SQLiteParameter("@Icon", pluginDescriptor.Icon)
            };
            try
            {
                result = new SqlLiteHelper().RunSQL(sql, para);
            }
            catch (Exception ex)
            {
            }
            return(result);
        }
Beispiel #3
0
        /// <summary>添加模块
        /// </summary>
        /// <param name="pluginEntity"></param>
        /// <returns></returns>
        public string AddModule(PluginEntity pluginEntity)
        {
            if (Request.Files.Count < 1)
            {
                return("0");
            }
            HttpPostedFileBase fileBase = Request.Files[0];

            if (fileBase == null || !fileBase.FileName.EndsWith(".zip"))
            {
                return("0");
            }
            pluginEntity.Icon              = "fa fa-files-o";
            pluginEntity.DefaultAction     = string.Empty;
            pluginEntity.DefaultController = string.Empty;
            PluginEntity result = _PluginBll.AddPlugin(pluginEntity);

            if (result != null)
            {
                saveZip(fileBase, result);
                UnZipFile(pluginEntity, fileBase.InputStream);
                return("1");
            }
            return("-2");
        }
Beispiel #4
0
        private MenuEntity GetMenu(RightEntity rightEntity, PluginEntity pluginEntity)
        {
            string startWith = "/" + pluginEntity.Name + "/";
            string replace   = "/" + pluginEntity.Name + "/" + pluginEntity.PVersion + "/";

            MenuEntity mm = new MenuEntity(rightEntity.Id, rightEntity.Name, "/plugins" + rightEntity.Url.Replace(startWith, replace), false, pluginEntity.Icon);

            foreach (var item in rightEntity.Children)
            {
                mm.Children.Add(GetMenu(item, pluginEntity));
            }
            return(mm);
        }
Beispiel #5
0
        /// <summary>停用插件
        /// </summary>
        /// <param name="id"></param>
        public bool DisablePlugin(int id)
        {
            int result = PluginDao.SetPlugin(id, 0);

            if (result > 0)
            {
                PluginEntity pluginEntity = PluginDao.GetPlugin(id);
                if (pluginEntity != null)
                {
                    HuberPluginHandle.UnLoadPlugin(pluginEntity);
                }
            }
            return(result > 0);
        }
Beispiel #6
0
        /// <summary>将row转换为实体类
        /// </summary>
        /// <param name="dataRow"></param>
        /// <returns></returns>
        private static PluginEntity Convert2Entity(DataRow dataRow)
        {
            PluginEntity pluginEntity = new PluginEntity();

            pluginEntity.Id                = Int32.Parse(dataRow["Id"].ToString());
            pluginEntity.Name              = dataRow["Name"].ToString();
            pluginEntity.Status            = Int32.Parse(dataRow["Status"].ToString());
            pluginEntity.Describe          = dataRow["Describe"].ToString();
            pluginEntity.DefaultAction     = dataRow["DefaultAction"].ToString();
            pluginEntity.DefaultController = dataRow["DefaultController"].ToString();
            pluginEntity.Author            = dataRow["Author"].ToString();
            pluginEntity.PVersion          = int.Parse(dataRow["PVersion"].ToString());
            pluginEntity.MenuShow          = int.Parse(dataRow["MenuShow"].ToString());
            pluginEntity.Icon              = dataRow["Icon"].ToString();
            return(pluginEntity);
        }
Beispiel #7
0
        private static void saveZip(HttpPostedFileBase fileBase, PluginEntity pluginEntity)
        {
            string dirName = AppDomain.CurrentDomain.BaseDirectory + "Plugins\\Plugin_updates_temp\\";
            string zipName = dirName + pluginEntity.Name + "." + pluginEntity.PVersion + ".zip";

            if (!Directory.Exists(dirName))
            {
                lock (_PluginBll)
                {
                    if (!Directory.Exists(dirName))
                    {
                        Directory.CreateDirectory(dirName);
                    }
                }
            }

            fileBase.SaveAs(zipName);//保存文件
        }
Beispiel #8
0
 /// <summary>添加插件,暂不启用
 /// </summary>
 /// <param name="pluginEntity"></param>
 /// <returns>如果该插件已存在则返回null</returns>
 public PluginEntity AddPlugin(PluginEntity pluginEntity)
 {
     lock (PluginDao)
     {
         int result = 0;
         if (!PluginDao.ExsitPlugin(pluginEntity.Name, pluginEntity.PVersion))
         {
             pluginEntity.MenuShow          = 0;
             pluginEntity.Status            = 0;
             pluginEntity.DefaultAction     = string.Empty;
             pluginEntity.DefaultController = string.Empty;
             result = PluginDao.AddPlugin(pluginEntity);
             if (result > 0)
             {
                 pluginEntity.Id = PluginDao.GetMaxID();
                 return(pluginEntity);
             }
         }
         return(null);
     }
 }
        public async Task <PluginEntity> CreatePluginAsync(CreatePluginRequest request, int userId)
        {
            var pluginEntity = new PluginEntity
            {
                Guid                = request.Guid,
                Name                = request.Name,
                Description         = request.Description,
                MarkdownDescription = request.MarkdownDescription,
                StarCount           = 0,
                CreatorUserId       = userId,
                ServerDistroId      = request.ServerDistroId,
                ImageUrl            = request.ImageUrl,
                CreatedAt           = DateTimeOffset.UtcNow,
                UpdatedAt           = DateTimeOffset.UtcNow
            };
            await _database.Plugins.AddAsync(pluginEntity);

            await _database.SaveChangesAsync();

            return(pluginEntity);
        }
Beispiel #10
0
        /// <summary>解压
        /// </summary>
        /// <param name="zipName"></param>
        /// <param name="baseStream"></param>
        private static void UnZipFile(PluginEntity pluginEntity, Stream baseStream)
        {
            using (ZipInputStream s = new ZipInputStream(baseStream))
            {
                string   baseDir = AppDomain.CurrentDomain.BaseDirectory + "Plugins\\" + pluginEntity.Name + "\\" + pluginEntity.PVersion + "\\";
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = baseDir + Path.GetDirectoryName(theEntry.Name) + "\\";
                    string fileName      = Path.GetFileName(theEntry.Name);

                    // create directory
                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = System.IO.File.Create(directoryName + fileName))
                        {
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                var size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #11
0
        /// <summary>启动插件
        /// </summary>
        /// <param name="plugipEntity"></param>
        public void StartPlugins(PluginEntity plugipEntity)
        {
            //PluginDescriptor pluginDescriptor = PluginLoader.Load(plugipEntity);
            //if (pluginDescriptor == null)
            //{
            //    return;
            //}
            //Type[] types = pluginDescriptor.PluginAssembly.GetTypes();
            ////继承的MVC控制器版本必须是程序集 System.Web.Mvc.dll, v4.0.0.0
            //pluginDescriptor.ControllerTypes = types.Where(t => typeof(IController).IsAssignableFrom(t) && t.Name.EndsWith("Controller")).ToArray();

            //RouteValueDictionary routeValueDictionary = new RouteValueDictionary
            //{
            //    {"controller", plugipEntity.DefaultController},
            //    {"action", plugipEntity.DefaultAction},
            //    {"id", UrlParameter.Optional},
            //    {"pluginName", plugipEntity.Name}
            //};
            //Route route = new Route("plugins" + "/" + pluginDescriptor.Plugin.Name + "/{controller}/{action}/{id}", routeValueDictionary, new MvcRouteHandler(ControllerBuilder.Current.GetControllerFactory()));
            //RouteTable.Routes.Insert(0, route);
            //PluginDescriptorlist.Add(pluginDescriptor);
        }
Beispiel #12
0
 /// <summary>卸载组件
 /// </summary>
 /// <param name="plugin"></param>
 public static void UnLoadPlugin(PluginEntity plugin)
 {
     lock (_Plugins)
     {
         if (_Plugins.Exists(p => p.Id == plugin.Id))
         {
             var loader = getSandBox(plugin.Name, plugin.PVersion);
             loader.Unload();
             _LoaderDic.Remove(loader.PluginName);
             var plist = _Plugins.Where(p => p.Id == plugin.Id);
             if (plist.Any())
             {
                 var pplist = plist.ToList();
                 for (int i = 0; i < pplist.Count; i++)
                 {
                     _Plugins.Remove(pplist[i]);
                     break;
                 }
             }
         }
     }
 }
Beispiel #13
0
        /// <summary>升级模块
        /// </summary>
        /// <param name="pluginId"></param>
        /// <returns></returns>
        public string UpdateModule(int pluginId)
        {
            if (Request.Files.Count < 1)
            {
                return("0");
            }
            HttpPostedFileBase fileBase = Request.Files[0];

            if (fileBase == null || !fileBase.FileName.EndsWith(".zip"))
            {
                return("0");
            }
            PluginEntity pluginEntity = _PluginBll.UpdatePlugin(pluginId);

            if (pluginEntity != null)
            {
                saveZip(fileBase, pluginEntity);
                UnZipFile(pluginEntity, fileBase.InputStream);
                return("1");
            }

            return("-2");
        }
Beispiel #14
0
        public static void LoadPlugin(this IServiceCollection services)
        {
            var pluginDir = Path.Combine(_baseDir, "Plugins");

            if (!Directory.Exists(pluginDir))
            {
                return;
            }
            Console.ForegroundColor = ConsoleColor.Green;
            IList <PluginEntity> plugins = new List <PluginEntity>();

            foreach (string dll in Directory.GetFiles(pluginDir, "*.dll"))
            {
                try
                {
                    var assemb   = AssemblyLoadContext.Default.LoadFromAssemblyPath(dll);
                    var types    = assemb.GetTypes();
                    var query    = from t in types where t.IsClass && t.BaseType.Name == "WebApiController" select t;
                    var type     = query.ToList().First();
                    var obj      = Activator.CreateInstance(type);
                    var priority = type.GetProperty("Priority").GetValue(obj);
                    var name     = type.GetProperty("Name").GetValue(obj);
                    var id       = type.GetProperty("Id").GetValue(obj);
                    var isRpc    = type.GetProperty("IsRegisterRpc").GetValue(obj);
                    var isAuth   = type.GetProperty("IsAuth").GetValue(obj);
                    var plugin   = new PluginEntity {
                        Name     = (string)name,
                        Id       = (string)id,
                        Priority = (int)priority,
                        Assembly = assemb,
                        IsAuth   = (bool)isAuth
                    };
                    plugins.Add(plugin);
                    if ((bool)isRpc)
                    {
                        var contract = type.GetInterfaces().First().FullName;
                        MqRpcHelper.RegisterRpcServer(contract, (r) => {
                            var c        = r.Content;
                            MethodInfo m = type.GetMethod(c.Method);
                            if (m != null)
                            {
                                return(m.Invoke(obj, c.Params));
                            }
                            return(DResult.Error("Rpc服务中心没有找到该方法!"));
                        });

                        Console.WriteLine($"【{plugin.Priority}】{plugin.Name}插件({plugin.Id})rpc注册成功!");
                    }
                }
                catch (Exception ex) {
                    //Console.WriteLine(ex.Message);
                }
            }
            var sort = from k in plugins orderby k.Priority ascending select k;

            foreach (var k in sort)
            {
                services.AddMvcCore().AddApplicationPart(k.Assembly);
                Console.WriteLine($"【{k.Priority}】{k.Name}插件({k.Id})加载成功!");
                if (k.IsAuth)
                {
                    Console.WriteLine($"【{k.Priority}】{k.Name}插件({k.Id})开启token验证!");
                }
            }
            Console.ResetColor();
        }
Beispiel #15
0
 public void AddPlugin(PluginEntity pluginEntity)
 {
     _repository.Insert(pluginEntity);
 }
Beispiel #16
0
        public void LoadPlugin(PluginInfo pluginInfo)
        {
            lock (_plugins)
            {
                _logger.Debug("Loading plugin {pluginInfo}", pluginInfo);
                OnPluginLoading(new PluginEventArgs(pluginInfo));

                // Unload the plugin first if it is already loaded
                if (_plugins.Contains(pluginInfo))
                {
                    UnloadPlugin(pluginInfo);
                }

                PluginEntity pluginEntity = _pluginRepository.GetPluginByGuid(pluginInfo.Guid);
                if (pluginEntity == null)
                {
                    pluginEntity = new PluginEntity {
                        Id = pluginInfo.Guid, IsEnabled = true
                    }
                }
                ;

                pluginInfo.PluginEntity = pluginEntity;
                pluginInfo.Enabled      = pluginEntity.IsEnabled;

                string mainFile = Path.Combine(pluginInfo.Directory.FullName, pluginInfo.Main);
                if (!File.Exists(mainFile))
                {
                    throw new ArtemisPluginException(pluginInfo, "Couldn't find the plugins main entry at " + mainFile);
                }

                // Load the plugin, all types implementing Plugin and register them with DI
                pluginInfo.PluginLoader = PluginLoader.CreateFromAssemblyFile(mainFile, configure =>
                {
                    configure.IsUnloadable      = true;
                    configure.PreferSharedTypes = true;
                });

                try
                {
                    pluginInfo.Assembly = pluginInfo.PluginLoader.LoadDefaultAssembly();
                }
                catch (Exception e)
                {
                    throw new ArtemisPluginException(pluginInfo, "Failed to load the plugins assembly", e);
                }

                // Get the Plugin implementation from the main assembly and if there is only one, instantiate it
                List <Type> pluginTypes;
                try
                {
                    pluginTypes = pluginInfo.Assembly.GetTypes().Where(t => typeof(Plugin).IsAssignableFrom(t)).ToList();
                }
                catch (ReflectionTypeLoadException e)
                {
                    throw new ArtemisPluginException(pluginInfo, "Failed to initialize the plugin assembly", new AggregateException(e.LoaderExceptions));
                }

                if (pluginTypes.Count > 1)
                {
                    throw new ArtemisPluginException(pluginInfo, $"Plugin contains {pluginTypes.Count} implementations of Plugin, only 1 allowed");
                }
                if (pluginTypes.Count == 0)
                {
                    throw new ArtemisPluginException(pluginInfo, "Plugin contains no implementation of Plugin");
                }

                Type pluginType = pluginTypes.Single();
                try
                {
                    IParameter[] parameters = new IParameter[]
                    {
                        new Parameter("PluginInfo", pluginInfo, false)
                    };
                    pluginInfo.Kernel = new ChildKernel(_kernel);
                    pluginInfo.Kernel.Load(new PluginModule(pluginInfo));
                    pluginInfo.Instance            = (Plugin)pluginInfo.Kernel.Get(pluginType, constraint: null, parameters: parameters);
                    pluginInfo.Instance.PluginInfo = pluginInfo;
                }
                catch (Exception e)
                {
                    throw new ArtemisPluginException(pluginInfo, "Failed to instantiate the plugin", e);
                }

                _plugins.Add(pluginInfo);
                OnPluginLoaded(new PluginEventArgs(pluginInfo));
            }
        }
Beispiel #17
0
 public void SavePlugin(PluginEntity pluginEntity)
 {
     _repository.Upsert(pluginEntity);
     _repository.Database.Checkpoint();
 }
        public static void LoadPlugin(this IServiceCollection services)
        {
            var pluginDir = Path.Combine(_baseDir, "Plugins");

            if (!Directory.Exists(pluginDir))
            {
                return;
            }
            Console.ForegroundColor = ConsoleColor.Green;
            IList <PluginEntity> plugins = new List <PluginEntity>();
            var dlls = Directory.GetFiles(pluginDir, "*.dll");

            foreach (string dll in dlls)
            {
                Type type = null;
                try
                {
                    var assemb = AssemblyLoadContext.Default.LoadFromAssemblyPath(dll);
                    var types  = assemb.GetTypes();
                    var query  = from t in types where t.IsClass &&
                                 (t.BaseType == typeof(WebApiController) || t.BaseType == typeof(NoControllerBase)) select t;
                    type = query.ToList().First();
                    PluginEntity plugin = null;
                    if (type == null)
                    {
                        continue;
                    }
                    else
                    {
                        var  obj      = Activator.CreateInstance(type);
                        var  priority = type.GetProperty("Priority").GetValue(obj);
                        var  name     = type.GetProperty("Name").GetValue(obj);
                        var  id       = type.GetProperty("Id").GetValue(obj);
                        bool isAuth   = false;
                        if (type.BaseType == typeof(WebApiController))
                        {
                            isAuth = (bool)type.GetProperty("IsAuth").GetValue(obj);
                        }
                        plugin = new PluginEntity
                        {
                            Name     = (string)name,
                            Id       = (string)id,
                            Priority = (int)priority,
                            Assembly = assemb,
                            IsAuth   = isAuth,
                            Type     = type,
                            Obj      = obj
                        };
                    }
                    plugins.Add(plugin);
                }
                catch (Exception ex) {
                    Console.ResetColor();
                    Console.WriteLine(type?.FullName + ex.ToString());
                    Console.ForegroundColor = ConsoleColor.Green;
                }
            }
            var sort = from k in plugins orderby k.Priority ascending select k;

            foreach (var k in sort)
            {
                if (k.Type.BaseType == typeof(WebApiController))
                {
                    services.AddMvcCore().AddApplicationPart(k.Assembly);
                    MethodInfo m1 = k.Type.GetMethod("Config");
                    m1.Invoke(k.Obj, new object[] { });
                }
                Console.WriteLine($"【{k.Priority}】{k.Name}插件({k.Id})加载成功!");
                if (k.IsAuth)
                {
                    Console.WriteLine($"【{k.Priority}】{k.Name}插件({k.Id})开启token验证!");
                }
                var interfaces = k.Type.GetInterfaces();
                if (interfaces == null || interfaces.ToList().Count == 0)
                {
                    continue;
                }
                var contract = (from t in interfaces where t.GetInterface("RpcApi") != null select t.FullName).FirstOrDefault();
                if (contract == null)
                {
                    continue;
                }
                MqRpcHelper.RegisterRpcServer(contract, (r) =>
                {
                    var c        = r.Content;
                    MethodInfo m = k.Type.GetMethod(c.Method);
                    if (m != null)
                    {
                        return(m.Invoke(k.Obj, c.Params));
                    }
                    return(DResult.Error("Rpc服务中心没有找到该方法!"));
                });

                Console.WriteLine($"【{k.Priority}】{k.Name}插件({k.Id})rpc注册成功!");
            }
            Console.ResetColor();
        }