示例#1
0
        /// <summary>
        /// The main method of the sample. Please make sure you have set settings in appsettings.json or in the .env file in the root folder
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static async Task Main(string[] args)
        {
            // If Visual Studio is used, let's read the .env file which should be in the root folder (same folder than the solution .sln file).
            // Same code will work in VS Code, but VS Code uses also launch.json to get the .env file.
            // You can create this ".env" file by saving the "sample.env" file as ".env" file and fill it with the right values.
            try
            {
                DotEnv.Load(".env");
            }
            catch
            {
            }

            ConfigWrapper config = new(new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                       .AddEnvironmentVariables() // parses the values from the optional .env file at the solution root
                                       .Build());

            try
            {
                await RunAsync(config);
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine($"{exception.Message}");

                if (exception.GetBaseException() is ErrorResponseException apiException)
                {
                    Console.Error.WriteLine(
                        $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'.");
                }
            }

            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
        public static void Main(string[] args)
        {
            // Force Globalization to en-US because we use periods instead of commas for decimals
            CultureInfo.CurrentCulture = new CultureInfo("en-US");

            // Load .env file
            string dotenv = Path.Combine(Paths.SOLUTION_DIR, ".env");

            if (!File.Exists(dotenv))
            {
                throw new ArgumentException(".env file not found!");
            }
            DotEnv.Load(dotenv);

            InitDatabase();

            // No DI here because MapleServer is static
            Logger logger = LogManager.GetCurrentClassLogger();

            logger.Info($"MapleServer started with {args.Length} args: {string.Join(", ", args)}");

            IContainer loginContainer = LoginContainerConfig.Configure();

            using ILifetimeScope loginScope = loginContainer.BeginLifetimeScope();
            LoginServer loginServer = loginScope.Resolve <LoginServer>();

            loginServer.Start();

            IContainer gameContainer = GameContainerConfig.Configure();

            using ILifetimeScope gameScope = gameContainer.BeginLifetimeScope();
            gameServer = gameScope.Resolve <GameServer>();
            gameServer.Start();

            // Input commands to the server
            while (true)
            {
                string[] input = (Console.ReadLine() ?? string.Empty).Split(" ", 2);
                switch (input[0])
                {
                case "exit":
                case "quit":
                    gameServer.Stop();
                    loginServer.Stop();
                    return;

                case "send":
                    string       packet  = input[1];
                    PacketWriter pWriter = new PacketWriter();
                    pWriter.Write(packet.ToByteArray());
                    logger.Info(pWriter);

                    foreach (Session session in GetSessions(loginServer, gameServer))
                    {
                        logger.Info($"Sending packet to {session}: {pWriter}");
                        session.Send(pWriter);
                    }

                    break;

                case "resolve":
                    PacketStructureResolver resolver = PacketStructureResolver.Parse(input[1]);
                    GameSession             first    = gameServer.GetSessions().Single();
                    resolver.Start(first);
                    break;

                default:
                    logger.Info($"Unknown command:{input[0]} args:{(input.Length > 1 ? input[1] : "N/A")}");
                    break;
                }
            }
        }
示例#3
0
 public void MissingFilenameThrowsException()
 {
     Assert.Throws <ArgumentNullException>(() => DotEnv.Load(null));
 }
示例#4
0
 public void InvalidFilenameDoesNotThrowException()
 {
     DotEnv.Load(".env.that.does.not.exist");
 }
示例#5
0
 public static void Main(string[] args)
 {
     CreateWebHostBuilder(args).Build().Run();
     DotEnv.Load();
 }
示例#6
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
                                                     FunctionContext executionContext)
        {
            var log = executionContext.GetLogger("Function1");

            log.LogInformation("C# HTTP trigger function processed a request.");

            string triggerStart = DateTime.UtcNow.ToString("yyMMddHHmmss");

            // Get request body data.
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    data        = (RequestBodyModel)JsonConvert.DeserializeObject(requestBody, typeof(RequestBodyModel));

            // Return bad request if input asset name is not passed in
            if (data.LiveEventName == null || data.LiveOutputName == null)
            {
                return(new BadRequestObjectResult("Please pass live event name and live output name in the request body"));
            }

            data.IntervalSec ??= 60;

            // If Visual Studio is used, let's read the .env file which should be in the root folder (same folder than the solution .sln file).
            // Same code will work in VS Code, but VS Code uses also launch.json to get the .env file.
            // You can create this ".env" file by saving the "sample.env" file as ".env" file and fill it with the right values.
            try
            {
                DotEnv.Load(".env");
            }
            catch
            {
            }

            ConfigWrapper config = new(new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                       .AddEnvironmentVariables() // parses the values from the optional .env file at the solution root
                                       .Build());

            IAzureMediaServicesClient client;

            try
            {
                client = await Authentication.CreateMediaServicesClientAsync(config);
            }
            catch (Exception e)
            {
                if (e.Source.Contains("ActiveDirectory"))
                {
                    Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
                    Console.Error.WriteLine();
                }
                Console.Error.WriteLine($"{e.Message}");

                return(new BadRequestObjectResult(e.Message));
            }

            // Set the polling interval for long running operations to 2 seconds.
            // The default value is 30 seconds for the .NET client SDK
            client.LongRunningOperationRetryTimeout = 2;

            // Ensure that you have customized encoding Transform.  This is really a one time setup operation.
            Transform transform = await CreateSubclipTransform(client, config.ResourceGroup, config.AccountName, SubclipTransformName);

            var liveOutput = await client.LiveOutputs.GetAsync(config.ResourceGroup, config.AccountName, data.LiveEventName, data.LiveOutputName);


            // let's analyze the client manifest and adjust times for the subclip job
            var doc = await LiveManifest.TryToGetClientManifestContentAsABlobAsync(client, config.ResourceGroup, config.AccountName, liveOutput.AssetName);

            var assetmanifestdata = LiveManifest.GetManifestTimingData(doc);

            if (assetmanifestdata.Error)
            {
                return(new NotFoundObjectResult(new
                {
                    message = "Data cannot be read from live output / asset manifest."
                }));
            }

            log.LogInformation("Timestamps : " + string.Join(",", assetmanifestdata.TimestampList.Select(n => n.ToString()).ToArray()));

            var livetime = TimeSpan.FromSeconds(assetmanifestdata.TimestampEndLastChunk / (double)assetmanifestdata.TimeScale);

            log.LogInformation($"Livetime : {livetime}");

            var starttime = LiveManifest.ReturnTimeSpanOnGOP(assetmanifestdata, livetime.Subtract(TimeSpan.FromSeconds((int)data.IntervalSec)));

            log.LogInformation($"Value starttime : {starttime}");

            if (data.LastSubclipEndTime != null)
            {
                var lastEndTime = (TimeSpan)data.LastSubclipEndTime;
                log.LogInformation($"Value lastEndTime : {lastEndTime}");

                var delta = (livetime - lastEndTime - TimeSpan.FromSeconds((int)data.IntervalSec)).Duration();
                log.LogInformation($"Delta: {delta}");

                if (delta < (TimeSpan.FromSeconds(3 * (int)data.IntervalSec))) // less than 3 times the normal duration (3*60s)
                {
                    starttime = lastEndTime;
                    log.LogInformation($"Value new starttime : {starttime}");
                }
            }

            var duration = livetime - starttime;

            log.LogInformation($"Value duration: {duration}");
            if (duration == new TimeSpan(0)) // Duration is zero, this may happen sometimes !
            {
                return(new NotFoundObjectResult(new
                {
                    message = "Stopping. Duration of subclip is zero."
                }));
            }

            // Output from the Job must be written to an Asset, so let's create one
            Asset outputAsset = await CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName, liveOutput.Name + "-subclip-" + triggerStart, data.OutputAssetStorageAccount);

            Job job = await SubmitJobAsync(
                client,
                config.ResourceGroup,
                config.AccountName,
                SubclipTransformName,
                $"Subclip-{liveOutput.Name}-{triggerStart}",
                liveOutput.AssetName,
                outputAsset.Name,
                new AbsoluteClipTime(starttime.Subtract(TimeSpan.FromMilliseconds(100))),
                new AbsoluteClipTime(livetime.Add(TimeSpan.FromMilliseconds(100)))
                );


            return(new OkObjectResult(new AnswerBodyModel
            {
                SubclipAssetName = outputAsset.Name,
                SubclipJobName = job.Name,
                SubclipTransformName = SubclipTransformName,
                SubclipEndTime = starttime + duration
            }));
        }
        public static async Task Main()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);
            currentDomain.ProcessExit        += new EventHandler(SaveAll);

            // Force Globalization to en-US because we use periods instead of commas for decimals
            CultureInfo.CurrentCulture = new CultureInfo("en-US");

            // Load .env file
            string dotenv = Path.Combine(Paths.SOLUTION_DIR, ".env");

            if (!File.Exists(dotenv))
            {
                throw new ArgumentException(".env file not found!");
            }
            DotEnv.Load(dotenv);

            InitDatabase();

            // Load Mob AI files
            string mobAiSchema = Path.Combine(Paths.AI_DIR, "mob-ai.xsd");

            MobAIManager.Load(Paths.AI_DIR, mobAiSchema);

            // Initialize all metadata.
            await MetadataHelper.InitializeAll();

            IContainer loginContainer = LoginContainerConfig.Configure();

            using ILifetimeScope loginScope = loginContainer.BeginLifetimeScope();
            LoginServer loginServer = loginScope.Resolve <LoginServer>();

            loginServer.Start();

            IContainer gameContainer = GameContainerConfig.Configure();

            using ILifetimeScope gameScope = gameContainer.BeginLifetimeScope();
            GameServer = gameScope.Resolve <GameServer>();
            GameServer.Start();

            Logger.Info("Server Started.".ColorGreen());

            // Input commands to the server
            while (true)
            {
                string[] input = (Console.ReadLine() ?? string.Empty).Split(" ", 2);
                switch (input[0])
                {
                case "exit":
                case "quit":
                    GameServer.Stop();
                    loginServer.Stop();
                    return;

                case "send":
                    if (input.Length <= 1)
                    {
                        break;
                    }
                    string       packet  = input[1];
                    PacketWriter pWriter = new PacketWriter();
                    pWriter.Write(packet.ToByteArray());
                    Logger.Info(pWriter);

                    foreach (Session session in GetSessions(loginServer, GameServer))
                    {
                        Logger.Info($"Sending packet to {session}: {pWriter}");
                        session.Send(pWriter);
                    }

                    break;

                case "resolve":
                    PacketStructureResolver resolver = PacketStructureResolver.Parse(input[1]);
                    GameSession             first    = GameServer.GetSessions().Single();
                    resolver.Start(first);
                    break;

                default:
                    Logger.Info($"Unknown command:{input[0]} args:{(input.Length > 1 ? input[1] : "N/A")}");
                    break;
                }
            }
        }
示例#8
0
    public static async Task Main()
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;

        currentDomain.UnhandledException += UnhandledExceptionEventHandler;
        currentDomain.ProcessExit        += SaveAll;

        // Force Globalization to en-US because we use periods instead of commas for decimals
        CultureInfo.CurrentCulture = new("en-US");

        // Load .env file
        string dotenv = Path.Combine(Paths.SOLUTION_DIR, ".env");

        if (!File.Exists(dotenv))
        {
            throw new ArgumentException(".env file not found!");
        }
        DotEnv.Load(dotenv);

        DatabaseManager.Init();

        DateTimeOffset lastReset    = DatabaseManager.ServerInfo.GetLastDailyReset();
        DateTimeOffset now          = DateTimeOffset.UtcNow;
        DateTime       lastMidnight = new(now.Year, now.Month, now.Day, 0, 0, 0, 0);

        // Check if lastReset is before lastMidnight
        if (lastReset < lastMidnight)
        {
            DailyReset();
        }

        // Schedule daily reset and repeat every 24 hours
        TaskScheduler.Instance.ScheduleTask(0, 0, 24, DailyReset);

        // Load Mob AI files
        string mobAiSchema = Path.Combine(Paths.AI_DIR, "mob-ai.xsd");

        MobAIManager.Load(Paths.AI_DIR, mobAiSchema);

        // Initialize all metadata.
        await MetadataHelper.InitializeAll();

        IContainer loginContainer = LoginContainerConfig.Configure();

        using ILifetimeScope loginScope = loginContainer.BeginLifetimeScope();
        _loginServer = loginScope.Resolve <LoginServer>();
        _loginServer.Start();

        IContainer gameContainer = GameContainerConfig.Configure();

        using ILifetimeScope gameScope = gameContainer.BeginLifetimeScope();
        _gameServer = gameScope.Resolve <GameServer>();
        _gameServer.Start();

        Logger.Info("All Servers have been Started.".ColorGreen());

        // Input commands to the server
        while (true)
        {
            string[] input = (Console.ReadLine() ?? string.Empty).Split(" ", 2);
            switch (input[0])
            {
            case "exit":
            case "quit":
                _gameServer.Stop();
                _loginServer.Stop();
                return;

            case "send":
                if (input.Length <= 1)
                {
                    break;
                }
                string       packet  = input[1];
                PacketWriter pWriter = new();
                pWriter.WriteBytes(packet.ToByteArray());
                Logger.Info(pWriter);

                foreach (Session session in GetSessions(_loginServer, _gameServer))
                {
                    Logger.Info($"Sending packet to {session}: {pWriter}");
                    session.Send(pWriter);
                }

                break;

            case "resolve":
                // How to use inside the PacketStructureResolver class
                PacketStructureResolver resolver = PacketStructureResolver.Parse(input[1]);
                if (resolver is null)
                {
                    break;
                }
                GameSession first = _gameServer.GetSessions().Single();
                resolver.Start(first);
                break;

            default:
                Logger.Info($"Unknown command:{input[0]} args:{(input.Length > 1 ? input[1] : "N/A")}");
                break;
            }
        }
    }
示例#9
0
文件: Program.cs 项目: aurlaw/VueCore
 public static void Main(string[] args)
 {
     // load .env
     DotEnv.Load();
     CreateHostBuilder(args).Build().Run();
 }
示例#10
0
        public static async Task Main(string[] args = null)
        {
            string defaultEnv = Path.Combine(SkuldAppContext.BaseDirectory, ".env");

            if (!File.Exists(defaultEnv))
            {
                Console.WriteLine("Copy .env.default into .env and enter details");
                return;
            }

            DotEnv.Load(new DotEnvOptions(envFilePaths: new[] { defaultEnv }));

            if (args.Contains("--pq"))
            {
                GeneratePixelQuery();
                return;
            }

            SkuldConfig Configuration = null;

            Log.Configure();

            if (!Directory.Exists(SkuldAppContext.StorageDirectory))
            {
                Directory.CreateDirectory(SkuldAppContext.StorageDirectory);
                Log.Verbose(Key, "Created Storage Directory", null);
            }
            if (!Directory.Exists(SkuldAppContext.FontDirectory))
            {
                Directory.CreateDirectory(SkuldAppContext.FontDirectory);
                Log.Verbose(Key, "Created Font Directory", null);
            }

            try
            {
                var database = new SkuldDbContextFactory().CreateDbContext();

                if (!database.Configurations.Any() ||
                    args.Contains("--newconf") ||
                    args.Contains("-nc"))
                {
                    var conf = new SkuldConfig();
                    database.Configurations.Add(conf);
                    await database.SaveChangesAsync().ConfigureAwait(false);

                    Log.Verbose(Key, $"Created new configuration with Id: {conf.Id}", null);

                    Log.Info(Key, $"Please fill out the configuration information in the database matching the Id \"{database.Configurations.LastOrDefault().Id}\"");
                    Console.ReadKey();
                    Environment.Exit(0);
                }

                var configId = SkuldAppContext.GetEnvVar(SkuldAppContext.ConfigEnvVar);

                var c = database.Configurations.Find(configId);

                Configuration = c ?? database.Configurations.FirstOrDefault();

                SkuldAppContext.SetConfigurationId(Configuration.Id);
            }
            catch (Exception ex)
            {
                Log.Critical(Key, ex.Message, null, ex);
            }

            if (Configuration.DiscordToken.IsNullOrWhiteSpace())
            {
                Log.Critical(Key, "You haven't provided a discord token, exiting", null);
                return;
            }

            await ConfigureBotAsync(
                Configuration,
                new DiscordSocketConfig
            {
                MessageCacheSize = 100,
                DefaultRetryMode = RetryMode.AlwaysRetry,
                LogLevel         = LogSeverity.Verbose,
                GatewayIntents   = GatewayIntents.Guilds |
                                   GatewayIntents.GuildMembers |
                                   GatewayIntents.GuildBans |
                                   GatewayIntents.GuildEmojis |
                                   GatewayIntents.GuildIntegrations |
                                   GatewayIntents.GuildWebhooks |
                                   GatewayIntents.GuildInvites |
                                   GatewayIntents.GuildVoiceStates |
                                   GatewayIntents.GuildMessages |
                                   GatewayIntents.GuildMessageReactions |
                                   GatewayIntents.DirectMessages |
                                   GatewayIntents.DirectMessageReactions
            },
                new CommandServiceConfig
            {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Async,
                LogLevel        = LogSeverity.Verbose,
                IgnoreExtraArgs = true
            },
                new MessageServiceConfig
            {
                Prefix    = Configuration.Prefix,
                AltPrefix = Configuration.AltPrefix
            }
                ).ConfigureAwait(false);

            Log.Info(Key, "Loaded Skuld v" + SkuldAppContext.Skuld.Key.Version);

            await StartBotAsync().ConfigureAwait(false);

            await Task.Delay(-1).ConfigureAwait(false);

            await StopBotAsync(Key);

            WebSocket.ShutdownServer();

            Environment.Exit(0);
        }
示例#11
0
 static AppSettings()
 {
     DotEnv.Load();
     Global = DotEnv.Load <GlobalSettings>();
 }