Exemple #1
0
        private async Task CreateCalendarEvents(LtiParamDTO param, LmsCourseMeeting meeting)
        {
            if (_calendarEventService == null)
            {
                return;
            }


            foreach (var session in meeting.MeetingSessions)
            {
                var eventDto = new LmsCalendarEventDTO
                {
                    StartAt = session.StartDate,
                    EndAt   = session.EndDate,
                    Title   = session.Name
                };

                var lmsSettings = _license.GetLMSSettings(Settings);

                try
                {
                    LmsCalendarEventDTO lmsCalendarEvent =
                        await _calendarEventService.CreateEvent(param.course_id.ToString(), lmsSettings, eventDto);

                    session.LmsCalendarEventId = lmsCalendarEvent?.Id;
                }
                catch (Exception e)
                {
                    _logger.Error(e.Message);
                    return;
                }
            }
        }
Exemple #2
0
        public async Task <IEnumerable <MeetingSessionDTO> > SaveEventsAsync(int meetingId, IEnumerable <MeetingSessionDTO> eventDtos, LtiParamDTO param, ILmsLicense license)
        {
            List <MeetingSessionDTO>          result   = eventDtos.ToList();
            IEnumerable <LiveSessionResponse> sessions = await _api.CreateSessions(param.course_id.ToString(),
                                                                                   eventDtos.Select(x => new LiveSessionRequest {
                start_at = x.StartDate, end_at = x.EndDate, notes = x.Summary
            }), license.GetLMSSettings(_settings));

            var users = await _api.GetCourseUsers(param.course_id.ToString(), license.GetLMSSettings(_settings));

            foreach (var session in sessions)
            {
                var webConf = await _api.UpdateSessionWebconference(param.course_id.ToString(), session.id,
                                                                    new WebConferenceRequest
                {
                    provider       = "Other",
                    other_provider = "eSyncTraining AC",
                    meeting_url    = $"{_settings.BasePath.TrimEnd('/')}/lti/meeting/join?session={"123"}&meetingId={meetingId}"
                }, license.GetLMSSettings(_settings));

                var publishedSession = await _api.PublishSession(param.course_id.ToString(), session.id, license.GetLMSSettings(_settings));

                foreach (var user in users)
                {
                    var userRegistered = await _api.RegisterUserToSession(session.id, user.Id, license.GetLMSSettings(_settings));
                }

                //var evt = result.FirstOrDefault(x => session.start_at.Value == x.StartDate);
                //if (evt != null)
                //{
                //    evt.EventId = session.id.ToString();
                //}
            }

            //return result;

            return(sessions.Select(ConvertToDto));
        }
Exemple #3
0
        public async Task <IEnumerable <string> > DeleteEventsAsync(IEnumerable <string> eventIds, LtiParamDTO param, ILmsLicense license)
        {
            List <string> ids = new List <string>();

            foreach (var id in eventIds)
            {
                var result = await _api.DeleteSession(param.course_id.ToString(), id, license.GetLMSSettings(_settings));

                if (result)
                {
                    ids.Add(id);
                }
            }

            return(ids);
            //var events = eventIds.Select(x => new SakaiEventDelete()
            //{
            //    SakaiId = x
            //});

            //var apiParam = new SakaiApiDeleteObject
            //{
            //    Params = new SakaiParams { LtiMessageType = "egc-delete-calendars" },
            //    Calendars = new SakaiCalendarDelete[]
            //    {
            //        new SakaiCalendarDelete()
            //        {
            //            SiteId = param.context_id,
            //            CalendarReference = "main",
            //            Events = events.ToArray()
            //        }
            //    }
            //};

            //var json = JsonConvert.SerializeObject(apiParam);
            //string resp = await _httpClientWrapper.UploadJsonStringAsync(GetApiUrl(param), json);

            //return resp.Replace("\n", String.Empty).Replace("\r", String.Empty).Split(',');
        }
Exemple #4
0
        private async Task CreateAnnouncement(
            LmsMeetingType meetingType,
            ILmsLicense lmsCompany,
            ILtiParam param,
            MeetingDTOInput meetingDto)
        {
            if (!lmsCompany.ShowAnnouncements.GetValueOrDefault() || string.IsNullOrEmpty(param.context_title))
            {
                return;
            }

            var announcementTitle = string.Format(
                "A new {0} room was created for course {1}",
                meetingNames[meetingType],
                param.context_title);
            string announcementMessage = GetAnnouncementMessage(meetingType, meetingDto, param.referer);

            switch (lmsCompany.LmsProviderId)
            {
            case (int)LmsProviderEnum.Canvas:
                var lmsUser = LmsUserModel.GetOneByUserIdAndCompanyLms(param.lms_user_id, lmsCompany.Id).Value;
                var token   = UsersSetup.IsTeacher(param, lmsCompany) && !string.IsNullOrEmpty(lmsUser.Token)
                        ? lmsUser.Token
                        : lmsCompany.AdminUser.Return(a => a.Token, string.Empty);

                await CanvasApi.CreateAnnouncement(
                    lmsCompany.LmsDomain,
                    token,
                    param.course_id,
                    announcementTitle,
                    announcementMessage);

                break;

            case (int)LmsProviderEnum.Blackboard:
                BlackboardApi.CreateAnnouncement(param.course_id.ToString(), param.lms_user_id, lmsCompany.GetLMSSettings(Settings), announcementTitle, announcementMessage);
                break;

            case (int)LmsProviderEnum.AgilixBuzz:
                // string error;
//                    this.dlapApi.CreateAnnouncement(
//                        credentials,
//                        param.course_id,
//                        announcementTitle,
//                        announcementMessage,
//                        out error);
                break;
            }
        }
Exemple #5
0
        public async Task SynchronizeUsers(ILmsLicense lmsCompany, bool syncACUsers, IEnumerable <int> meetingIds = null)
        {
            LmsUserServiceBase service = null;

            if ((LmsProviderEnum)lmsCompany.LmsProviderId == LmsProviderEnum.Brightspace)
            {
                service = IoC.Resolve <LmsUserServiceBase>(LmsProviderEnum.Brightspace.ToString() + "_Sync");
            }
            else
            {
                service = lmsFactory.GetUserService((LmsProviderEnum)lmsCompany.LmsProviderId);
            }

            var acProvider = acAccountService.GetProvider(lmsCompany);
            var meetings   = lmsCompany.LmsCourseMeetings.Where(x =>
                                                                meetingIds == null || meetingIds.Any(m => m == x.Id)).ToList();
            var scoIds          = new HashSet <string>(meetings.Select(x => x.GetMeetingScoId())).ToList();
            var scos            = acProvider.ReportBulkObjects(scoIds).Values;
            var settings        = lmsCompany.Settings.ToList(); //to avoid nhibernate errors
            var groupedMeetings = meetings
                                  .Where(x => scos.Any(s => s.ScoId == x.ScoId))
                                  .GroupBy(y => y.CourseId);
            List <LmsUser> users = lmsCompany.LmsUsers.ToList();//meetingIds == null ? lmsCompany.LmsUsers.ToList() : null;

            object localLockObject = new object();
            Dictionary <string, IEnumerable <LmsUserDTO> > licenseUsers = new Dictionary <string, IEnumerable <LmsUserDTO> >();
//            var input = meetings.Select(x => new Tuple<LmsCourseMeeting, string>(x, x.GetMeetingScoId())).ToList();
            var timer = Stopwatch.StartNew();

//synchronous version
            //var parallelMode = ConfigurationManager.AppSettings["ParallelMode"];
            //if (parallelMode == null || parallelMode != "1")
            //{
            foreach (var groupedMeeting in groupedMeetings)
            {
                var courseId = groupedMeeting.Key;
                var opResult = await service.GetUsers(lmsCompany.GetLMSSettings(_settings), courseId);

                if (opResult.IsSuccess)
                {
                    licenseUsers.Add(courseId, opResult.Data);
                }
                else
                {
                    licenseUsers.Add(courseId, new List <LmsUserDTO>());
                }
            }
            //}
//parallel version
            //else
            //{
            //    Parallel.ForEach<int, Dictionary<int, IEnumerable<LmsUserDTO>>>(
            //        groupedMeetings.Select(x => x.Key),
            //        () => new Dictionary<int, IEnumerable<LmsUserDTO>>(),
            //        (courseId, state, localDictionary) =>
            //        {
            //            var opResult = service.GetUsers(lmsCompany, courseId);
            //            if (opResult.IsSuccess)
            //            {
            //                localDictionary.Add(courseId, opResult.Data);
            //            }
            //            else
            //            {
            //                localDictionary.Add(courseId, new List<LmsUserDTO>());
            //            }

            //            return localDictionary;
            //        },
            //        (finalResult) =>
            //        {
            //            lock (localLockObject)
            //                foreach (var item in finalResult)
            //                {
            //                    licenseUsers.Add(item.Key, item.Value);
            //                }
            //        }
            //    );
            //}
            timer.Stop();
            logger.Warn($"Users from API elapsed seconds:{timer.Elapsed.ToString()}");
            acProvider = acAccountService.GetProvider(lmsCompany); //users retrieve can take more than session timeout

            foreach (var courseGroup in groupedMeetings)
            {
                logger.InfoFormat("Retrieving users for LmsCompanyId={0}, LmsProvider={1}, CourseId={2}; MeetingIds:{3}",
                                  lmsCompany.Id, (LmsProviderEnum)lmsCompany.LmsProviderId, courseGroup.Key, String.Join(",", courseGroup.Select(x => x.Id)));
                try
                {
                    //todo: set extra data param
//                    var opResult = service.GetUsers(lmsCompany, lmsCompany.AdminUser, courseGroup.Key);
//                    if (opResult.IsSuccess)
//                    {
                    var usersCount = licenseUsers[courseGroup.Key].Count();
                    if (usersCount == 0)
                    {
                        //todo: take all users (meeting.Users) and make foreach trying to retrieve
                        logger.WarnFormat("Couldn't retrieve users from API for LmsCompanyId={0}, LmsProvider={1}, CourseId={2}",
                                          lmsCompany.Id, (LmsProviderEnum)lmsCompany.LmsProviderId, courseGroup.Key);
                    }
                    else if (usersCount > Core.Utils.Constants.SyncUsersCountLimit)
                    {
                        logger.WarnFormat("Course contains {0} users that is more than limit for users sync ({1}). LmsCompanyId={2}, LmsProvider={3}, CourseId={4}",
                                          usersCount, Core.Utils.Constants.SyncUsersCountLimit, lmsCompany.Id, (LmsProviderEnum)lmsCompany.LmsProviderId, courseGroup.Key);
                        foreach (var meeting in courseGroup)
                        {
                            if (!meeting.EnableDynamicProvisioning)
                            {
                                meeting.EnableDynamicProvisioning = true;
                                lmsCourseMeetingModel.RegisterSave(meeting, true);
                            }
                        }
                    }
                    else
                    {
                        var licenseUsersVar = licenseUsers[courseGroup.Key].ToList();

                        // var userIds = licenseUsersVar.Select(x => x.LtiId ?? x.Id);
//                        logger.InfoFormat("API user ids: {0}", String.Join(",", userIds));
                        var existedDbUsers = users.Where(x => licenseUsersVar.Any(u => (u.LtiId ?? u.Id) == x.UserId));
                        //?? lmsUserModel.GetByUserIdAndCompanyLms(userIds.ToArray(), lmsCompany.Id);
                        var existedUserIds = existedDbUsers.Select(x => x.Id).ToList();

                        var newUsers = UpdateDbUsers(licenseUsers[courseGroup.Key].ToList(), lmsCompany, users, acProvider);
                        users.AddRange(newUsers);
                        // merge results;
                        foreach (var meeting in courseGroup)
                        {
                            if (lmsCompany.GetSetting <bool>(LmsLicenseSettingNames.UseCourseSections))
                            {
                                licenseUsersVar =
                                    licenseUsers[courseGroup.Key].Where(
                                        x => x.SectionIds == null || x.SectionIds.Any(s => meeting.CourseSections.Any(cs => cs.LmsId == s))).ToList();
                                existedDbUsers =
                                    users.Where(x => licenseUsersVar.Any(u => (u.LtiId ?? u.Id) == x.UserId));
                                existedUserIds = existedDbUsers.Select(x => x.Id).ToList();
                                newUsers       = new List <LmsUser>();
                            }

                            //sync DB roles
                            foreach (var dbRole in meeting.MeetingRoles)
                            {
                                var lmsUser =
                                    licenseUsersVar.FirstOrDefault(x => (x.LtiId ?? x.Id) == dbRole.User.UserId);
                                if (lmsUser != null)
                                {
                                    dbRole.LmsRole = lmsUser.LmsRole;
                                }
                            }

                            var userRolesToDelete =
                                meeting.MeetingRoles.Where(x => existedUserIds.All(u => u != x.User.Id)).ToList();

                            var usersToAddToMeeting = new List <LmsUser>(newUsers);
                            usersToAddToMeeting.AddRange(
                                existedDbUsers.Where(
                                    x => meeting.MeetingRoles.Select(mr => mr.User).All(u => u.Id != x.Id)).ToList());

                            if (userRolesToDelete.Any())
                            {
                                logger.InfoFormat(
                                    "LmsUser ids to delete from meetingId={0}, courseId={1}: {2}",
                                    meeting.Id, meeting.CourseId,
                                    String.Join(", ", userRolesToDelete.Select(x => x.User.Id)));
                            }
                            if (usersToAddToMeeting.Any())
                            {
                                logger.InfoFormat(
                                    "LmsUser ids to add to meetingId={0}, courseId={1}: {2}",
                                    meeting.Id, meeting.CourseId,
                                    String.Join(", ", usersToAddToMeeting.Select(x => x.UserId)));
                            }

                            userRolesToDelete.ForEach(x => meeting.MeetingRoles.Remove(x));
                            usersToAddToMeeting.ForEach(x => meeting.MeetingRoles.Add(new LmsUserMeetingRole
                            {
                                Meeting = meeting,
                                User    = x,
                                LmsRole =
                                    licenseUsers[courseGroup.Key].First(dto => x.UserId == (dto.LtiId ?? dto.Id))
                                    .LmsRole
                            }));
                            meeting.EnableDynamicProvisioning = false;
                            lmsCourseMeetingModel.RegisterSave(meeting, true);
                            // todo: optimize condition, probably refresh roles not for all users
                            var dbPrincipalIds = new HashSet <string>(
                                meeting.MeetingRoles.Where(x => x.User.PrincipalId != null).Select(x => x.User.PrincipalId));
                            List <MeetingPermissionInfo> enrollments = usersSetup.GetMeetingAttendees(acProvider, meeting.GetMeetingScoId());
                            var acPrincipalIds = new HashSet <string>(enrollments.Select(e => e.PrincipalId));

                            if (syncACUsers &&
                                (meeting.LmsMeetingType == (int)LmsMeetingType.Meeting || meeting.LmsMeetingType == (int)LmsMeetingType.VirtualClassroom || meeting.LmsMeetingType == (int)LmsMeetingType.Seminar)
                                &&
                                (dbPrincipalIds.Count != meeting.MeetingRoles.Count ||
                                 dbPrincipalIds.Count != acPrincipalIds.Count ||
                                 dbPrincipalIds.Any(x => acPrincipalIds.All(p => p != x))))
                            {
                                logger.InfoFormat("Synchronizing AC for meetingId={0}, courseId={1}", meeting.Id, meeting.CourseId);
                                UpdateACRoles(lmsCompany, meeting, acProvider, enrollments);
                            }
                        }
                    }
//                    }
                }

                catch (Exception e)
                {
                    var message = String.Format(
                        $"Error happened when tried to update users for LmsCompany with id={lmsCompany.Id}, lmsCourseId={courseGroup.Key}");
                    logger.Error(message, e);
                }
            }
        }
Exemple #6
0
        public async Task <IEnumerable <MeetingSessionDTO> > GetSessions(int meetingId)
        {
            var sessions = await _api.ListSessions(_param.course_id.ToString(), _license.GetLMSSettings(null)); //todo: settings parameter

            return(sessions.Select(ConvertToDto));
        }