Example #1
0
        private void StartBirthdayServiceFor(String employeeFileName, String date)
        {
            var service = new BirthdayService();

            service.SendGreetings(employeeFileName, new XDate(date), "localhost", NONSTANDARD_PORT);
            emailIterator = server.ReceivedEmail;
        }
        public override bool OnStartJob(JobParameters jobParams)
        {
            Log.Info("Starte BirthdayCheck Job...");

            if (notificationService == null)
            {
                notificationService  = new NotificationService(this);
                birthdayService      = new BirthdayService(this);
                ConfigurationService = new ConfigurationService();
            }

            int checkDaysInFuture = jobParams.Extras.GetInt(JOBPARAM_DAYS_IN_FUTURE, 30);

            int[] checkTimeArray = jobParams.Extras.GetIntArray(JOBPARAM_CHECKTIME);
            (int hour, int minute)checkTime = (checkTimeArray[0], checkTimeArray[1]);

            if (ShouldCheck(DateTime.Now, checkTime, ConfigurationService.GetLastCheckTime()))
            {
                Task.Run(() =>
                {
                    Log.Debug($"Job wird ausgeführt (CheckTime: {checkTime.hour:00}:{checkTime.minute:00})...");
                    CheckForNextBirthdays(checkDaysInFuture);
                    ConfigurationService.SaveLastCheckTime(DateTime.Now);

                    Log.Debug("Job erfolgreich ausgeführt.");
                    JobFinished(jobParams, false);
                });

                Log.Debug("Job gestartet.");
            }
            return(true);
        }
Example #3
0
        /// <summary>
        /// Configure background services
        /// </summary>
        /// <returns></returns>
        public Startup ConfigureServices()
        {
            ServiceHandler serviceHandler = Container.Get <ServiceHandler>();

            // In 1m
            int startupDelay = TimeSpan.FromMinutes(1).Milliseconds;

            // Every 30s
            int interval = TimeSpan.FromSeconds(30).Milliseconds;

            EventService eventService = Container.Get <EventService>();

            eventService.Trigger += serviceHandler.OnEventServiceTriggerAsync;
            eventService.Init(startupDelay, interval);

            // Next day @ 07:00
            startupDelay = DateTime.UtcNow.Date.AddDays(1).AddHours(7).Millisecond;

            // Every 24H
            interval = TimeSpan.FromDays(1).Milliseconds;

            BirthdayService birthdayService = Container.Get <BirthdayService>();

            birthdayService.Trigger += serviceHandler.OnBirthdayServiceTriggerAsync;
            birthdayService.Init(startupDelay, interval);

            return(this);
        }
Example #4
0
        void ExecuteBirthdayServiceFor(string employeeFileName, string date)
        {
            IGreetingMessageService greetingMessageService = new GreetingMessageService("localhost", NONSTANDARD_PORT, "*****@*****.**");
            IEmployeeRepository     employeeRepository     = new FileEmployeeRepository(employeeFileName);
            var service = new BirthdayService(greetingMessageService, employeeRepository);

            service.SendGreetings(new XDate(date));
            emailIterator = server.ReceivedEmail;
        }
Example #5
0
        public BirthdayServiceTests()
        {
            _database             = new TestDatabaseContext();
            _user                 = new TestUserContext();
            _personGreeterService = new Mock_PersonService();
            _personRepo           = new Mock_PersonRepository();

            _birthdayService = new BirthdayService(_personRepo, _user, _personGreeterService);
        }
Example #6
0
        public async Task SetBirthday([Remainder] string dateTime = null)
        {
            var user = BirthdayService.GetUser(Context.User.Id);

            if (user != null && user.Attempts >= 3)
            {
                await ReplyAsync("Your have already exhausted all 3 of your attempts to set your birthday.");

                return;
            }

            if (dateTime == null)
            {
                await ReplyAsync("Please use the following example to set your birthday: `01 Jan 2000` or `05 Feb`");

                return;
            }

            DateTime?parsedTime;

            if (DateTime.TryParseExact(dateTime, BirthdayService.GetTimeFormats(true), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out DateTime resultWithYear))
            {
                parsedTime = resultWithYear;
            }
            else if (DateTime.TryParseExact(dateTime, BirthdayService.GetTimeFormats(false), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out DateTime resultWithoutYear))
            {
                parsedTime = new DateTime(0001, resultWithoutYear.Month, resultWithoutYear.Day);
            }
            else
            {
                await ReplyAsync("Unable to retrieve a valid date format. Please use the following example: `01 Jan 2000` or `05 Feb`");

                return;
            }

            if (parsedTime > DateTime.UtcNow)
            {
                await ReplyAsync("Birth date cannot be in the future");

                return;
            }

            if (user == null)
            {
                user          = new Models.BirthdayModel(Context.User.Id, parsedTime.Value, parsedTime.Value.Year != 0001);
                user.Attempts = 1;
            }
            else
            {
                user.Birthday = parsedTime.Value;
                user.ShowYear = parsedTime.Value.Year != 0001;
                user.Attempts++;
            }

            BirthdayService.SaveUser(user);
            await ReplyAsync($"Birthday set to {parsedTime.Value.Day} {CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(parsedTime.Value.Month)} {(parsedTime.Value.Year == 0001 ? "" : parsedTime.Value.Year.ToString())}");
        }
Example #7
0
        public async Task SetChannel()
        {
            var model = BirthdayService.GetConfig(Context.Guild.Id);

            model.BirthdayAnnouncementChannelId = Context.Channel.Id;
            BirthdayService.SaveConfig(model);

            await ReplyAsync($"Birthday Service Enabled: {model.Enabled}\n" +
                             $"Channel has been set to: {Context.Channel.Name}");
        }
Example #8
0
        public async Task SetBirthdayRole(IRole role = null)
        {
            var model = BirthdayService.GetConfig(Context.Guild.Id);

            model.BirthdayRole = role?.Id ?? 0;
            BirthdayService.SaveConfig(model);

            await ReplyAsync($"Birthday Service Enabled: {model.Enabled}\n" +
                             $"Birthday Role: {role?.Mention ?? "N/A"}");
        }
Example #9
0
        public void GetBirthdaysForNotification_BirthdaysCount_Match_Specified(string todayStr, byte daysCountBeforeNotificaiton, int correctResult)
        {
            var today = DateTime.ParseExact(todayStr, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);

            var service = new BirthdayService();

            var result = service.GetBirthdaysForNotification(today, GetBirthdaySchedule(daysCountBeforeNotificaiton));

            Assert.AreEqual(correctResult, result.Count);
        }
Example #10
0
        public async Task ToggleEnabled()
        {
            var model = BirthdayService.GetConfig(Context.Guild.Id);

            model.Enabled = !model.Enabled;
            BirthdayService.SaveConfig(model);

            await ReplyAsync($"Birthday Service Enabled: {model.Enabled}\n" +
                             $"NOTE: You need to run the setchannel and setrole command in order for this to work");
        }
Example #11
0
        public void GetBirthdayDatePeriodType_BirthdayDatePeriodType_Match_Specified(string todayStr, string birthdayStr, byte daysCountBeforeNotificaiton, BirthdayDatePeriodTypes correctResult)
        {
            var today    = DateTime.ParseExact(todayStr, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);
            var birthday = DateTime.ParseExact(birthdayStr, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);

            var service = new BirthdayService();

            var result = service.GetBirthdayDatePeriodType(today, birthday);

            Assert.AreEqual(correctResult, result);
        }
Example #12
0
        public async Task VerifyBirthdayService()
        {
            var uniqueLocation  = Guid.NewGuid().ToString("N");
            var birthdayService = new BirthdayService(new Location(uniqueLocation));

            var birthdate  = DateTime.Today + TimeSpan.FromDays(1);
            var uniqueName = Guid.NewGuid().ToString("N");
            var birthday   = new Birthday(uniqueName, birthdate);

            await birthdayService.SaveBirthday(birthday);

            var persons = await birthdayService.GetBirthdays();

            Assert.True(persons.Any());
            Assert.Equal(birthday.Name, persons[0].Name);

            await birthdayService.DeleteBirthday(persons[0]);

            persons = await birthdayService.GetBirthdays();

            Assert.False(persons.Any());
        }
Example #13
0
        public async Task SetTimeZone(double offset = 0)
        {
            var user = BirthdayService.GetUser(Context.User.Id);

            if (user == null)
            {
                await ReplyAsync("You must set your birthday prior to setting a time zone.");

                return;
            }

            if (offset < -12 || offset > 14)
            {
                await ReplyAsync("UTC Offsets range from -12.00 to +14.00\nNOTE: if your offset is on a half hour use .5 instead of .30");

                return;
            }

            user.Offset = offset;
            await ReplyAsync("Your UTC offset has been set.");

            BirthdayService.SaveUser(user);
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TimerService"/> class.
        /// </summary>
        /// <param name="client">
        /// The client.
        /// </param>
        /// <param name="partnerService">
        /// The partner Service.
        /// </param>
        /// <param name="pHelper">
        /// The p Helper.
        /// </param>
        /// <param name="provider">
        /// The provider.
        /// </param>
        public TimerService(DiscordShardedClient client, PartnerService partnerService, PartnerHelper pHelper, BirthdayService bService, DatabaseObject config, IServiceProvider provider)
        {
            partnerHelper   = pHelper;
            PartnerService  = partnerService;
            Provider        = provider;
            ShardedClient   = client;
            BirthdayService = bService;

            timer = new Timer(
                async _ =>
            {
                try
                {
                    if (config.RunPartner)
                    {
                        var t = Task.Run(PartnerAsync);
                    }

                    if (config.RunBirthday)
                    {
                        var b = Task.Run(BirthdayAsync);
                    }
                }
                catch (Exception e)
                {
                    LogHandler.LogMessage("Partner Error:\n" + $"{e}", LogSeverity.Error);
                }

                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                GC.WaitForPendingFinalizers();

                LastFireTime = DateTime.UtcNow;
            },
                null,
                TimeSpan.Zero,
                TimeSpan.FromMinutes(FirePeriod));
        }
Example #15
0
 public void setUp()
 {
     service    = new BirthdayService();
     smtpServer = SimpleSmtpServer.Start();
 }
        static void Main(string[] args)
        {
            BirthdayPersonService service       = new BirthdayPersonService(new BirthdayPersonFileRepository());
            BirthdayService       daysLeft      = new BirthdayService(new BirthdayPersonFileRepository());
            BirthdayService       birthdayToday = new BirthdayService(new BirthdayPersonFileRepository());
            var file = new StreamWriter(@"D:\BirthdayRegistrationFileDb.txt", true);

            file.Close();
            int select = 0;

            do
            {
                Console.WriteLine("Birthdays of the Day " + DateTime.Today);

                foreach (var person in birthdayToday.BirthdayToday())
                {
                    Console.WriteLine(person.Name + " " + person.Surname);
                }

                Console.WriteLine();
                Console.WriteLine("####### ### #######");
                Console.WriteLine("Choose the options you want");
                Console.WriteLine("1 - Register person");
                Console.WriteLine("2 - Edit record");
                Console.WriteLine("3 - Show logs");
                Console.WriteLine("4 - Delete records");
                Console.WriteLine("5 - Search person by name");
                Console.WriteLine("6 - Close");
                Console.WriteLine();
                select = int.Parse(Console.ReadLine());
                BirthdayPerson birthdayPerson;

                switch (select)
                {
                case 1:
                    Console.Clear();
                    Console.WriteLine("Selected - Register person");
                    Console.WriteLine();
                    birthdayPerson = new BirthdayPerson();
                    Console.WriteLine("Enter the person's name");
                    birthdayPerson.Name = Console.ReadLine();
                    Console.WriteLine("Enter the person's last name");
                    birthdayPerson.Surname = Console.ReadLine();
                    Console.WriteLine("Enter the person's date of birth in the dd / MM / yyyy template");
                    birthdayPerson.Birthdate = Convert.ToDateTime(Console.ReadLine());
                    service.RegisterPerson(birthdayPerson);
                    Console.WriteLine("Congratulations you have been registered!");
                    break;

                case 2:
                    Console.Clear();
                    Console.WriteLine("Selected - Edit record");
                    Console.WriteLine();
                    birthdayPerson = new BirthdayPerson();
                    Console.WriteLine("Enter the ID of the person you want to edit");
                    birthdayPerson.Id = Guid.Parse(Console.ReadLine());
                    Console.WriteLine("Enter the name you want to edit");
                    birthdayPerson.Name = Console.ReadLine();
                    Console.WriteLine("Enter the last name you want to edit");
                    birthdayPerson.Surname = Console.ReadLine();
                    Console.WriteLine("Enter the new birth date of the person dd / MM / yyyy");
                    birthdayPerson.Birthdate = Convert.ToDateTime(Console.ReadLine());
                    service.EditPerson(birthdayPerson, birthdayPerson.Id);
                    break;

                case 3:
                    Console.Clear();
                    Console.WriteLine("Selected - Show logs");
                    Console.WriteLine();
                    var persons = service.GetAllPerson();
                    foreach (var onePerson in persons)
                    {
                        Console.WriteLine("Id: " + onePerson.Id);
                        Console.WriteLine("Name or surname: " + onePerson.Name + " " + onePerson.Surname);
                        Console.WriteLine("Date of birth: " + onePerson.Birthdate);
                        Console.WriteLine("Missing " + daysLeft.DaysToBirthday(onePerson.Birthdate.Day, onePerson.Birthdate.Month) + " days for this person's birthday!");
                        Console.WriteLine();
                    }
                    break;

                case 4:
                    Console.Clear();
                    Console.WriteLine("Selected - Delete record");
                    Console.WriteLine();
                    Console.WriteLine("Enter the ID of the person you want to remove: ");
                    var id = Guid.Parse(Console.ReadLine());
                    service.DeleteBirthdayPerson(id);
                    break;

                case 5:
                    Console.Clear();
                    Console.WriteLine("Selected - Search for person by name");
                    Console.WriteLine();
                    Console.WriteLine("Enter the name of the person you want to search: ");
                    var search = Console.ReadLine();
                    var result = service.SearchByName(search);
                    foreach (var onePerson in result)
                    {
                        Console.WriteLine("Id: " + onePerson.Id);
                        Console.WriteLine("Name and surname: " + onePerson.Name + " " + onePerson.Surname);
                        Console.WriteLine("Date of birth: " + onePerson.Birthdate);
                        Console.WriteLine("Missing " + daysLeft.DaysToBirthday(onePerson.Birthdate.Day, onePerson.Birthdate.Month) + " days for this person's birthday!");
                        Console.WriteLine();
                    }
                    break;
                }
            } while (select != 6);
        }
Example #17
0
        /// <summary>
        ///     Initialization of our service provider and bot
        /// </summary>
        /// <returns>
        ///     The <see cref="Task" />.
        /// </returns>
        public static async Task StartAsync()
        {
            // This ensures that our bots setup directory is initialized and will be were the database config is stored.
            if (!Directory.Exists(Path.Combine(AppContext.BaseDirectory, "setup/")))
            {
                Directory.CreateDirectory(Path.Combine(AppContext.BaseDirectory, "setup/"));
            }

            LogHandler.LogMessage("Loading initial provider", LogSeverity.Verbose);
            var services = new ServiceCollection()
                           .AddSingleton <DatabaseHandler>()
                           .AddSingleton(x => x.GetRequiredService <DatabaseHandler>().Execute <ConfigModel>(DatabaseHandler.Operation.LOAD, id: "Config"))
                           .AddSingleton(new CommandService(new CommandServiceConfig
            {
                ThrowOnError    = false,
                IgnoreExtraArgs = false,
                DefaultRunMode  = RunMode.Async
            }))
                           .AddSingleton(
                x =>
            {
                if (File.Exists(Path.Combine(AppContext.BaseDirectory, "setup/DBConfig.json")))
                {
                    var Settings = JsonConvert.DeserializeObject <DatabaseObject>(File.ReadAllText("setup/DBConfig.json"));
                    return(Settings);
                }

                return(new DatabaseObject());
            })
                           .AddSingleton(x =>
            {
                if (File.Exists(Path.Combine(AppContext.BaseDirectory, "setup/DBConfig.json")))
                {
                    var Settings = JsonConvert.DeserializeObject <DatabaseObject>(File.ReadAllText("setup/DBConfig.json"));
                    if (!string.IsNullOrEmpty(Settings.ProxyUrl))
                    {
                        return(new HttpClientHandler {
                            Proxy = new WebProxy(Settings.ProxyUrl), UseProxy = true
                        });
                    }
                }

                return(new HttpClientHandler());
            })
                           .AddSingleton(x => new HttpClient(x.GetRequiredService <HttpClientHandler>()))
                           .AddSingleton <BotHandler>()
                           .AddSingleton <EventHandler>()
                           .AddSingleton <Events>()
                           .AddSingleton(x => x.GetRequiredService <DatabaseHandler>().InitializeAsync().Result)
                           .AddSingleton(new Random(Guid.NewGuid().GetHashCode()))
                           .AddSingleton(x =>
                                         new DiscordShardedClient(
                                             new DiscordSocketConfig
            {
                MessageCacheSize    = 0,
                AlwaysDownloadUsers = false,
                LogLevel            = LogSeverity.Info,
                TotalShards         = x.GetRequiredService <ConfigModel>().Shards
            }))
                           .AddSingleton(
                x =>
            {
                var config = x.GetRequiredService <ConfigModel>().Prefix;
                var store  = x.GetRequiredService <IDocumentStore>();
                return(new PrefixService(config, store));
            })
                           .AddSingleton <TagService>()
                           .AddSingleton <PartnerService>()
                           .AddSingleton <LevelService>()
                           .AddSingleton <ChannelService>()
                           .AddSingleton <HomeService>()
                           .AddSingleton <ChannelHelper>()
                           .AddSingleton <PartnerHelper>()
                           .AddSingleton <Interactive>()
                           .AddSingleton(
                x =>
            {
                var limits = new TranslateLimitsNew(x.GetRequiredService <IDocumentStore>());
                limits.Initialize();
                return(limits);
            })
                           .AddSingleton(x => new TranslateMethodsNew(x.GetRequiredService <DatabaseObject>(), x.GetRequiredService <TranslateLimitsNew>(), x.GetRequiredService <ConfigModel>()))
                           .AddSingleton <LevelHelper>()
                           .AddSingleton <TranslationService>()
                           .AddSingleton(
                x =>
            {
                var birthdayService = new BirthdayService(x.GetRequiredService <DiscordShardedClient>(), x.GetRequiredService <IDocumentStore>());
                birthdayService.Initialize();
                return(birthdayService);
            })
                           .AddSingleton(
                x =>
            {
                var gameService = new GameService(x.GetRequiredService <IDocumentStore>(), x.GetRequiredService <DatabaseObject>());
                gameService.Initialize();
                return(gameService);
            })
                           .AddSingleton <TimerService>()
                           .AddSingleton <DBLApiService>()
                           .AddSingleton <WaitService>();

            var provider = services.BuildServiceProvider();

            LogHandler.LogMessage("Initializing HomeService", LogSeverity.Verbose);
            provider.GetRequiredService <HomeService>().Update();
            LogHandler.LogMessage("Initializing PrefixService", LogSeverity.Verbose);
            await provider.GetRequiredService <PrefixService>().InitializeAsync();

            LogHandler.LogMessage("Initializing BotHandler", LogSeverity.Verbose);
            await provider.GetRequiredService <BotHandler>().InitializeAsync();

            LogHandler.LogMessage("Initializing EventHandler", LogSeverity.Verbose);
            await provider.GetRequiredService <EventHandler>().InitializeAsync();


            // Indefinitely delay the method from finishing so that the program stays running until stopped.
            await Task.Delay(-1);
        }
Example #18
0
 public BirthdaySetup(BirthdayService bService)
 {
     Service = bService;
 }
Example #19
0
        public async Task BirthdayAsync()
        {
            try
            {
                var notifiableList = await BirthdayService.GetNotifiableList();

                foreach (var guildSetup in notifiableList)
                {
                    var guild   = ShardedClient.GetGuild(guildSetup.Item1.GuildId);
                    var channel = guild?.GetTextChannel(guildSetup.Item1.BirthdayChannelId);
                    if (channel == null)
                    {
                        continue;
                    }

                    bool?manageRoles = guild.GetUser(ShardedClient.CurrentUser.Id)?.GuildPermissions.ManageRoles;

                    SocketRole birthdayRole = null;
                    if (guildSetup.Item1.BirthdayRole != 0)
                    {
                        birthdayRole = guild.GetRole(guildSetup.Item1.BirthdayRole);
                    }

                    if (birthdayRole == null)
                    {
                        continue;
                    }

                    var userList = new List <string>();
                    foreach (var person in guildSetup.Item2)
                    {
                        string mentionContent = "";
                        int    age            = person.Age();
                        var    user           = guild.GetUser(person.UserId);
                        if (user.Roles.Contains(birthdayRole))
                        {
                            continue;
                        }

                        mentionContent = age > 0 ? $"{user.Mention} | Age: {age}" : user.Mention;

                        userList.Add(mentionContent);

                        if (manageRoles == true)
                        {
                            try
                            {
                                await user.AddRoleAsync(birthdayRole);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.ToString());
                            }
                        }
                    }

                    if (userList.Any(x => !string.IsNullOrEmpty(x)))
                    {
                        await channel.SendMessageAsync("Today's Current birthdays are: \n" + string.Join("\n", userList.Where(x => !string.IsNullOrEmpty(x))));
                    }

                    if (manageRoles == true)
                    {
                        foreach (var member in birthdayRole.Members)
                        {
                            if (guildSetup.Item2.All(x => x.UserId != member.Id))
                            {
                                try
                                {
                                    await member.RemoveRoleAsync(birthdayRole);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.ToString());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #20
0
 public Birthday(BirthdayService birthdayService, HelpService helpService)
 {
     BirthdayService = birthdayService;
     HelpService     = helpService;
 }