/// <summary>
        /// Convienance method for logging and printing errors and warnings found in a <see cref="ValidationResult" />.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="validationResult"></param>
        public static void LogPrint(this TerrariaPlugin plugin, ValidationResult validationResult)
        {
            var traceLevel = TraceLevel.Info;
            var endPart    = ".";
            int warnings   = 0;
            int errors     = 0;

            validationResult.GetTotals(ref errors, ref warnings);

            if (warnings == 0 && errors == 0)
            {
                return;
            }

            if (warnings > 0)
            {
                traceLevel = TraceLevel.Warning;
            }

            if (errors > 0)
            {
                traceLevel = TraceLevel.Error;
            }

            if (validationResult.Source != null)
            {
                endPart = $" in {validationResult.Source.ToString()}.";
            }

            plugin.LogPrint($"Found {errors} Errors, {warnings} Warnings{endPart}", traceLevel);

            RecurseLogPrintValidationResult(plugin, validationResult);
        }
Esempio n. 2
0
 public WorldWatchdog(TerrariaPlugin pluginInstance)
 {
     this.instance = pluginInstance;
     ServerApi.Hooks.NetGetData.Register(pluginInstance, NetHooks_GetData);
     ServerApi.Hooks.NetSendData.Register(pluginInstance, NetHooks_SendData);
     ServerApi.Hooks.GameUpdate.Register(pluginInstance, Game_Update);
 }
        public PlayerDataDictionary(
            TerrariaPlugin plugin, Func <int, DataType> playerDataFactoryFunction, bool addPlayersAfterLoginOnly = true, bool registerHooks = false
            )
        {
            if (plugin == null)
            {
                throw new ArgumentNullException();
            }
            if (playerDataFactoryFunction == null)
            {
                throw new ArgumentNullException();
            }

            this.dataList                  = new List <DataType>(new DataType[100]);
            this.owningPlugin              = plugin;
            this.addAfterLogin             = addPlayersAfterLoginOnly;
            this.PlayerDataFactoryFunction = playerDataFactoryFunction;
            this.SyncRoot                  = new object();

            if (registerHooks)
            {
                if (addPlayersAfterLoginOnly)
                {
                    TShockAPI.Hooks.PlayerHooks.PlayerPostLogin += this.TShock_PlayerPostLogin;
                }
                else
                {
                    ServerApi.Hooks.ServerJoin.Register(plugin, this.Server_Join);
                }

                ServerApi.Hooks.ServerLeave.Register(plugin, this.Server_Leave);
            }
        }
 public static void LogPrintBooErrors(this TerrariaPlugin plugin, CompilerContext context)
 {
     foreach (var err in context.Errors)
     {
         logPrint(plugin, $"{err.LexicalInfo.FileName} {err.LexicalInfo.Line},{err.LexicalInfo.Column}: {err.Message}", TraceLevel.Error);
     }
 }
 public static void LogPrintBooWarnings(this TerrariaPlugin plugin, CompilerContext context)
 {
     foreach (var warn in context.Warnings)
     {
         logPrint(plugin, $"{warn.LexicalInfo.FileName} {warn.LexicalInfo.Line},{warn.LexicalInfo.Column}: {warn.Message}", TraceLevel.Warning);
     }
 }
Esempio n. 6
0
 public BooModuleManager(TerrariaPlugin plugin, IEnumerable <Assembly> references, IEnumerable <string> defaultImports, IEnumerable <EnsuredMethodSignature> ensuredMethodSignatures)
 {
     Plugin                       = plugin;
     modules                      = new Dictionary <string, ModuleInfo>();
     this.references              = references;
     this.defaultImports          = defaultImports;
     this.ensuredMethodSignatures = ensuredMethodSignatures;
 }
Esempio n. 7
0
        public GetDataHookHandler(TerrariaPlugin plugin, bool invokeTileEditOnChestKill = false, int hookPriority = 0)
        {
            Contract.Requires <ArgumentNullException>(plugin != null);

            this.Plugin = plugin;
            this.InvokeTileEditOnChestKill = invokeTileEditOnChestKill;

            ServerApi.Hooks.NetGetData.Register(plugin, this.NetHooks_GetData, hookPriority);
        }
Esempio n. 8
0
        public JistHook(JistEngine engine, HandlerCollection <T> collection, JsValue func)
        {
            this.HookID         = new Guid();
            this.enabled        = true;
            this.collection     = collection;
            this.pluginInstance = engine.PluginInstance;
            this.handler        = (args) => engine.CallFunction(func, this, args);

            collection.Register(engine.PluginInstance, handler);
        }
Esempio n. 9
0
        /// <summary>
        /// Wrapper around <see cref="ServerApi.LogWriter.PluginWriteLine"/>
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="message"></param>
        /// <param name="kind"></param>
        public static void LogPrint(this TerrariaPlugin plugin, string message, TraceLevel kind = TraceLevel.Info)
        {
            //try safeguard against occasional NREs thrown on abrupt shutdown.
            if (plugin == null)
            {
                return;
            }

            ServerApi.LogWriter?.PluginWriteLine(plugin, message, kind);
        }
Esempio n. 10
0
        ///<summary>
        /// Method to Initialize plugin's code.
        ///</summary>
        public override void Initialize()
        {
            that = this;
            ConsoleLOG("Initializing TSGeoIP!");

            if (!Directory.Exists(dataDir))
            {
                ConsoleLOG("Didn't found TSGeoIP folder!");
                Directory.CreateDirectory(dataDir);
                ConsoleLOG("Created TSGeoIP folder!");
            }
            else
            {
                ConsoleLOG("Found TSGeoIP folder!");
            }

            iSettings = new Settings();

            Settings.LoadSettings();


            if (iSettings.GeoIP_API.ToLower() == "geoip")
            {
                if (File.Exists(this.geoIPDB))
                {
                    this.geoIPLS = new LookupService(this.geoIPDB, LookupService.GEOIP_STANDARD);
                }
                else
                {
                    ConsoleLOG("There is no GeoLiteCity.dat", TraceLevel.Error);
                    this.geoIPLS = null;
                }
            }

            if (iSettings.GeoIP_API.ToLower() == "geoip2")
            {
                if (File.Exists(this.geoIP2DB))
                {
                    this.geoIP2DBR = new DatabaseReader(this.geoIP2DB);
                }
                else
                {
                    ConsoleLOG("There is no GeoLite2-City.mmdb", TraceLevel.Error);
                    this.geoIP2DBR = null;
                }
            }

            ServerApi.Hooks.GameInitialize.Register(this, this.OnInitialize);
            ServerApi.Hooks.ServerJoin.Register(this, this.OnJoin);
            ServerApi.Hooks.NetGreetPlayer.Register(this, this.OnNetGreet);
            ServerApi.Hooks.ServerChat.Register(this, this.OnChat);
            ServerApi.Hooks.ServerLeave.Register(this, this.OnLeave);
        }
Esempio n. 11
0
 /// <summary>
 /// Saves the config object to the file path specified.
 /// </summary>
 /// <param name="plugin">TerrariaPlugin that houses this JsonConfig.</param>
 /// <param name="config">JsonConfig type.</param>
 /// <param name="filePath">File path to write the config.</param>
 public static void Save(TerrariaPlugin plugin, JsonConfig config, string filePath)
 {
     try
     {
         Directory.CreateDirectory(Path.GetDirectoryName(filePath));
         config.Save(filePath);
     }
     catch (Exception ex)
     {
         ServerApi.LogWriter.PluginWriteLine(plugin, ex.Message, TraceLevel.Error);
     }
 }
Esempio n. 12
0
        public GetDataHookHandler(TerrariaPlugin plugin, bool invokeTileEditOnChestKill = false, int hookPriority = 0)
        {
            if (plugin == null)
            {
                throw new ArgumentNullException();
            }

            this.Plugin = plugin;
            this.InvokeTileEditOnChestKill = invokeTileEditOnChestKill;

            ServerApi.Hooks.NetGetData.Register(plugin, this.NetHooks_GetData, hookPriority);
        }
Esempio n. 13
0
        Task InfoCommand(CommandArgs e)
        {
            return(Task.Run(() =>
            {
                if (e.Parameters.Count == 0)
                {
                    e.Player.SendInfoMessage("No plugin name was provided, so own info will be displayed.");
                    DisplayPluginInfo(e.Player, this);
                    return;
                }

                bool help = false;
                var o = new OptionSet()
                {
                    { "h|?|help", v => help = true }
                };

                // Should only ever support boolean options, so no catching is required
                var parsedParams = o.Parse(e.Parameters);

                if (help)
                {
                    // Do InfoCommand.Help

                    return;
                }

                if (parsedParams.Count == 0)
                {
                    // Mirror top behaviour
                    e.Player.SendInfoMessage("No plugin name was provided, so own info will be displayed.");
                    DisplayPluginInfo(e.Player, this);
                    return;
                }

                string pluginName = String.Join(" ", parsedParams);
                TerrariaPlugin result = ServerApi.Plugins.FirstOrDefault(p =>
                                                                         p.Plugin.Name.Equals(pluginName, StringComparison.OrdinalIgnoreCase))?.Plugin;

                if (result == null)
                {
                    e.Player.SendErrorMessage($"A plugin named '{pluginName}' is not currently installed.");
                }
                else
                {
                    DisplayPluginInfo(e.Player, result);
                }
            }));
        }
Esempio n. 14
0
        void DisplayPluginInfo(TSPlayer receiver, TerrariaPlugin plugin)
        {
            string format;

            if (receiver.RealPlayer)
            {
                format = $"{TShock.Utils.ColorTag("{0}", Color.Violet)}: {{1}}";
            }
            else
            {
                format = "{0}: {1}";
            }

            receiver.SendInfoMessage(format, "Name", $"{plugin.Name} (v{plugin.Version.ToString()})");
            receiver.SendInfoMessage(format, "Author", plugin.Author);
            receiver.SendInfoMessage(format, "Description", plugin.Description);
        }
Esempio n. 15
0
        public DotNetStats(TerrariaPlugin plugin) : base(plugin)
        {
            for (var gen = 0; gen <= GC.MaxGeneration; gen++)
            {
                collectionCounts.Add(collectionCountsParent.Labels(gen.ToString()));
            }

            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            startTime.Set((process.StartTime.ToUniversalTime() - epoch).TotalSeconds);

            // We hook here to prevent hooking the same thing twice
            // seeing that we can't unhook from this hook
            // Otherwise Initialize(); Dispose(); Initialize(); could cause
            // the hook to be added twice
            Metrics.DefaultRegistry.AddBeforeCollectCallback(Collect);
        }
        private static void RecurseLogPrintValidationResult(TerrariaPlugin plugin, ValidationResult validationResult)
        {
            foreach (var err in validationResult.Errors)
            {
                plugin.LogPrint(err.ToString(), TraceLevel.Error);
            }

            foreach (var warn in validationResult.Warnings)
            {
                plugin.LogPrint(warn.ToString(), TraceLevel.Warning);
            }

            foreach (var ch in validationResult.Children)
            {
                RecurseLogPrintValidationResult(plugin, ch);
            }
        }
Esempio n. 17
0
        /// <summary> Deregisters all automatically
        /// and mainly registered commands. </summary>
        public static void Deregister(TerrariaPlugin Plugin)
        {
            int count = 0;

            foreach (Type type in Assembly.GetAssembly(Plugin.GetType()).GetTypes())
            {
                foreach (MethodInfo method in type.GetMethods())
                {
                    if (Deregister(method))
                    {
                        count++;
                    }
                }
            }
            if (count > 0)
            {
                TShock.Log.ConsoleInfo($"[CommandManager] Deregistered " +
                                       $"{count} commands in plugin '{Plugin.Name}'.");
            }
        }
Esempio n. 18
0
        /// <summary> Registers all <see cref="CommandManagerDelegate"/>
        /// with <see cref="CommandInfoAttribute"/>. </summary>
        public static string[] Register(TerrariaPlugin Plugin,
                                        bool SkipIfHasNotRegisterAttribute = false)
        {
            List <string> names = new List <string>();

            MethodInfo[] methods = Assembly.GetAssembly(Plugin.GetType())
                                   .GetTypes()
                                   .SelectMany(t => t.GetMethods())
                                   .Where(m => m.IsCMDelegate())
                                   .ToArray();

            foreach (MethodInfo method in methods)
            {
                if (Register(method, SkipIfHasNotRegisterAttribute,
                             out string name))
                {
                    names.Add(name);
                }
            }
            return(names.ToArray());
        }
Esempio n. 19
0
        /// <summary>
        /// Attempts to load a json configuration saved at the specified path. If none exists, one will be created. Also checks for configuration errors, by
        /// calling JsonConfig.Validate().
        /// </summary>
        /// <typeparam name="TConfig">JsonConfig subclass.</typeparam>
        /// <param name="plugin">TerrariaPlugin that houses the JsonConfig.</param>
        /// <param name="filePath">File path at which the config should resided.</param>
        /// <returns></returns>
        public static TConfig LoadOrCreate <TConfig>(TerrariaPlugin plugin, string filePath) where TConfig : JsonConfig, new()
        {
            TConfig config = default(TConfig);

            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));

                if (File.Exists(filePath))
                {
                    ServerApi.LogWriter.PluginWriteLine(plugin, $"Loading config from {filePath} ...", TraceLevel.Info);
                    var json = File.ReadAllText(filePath);
                    config = JsonConvert.DeserializeObject <TConfig>(json);
                }
                else
                {
                    ServerApi.LogWriter.PluginWriteLine(plugin, $"Creating config at {filePath} ...", TraceLevel.Info);
                    config = new TConfig();
                    Save(plugin, config, filePath);
                }

                int errors = 0, warnings = 0;
                var validationResult = config.Validate();

                validationResult.Source = $"config file {filePath}.";
                validationResult.GetTotals(ref errors, ref warnings);

                if (errors > 0 || warnings > 0)
                {
                    plugin.LogPrint(validationResult);
                }
            }
            catch (Exception ex)
            {
                ServerApi.LogWriter.PluginWriteLine(plugin, ex.Message, TraceLevel.Error);
            }

            return(config);
        }
Esempio n. 20
0
        void DisplayPluginInfo(TSPlayer receiver, TerrariaPlugin plugin)
        {
            string opt = GetAssemblyConfiguration(plugin.GetType().Assembly);
            string format;

            if (receiver.RealPlayer)
            {
                format = $"{TShock.Utils.ColorTag("{0}", Color.Violet)}: {{1}}";
            }
            else
            {
                format = "{0}: {1}";
            }

            receiver.SendInfoMessage(format, "Name",
                                     string.Format("{0} (v{1}) ({2})", plugin.Name, plugin.Version.ToString(),
                                                   opt == "Debug"
                        ? TShock.Utils.ColorTag("Debug", Color.OrangeRed)
                        : TShock.Utils.ColorTag("Release", Color.LimeGreen)));

            receiver.SendInfoMessage(format, "Author", plugin.Author);
            receiver.SendInfoMessage(format, "Description", plugin.Description);
        }
 private static void logPrint(TerrariaPlugin plugin, string message, TraceLevel level)
 {
     ServerApi.LogWriter.PluginWriteLine(plugin, message, level);
 }
Esempio n. 22
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="CommandRegistry" /> class with the specified
 ///     <see cref="TerrariaPlugin" /> registrator.
 /// </summary>
 /// <param name="registrator">The registrator.</param>
 public CommandRegistry(TerrariaPlugin registrator)
 {
     _plugin = registrator;
 }
 public TicksPerSecond(TerrariaPlugin plugin) : base(plugin)
 {
     // See DotNetStats.cs for why we're adding this hook here
     Metrics.DefaultRegistry.AddBeforeCollectCallback(Collect);
 }
Esempio n. 24
0
 public static void AddPlugIn(TerrariaPlugin plugin)
 {
     LoadedPlugins.Add(plugin);
 }
Esempio n. 25
0
 public static void RemovePlugIn(TerrariaPlugin plugin)
 {
     LoadedPlugins.Remove(plugin);
 }
Esempio n. 26
0
 public static void RemovePlugIn(TerrariaPlugin plugin)
 {
     LoadedPlugins.Remove(plugin);
 }
Esempio n. 27
0
 public static void AddPlugIn(TerrariaPlugin plugin)
 {
     LoadedPlugins.Add(plugin);
 }
 public PluginContainer(TerrariaPlugin plugin) : this(plugin, true)
 {
 }
 public ConnectedPlayers(TerrariaPlugin plugin) : base(plugin)
 {
 }
Esempio n. 30
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="plugin">The Terraria Plugin</param>
 public BaseCollector(TerrariaPlugin plugin)
 {
     this.plugin = plugin;
 }
Esempio n. 31
0
 public SpectatorManager(TerrariaPlugin registrator)
 {
     _registrator = registrator;
 }
 public PluginContainer(TerrariaPlugin plugin, bool dll)
 {
     this.Plugin      = plugin;
     this.Initialized = false;
     this.Dll         = dll;
 }