Beispiel #1
0
        public async Task TestCallUpdateCalendarAsync()
        {
            CalendarApi calendarApi = new CalendarApi(graphClient);
            bool        result      = await calendarApi.CallUpdateCalendarAsync();

            Assert.IsTrue(result);
        }
Beispiel #2
0
        public static async Task Handler(DiscordSocketClient client, CalendarApi calendar, IDbService db, SocketMessage message)
        {
            var guildConfig = db.Guilds.FirstOrDefault(g => g.Id == SpecialGuilds.CrystalExploratoryMissions);

            if (guildConfig == null)
            {
                Log.Error("No guild configuration found for the default guild!");
                return;
            }

            var guild = client.GetGuild(guildConfig.Id);

            var prefix = db.Config.Prefix;

            if (message.Content == null || !message.Content.StartsWith(prefix + "announce"))
            {
                return;
            }

            Log.Information("Announcement message being edited.");

            var outputChannel = ScheduleUtils.GetOutputChannel(guildConfig, guild, message.Channel);

            if (outputChannel == null)
            {
                Log.Information("Could not get output channel; aborting.");
                return;
            }

            var args = message.Content[(message.Content.IndexOf(' ') + 1)..];
Beispiel #3
0
        //public async Task<int> CancelAppointment(Guid appointmentId)
        //{
        //    try
        //    {
        //        int count = 0;
        //        Guid requestId = appointmentId;
        //        string userId = string.Empty;
        //        var value = Convert.ToInt32(_context.Configurations.FirstOrDefault(r => r.Name == "NumberOfDates").Value);
        //        var appoinments = _context.Appoinments.Where(r => r.AppoinmentId.Equals(appointmentId));
        //        foreach (var apoin in appoinments)
        //        {
        //            var allAppoinments = _context.Appoinments.Where(r => r.RequestId.Equals(apoin.RequestId)).ToList();
        //            foreach (var all in allAppoinments)
        //            {
        //                count = count + 1;
        //                requestId = all.RequestId;
        //            }
        //        }
        //        if (count == value)
        //        {
        //            /* CANCELAR Appoinments */
        //            var apps = _context.Appoinments.Find(appointmentId);
        //            var reqStas = new List<RequestStatu>();
        //            apps.IsAttended = false;
        //            apps.IsCancelled = true;
        //            //_context.Appoinments.AddOrUpdate(apps);

        //            /* CANCELAR RequestStatus (Cancelar los IsCurrentStatus = 1 y Agregar nueva fila) */
        //            var selectRequestStatus = _context.RequestStatus.Where(r => r.RequestId == requestId && r.IsCurrentStatus == true);
        //            foreach (var query in selectRequestStatus)
        //            {
        //                query.IsCurrentStatus = false;
        //                //userId = query.UserId;
        //            }
        //            var reqStatus = new RequestStatu
        //            {
        //                RequestId = requestId,
        //                StatusId = 410,
        //                Date = DateTime.Now,
        //                IsCurrentStatus = true,
        //                //UserId = userId,
        //                Observations = "",
        //                //ElapsedDays = 0,
        //                //ElapsedWorkDays = 0,
        //                //Data = null
        //            };

        //            Request req = new Request();
        //            req.RequestId = reqStatus.RequestId;
        //            req.IsComplete = false;
        //            reqStas.Add(reqStatus);
        //          //  _context.Requests.AddOrUpdate(req);
        //            _context.RequestStatus.AddOrUpdate(reqStatus);
        //        }
        //        else
        //        {
        //            var app = _context.Appoinments.Find(appointmentId);
        //            app.IsAttended = false;
        //            app.IsCancelled = true;
        //            _context.Appoinments.AddOrUpdate(app);
        //        }
        //        return await _context.SaveChangesAsync();
        //    }
        //    catch (Exception exception)
        //    {
        //        throw exception;
        //    }
        //}


        public async Task <CalendarApi> GetCalendarByMonthAndDelegation(int delegationId, DateTime montYear)


        {
            try
            {
                var calendar = new CalendarApi {
                    Days = new DayCalendar[6, 7]
                };
                var initDate = new DateTime(montYear.Year, montYear.Month, 1, 0, 0, 0);
                var init     = new DateTime(montYear.Year, montYear.Month, 1, 0, 0, 0);
                var day      = ConverterData.GetWeekEnumDay(init.DayOfWeek);
                var space    = 0;
                var occu     = 0;

                for (var i = 0; i < 6; i++)
                {
                    for (var j = 0; j < 7; j++)
                    {
                        if (i == 0)
                        {
                            if (j + 1 >= (int)day)
                            {
                                init  = j + 1 == (int)day ? init : init.AddDays(1);
                                space = GetFreeSpace(init, delegationId);
                                occu  = GetOccupiedSpace(init, delegationId);
                                calendar.Days[i, j] = FillAvalitiyAndRate(space, occu, init);
                            }
                            else
                            {
                                calendar.Days[i, j] = FillAvalitiyAndRate(space, occu, null);
                            }
                        }
                        else
                        {
                            if (init.AddDays(1).Month == initDate.Month)
                            {
                                init  = init.AddDays(1);
                                space = GetFreeSpace(init, delegationId);
                                occu  = GetOccupiedSpace(init, delegationId);
                                calendar.Days[i, j] = FillAvalitiyAndRate(space, occu, init);
                            }
                            else
                            {
                                calendar.Days[i, j] = FillAvalitiyAndRate(space, occu, null);
                            }
                        }
                    }
                }
                return(calendar);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
Beispiel #4
0
        private static async Task <MiniEvent> FindEvent(CalendarApi calendar, string calendarClass, string title, DateTime startTime)
        {
            var tzi = TimeZoneInfo.FindSystemTimeZoneById(Util.PstIdString());
            var events = await calendar.GetEvents(calendarClass);

            return(events.FirstOrDefault(e =>
            {
                var eventStartTime = XmlConvert.ToDateTime(e.StartTime, XmlDateTimeSerializationMode.Utc).AddHours(tzi.BaseUtcOffset.Hours);
                return e.Title == title && eventStartTime == startTime;
            }));
        }
Beispiel #5
0
        public void CreateEvent()
        {
            var startTime = DateTime.Now.AddHours(2);
            var duration  = new TimeSpan(0, 3, 0, 0);
            var @event    = CalendarApi.CreateEvent(CalendarId, "test summary", "test description", startTime, duration).Result;

            @event.ShouldNotBeNull();
            var events    = CalendarApi.GetEvents(CalendarId);
            var theEvents = events.Result;
            var theEvent  = theEvents.Find(id => id.Id == @event.Id);

            theEvent.Id.ShouldEqual(@event.Id);
            theEvent.Description.ShouldEqual(@event.Description);
            theEvent.Summary.ShouldEqual(@event.Summary);
            CalendarApi.DeleteEvent(CalendarId, @event.Id);
        }
Beispiel #6
0
        public void Get10Events()
        {
            var numberOfEvents = CalendarApi.GetEvents(CalendarId).Result;

            numberOfEvents.Count.ShouldBeGreaterThanOrEqualTo(1);
        }
Beispiel #7
0
        public void GetNumberOfCalendars()
        {
            int numberOfCalendars = CalendarApi.GetNumberOfCalendars().Result;

            numberOfCalendars.ShouldBeGreaterThanOrEqualTo(1);
        }
Beispiel #8
0
        public static async Task Handler(DiscordSocketClient client, CalendarApi calendar, DbService db, SocketMessage message)
        {
            var guildConfig = db.Guilds.FirstOrDefault(g => g.Id == SpecialGuilds.CrystalExploratoryMissions);

            if (guildConfig == null)
            {
                Log.Error("No guild configuration found for the default guild!");
                return;
            }

            var guild = client.GetGuild(guildConfig.Id);

            var prefix = db.Config.Prefix;

            if (message.Content == null || !message.Content.StartsWith(prefix + "announce"))
            {
                return;
            }

            Log.Information("Announcement message being edited.");

            var outputChannel = GetOutputChannel(guildConfig, guild, message.Channel);

            if (outputChannel == null)
            {
                Log.Information("Could not get output channel; aborting.");
                return;
            }

            var args = message.Content.Substring(message.Content.IndexOf(' ') + 1);

            var splitIndex = args.IndexOf("|", StringComparison.Ordinal);

            if (splitIndex == -1)
            {
                await message.Channel.SendMessageAsync(
                    $"{message.Author.Mention}, please provide parameters with that command.\n" +
                    "A well-formed command would look something like:\n" +
                    $"`{prefix}announce 5:00PM | This is a fancy description!`");

                return;
            }

            var parameters         = args.Substring(0, splitIndex).Trim();
            var description        = args.Substring(splitIndex + 1).Trim();
            var trimmedDescription = description.Substring(0, Math.Min(1700, description.Length));

            if (trimmedDescription.Length != description.Length)
            {
                trimmedDescription += "...";
            }

            var time = Util.GetDateTime(parameters);

            if (time < DateTime.Now)
            {
                await message.Channel.SendMessageAsync("You cannot announce an event in the past!");

                return;
            }

            var tzi     = TimeZoneInfo.FindSystemTimeZoneById(Util.PstIdString());
            var tzAbbrs = TZNames.GetAbbreviationsForTimeZone(tzi.Id, "en-US");
            var tzAbbr  = tzi.IsDaylightSavingTime(DateTime.Now) ? tzAbbrs.Daylight : tzAbbrs.Standard;

#if DEBUG
            var @event = await FindEvent(calendar, "drs", message.Author.ToString(), time);
#else
            var calendarCode = GetCalendarCode(guildConfig, outputChannel.Id);
            var @event       = await FindEvent(calendar, calendarCode, message.Author.ToString(), time);
#endif

            if (@event != null)
            {
#if DEBUG
                await calendar.UpdateEvent("drs", new MiniEvent
#else
                await calendar.UpdateEvent(calendarCode, new MiniEvent
#endif
                {
                    Title       = message.Author.ToString(),
                    Description = description,
                    StartTime   = XmlConvert.ToString(time.AddHours(-tzi.BaseUtcOffset.Hours), XmlDateTimeSerializationMode.Utc),
                    ID          = @event.ID,
                });

                Log.Information("Updated calendar entry.");
            }

            var(embedMessage, embed) = await FindAnnouncement(outputChannel, message.Id);

            var lines            = embed.Description.Split('\n');
            var messageLinkLine  = lines.LastOrDefault(l => l.StartsWith("Message Link: https://discordapp.com/channels/"));
            var calendarLinkLine = lines.LastOrDefault(l => l.StartsWith("[Copy to Google Calendar]"));
            await embedMessage.ModifyAsync(props =>
            {
                props.Embed = embed
                              .ToEmbedBuilder()
                              .WithTimestamp(time.AddHours(-tzi.BaseUtcOffset.Hours))
                              .WithTitle($"Event scheduled by {message.Author} on {time.DayOfWeek} at {time.ToShortTimeString()} ({tzAbbr})!")
                              .WithDescription(trimmedDescription + (calendarLinkLine != null
                        ? $"\n\n{calendarLinkLine}"
                        : "") + (messageLinkLine != null
                        ? $"\n{messageLinkLine}"
                        : ""))
                              .Build();
            });

            Log.Information("Updated announcement embed.");
        }