Example #1
0
 public SpecEngGroupsRule(string name, Func <string, string, bool> academicAndEngNamesFunc) : base(name, (g1, g2) => true)
 {
     CheckFunc = (first, second) =>
     {
         IScheduleGroup academic = null;
         IScheduleGroup eng      = null;
         if (first.GType == ScheduleGroupType.Academic)
         {
             academic = first;
         }
         if (first.GType == ScheduleGroupType.Eng)
         {
             eng = first;
         }
         if (second.GType == ScheduleGroupType.Academic)
         {
             academic = second;
         }
         if (second.GType == ScheduleGroupType.Eng)
         {
             eng = second;
         }
         if (eng == null || academic == null)
         {
             return(false);
         }
         return(academicAndEngNamesFunc(academic.Name.Trim().ToLowerInvariant(),
                                        eng.Name.Trim().ToLowerInvariant()));
     };
 }
        public Task <bool> UpdateScheduleAsync(IScheduleGroup targetGroup, IScheduleElem scheduleRoot)
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    string key = KeyFromGroup(targetGroup);
                    storage.AddOrUpdate(key,
                                        //if new key
                                        keyS =>
                    {
                        switch (scheduleRoot.Level)
                        {
                        case ScheduleElemLevel.Week:
                            return ((IScheduleElem)scheduleRoot.Clone()).Elems;

                        case ScheduleElemLevel.Day:
                            return new List <IScheduleElem>()
                            {
                                scheduleRoot
                            };

                        default:
                            throw new ArgumentOutOfRangeException(
                                $"Db cannot add root with level {scheduleRoot.Level.ToString()}");
                        }
                    },
                                        //if already exists
                                        (keyS, days) =>
                    {
                        switch (scheduleRoot.Level)
                        {
                        case ScheduleElemLevel.Week:
                            return ((IScheduleElem)scheduleRoot.Clone()).Elems;

                        case ScheduleElemLevel.Day:
                            var casted = (Day)scheduleRoot;
                            var toUpd = days.OfType <Day>().FirstOrDefault(d => d.DayOfWeek == casted.DayOfWeek);
                            if (toUpd != null)
                            {
                                days.Remove(toUpd);
                            }
                            days.Add((IScheduleElem)casted.Clone());
                            return days;

                        default:
                            throw new ArgumentOutOfRangeException(
                                $"Db cannot update root with level {scheduleRoot.Level.ToString()}");
                        }
                    });
                    return true;
                }
                catch (ArgumentOutOfRangeException e)
                {
                    //todo: logger
                    return false;
                }
            }));
        }
Example #3
0
 public bool IsGroupPresent(IScheduleGroup group)
 {
     if (group != null)
     {
         return(backup.TryGetValue(group.Name, out IScheduleGroup value) && value.Equals(group));
     }
     throw new ArgumentNullException("group");
 }
Example #4
0
 public bool TryGetCorrectGroup(IScheduleGroup sample, out IScheduleGroup correct)
 {
     if (sample != null)
     {
         return(allGroups.TryGetValue(sample.Name, out correct));
     }
     throw new ArgumentNullException("sample");
 }
Example #5
0
 public bool Equals(IScheduleGroup obj)
 {
     if (obj.GetType() != this.GetType())
     {
         return(false);
     }
     return(Equals((ScheduleGroup)obj));
 }
Example #6
0
        protected IScheduleGroup GetFirstMatchAllowed(IScheduleGroup academic, Update update)
        {
            var allowed = Scheduler.GroupsMonitor
                          .GetAllowedGroups(GroupType, academic)
                          ?.ToList() ?? new List <IScheduleGroup>();

            return(allowed?.FirstOrDefault(g => g.GType == GroupType && g.Name.ToLowerInvariant()
                                           .StartsWith(update.Message.Text.ToLowerInvariant()
                                                       .Trim())));
        }
Example #7
0
 public Task <ISchedule> GetScheduleForAsync(IScheduleGroup @group, ScheduleRequiredFor period)
 {
     if (period != ScheduleRequiredFor.Week)
     {
         return(GetScheduleForAsync(new[] { group }, DayOfWeekFromPeriod(period)));
     }
     else
     {
         return(GetWeekScheduleForAsync(new[] { group }));
     }
 }
        private bool HasConflictsWithMemory(IScheduleGroup group, Dictionary <ScheduleGroupType, IScheduleGroup> memory)
        {
            if (group != null)
            {
                if (!memory.ContainsKey(group.GType))
                {
                    memory.Add(group.GType, group);
                    return(false);
                }

                return(!group.Equals(memory[group.GType]));
            }

            throw new ArgumentNullException("Name for group cannot be null");
        }
 public Task RemoveScheduleAsync(IScheduleGroup targetGroup, DayOfWeek day)
 {
     return(Task.Run(() =>
     {
         string key = KeyFromGroup(targetGroup);
         if (storage.TryGetValue(key, out var days))
         {
             var toRemove = days.OfType <Day>().FirstOrDefault(d => d.DayOfWeek == day);
             if (toRemove != null)
             {
                 days.Remove(toRemove);
             }
         }
     }));
 }
Example #10
0
            public CommonEngGroupsRule(string name, string engEndsWith, string engContains, string academicStarts, string academicRegexp) : base(name, (g1, g2) => true)
            {
                CheckFunc = (first, second) =>
                {
                    IScheduleGroup academic = null;
                    IScheduleGroup eng      = null;
                    if (first.GType == ScheduleGroupType.Academic)
                    {
                        academic = first;
                    }
                    if (first.GType == ScheduleGroupType.Eng)
                    {
                        eng = first;
                    }
                    if (second.GType == ScheduleGroupType.Academic)
                    {
                        academic = second;
                    }
                    if (second.GType == ScheduleGroupType.Eng)
                    {
                        eng = second;
                    }
                    if (eng == null || academic == null)
                    {
                        return(false);
                    }
                    if (eng.Name.ToLowerInvariant().EndsWith(engEndsWith) &&
                        eng.Name.ToLowerInvariant().Contains(engContains))
                    {
                        var trimmed = (academic.Name.Trim());
                        if (trimmed.StartsWith(academicStarts) && Regex.IsMatch(trimmed, academicRegexp))
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    return(false);
                };
            }
Example #11
0
            public CommonTypedRule(string name, ScheduleGroupType secondType,
                                   string academicStarts, string targetCourse, string flow = "1",
                                   string academicRegexp = null) : base(name, (g1, g2) => true)
            {
                CheckFunc = (first, second) =>
                {
                    IScheduleGroup academic = null;
                    IScheduleGroup typed    = null;
                    if (first.GType == ScheduleGroupType.Academic)
                    {
                        academic = first;
                    }
                    if (first.GType == secondType)
                    {
                        typed = first;
                    }
                    if (second.GType == ScheduleGroupType.Academic)
                    {
                        academic = second;
                    }
                    if (second.GType == secondType)
                    {
                        typed = second;
                    }
                    if (typed == null || academic == null)
                    {
                        return(false);
                    }
                    if (typed.Name.ToLowerInvariant().EndsWith(flow) &&
                        typed.Name.ToLowerInvariant().Contains(targetCourse))
                    {
                        var trimmed = (academic.Name.Trim());
                        return(trimmed.StartsWith(academicStarts) && (academicRegexp == null || Regex.IsMatch(trimmed, academicRegexp)));
                    }

                    return(false);
                };
            }
Example #12
0
        public Task <bool> TryAddGroupToChatAsync(IScheduleGroup scheduleGroup, Chat chat)
        {
            return(Task.Run(() =>
            {
                if (service.GroupsMonitor.TryGetCorrectGroup(scheduleGroup, out var groupFromStorage))
                {
                    AddGroupToUserInMemory(chat.Id, groupFromStorage);

                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            lock (path)
                            {
                                var xdoc = XDocument.Load(path);
                                var user = xdoc.Element("users")
                                           ?.Elements("user")
                                           .FirstOrDefault(u => u.Element("chatId")?.Value == chat.Id.ToString());
                                if (user == null)
                                {
                                    xdoc.Element("users")?.Add(new XElement("user",
                                                                            new XAttribute("name", chat.FirstName),
                                                                            new XElement("chatId", chat.Id.ToString()), new XElement("groups")));
                                }
                                var group = user?.Element("groups")
                                            ?.Elements("group").FirstOrDefault(g =>
                                                                               g.Attribute("type")?.Value == groupFromStorage.GType.ToString());
                                if (group == null)
                                {
                                    xdoc.Element("users")
                                    ?.Elements("user")
                                    .FirstOrDefault(u => u.Element("chatId")?.Value == chat.Id.ToString())
                                    ?.Element("groups")
                                    ?.Add(new XElement("group",
                                                       new XAttribute("type", groupFromStorage.GType.ToString()),
                                                       new XAttribute("name", groupFromStorage.Name)));
                                }
                                else
                                {
                                    if (groupFromStorage.GType == ScheduleGroupType.Academic &&
                                        group.Attribute("name").Value
                                        .Substring(0, group.Attribute("name").Value.Length - 1) !=
                                        groupFromStorage.Name.Substring(0, groupFromStorage.Name.Length - 1))
                                    {
                                        xdoc.Element("users").Elements("user")
                                        .FirstOrDefault(u => u.Element("chatId").Value == chat.Id.ToString())
                                        .Element("groups").Elements("group")
                                        .Where(g => g.Attribute("type").Value != "Academic").Remove();
                                    }

                                    xdoc.Element("users").Elements("user")
                                    .FirstOrDefault(u => u.Element("chatId").Value == chat.Id.ToString())
                                    .Element("groups").Elements("group").FirstOrDefault(g =>
                                                                                        g.Attribute("type").Value == groupFromStorage.GType.ToString())
                                    .Attribute("name")
                                    .Value = groupFromStorage.Name;
                                }

                                xdoc.Save(path);
                            }
                        }
                        catch (Exception e)
                        {
                            logger?.LogError(e, "Exc");
                        }
                    }, TaskCreationOptions.RunContinuationsAsynchronously).ContinueWith(async t => await t)
                    .ConfigureAwait(false);

                    return true;
                }

                return false;
            }));
        }
 private string KeyFromGroup(IScheduleGroup group)
 {
     return(group.GType.ToString() + "^" + group.Name);
 }
Example #14
0
 public Task <ISchedule> GetScheduleForAsync(IScheduleGroup @group, DayOfWeek day)
 {
     return(GetScheduleForAsync(new[] { group }, day));
 }
Example #15
0
 public virtual bool AreCompatible(IScheduleGroup first, IScheduleGroup second)
 {
     return(CheckFunc.Invoke(first, second));
 }
Example #16
0
 public override bool AreCompatible(IScheduleGroup first, IScheduleGroup second)
 {
     return(checkFuncWithStorage.Invoke(storage, first, second));
 }
Example #17
0
 public IEnumerable <IScheduleGroup> GetAllowedGroups(ScheduleGroupType ofType, IScheduleGroup target)
 {
     return(allGroups.Values.Where(g =>
                                   g.GType == ofType && (rules?.Any(rule => rule.AreCompatible(target, g)) ?? true))
            .ToList());
 }
Example #18
0
 public bool TryFindGroupByName(string name, out IScheduleGroup resultGroup)
 {
     return(allGroups.TryGetValue(name, out resultGroup));
 }
Example #19
0
        private void AddGroupToUserInMemory(long chatId, IScheduleGroup group)
        {
            var                    clearOther  = group.Name.StartsWith("11-");
            IScheduleGroup         duplicate   = null;
            IList <IScheduleGroup> otherGroups = null;

            usersGroups.AddOrUpdate(chatId, new List <IScheduleGroup> {
                group
            }, (id, oldList) =>
            {
                duplicate = oldList.FirstOrDefault(g =>
                                                   g.GType == group.GType);
                if (duplicate != null)
                {
                    if (!duplicate.Equals(group))
                    {
                        oldList.Remove(duplicate);
                        if (clearOther)
                        {
                            otherGroups = oldList.ToList();
                            oldList.Clear();
                        }

                        oldList.Add(group);
                    }
                }
                else
                {
                    oldList.Add(group);
                }

                return(oldList);
            });
            try
            {
                if (!groupToUsers.ContainsKey(group))
                {
                    group.ScheduleChanged += HandleGroupScheduleChanged;
                }
                groupToUsers.AddOrUpdate(group, new List <long> {
                    chatId
                }, (schGroup, oldList) =>
                {
                    if (!oldList.Contains(chatId))
                    {
                        oldList.Add(chatId);
                    }
                    return(oldList);
                });


                if (duplicate != null && !duplicate.Equals(group))
                {
                    RemoveIdFromGroup(duplicate, chatId);
                    if (clearOther && otherGroups != null && otherGroups.Any())
                    {
                        foreach (var otherGroup in otherGroups)
                        {
                            RemoveIdFromGroup(otherGroup, chatId);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger?.LogError(e, "Exc");
            }

            void RemoveIdFromGroup(IScheduleGroup rgroup, long id)
            {
                if (groupToUsers.TryGetValue(rgroup, out var list))
                {
                    list.Remove(id);
                    if (!list.Any())
                    {
                        groupToUsers.Remove(rgroup, out list);
                    }
                }

                if (!groupToUsers.ContainsKey(rgroup))
                {
                    rgroup.ScheduleChanged -= HandleGroupScheduleChanged;
                }
            }
        }