Merge pull request #2722 from dpalou/MOBILE-3638

Mobile 3638
main
Dani Palou 2021-04-20 09:13:21 +02:00 committed by GitHub
commit 6a846488ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 2819 additions and 4 deletions

View File

@ -3,7 +3,7 @@
<ion-title>{{ 'addon.messages.groupinfo' | translate }}</ion-title>
<ion-buttons slot="end">
<ion-button (click)="closeModal()" [attr.aria-label]="'core.close' | translate">
<ion-icon name="close" slot="icon-only"></ion-icon>
<ion-icon name="fas-times" slot="icon-only"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>

View File

@ -1,6 +1,6 @@
:host {
ion-content {
background-color: var(--background-lighter);
--background: var(--background-lighter);
&::part(scroll) {
padding-bottom: 0 !important;

View File

@ -0,0 +1,81 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CoreSharedModule } from '@/core/shared.module';
import { AddonModChatComponentsModule } from './components/components.module';
import { AddonModChatIndexPage } from './pages/index/index';
import { AddonModChatChatPage } from './pages/chat/chat';
import { AddonModChatSessionMessagesPage } from './pages/session-messages/session-messages';
import { CoreScreen } from '@services/screen';
import { conditionalRoutes } from '@/app/app-routing.module';
import { AddonModChatSessionsPage } from './pages/sessions/sessions';
const commonRoutes: Routes = [
{
path: ':courseId/:cmId',
component: AddonModChatIndexPage,
},
{
path: ':courseId/:cmId/chat',
component: AddonModChatChatPage,
},
];
const mobileRoutes: Routes = [
...commonRoutes,
{
path: ':courseId/:cmId/sessions',
component: AddonModChatSessionsPage,
},
{
path: ':courseId/:cmId/sessions/:sessionStart/:sessionEnd',
component: AddonModChatSessionMessagesPage,
},
];
const tabletRoutes: Routes = [
...commonRoutes,
{
path: ':courseId/:cmId/sessions',
component: AddonModChatSessionsPage,
children: [
{
path: ':sessionStart/:sessionEnd',
component: AddonModChatSessionMessagesPage,
},
],
},
];
const routes: Routes = [
...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile),
...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet),
];
@NgModule({
imports: [
RouterModule.forChild(routes),
CoreSharedModule,
AddonModChatComponentsModule,
],
declarations: [
AddonModChatIndexPage,
AddonModChatChatPage,
AddonModChatSessionsPage,
AddonModChatSessionMessagesPage,
],
})
export class AddonModChatLazyModule {}

View File

@ -0,0 +1,60 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { APP_INITIALIZER, NgModule, Type } from '@angular/core';
import { Routes } from '@angular/router';
import { CoreContentLinksDelegate } from '@features/contentlinks/services/contentlinks-delegate';
import { CoreCourseModuleDelegate } from '@features/course/services/module-delegate';
import { CoreCourseModulePrefetchDelegate } from '@features/course/services/module-prefetch-delegate';
import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-routing.module';
import { AddonModChatComponentsModule } from './components/components.module';
import { AddonModChatProvider } from './services/chat';
import { AddonModChatHelperProvider } from './services/chat-helper';
import { AddonModChatIndexLinkHandler } from './services/handlers/index-link';
import { AddonModChatListLinkHandler } from './services/handlers/list-link';
import { AddonModChatModuleHandler, AddonModChatModuleHandlerService } from './services/handlers/module';
import { AddonModChatPrefetchHandler } from './services/handlers/prefetch';
export const ADDON_MOD_CHAT_SERVICES: Type<unknown>[] = [
AddonModChatProvider,
AddonModChatHelperProvider,
];
const routes: Routes = [
{
path: AddonModChatModuleHandlerService.PAGE_NAME,
loadChildren: () => import('./chat-lazy.module').then(m => m.AddonModChatLazyModule),
},
];
@NgModule({
imports: [
CoreMainMenuTabRoutingModule.forChild(routes),
AddonModChatComponentsModule,
],
providers: [
{
provide: APP_INITIALIZER,
multi: true,
deps: [],
useFactory: () => () => {
CoreCourseModuleDelegate.registerHandler(AddonModChatModuleHandler.instance);
CoreContentLinksDelegate.registerHandler(AddonModChatIndexLinkHandler.instance);
CoreContentLinksDelegate.registerHandler(AddonModChatListLinkHandler.instance);
CoreCourseModulePrefetchDelegate.registerHandler(AddonModChatPrefetchHandler.instance);
},
},
],
})
export class AddonModChatModule {}

View File

@ -0,0 +1,37 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { NgModule } from '@angular/core';
import { AddonModChatIndexComponent } from './index/index';
import { CoreSharedModule } from '@/core/shared.module';
import { CoreCourseComponentsModule } from '@features/course/components/components.module';
import { AddonModChatUsersModalComponent } from './users-modal/users-modal';
@NgModule({
declarations: [
AddonModChatIndexComponent,
AddonModChatUsersModalComponent,
],
imports: [
CoreSharedModule,
CoreCourseComponentsModule,
],
providers: [
],
exports: [
AddonModChatIndexComponent,
AddonModChatUsersModalComponent,
],
})
export class AddonModChatComponentsModule {}

View File

@ -0,0 +1,48 @@
<!-- Buttons to add to the header. -->
<core-navbar-buttons slot="end">
<core-context-menu>
<core-context-menu-item *ngIf="externalUrl" [priority]="900" [content]="'core.openinbrowser' | translate"
[href]="externalUrl" iconAction="fas-external-link-alt">
</core-context-menu-item>
<core-context-menu-item *ngIf="description" [priority]="800" [content]="'core.moduleintro' | translate"
(action)="expandDescription()" iconAction="fas-arrow-right">
</core-context-menu-item>
<core-context-menu-item *ngIf="blog" [priority]="750" content="{{'addon.blog.blog' | translate}}"
iconAction="far-newspaper" (action)="gotoBlog()">
</core-context-menu-item>
<core-context-menu-item *ngIf="loaded && isOnline" [priority]="700" [content]="'core.refresh' | translate"
(action)="doRefresh(null, $event)" [iconAction]="refreshIcon" [closeOnClick]="false">
</core-context-menu-item>
<core-context-menu-item *ngIf="loaded && hasOffline && isOnline" [priority]="600"
[content]="'core.settings.synchronizenow' | translate" (action)="doRefresh(null, $event, true)" [iconAction]="syncIcon"
[closeOnClick]="false">
</core-context-menu-item>
<core-context-menu-item *ngIf="prefetchStatusIcon" [priority]="500" [content]="prefetchText" (action)="prefetch($event)"
[iconAction]="prefetchStatusIcon" [closeOnClick]="false">
</core-context-menu-item>
</core-context-menu>
</core-navbar-buttons>
<!-- Content. -->
<core-loading [hideUntil]="loaded" class="core-loading-center safe-area-page">
<core-course-module-description [description]="description" [component]="component" [componentId]="componentId"
contextLevel="module" [contextInstanceId]="module.id" [courseId]="courseId">
</core-course-module-description>
<ion-card *ngIf="chatInfo" class="core-info-card">
<ion-item>
<ion-icon name="fas-clock" slot="start"></ion-icon>
<ion-label>{{ 'addon.mod_chat.sessionstart' | translate:{$a: chatInfo} }}</ion-label>
</ion-item>
</ion-card>
<ng-container *ngIf="chat">
<ion-button class="ion-margin" expand="block" color="primary" (click)="enterChat()">
{{ 'addon.mod_chat.enterchat' | translate }}
</ion-button>
<ion-button class="ion-margin" expand="block" color="light" *ngIf="sessionsAvailable" (click)="viewSessions()">
{{ 'addon.mod_chat.viewreport' | translate }}
</ion-button>
</ng-container>
</core-loading>

View File

@ -0,0 +1,130 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, OnInit, Optional } from '@angular/core';
import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component';
import { CoreCourseContentsPage } from '@features/course/pages/contents/contents';
import { CoreCourse } from '@features/course/services/course';
import { IonContent } from '@ionic/angular';
import { CoreNavigator } from '@services/navigator';
import { CoreTimeUtils } from '@services/utils/time';
import { AddonModChat, AddonModChatChat, AddonModChatProvider } from '../../services/chat';
import { AddonModChatModuleHandlerService } from '../../services/handlers/module';
/**
* Component that displays a chat.
*/
@Component({
selector: 'addon-mod-chat-index',
templateUrl: 'addon-mod-chat-index.html',
})
export class AddonModChatIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit {
component = AddonModChatProvider.COMPONENT;
moduleName = 'chat';
chat?: AddonModChatChat;
sessionsAvailable = false;
chatInfo?: {
date: string;
fromnow: string;
};
constructor(
protected content?: IonContent,
@Optional() courseContentsPage?: CoreCourseContentsPage,
) {
super('AddonModChatIndexComponent', content, courseContentsPage);
}
/**
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
super.ngOnInit();
await this.loadContent();
if (!this.chat) {
return;
}
try {
await AddonModChat.logView(this.chat.id, this.chat.name);
CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata);
} catch {
// Ignore errors.
}
}
/**
* @inheritdoc
*/
protected async fetchContent(refresh: boolean = false): Promise<void> {
try {
this.chat = await AddonModChat.getChat(this.courseId, this.module.id);
this.description = this.chat.intro;
const now = CoreTimeUtils.timestamp();
const span = (this.chat.chattime || 0) - now;
if (this.chat.chattime && this.chat.schedule && span > 0) {
this.chatInfo = {
date: CoreTimeUtils.userDate(this.chat.chattime * 1000),
fromnow: CoreTimeUtils.formatTime(span),
};
} else {
this.chatInfo = undefined;
}
this.dataRetrieved.emit(this.chat);
this.sessionsAvailable = await AddonModChat.areSessionsAvailable();
} finally {
this.fillContextMenu(refresh);
}
}
/**
* Enter the chat.
*/
enterChat(): void {
const title = this.chat?.name || this.moduleName;
CoreNavigator.navigateToSitePath(
AddonModChatModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/chat`,
{
params: {
title,
chatId: this.chat!.id,
},
},
);
}
/**
* View past sessions.
*/
viewSessions(): void {
CoreNavigator.navigateToSitePath(
AddonModChatModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/sessions`,
{
params: {
chatId: this.chat!.id,
},
},
);
}
}

View File

@ -0,0 +1,35 @@
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button [attr.aria-label]="'core.back' | translate"></ion-back-button>
</ion-buttons>
<ion-title>{{ 'addon.mod_chat.currentusers' | translate }}</ion-title>
<ion-buttons slot="end">
<ion-button (click)="closeModal()" [attr.aria-label]="'core.close' | translate">
<ion-icon slot="icon-only" name="fas-times"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<core-loading [hideUntil]="usersLoaded">
<ion-item class="ion-text-wrap" *ngFor="let user of users"
[class.addon-mod-chat-user]="currentUserId != user.id && isOnline">
<core-user-avatar [user]="user" slot="start" [linkProfile]="false"></core-user-avatar>
<ion-label>
<h2>{{ user.fullname }}</h2>
<ng-container *ngIf="currentUserId != user.id && isOnline">
<ion-button fill="clear" (click)="talkTo(user)">
<ion-icon name="fas-comments" slot="start"></ion-icon>
{{ 'addon.mod_chat.talk' | translate }}
</ion-button>
<ion-button fill="clear" (click)="beepTo(user)">
<ion-icon name="fas-bell" slot="start"></ion-icon>
{{ 'addon.mod_chat.beep' | translate }}
</ion-button>
</ng-container>
</ion-label>
</ion-item>
</core-loading>
</ion-content>

View File

@ -0,0 +1,106 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { CoreApp } from '@services/app';
import { CoreSites } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { ModalController, Network, NgZone } from '@singletons';
import { Subscription } from 'rxjs';
import { AddonModChat, AddonModChatUser } from '../../services/chat';
/**
* MMdal that displays the chat session users.
*/
@Component({
selector: 'addon-mod-chat-users-modal',
templateUrl: 'users-modal.html',
})
export class AddonModChatUsersModalComponent implements OnInit, OnDestroy {
@Input() sessionId!: string;
@Input() cmId!: number;
users: AddonModChatUser[] = [];
usersLoaded = false;
currentUserId: number;
isOnline: boolean;
protected onlineSubscription: Subscription;
constructor() {
this.isOnline = CoreApp.isOnline();
this.currentUserId = CoreSites.getCurrentSiteUserId();
this.onlineSubscription = Network.onChange().subscribe(() => {
// Execute the callback in the Angular zone, so change detection doesn't stop working.
NgZone.run(() => {
this.isOnline = CoreApp.isOnline();
});
});
}
/**
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
try {
const data = await AddonModChat.getChatUsers(this.sessionId, { cmId: this.cmId });
this.users = data.users;
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_chat.errorwhilegettingchatusers', true);
} finally {
this.usersLoaded = true;
}
}
/**
* Close the chat users modal.
*/
closeModal(): void {
ModalController.dismiss(<AddonModChatUsersModalResult> { users: this.users });
}
/**
* Add "To user:".
*
* @param user User object.
*/
talkTo(user: AddonModChatUser): void {
ModalController.dismiss(<AddonModChatUsersModalResult> { talkTo: user.fullname, users: this.users });
}
/**
* Beep a user.
*
* @param user User object.
*/
beepTo(user: AddonModChatUser): void {
ModalController.dismiss(<AddonModChatUsersModalResult> { beepTo: user.id, users: this.users });
}
/**
* @inheritdoc
*/
ngOnDestroy(): void {
this.onlineSubscription.unsubscribe();
}
}
export type AddonModChatUsersModalResult = {
users: AddonModChatUser[];
talkTo?: string;
beepTo?: number;
};

View File

@ -0,0 +1,28 @@
{
"beep": "Beep",
"chatreport": "Chat sessions",
"currentusers": "Current users",
"enterchat": "Click here to enter the chat now",
"entermessage": "Enter your message",
"errorwhileconnecting": "Error while connecting to the chat.",
"errorwhilegettingchatdata": "Error while getting chat data.",
"errorwhilegettingchatusers": "Error while getting chat users.",
"errorwhileretrievingmessages": "Error while retrieving messages from the server.",
"errorwhilesendingmessage": "Error while sending the message.",
"messagebeepseveryone": "{{$a}} beeps everyone!",
"messagebeepsyou": "{{$a}} has just beeped you!",
"messageenter": "{{$a}} has just entered this chat",
"messageexit": "{{$a}} has left this chat",
"messages": "Messages",
"messageyoubeep": "You beeped {{$a}}",
"modulenameplural": "Chats",
"mustbeonlinetosendmessages": "You must be online to send messages.",
"nomessages": "No messages yet",
"nosessionsfound": "No sessions found",
"saidto": "said to",
"send": "Send",
"sessionstart": "The next chat session will start on {{$a.date}}, ({{$a.fromnow}} from now)",
"showincompletesessions": "Show incomplete sessions",
"talk": "Talk",
"viewreport": "View past chat sessions"
}

View File

@ -0,0 +1,126 @@
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button [attr.aria-label]="'core.back' | translate"></ion-back-button>
</ion-buttons>
<ion-title>
<core-format-text [text]="title" contextLevel="module" [contextInstanceId]="cmId" [courseId]="courseId">
</core-format-text>
</ion-title>
<ion-buttons slot="end">
<ion-button *ngIf="loaded" (click)="showChatUsers()" [attr.aria-label]="'core.users' | translate">
<ion-icon name="fas-users" slot="icon-only"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="has-footer">
<core-loading [hideUntil]="loaded" class="safe-area-page">
<ion-list class="addon-messages-discussion-container" aria-live="polite">
<ng-container *ngFor="let message of messages; index as index; last as last">
<h6 class="ion-text-center addon-messages-date" *ngIf="message.showDate">
{{ message.timestamp * 1000 | coreFormatDate: "strftimedayshort" }}
</h6>
<div class="ion-text-center addon-mod_chat-notice" *ngIf="message.special">
<ion-badge class="ion-text-wrap" color="success" *ngIf="message.system && message.message == 'enter'">
<span>
<ion-icon name="fas-sign-in-alt"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messageenter' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="danger" *ngIf="message.system && message.message == 'exit'">
<span>
<ion-icon name="fas-sign-out-alt"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messageexit' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="primary" *ngIf="message.beep == 'all'">
<span>
<ion-icon name="fas-bell"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messagebeepseveryone' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="primary"
*ngIf="message.userid != currentUserId && message.beep == currentUserId">
<span>
<ion-icon name="fas-bell"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messagebeepsyou' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="light"
*ngIf="message.userid == currentUserId && message.beep && message.beep != 'all'">
<span>
<ion-icon name="fas-bell"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messageyoubeep' | translate:{$a: message.beepWho} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="info" *ngIf="!message.system && !message.beep">
<span>
<ion-icon name="fas-asterisk"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
<strong>
{{ message.userfullname }} <core-format-text [text]="message.message" contextLevel="module"
[contextInstanceId]="cmId" [courseId]="courseId" (afterRender)="last && scrollToBottom()">
</core-format-text>
</strong>
</span>
</ion-badge>
</div>
<ion-item *ngIf="!message.special" class="ion-text-wrap addon-message"
[class.addon-message-mine]="message.userid == currentUserId"
[class.addon-message-not-mine]="message.userid != currentUserId"
[class.addon-message-no-user]="!message.showUserData"
[@coreSlideInOut]="message.userid == currentUserId ? '' : 'fromLeft'">
<ion-label>
<!-- User data. -->
<h2 class="addon-message-user">
<core-user-avatar slot="start" [user]="message" [linkProfile]="false" *ngIf="message.showUserData">
</core-user-avatar>
<div *ngIf="message.showUserData">{{ message.userfullname }}</div>
<ion-note>{{ message.timestamp * 1000 | coreFormatDate: "strftimetime" }}</ion-note>
</h2>
<p class="addon-message-text">
<core-format-text [text]="message.message" contextLevel="module" [contextInstanceId]="cmId"
[courseId]="courseId" (afterRender)="last && scrollToBottom()">
</core-format-text>
</p>
</ion-label>
<div class="tail" *ngIf="message.showTail"></div>
</ion-item>
</ng-container>
</ion-list>
<core-empty-box *ngIf="!messages || messages.length <= 0" icon="far-comments"
[message]="'addon.mod_chat.nomessages' | translate">
</core-empty-box>
</core-loading>
</ion-content>
<ion-footer color="light" class="footer-adjustable">
<ion-toolbar color="light">
<p class="ion-text-center" *ngIf="!isOnline">
{{ 'addon.mod_chat.mustbeonlinetosendmessages' | translate }}
</p>
<core-send-message-form [sendDisabled]="sending" *ngIf="isOnline && polling && loaded" [message]="newMessage"
(onSubmit)="sendMessage($event)" [placeholder]="'addon.messages.newmessage' | translate" (onResize)="resizeContent()">
</core-send-message-form>
<ion-button *ngIf="isOnline && !polling && loaded" (click)="reconnect()" expand="block" color="light">
{{ 'core.login.reconnect' | translate }}
</ion-button>
</ion-toolbar>
</ion-footer>

View File

@ -0,0 +1,6 @@
:host {
.addon-mod_chat-notice {
margin-top: 8px;
margin-bottom: 8px;
}
}

View File

@ -0,0 +1,403 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { CoreAnimations } from '@components/animations';
import { CoreSendMessageFormComponent } from '@components/send-message-form/send-message-form';
import { IonContent } from '@ionic/angular';
import { CoreApp } from '@services/app';
import { CoreNavigator } from '@services/navigator';
import { CoreSites } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreUtils } from '@services/utils/utils';
import { ModalController, Network, NgZone } from '@singletons';
import { CoreEventObserver, CoreEvents } from '@singletons/events';
import { Subscription } from 'rxjs';
import { AddonModChatUsersModalComponent, AddonModChatUsersModalResult } from '../../components/users-modal/users-modal';
import { AddonModChat, AddonModChatProvider, AddonModChatUser } from '../../services/chat';
import { AddonModChatFormattedMessage, AddonModChatHelper } from '../../services/chat-helper';
/**
* Page that displays a chat session.
*/
@Component({
selector: 'page-addon-mod-chat-chat',
templateUrl: 'chat.html',
animations: [CoreAnimations.SLIDE_IN_OUT],
styleUrls: ['chat.scss', '../../../../messages/pages/discussion/discussion.scss'],
})
export class AddonModChatChatPage implements OnInit, OnDestroy {
@ViewChild(IonContent) content?: IonContent;
@ViewChild(CoreSendMessageFormComponent) sendMessageForm?: CoreSendMessageFormComponent;
loaded = false;
title = '';
messages: AddonModChatFormattedMessage[] = [];
newMessage?: string;
polling?: number;
isOnline: boolean;
currentUserId: number;
sending = false;
courseId!: number;
cmId!: number;
protected logger;
protected chatId!: number;
protected sessionId?: string;
protected lastTime = 0;
protected oldContentHeight = 0;
protected onlineSubscription: Subscription;
protected keyboardObserver: CoreEventObserver;
protected viewDestroyed = false;
protected pollingRunning = false;
protected users: AddonModChatUser[] = [];
constructor() {
this.currentUserId = CoreSites.getCurrentSiteUserId();
this.isOnline = CoreApp.isOnline();
this.onlineSubscription = Network.onChange().subscribe(() => {
// Execute the callback in the Angular zone, so change detection doesn't stop working.
NgZone.run(() => {
this.isOnline = CoreApp.isOnline();
});
});
// Recalculate footer position when keyboard is shown or hidden.
this.keyboardObserver = CoreEvents.on(CoreEvents.KEYBOARD_CHANGE, () => {
// @todo probably not needed.
// this.content.resize();
});
}
/**
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
this.courseId = CoreNavigator.getRouteNumberParam('courseId')!;
this.cmId = CoreNavigator.getRouteNumberParam('cmId')!;
this.chatId = CoreNavigator.getRouteNumberParam('chatId')!;
this.title = CoreNavigator.getRouteParam('title') || '';
try {
await this.loginUser();
await this.fetchMessages();
this.startPolling();
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_chat.errorwhileconnecting', true);
CoreNavigator.back();
} finally {
this.loaded = true;
}
}
/**
* Runs when the page has fully entered and is now the active page.
* This event will fire, whether it was the first load or a cached page.
*/
ionViewDidEnter(): void {
this.startPolling();
}
/**
* Runs when the page is about to leave and no longer be the active page.
*/
ionViewWillLeave(): void {
CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: 'chat' });
this.stopPolling();
}
/**
* Convenience function to login the user.
*
* @return Promise resolved when done.
*/
protected async loginUser(): Promise<void> {
this.sessionId = await AddonModChat.loginUser(this.chatId);
}
/**
* Convenience function to fetch chat messages.
*
* @return Promise resolved when done.
*/
protected async fetchMessages(): Promise<void> {
const messagesInfo = await AddonModChat.getLatestMessages(this.sessionId!, this.lastTime);
this.lastTime = messagesInfo.chatnewlasttime || 0;
const messages = await AddonModChat.getMessagesUserData(messagesInfo.messages, this.courseId);
if (!messages.length) {
// No messages yet, nothing else to do.
return;
}
const previousLength = this.messages.length;
this.messages = this.messages.concat(messages);
// Calculate which messages need to display the date or user data.
for (let index = previousLength; index < this.messages.length; index++) {
const prevMessage = index > 0 ? this.messages[index - 1] : undefined;
this.messages[index] = AddonModChatHelper.formatMessage(this.currentUserId, this.messages[index], prevMessage);
const message = this.messages[index];
if (message.beep && message.beep != String(this.currentUserId)) {
this.loadMessageBeepWho(message);
}
}
this.messages[this.messages.length - 1].showTail = true;
// New messages or beeps, scroll to bottom.
setTimeout(() => this.scrollToBottom());
}
protected async loadMessageBeepWho(message: AddonModChatFormattedMessage): Promise<void> {
message.beepWho = await this.getUserFullname(message.beep!);
}
/**
* Display the chat users modal.
*/
async showChatUsers(): Promise<void> {
// Create the toc modal.
const modal = await ModalController.create({
component: AddonModChatUsersModalComponent,
componentProps: {
sessionId: this.sessionId,
cmId: this.cmId,
},
cssClass: 'core-modal-lateral',
showBackdrop: true,
backdropDismiss: true,
// @todo enterAnimation: 'core-modal-lateral-transition',
// @todo leaveAnimation: 'core-modal-lateral-transition',
});
await modal.present();
const result = await modal.onDidDismiss<AddonModChatUsersModalResult>();
if (result.data) {
if (result.data.talkTo) {
this.newMessage = `To ${result.data.talkTo}: ` + (this.sendMessageForm?.message || '');
}
if (result.data.beepTo) {
this.sendMessage('', result.data.beepTo);
}
this.users = result.data.users;
}
}
/**
* Get the user fullname for a beep.
*
* @param id User Id before parsing.
* @return User fullname.
*/
protected async getUserFullname(id: string): Promise<string> {
const idNumber = parseInt(id, 10);
if (isNaN(idNumber)) {
return id;
}
const user = this.users.find((user) => user.id == idNumber);
if (user) {
return user.fullname;
}
try {
const data = await AddonModChat.getChatUsers(this.sessionId!, { cmId: this.cmId });
this.users = data.users;
const user = this.users.find((user) => user.id == idNumber);
if (user) {
return user.fullname;
}
return id;
} catch (error) {
// Ignore errors.
return id;
}
}
/**
* Start the polling to get chat messages periodically.
*/
protected startPolling(): void {
// We already have the polling in place.
if (this.polling) {
return;
}
// Start polling.
this.polling = window.setInterval(() => {
CoreUtils.ignoreErrors(this.fetchMessagesInterval());
}, AddonModChatProvider.POLL_INTERVAL);
}
/**
* Stop polling for messages.
*/
protected stopPolling(): void {
clearInterval(this.polling);
this.polling = undefined;
}
/**
* Convenience function to be called every certain time to fetch chat messages.
*
* @return Promise resolved when done.
*/
protected async fetchMessagesInterval(): Promise<void> {
if (!this.isOnline || this.pollingRunning) {
// Obviously we cannot check for new messages when the app is offline.
return;
}
this.pollingRunning = true;
try {
await this.fetchMessages();
} catch {
try {
// Try to login, it might have failed because the session expired.
await this.loginUser();
await this.fetchMessages();
} catch (error) {
// Fail again. Stop polling if needed.
this.stopPolling();
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_chat.errorwhileretrievingmessages', true);
throw error;
}
} finally {
this.pollingRunning = false;
}
}
/**
* Send a message to the chat.
*
* @param text Text of the nessage.
* @param beep ID of the user to beep.
*/
async sendMessage(text: string, beep: number = 0): Promise<void> {
if (!this.isOnline) {
// Silent error, the view should prevent this.
return;
} else if (beep === 0 && !text.trim()) {
// Silent error.
return;
}
this.sending = true;
try {
await AddonModChat.sendMessage(this.sessionId!, text, beep);
// Update messages to show the sent message.
CoreUtils.ignoreErrors(this.fetchMessagesInterval());
} catch (error) {
// Only close the keyboard if an error happens, we want the user to be able to send multiple
// messages without the keyboard being closed.
CoreApp.closeKeyboard();
this.newMessage = text;
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_chat.errorwhilesendingmessage', true);
} finally {
this.sending = false;
}
}
/**
* Try to reconnect.
*
* @return Promise resolved when done.
*/
async reconnect(): Promise<void> {
const modal = await CoreDomUtils.showModalLoading();
try {
// Call startPolling would take a while for the first execution, so we'll execute it manually to check if it works now.
await this.fetchMessagesInterval();
// It works, start the polling again.
this.startPolling();
} catch {
// Ignore errors.
} finally {
modal.dismiss();
}
}
/**
* Scroll bottom when render has finished.
*/
scrollToBottom(): void {
// Need a timeout to leave time to the view to be rendered.
setTimeout(() => {
if (!this.viewDestroyed) {
this.content?.scrollToBottom();
}
});
}
/**
* Content or scroll has been resized. For content, only call it if it's been added on top.
*/
resizeContent(): void {
// @todo probably not needed.
// let top = this.content.getContentDimensions().scrollTop;
// this.content.resize();
// // Wait for new content height to be calculated.
// setTimeout(() => {
// // Visible content size changed, maintain the bottom position.
// if (!this.viewDestroyed && this.content && this.domUtils.getContentHeight(this.content) != this.oldContentHeight) {
// if (!top) {
// top = this.content.getContentDimensions().scrollTop;
// }
// top += this.oldContentHeight - this.domUtils.getContentHeight(this.content);
// this.oldContentHeight = this.domUtils.getContentHeight(this.content);
// this.content.scrollTo(0, top, 0);
// }
// });
}
/**
* @inheritdoc
*/
ngOnDestroy(): void {
this.onlineSubscription && this.onlineSubscription.unsubscribe();
this.keyboardObserver && this.keyboardObserver.off();
this.stopPolling();
this.viewDestroyed = true;
}
}

View File

@ -0,0 +1,21 @@
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button [attr.aria-label]="'core.back' | translate"></ion-back-button>
</ion-buttons>
<ion-title>
<core-format-text [text]="title" contextLevel="module" [contextInstanceId]="module?.id" [courseId]="courseId">
</core-format-text>
</ion-title>
<ion-buttons slot="end">
<!-- The buttons defined by the component will be added in here. -->
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-refresher slot="fixed" [disabled]="!activityComponent?.loaded" (ionRefresh)="activityComponent?.doRefresh($event.target)">
<ion-refresher-content pullingText="{{ 'core.pulltorefresh' | translate }}"></ion-refresher-content>
</ion-refresher>
<addon-mod-chat-index [module]="module" [courseId]="courseId" (dataRetrieved)="updateData($event)"></addon-mod-chat-index>
</ion-content>

View File

@ -0,0 +1,30 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, ViewChild } from '@angular/core';
import { CoreCourseModuleMainActivityPage } from '@features/course/classes/main-activity-page';
import { AddonModChatIndexComponent } from '../../components/index/index';
/**
* Page that displays a chat.
*/
@Component({
selector: 'page-addon-mod-chat-index',
templateUrl: 'index.html',
})
export class AddonModChatIndexPage extends CoreCourseModuleMainActivityPage<AddonModChatIndexComponent> {
@ViewChild(AddonModChatIndexComponent) activityComponent?: AddonModChatIndexComponent;
}

View File

@ -0,0 +1,100 @@
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button [attr.aria-label]="'core.back' | translate"></ion-back-button>
</ion-buttons>
<ion-title>{{ 'addon.mod_chat.messages' | translate }}</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-refresher slot="fixed" [disabled]="!loaded" (ionRefresh)="refreshMessages($event.target)">
<ion-refresher-content pullingText="{{ 'core.pulltorefresh' | translate }}"></ion-refresher-content>
</ion-refresher>
<core-loading [hideUntil]="loaded" class="safe-area-page">
<ion-list class="addon-messages-discussion-container" aria-live="polite">
<ng-container *ngFor="let message of messages; index as index;">
<h6 class="ion-text-center addon-messages-date" *ngIf="message.showDate">
{{ message.timestamp * 1000 | coreFormatDate:"strftimedayshort" }}
</h6>
<div class="ion-text-center addon-mod_chat-notice" *ngIf="message.special">
<ion-badge class="ion-text-wrap" color="success" *ngIf="message.issystem && message.message == 'enter'">
<span>
<ion-icon name="fas-sign-in-alt"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messageenter' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="danger" *ngIf="message.issystem && message.message == 'exit'">
<span>
<ion-icon name="fas-sign-out-alt"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messageexit' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="primary" *ngIf="message.beep == 'all'">
<span>
<ion-icon name="fas-bell"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messagebeepseveryone' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="primary"
*ngIf="message.userid != currentUserId && message.beep == currentUserId">
<span>
<ion-icon name="fas-bell"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messagebeepsyou' | translate:{$a: message.userfullname} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="light"
*ngIf="message.userid == currentUserId && message.beep && message.beep != 'all'">
<span>
<ion-icon name="fas-bell"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
{{ 'addon.mod_chat.messageyoubeep' | translate:{$a: message.beepWho} }}
</span>
</ion-badge>
<ion-badge class="ion-text-wrap" color="info" *ngIf="!message.issystem && !message.beep">
<span>
<ion-icon name="fas-asterisk"></ion-icon>
{{ message.timestamp * 1000 | coreFormatDate:"strftimetime" }}
<strong>
{{ message.userfullname }} <core-format-text [text]="message.message" contextLevel="module"
[contextInstanceId]="cmId" [courseId]="courseId"></core-format-text>
</strong>
</span>
</ion-badge>
</div>
<ion-item *ngIf="!message.special" class="ion-text-wrap addon-message"
[class.addon-message-mine]="message.userid == currentUserId"
[class.addon-message-not-mine]="message.userid != currentUserId"
[class.addon-message-no-user]="!message.showUserData">
<ion-label>
<!-- User data. -->
<h2 class="addon-message-user">
<core-user-avatar slot="start" [user]="message" [linkProfile]="false" *ngIf="message.showUserData">
</core-user-avatar>
<div *ngIf="message.showUserData">{{ message.userfullname }}</div>
<ion-note>{{ message.timestamp * 1000 | coreFormatDate: "strftimetime" }}</ion-note>
</h2>
<p class="addon-message-text">
<core-format-text [text]="message.message" contextLevel="module" [contextInstanceId]="cmId"
[courseId]="courseId">
</core-format-text>
</p>
</ion-label>
<div class="tail" *ngIf="message.showTail"></div>
</ion-item>
</ng-container>
</ion-list>
</core-loading>
</ion-content>

View File

@ -0,0 +1,6 @@
:host {
.addon-mod_chat-notice {
margin-top: 8px;
margin-bottom: 8px;
}
}

View File

@ -0,0 +1,142 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, OnInit } from '@angular/core';
import { CoreUser } from '@features/user/services/user';
import { IonRefresher } from '@ionic/angular';
import { CoreNavigator } from '@services/navigator';
import { CoreSites } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreUtils } from '@services/utils/utils';
import { AddonModChat } from '../../services/chat';
import { AddonModChatFormattedSessionMessage, AddonModChatHelper } from '../../services/chat-helper';
/**
* Page that displays list of chat session messages.
*/
@Component({
selector: 'page-addon-mod-chat-session-messages',
templateUrl: 'session-messages.html',
styleUrls: ['session-messages.scss', '../../../../messages/pages/discussion/discussion.scss'],
})
export class AddonModChatSessionMessagesPage implements OnInit {
currentUserId!: number;
cmId!: number;
messages: AddonModChatFormattedSessionMessage[] = [];
loaded = false;
courseId!: number;
protected chatId!: number;
protected sessionStart!: number;
protected sessionEnd!: number;
protected groupId!: number;
/**
* @inheritdoc
*/
ngOnInit(): void {
this.courseId = CoreNavigator.getRouteNumberParam('courseId')!;
this.cmId = CoreNavigator.getRouteNumberParam('cmId')!;
this.sessionStart = CoreNavigator.getRouteNumberParam('sessionStart')!;
this.sessionEnd = CoreNavigator.getRouteNumberParam('sessionEnd')!;
this.chatId = CoreNavigator.getRouteNumberParam('chatId')!;
this.groupId = CoreNavigator.getRouteNumberParam('groupId') || 0;
this.currentUserId = CoreSites.getCurrentSiteUserId();
this.fetchMessages();
}
/**
* Fetch session messages.
*
* @return Promise resolved when done.
*/
protected async fetchMessages(): Promise<void> {
try {
const messages = await AddonModChat.getSessionMessages(
this.chatId,
this.sessionStart,
this.sessionEnd,
this.groupId,
{ cmId: this.cmId },
);
this.messages = await AddonModChat.getMessagesUserData(messages, this.courseId);
// Calculate which messages need to display the date or user data.
for (let index = 0 ; index < this.messages.length; index++) {
const prevMessage = index > 0 ? this.messages[index - 1] : undefined;
this.messages[index] = AddonModChatHelper.formatMessage(this.currentUserId, this.messages[index], prevMessage);
const message = this.messages[index];
if (message.beep && message.beep != String(this.currentUserId)) {
this.loadMessageBeepWho(message);
}
}
this.messages[this.messages.length - 1].showTail = true;
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'core.errorloadingcontent', true);
} finally {
this.loaded = true;
}
}
protected async loadMessageBeepWho(message: AddonModChatFormattedSessionMessage): Promise<void> {
message.beepWho = await this.getUserFullname(message.beep!);
}
/**
* Get the user fullname for a beep.
*
* @param id User Id before parsing.
* @return User fullname.
*/
protected async getUserFullname(id: string): Promise<string> {
const idNumber = parseInt(id, 10);
if (isNaN(idNumber)) {
return id;
}
try {
const user = await CoreUser.getProfile(idNumber, this.courseId, true);
return user.fullname;
} catch {
// Error getting profile.
return id;
}
}
/**
* Refresh session messages.
*
* @param refresher Refresher.
*/
async refreshMessages(refresher: IonRefresher): Promise<void> {
try {
await CoreUtils.ignoreErrors(AddonModChat.invalidateSessionMessages(this.chatId, this.sessionStart, this.groupId));
await this.fetchMessages();
} finally {
refresher.complete();
}
}
}

View File

@ -0,0 +1,61 @@
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button [attr.aria-label]="'core.back' | translate"></ion-back-button>
</ion-buttons>
<ion-title>{{ 'addon.mod_chat.chatreport' | translate }}</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<core-split-view>
<ion-refresher slot="fixed" [disabled]="!sessions.loaded" (ionRefresh)="refreshSessions($event.target)">
<ion-refresher-content pullingText="{{ 'core.pulltorefresh' | translate }}"></ion-refresher-content>
</ion-refresher>
<core-loading [hideUntil]="sessions.loaded">
<ion-item class="ion-text-wrap" *ngIf="groupInfo && (groupInfo.separateGroups || groupInfo.visibleGroups)">
<ion-label id="addon-chat-groupslabel">
<ng-container *ngIf="groupInfo.separateGroups">{{'core.groupsseparate' | translate }}</ng-container>
<ng-container *ngIf="groupInfo.visibleGroups">{{'core.groupsvisible' | translate }}</ng-container>
</ion-label>
<ion-select [(ngModel)]="groupId" (ionChange)="fetchSessions(true)" aria-labelledby="addon-chat-groupslabel"
interface="action-sheet">
<ion-select-option *ngFor="let groupOpt of groupInfo.groups" [value]="groupOpt.id">
{{groupOpt.name}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label>{{ 'addon.mod_chat.showincompletesessions' | translate }}</ion-label>
<ion-toggle [(ngModel)]="showAll" (ionChange)="fetchSessions(true)"></ion-toggle>
</ion-item>
<ion-card *ngFor="let session of sessions.items" (click)="sessions.select(session)"
[class.core-selected-item]="sessions.isSelected(session)"
[class.addon-mod-chat-session-show-more]="session.sessionusers.length < session.allsessionusers.length">
<ion-item class="ion-text-wrap">
<ion-label>
<h2>{{ session.sessionstart * 1000 | coreFormatDate }}</h2>
<p *ngIf="session.duration">{{ session.duration | coreDuration }}</p>
</ion-label>
</ion-item>
<ion-card-content>
<ion-item *ngFor="let user of session.sessionusers">
<ion-label>
{{ user.userfullname }} <span *ngIf="user.messagecount">({{ user.messagecount }})</span>
</ion-label>
</ion-item>
</ion-card-content>
<div *ngIf="session.sessionusers.length < session.allsessionusers.length">
<ion-button fill="clear" (click)="showMoreUsers(session, $event)">
{{ 'core.showmore' | translate }}
</ion-button>
</div>
</ion-card>
<core-empty-box *ngIf="sessions.empty" icon="far-comments" [message]="'addon.mod_chat.nosessionsfound' | translate">
</core-empty-box>
</core-loading>
</core-split-view>
</ion-content>

View File

@ -0,0 +1,8 @@
ion-app.app-root page-addon-mod-chat-sessions {
.addon-mod-chat-session-show-more .card-content{
padding-bottom: 0;
}
.addon-mod-chat-session-selected {
border-top: 5px solid $core-splitview-selected;
}
}

View File

@ -0,0 +1,234 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { AfterViewInit, Component, OnDestroy, ViewChild } from '@angular/core';
import { Params } from '@angular/router';
import { CorePageItemsListManager } from '@classes/page-items-list-manager';
import { CoreSplitViewComponent } from '@components/split-view/split-view';
import { CoreUser } from '@features/user/services/user';
import { IonRefresher } from '@ionic/angular';
import { CoreGroupInfo, CoreGroups } from '@services/groups';
import { CoreNavigator } from '@services/navigator';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreUtils } from '@services/utils/utils';
import { Translate } from '@singletons';
import { AddonModChat, AddonModChatSession, AddonModChatSessionUser } from '../../services/chat';
/**
* Page that displays list of chat sessions.
*/
@Component({
selector: 'page-addon-mod-chat-sessions',
templateUrl: 'sessions.html',
})
export class AddonModChatSessionsPage implements AfterViewInit, OnDestroy {
@ViewChild(CoreSplitViewComponent) splitView!: CoreSplitViewComponent;
sessions!: AddonChatSessionsManager;
showAll = false;
groupId = 0;
groupInfo?: CoreGroupInfo;
protected courseId!: number;
protected cmId!: number;
protected chatId!: number;
constructor() {
this.sessions = new AddonChatSessionsManager(AddonModChatSessionsPage);
}
/**
* @inheritdoc
*/
async ngAfterViewInit(): Promise<void> {
this.courseId = CoreNavigator.getRouteNumberParam('courseId')!;
this.cmId = CoreNavigator.getRouteNumberParam('cmId')!;
this.chatId = CoreNavigator.getRouteNumberParam('chatId')!;
this.sessions.setChatId(this.chatId);
await this.fetchSessions();
this.sessions.start(this.splitView);
}
/**
* Fetch chat sessions.
*
* @param showLoading Display a loading modal.
* @return Promise resolved when done.
*/
async fetchSessions(showLoading?: boolean): Promise<void> {
const modal = showLoading ? await CoreDomUtils.showModalLoading() : null;
try {
this.groupInfo = await CoreGroups.getActivityGroupInfo(this.cmId, false);
this.groupId = CoreGroups.validateGroupId(this.groupId, this.groupInfo);
this.sessions.setGroupId(this.groupId);
const sessions = await AddonModChat.getSessions(this.chatId, this.groupId, this.showAll, { cmId: this.cmId });
// Fetch user profiles.
const promises: Promise<unknown>[] = [];
const formattedSessions = sessions.map((session: AddonModChatSessionFormatted) => {
session.duration = session.sessionend - session.sessionstart;
session.sessionusers.forEach((sessionUser) => {
// The WS does not return the user name, fetch user profile.
promises.push(this.loadUserFullname(sessionUser));
});
// If session has more than 4 users we display a "Show more" link.
session.allsessionusers = session.sessionusers;
if (session.sessionusers.length > 4) {
session.sessionusers = session.allsessionusers.slice(0, 3);
}
return session;
});
await Promise.all(promises);
this.sessions.setItems(formattedSessions);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'core.errorloadingcontent', true);
} finally {
modal?.dismiss();
}
}
/**
* Load the fullname of a user.
*
* @param id User ID.
* @return Promise resolved when done.
*/
protected async loadUserFullname(sessionUser: AddonModChatUserSessionFormatted): Promise<void> {
if (sessionUser.userfullname) {
return;
}
try {
const user = await CoreUser.getProfile(sessionUser.userid, this.courseId, true);
sessionUser.userfullname = user.fullname;
} catch {
// Error getting profile, most probably the user is deleted.
sessionUser.userfullname = Translate.instant('core.deleteduser') + ' ' + sessionUser.userid;
}
}
/**
* Refresh chat sessions.
*
* @param refresher Refresher.
*/
async refreshSessions(refresher: IonRefresher): Promise<void> {
try {
await CoreUtils.ignoreErrors(CoreUtils.allPromises([
CoreGroups.invalidateActivityGroupInfo(this.cmId),
AddonModChat.invalidateSessions(this.chatId, this.groupId, this.showAll),
]));
await this.fetchSessions();
} finally {
refresher.complete();
}
}
/**
* Show more session users.
*
* @param session Chat session.
* @param event The event.
*/
showMoreUsers(session: AddonModChatSessionFormatted, event: Event): void {
session.sessionusers = session.allsessionusers!;
event.stopPropagation();
}
/**
* @inheritdoc
*/
ngOnDestroy(): void {
this.sessions.destroy();
}
}
/**
* Helper class to manage sessions.
*/
class AddonChatSessionsManager extends CorePageItemsListManager<AddonModChatSessionFormatted> {
chatId = -1;
groupId = 0;
constructor(pageComponent: unknown) {
super(pageComponent);
}
/**
* Set chat ID.
*
* @param chatId Chat ID.
*/
setChatId(chatId: number): void {
this.chatId = chatId;
}
/**
* Set group ID.
*
* @param groupId Group ID.
*/
setGroupId(groupId: number): void {
this.groupId = groupId;
}
/**
* @inheritdoc
*/
protected getItemPath(session: AddonModChatSessionFormatted): string {
return `${session.sessionstart}/${session.sessionend}`;
}
/**
* @inheritdoc
*/
protected getItemQueryParams(): Params {
return {
chatId: this.chatId,
groupId: this.groupId,
};
}
}
/**
* Fields added to chat session in this view.
*/
type AddonModChatSessionFormatted = Omit<AddonModChatSession, 'sessionusers'> & {
duration?: number; // Session duration.
sessionusers: AddonModChatUserSessionFormatted[];
allsessionusers?: AddonModChatUserSessionFormatted[]; // All session users.
};
/**
* Fields added to user session in this view.
*/
type AddonModChatUserSessionFormatted = AddonModChatSessionUser & {
userfullname?: string; // User full name.
};

View File

@ -0,0 +1,154 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { makeSingleton, Translate } from '@singletons';
import * as moment from 'moment';
import { AddonModChatMessage, AddonModChatSessionMessage } from './chat';
const patternTo = new RegExp(/^To\s([^:]+):(.*)/);
/**
* Helper service that provides some features for chat.
*/
@Injectable({ providedIn: 'root' })
export class AddonModChatHelperProvider {
/**
* Give some format info about messages.
*
* @param currentUserId User Id.
* @param message Message.
* @param prevMessage Previous message (if any).
* @return Message with additional info.
*/
formatMessage(
currentUserId: number,
message: AddonModChatMessage,
prevMessage?: AddonModChatFormattedMessage,
): AddonModChatFormattedMessage;
formatMessage(
currentUserId: number,
message: AddonModChatSessionMessage,
prevMessage?: AddonModChatFormattedSessionMessage,
): AddonModChatFormattedSessionMessage;
formatMessage(
currentUserId: number,
message: AddonModChatMessage | AddonModChatSessionMessage,
prevMessage?: AddonModChatAnyFormattedMessage,
): AddonModChatAnyFormattedMessage {
const formattedMessage: AddonModChatAnyFormattedMessage = message;
formattedMessage.message = formattedMessage.message.trim();
formattedMessage.showDate = this.showDate(message, prevMessage);
formattedMessage.beep = (message.message.substr(0, 5) == 'beep ' && message.message.substr(5).trim()) || undefined;
formattedMessage.special = !!formattedMessage.beep || (<AddonModChatSessionMessage> message).issystem ||
(<AddonModChatMessage> message).system;
if (formattedMessage.message.substr(0, 4) == '/me ') {
formattedMessage.special = true;
formattedMessage.message = formattedMessage.message.substr(4).trim();
}
if (!formattedMessage.special && formattedMessage.message.match(patternTo)) {
const matches = formattedMessage.message.match(patternTo);
formattedMessage.message = '<b>' + Translate.instant('addon.mod_chat.saidto') +
'</b> <i>' + matches![1] + '</i>: ' + matches![2];
}
formattedMessage.showUserData = this.showUserData(currentUserId, message, prevMessage);
if (prevMessage) {
prevMessage.showTail = this.showTail(prevMessage, message);
}
return formattedMessage;
}
/**
* Check if the user info should be displayed for the current message.
* User data is only displayed if the previous message was from another user.
*
* @param message Current message where to show the user info.
* @param prevMessage Previous message.
* @return Whether user data should be shown.
*/
protected showUserData(
currentUserId: number,
message: AddonModChatAnyFormattedMessage,
prevMessage?: AddonModChatAnyFormattedMessage,
): boolean {
return message.userid != currentUserId &&
(!prevMessage || prevMessage.userid != message.userid || !!message.showDate || !!prevMessage.special);
}
/**
* Check if a css tail should be shown.
*
* @param message Current message where to show the user info.
* @param nextMessage Next message.
* @return Whether user data should be shown.
*/
protected showTail(message: AddonModChatAnyFormattedMessage, nextMessage?: AddonModChatAnyFormattedMessage): boolean {
return !nextMessage || nextMessage.userid != message.userid || !!nextMessage.showDate || !!nextMessage.special;
}
/**
* Check if the date should be displayed between messages (when the day changes at midnight for example).
*
* @param message New message object.
* @param prevMessage Previous message object.
* @return True if messages are from diferent days, false othetwise.
*/
protected showDate(message: AddonModChatAnyFormattedMessage, prevMessage?: AddonModChatAnyFormattedMessage): boolean {
if (!prevMessage) {
return true;
}
// Check if day has changed.
return !moment(message.timestamp * 1000).isSame(prevMessage.timestamp * 1000, 'day');
}
}
export const AddonModChatHelper = makeSingleton(AddonModChatHelperProvider);
/**
* Special info for view usage.
*/
type AddonModChatInfoForView = {
showDate?: boolean; // If date should be displayed before the message.
beep?: string; // User id of the beeped user or 'all'.
special?: boolean; // True if is an special message (system, beep or command).
showUserData?: boolean; // If user data should be displayed.
showTail?: boolean; // If tail should be displayed (decoration).
beepWho?: string; // Fullname of the beeped user.
};
/**
* Message with data for view usage.
*/
export type AddonModChatFormattedMessage = AddonModChatMessage & AddonModChatInfoForView;
/**
* Session message with data for view usage.
*/
export type AddonModChatFormattedSessionMessage = AddonModChatSessionMessage & AddonModChatInfoForView;
/**
* Any possivle formatted message.
*/
export type AddonModChatAnyFormattedMessage = AddonModChatFormattedMessage | AddonModChatFormattedSessionMessage;

View File

@ -0,0 +1,650 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreError } from '@classes/errors/error';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreUser } from '@features/user/services/user';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws';
import { makeSingleton, Translate } from '@singletons';
const ROOT_CACHE_KEY = 'AddonModChat:';
/**
* Service that provides some features for chats.
*/
@Injectable({ providedIn: 'root' })
export class AddonModChatProvider {
static readonly COMPONENT = 'mmaModChat';
static readonly POLL_INTERVAL = 4000;
/**
* Get a chat.
*
* @param courseId Course ID.
* @param cmId Course module ID.
* @param options Other options.
* @return Promise resolved when the chat is retrieved.
*/
async getChat(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModChatChat> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModChatGetChatsByCoursesWSParams = {
courseids: [courseId],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getChatsCacheKey(courseId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModChatProvider.COMPONENT,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModChatGetChatsByCoursesWSResponse>('mod_chat_get_chats_by_courses', params, preSets);
const chat = response.chats.find((chat) => chat.coursemodule == cmId);
if (chat) {
return chat;
}
throw new CoreError('Chat not found.');
}
/**
* Log the user into a chat room.
*
* @param chatId Chat instance ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS is executed.
*/
async loginUser(chatId: number, siteId?: string): Promise<string> {
const site = await CoreSites.getSite(siteId);
const params: AddonModChatLoginUserWSParams = {
chatid: chatId,
};
const response = await site.write<AddonModChatLoginUserWSResponse>('mod_chat_login_user', params);
return response.chatsid;
}
/**
* Report a chat as being viewed.
*
* @param id Chat instance ID.
* @param name Name of the chat.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
async logView(id: number, name?: string, siteId?: string): Promise<void> {
const params: AddonModChatViewChatWSParams = {
chatid: id,
};
await CoreCourseLogHelper.logSingle(
'mod_chat_view_chat',
params,
AddonModChatProvider.COMPONENT,
id,
name,
'chat',
{},
siteId,
);
}
/**
* Send a message to a chat.
*
* @param sessionId Chat sessiond ID.
* @param message Message text.
* @param beepUserId Beep user ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS is executed.
*/
async sendMessage(sessionId: string, message: string, beepUserId: number, siteId?: string): Promise<number> {
const site = await CoreSites.getSite(siteId);
const params: AddonModChatSendChatMessageWSParams = {
chatsid: sessionId,
messagetext: message,
beepid: String(beepUserId),
};
const response = await site.write<AddonModChatSendChatMessageWSResponse>('mod_chat_send_chat_message', params);
return response.messageid;
}
/**
* Get the latest messages from a chat session.
*
* @param sessionId Chat sessiond ID.
* @param lastTime Last time when messages were retrieved.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS is executed.
*/
async getLatestMessages(
sessionId: string,
lastTime: number,
siteId?: string,
): Promise<AddonModChatGetChatLatestMessagesWSResponse> {
const site = await CoreSites.getSite(siteId);
const params: AddonModChatGetChatLatestMessagesWSParams = {
chatsid: sessionId,
chatlasttime: lastTime,
};
/* We use write to not use cache. It doesn't make sense to store the messages in cache
because we won't be able to retireve them if AddonModChatProvider.loginUser fails. */
return site.write('mod_chat_get_chat_latest_messages', params);
}
/**
* Get user data for messages since they only have userid.
*
* @param messages Messages to get the user data for.
* @param courseId ID of the course the messages belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise always resolved with the formatted messages.
*/
async getMessagesUserData(messages: AddonModChatWSMessage[], courseId: number, siteId?: string): Promise<AddonModChatMessage[]>;
async getMessagesUserData(
messages: AddonModChatWSSessionMessage[],
courseId: number,
siteId?: string,
): Promise<AddonModChatSessionMessage[]>;
async getMessagesUserData(
messages: (AddonModChatWSMessage | AddonModChatWSSessionMessage)[],
courseId: number,
siteId?: string,
): Promise<(AddonModChatMessage | AddonModChatSessionMessage)[]> {
const formattedMessages: (AddonModChatMessage | AddonModChatSessionMessage)[] = messages;
await Promise.all(formattedMessages.map(async (message) => {
try {
const user = await CoreUser.getProfile(message.userid, courseId, true, siteId);
message.userfullname = user.fullname;
message.userprofileimageurl = user.profileimageurl;
} catch {
// Error getting profile, most probably the user is deleted.
message.userfullname = Translate.instant('core.deleteduser') + ' ' + message.userid;
}
}));
return formattedMessages;
}
/**
* Get the actives users of a current chat.
*
* @param sessionId Chat sessiond ID.
* @param options Other options.
* @return Promise resolved when the WS is executed.
*/
async getChatUsers(sessionId: string, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModChatGetChatUsersWSResponse> {
// By default, always try to get the latest data.
options.readingStrategy = options.readingStrategy || CoreSitesReadingStrategy.PreferNetwork;
const site = await CoreSites.getSite(options.siteId);
const params: AddonModChatGetChatUsersWSParams = {
chatsid: sessionId,
};
const preSets: CoreSiteWSPreSets = {
component: AddonModChatProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
return site.read('mod_chat_get_chat_users', params, preSets);
}
/**
* Return whether WS for passed sessions are available.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with a boolean.
* @since 3.5
*/
async areSessionsAvailable(siteId?: string): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
return site.wsAvailable('mod_chat_get_sessions') && site.wsAvailable('mod_chat_get_session_messages');
}
/**
* Get chat sessions.
*
* @param chatId Chat ID.
* @param groupId Group ID, 0 means that the function will determine the user group.
* @param showAll Whether to include incomplete sessions or not.
* @param options Other options.
* @return Promise resolved with the list of sessions.
* @since 3.5
*/
async getSessions(
chatId: number,
groupId: number = 0,
showAll: boolean = false,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModChatSession[]> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModChatGetSessionsWSParams = {
chatid: chatId,
groupid: groupId,
showall: showAll,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getSessionsCacheKey(chatId, groupId, showAll),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModChatProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModChatGetSessionsWSResponse>('mod_chat_get_sessions', params, preSets);
return response.sessions;
}
/**
* Get chat session messages.
*
* @param chatId Chat ID.
* @param sessionStart Session start time.
* @param sessionEnd Session end time.
* @param groupId Group ID, 0 means that the function will determine the user group.
* @param options Other options.
* @return Promise resolved with the list of messages.
* @since 3.5
*/
async getSessionMessages(
chatId: number,
sessionStart: number,
sessionEnd: number,
groupId: number = 0,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModChatWSSessionMessage[]> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModChatGetSessionMessagesWSParams = {
chatid: chatId,
sessionstart: sessionStart,
sessionend: sessionEnd,
groupid: groupId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getSessionMessagesCacheKey(chatId, sessionStart, groupId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModChatProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModChatGetSessionMessagesWSResponse>(
'mod_chat_get_session_messages',
params,
preSets,
);
return response.messages;
}
/**
* Invalidate chats.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateChats(courseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getChatsCacheKey(courseId));
}
/**
* Invalidate chat sessions.
*
* @param chatId Chat ID.
* @param groupId Group ID, 0 means that the function will determine the user group.
* @param showAll Whether to include incomplete sessions or not.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateSessions(chatId: number, groupId: number = 0, showAll: boolean = false, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getSessionsCacheKey(chatId, groupId, showAll));
}
/**
* Invalidate all chat sessions.
*
* @param chatId Chat ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAllSessions(chatId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getSessionsCacheKeyPrefix(chatId));
}
/**
* Invalidate chat session messages.
*
* @param chatId Chat ID.
* @param sessionStart Session start time.
* @param groupId Group ID, 0 means that the function will determine the user group.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateSessionMessages(chatId: number, sessionStart: number, groupId: number = 0, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getSessionMessagesCacheKey(chatId, sessionStart, groupId));
}
/**
* Invalidate all chat session messages.
*
* @param chatId Chat ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAllSessionMessages(chatId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getSessionMessagesCacheKeyPrefix(chatId));
}
/**
* Get cache key for chats WS call.
*
* @param courseId Course ID.
* @return Cache key.
*/
protected getChatsCacheKey(courseId: number): string {
return ROOT_CACHE_KEY + 'chats:' + courseId;
}
/**
* Get cache key for sessions WS call.
*
* @param chatId Chat ID.
* @param groupId Goup ID, 0 means that the function will determine the user group.
* @param showAll Whether to include incomplete sessions or not.
* @return Cache key.
*/
protected getSessionsCacheKey(chatId: number, groupId: number, showAll: boolean): string {
return this.getSessionsCacheKeyPrefix(chatId) + groupId + ':' + (showAll ? 1 : 0);
}
/**
* Get cache key prefix for sessions WS call.
*
* @param chatId Chat ID.
* @return Cache key prefix.
*/
protected getSessionsCacheKeyPrefix(chatId: number): string {
return ROOT_CACHE_KEY + 'sessions:' + chatId + ':';
}
/**
* Get cache key for session messages WS call.
*
* @param chatId Chat ID.
* @param sessionStart Session start time.
* @param groupId Group ID, 0 means that the function will determine the user group.
* @return Cache key.
*/
protected getSessionMessagesCacheKey(chatId: number, sessionStart: number, groupId: number): string {
return this.getSessionMessagesCacheKeyPrefix(chatId) + sessionStart + ':' + groupId;
}
/**
* Get cache key prefix for session messages WS call.
*
* @param chatId Chat ID.
* @return Cache key prefix.
*/
protected getSessionMessagesCacheKeyPrefix(chatId: number): string {
return ROOT_CACHE_KEY + 'sessionsMessages:' + chatId + ':';
}
}
export const AddonModChat = makeSingleton(AddonModChatProvider);
/**
* Params of mod_chat_get_chats_by_courses WS.
*/
export type AddonModChatGetChatsByCoursesWSParams = {
courseids?: number[]; // Array of course ids.
};
/**
* Data returned by mod_chat_get_chats_by_courses WS.
*/
export type AddonModChatGetChatsByCoursesWSResponse = {
chats: AddonModChatChat[];
warnings?: CoreWSExternalWarning[];
};
/**
* Chat returned by mod_chat_get_chats_by_courses.
*/
export type AddonModChatChat = {
id: number; // Chat id.
coursemodule: number; // Course module id.
course: number; // Course id.
name: string; // Chat name.
intro: string; // The Chat intro.
introformat: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
introfiles?: CoreWSExternalFile[]; // @since 3.2.
chatmethod?: string; // Chat method (sockets, ajax, header_js).
keepdays?: number; // Keep days.
studentlogs?: number; // Student logs visible to everyone.
chattime?: number; // Chat time.
schedule?: number; // Schedule type.
timemodified?: number; // Time of last modification.
section?: number; // Course section id.
visible?: boolean; // Visible.
groupmode?: number; // Group mode.
groupingid?: number; // Group id.
};
/**
* Params of mod_chat_login_user WS.
*/
export type AddonModChatLoginUserWSParams = {
chatid: number; // Chat instance id.
groupid?: number; // Group id, 0 means that the function will determine the user group.
};
/**
* Data returned by mod_chat_login_user WS.
*/
export type AddonModChatLoginUserWSResponse = {
chatsid: string; // Unique chat session id.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_chat_view_chat WS.
*/
export type AddonModChatViewChatWSParams = {
chatid: number; // Chat instance id.
};
/**
* Params of mod_chat_send_chat_message WS.
*/
export type AddonModChatSendChatMessageWSParams = {
chatsid: string; // Chat session id (obtained via mod_chat_login_user).
messagetext: string; // The message text.
beepid?: string; // The beep id.
};
/**
* Data returned by mod_chat_send_chat_message WS.
*/
export type AddonModChatSendChatMessageWSResponse = {
messageid: number; // Message sent id.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_chat_get_chat_latest_messages WS.
*/
export type AddonModChatGetChatLatestMessagesWSParams = {
chatsid: string; // Chat session id (obtained via mod_chat_login_user).
chatlasttime?: number; // Last time messages were retrieved (epoch time).
};
/**
* Data returned by mod_chat_get_chat_latest_messages WS.
*/
export type AddonModChatGetChatLatestMessagesWSResponse = {
messages: AddonModChatWSMessage[];
chatnewlasttime: number; // New last time.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_chat_get_chat_users WS.
*/
export type AddonModChatGetChatUsersWSParams = {
chatsid: string; // Chat session id (obtained via mod_chat_login_user).
};
/**
* Data returned by mod_chat_get_chat_users WS.
*/
export type AddonModChatGetChatUsersWSResponse = {
users: AddonModChatUser[]; // List of users.
warnings?: CoreWSExternalWarning[];
};
/**
* Chat user returned by mod_chat_get_chat_users.
*/
export type AddonModChatUser = {
id: number; // User id.
fullname: string; // User full name.
profileimageurl: string; // User picture URL.
};
/**
* Params of mod_chat_get_sessions WS.
*/
export type AddonModChatGetSessionsWSParams = {
chatid: number; // Chat instance id.
groupid?: number; // Get messages from users in this group. 0 means that the function will determine the user group.
showall?: boolean; // Whether to show completed sessions or not.
};
/**
* Data returned by mod_chat_get_sessions WS.
*/
export type AddonModChatGetSessionsWSResponse = {
sessions: AddonModChatSession[]; // List of sessions.
warnings?: CoreWSExternalWarning[];
};
/**
* Chat session returned by mod_chat_get_sessions.
*/
export type AddonModChatSession = {
sessionstart: number; // Session start time.
sessionend: number; // Session end time.
sessionusers: AddonModChatSessionUser[]; // Session users.
iscomplete: boolean; // Whether the session is completed or not.
};
/**
* Chat user returned by mod_chat_get_sessions.
*/
export type AddonModChatSessionUser = {
userid: number; // User id.
messagecount: number; // Number of messages in the session.
};
/**
* Params of mod_chat_get_session_messages WS.
*/
export type AddonModChatGetSessionMessagesWSParams = {
chatid: number; // Chat instance id.
sessionstart: number; // The session start time (timestamp).
sessionend: number; // The session end time (timestamp).
groupid?: number; // Get messages from users in this group. 0 means that the function will determine the user group.
};
/**
* Data returned by mod_chat_get_session_messages WS.
*/
export type AddonModChatGetSessionMessagesWSResponse = {
messages: AddonModChatWSSessionMessage[];
warnings?: CoreWSExternalWarning[];
};
/**
* Meessage returned by mod_chat_get_chat_latest_messages.
*/
export type AddonModChatWSMessage = {
id: number; // Message id.
userid: number; // User id.
system: boolean; // True if is a system message (like user joined).
message: string; // Message text.
timestamp: number; // Timestamp for the message.
};
/**
* Message with user data.
*/
export type AddonModChatMessage = AddonModChatWSMessage & AddonModChatMessageUserData;
/**
* Message returned by mod_chat_get_session_messages.
*/
export type AddonModChatWSSessionMessage = {
id: number; // The message record id.
chatid: number; // The chat id.
userid: number; // The user who wrote the message.
groupid: number; // The group this message belongs to.
issystem: boolean; // Whether is a system message or not.
message: string; // The message text.
timestamp: number; // The message timestamp (indicates when the message was sent).
};
/**
* Session message with user data.
*/
export type AddonModChatSessionMessage = AddonModChatWSSessionMessage & AddonModChatMessageUserData;
/**
* User data added to messages.
*/
type AddonModChatMessageUserData = {
userfullname?: string; // Calculated in the app. Full name of the user who wrote the message.
userprofileimageurl?: string; // Calculated in the app. Full name of the user who wrote the message.
};

View File

@ -0,0 +1,33 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreContentLinksModuleIndexHandler } from '@features/contentlinks/classes/module-index-handler';
import { makeSingleton } from '@singletons';
/**
* Handler to treat links to chat.
*/
@Injectable({ providedIn: 'root' })
export class AddonModChatIndexLinkHandlerService extends CoreContentLinksModuleIndexHandler {
name = 'AddonModChatIndexLinkHandlerService';
constructor() {
super('AddonModChat', 'chat', 'c');
}
}
export const AddonModChatIndexLinkHandler = makeSingleton(AddonModChatIndexLinkHandlerService);

View File

@ -0,0 +1,33 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreContentLinksModuleListHandler } from '@features/contentlinks/classes/module-list-handler';
import { makeSingleton } from '@singletons';
/**
* Handler to treat links to chat list page.
*/
@Injectable({ providedIn: 'root' })
export class AddonModChatListLinkHandlerService extends CoreContentLinksModuleListHandler {
name = 'AddonModChatListLinkHandler';
constructor() {
super('AddonModChat', 'chat');
}
}
export const AddonModChatListLinkHandler = makeSingleton(AddonModChatListLinkHandlerService);

View File

@ -0,0 +1,95 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { CoreConstants } from '@/core/constants';
import { Injectable, Type } from '@angular/core';
import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course';
import { CoreCourseModule } from '@features/course/services/course-helper';
import { CoreCourseModuleHandler, CoreCourseModuleHandlerData } from '@features/course/services/module-delegate';
import { CoreNavigationOptions, CoreNavigator } from '@services/navigator';
import { makeSingleton } from '@singletons';
import { AddonModChatIndexComponent } from '../../components/index';
import { AddonModChat } from '../chat';
/**
* Handler to support chat modules.
*/
@Injectable({ providedIn: 'root' })
export class AddonModChatModuleHandlerService implements CoreCourseModuleHandler {
static readonly PAGE_NAME = 'mod_chat';
name = 'AddonModChat';
modName = 'chat';
supportedFeatures = {
[CoreConstants.FEATURE_GROUPS]: true,
[CoreConstants.FEATURE_GROUPINGS]: true,
[CoreConstants.FEATURE_MOD_INTRO]: true,
[CoreConstants.FEATURE_COMPLETION_TRACKS_VIEWS]: true,
[CoreConstants.FEATURE_GRADE_HAS_GRADE]: false,
[CoreConstants.FEATURE_GRADE_OUTCOMES]: true,
[CoreConstants.FEATURE_BACKUP_MOODLE2]: true,
[CoreConstants.FEATURE_SHOW_DESCRIPTION]: true,
};
/**
* @inheritdoc
*/
async isEnabled(): Promise<boolean> {
return true;
}
/**
* @inheritdoc
*/
getData(module: CoreCourseAnyModuleData): CoreCourseModuleHandlerData {
const data: CoreCourseModuleHandlerData = {
icon: CoreCourse.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined),
title: module.name,
class: 'addon-mod_chat-handler',
action(event: Event, module: CoreCourseModule, courseId: number, options?: CoreNavigationOptions): void {
options = options || {};
options.params = options.params || {};
Object.assign(options.params, { module });
const routeParams = '/' + courseId + '/' + module.id;
CoreNavigator.navigateToSitePath(AddonModChatModuleHandlerService.PAGE_NAME + routeParams, options);
},
};
this.checkDownloadButton(data);
return data;
}
/**
* Check whether download button should be displayed.
*
* @param data Handler data.
*/
protected async checkDownloadButton(data: CoreCourseModuleHandlerData): Promise<void> {
data.showDownloadButton = await AddonModChat.areSessionsAvailable();
}
/**
* @inheritdoc
*/
async getMainComponent(): Promise<Type<unknown>> {
return AddonModChatIndexComponent;
}
}
export const AddonModChatModuleHandler = makeSingleton(AddonModChatModuleHandlerService);

View File

@ -0,0 +1,186 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreCourseActivityPrefetchHandlerBase } from '@features/course/classes/activity-prefetch-handler';
import { CoreCourse, CoreCourseAnyModuleData, CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { CoreUser } from '@features/user/services/user';
import { CoreGroups } from '@services/groups';
import { CoreSites, CoreSitesReadingStrategy } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton } from '@singletons';
import { AddonModChat, AddonModChatProvider, AddonModChatSession } from '../chat';
/**
* Handler to prefetch chats.
*/
@Injectable({ providedIn: 'root' })
export class AddonModChatPrefetchHandlerService extends CoreCourseActivityPrefetchHandlerBase {
name = 'AddonModChat';
modName = 'chat';
component = AddonModChatProvider.COMPONENT;
/**
* @inheritdoc
*/
async isEnabled(): Promise<boolean> {
return AddonModChat.areSessionsAvailable();
}
/**
* @inheritdoc
*/
async invalidateContent(moduleId: number, courseId: number): Promise<void> {
const chat = await AddonModChat.getChat(courseId, moduleId);
await CoreUtils.allPromises([
AddonModChat.invalidateAllSessions(chat.id),
AddonModChat.invalidateAllSessionMessages(chat.id),
]);
}
/**
* @inheritdoc
*/
async invalidateModule(module: CoreCourseAnyModuleData, courseId: number): Promise<void> {
await CoreUtils.allPromises([
AddonModChat.invalidateChats(courseId),
CoreCourse.invalidateModule(module.id),
]);
}
/**
* @inheritdoc
*/
prefetch(module: CoreCourseAnyModuleData, courseId?: number): Promise<void> {
return this.prefetchPackage(module, courseId, this.prefetchChat.bind(this, module, courseId));
}
/**
* Prefetch a chat.
*
* @param module The module object returned by WS.
* @param courseId Course ID the module belongs to.
* @return Promise resolved when done.
*/
protected async prefetchChat(module: CoreCourseAnyModuleData, courseId: number): Promise<void> {
const siteId = CoreSites.getCurrentSiteId();
const options = {
readingStrategy: CoreSitesReadingStrategy.OnlyNetwork,
siteId,
};
const modOptions = {
...options,
cmId: module.id,
};
// Prefetch chat and group info.
const [chat, groupInfo] = await Promise.all([
AddonModChat.getChat(courseId, module.id, options),
CoreGroups.getActivityGroupInfo(module.id, false, undefined, siteId),
]);
const promises: Promise<void>[] = [];
let groupIds = [0];
if (groupInfo.groups && groupInfo.groups.length > 0) {
groupIds = groupInfo.groups.map((group) => group.id);
}
groupIds.forEach((groupId) => {
// Prefetch complete sessions.
promises.push(this.prefetchSessions(chat.id, groupId, courseId, false, modOptions));
// Prefetch all sessions.
promises.push(this.prefetchSessions(chat.id, groupId, courseId, true, modOptions));
});
await Promise.all(promises);
}
/**
* Prefetch chat sessions.
*
* @param chatId Chat ID.
* @param groupId Group ID, 0 means that the function will determine the user group.
* @param courseId Course ID.
* @param showAll Whether to include incomplete sessions or not.
* @param modOptions Other options.
* @return Promise resolved with the list of sessions.
*/
protected async prefetchSessions(
chatId: number,
groupId: number,
courseId: number,
showAll: boolean,
modOptions: CoreCourseCommonModWSOptions,
): Promise<void> {
try {
const sessions = await AddonModChat.getSessions(chatId, groupId, showAll, modOptions);
if (showAll) {
// Prefetch each session data too.
await Promise.all(sessions.map((session) => this.prefetchSession(chatId, session, groupId, courseId, modOptions)));
}
} catch (error) {
// Ignore group error.
if (error && error.errorcode == 'notingroup') {
return;
}
throw error;
}
}
/**
* Prefetch chat session messages and user profiles.
*
* @param chatId Chat ID.
* @param session Session object.
* @param groupId Group ID.
* @param courseId Course ID the module belongs to.
* @param modOptions Other options.
* @return Promise resolved when done.
*/
protected async prefetchSession(
chatId: number,
session: AddonModChatSession,
groupId: number,
courseId: number,
modOptions: CoreCourseCommonModWSOptions,
): Promise<void> {
const messages = await AddonModChat.getSessionMessages(
chatId,
session.sessionstart,
session.sessionend,
groupId,
modOptions,
);
const users: Record<number, number> = {};
session.sessionusers.forEach((user) => {
users[user.userid] = user.userid;
});
messages.forEach((message) => {
users[message.userid] = message.userid;
});
const userIds = Object.values(users);
await CoreUser.prefetchProfiles(userIds, courseId, modOptions.siteId);
}
}
export const AddonModChatPrefetchHandler = makeSingleton(AddonModChatPrefetchHandlerService);

View File

@ -33,6 +33,7 @@ import { AddonModScormModule } from './scorm/scorm.module';
import { AddonModChoiceModule } from './choice/choice.module';
import { AddonModWikiModule } from './wiki/wiki.module';
import { AddonModGlossaryModule } from './glossary/glossary.module';
import { AddonModChatModule } from './chat/chat.module';
@NgModule({
imports: [
@ -55,6 +56,7 @@ import { AddonModGlossaryModule } from './glossary/glossary.module';
AddonModChoiceModule,
AddonModWikiModule,
AddonModGlossaryModule,
AddonModChatModule,
],
})
export class AddonModModule { }

View File

@ -124,7 +124,7 @@ import { ADDON_MESSAGEOUTPUT_SERVICES } from '@addons/messageoutput/messageoutpu
import { ADDON_MESSAGES_SERVICES } from '@addons/messages/messages.module';
import { ADDON_MOD_ASSIGN_SERVICES } from '@addons/mod/assign/assign.module';
import { ADDON_MOD_BOOK_SERVICES } from '@addons/mod/book/book.module';
// @todo import { ADDON_MOD_CHAT_SERVICES } from '@addons/mod/chat/chat.module';
import { ADDON_MOD_CHAT_SERVICES } from '@addons/mod/chat/chat.module';
import { ADDON_MOD_CHOICE_SERVICES } from '@addons/mod/choice/choice.module';
import { ADDON_MOD_DATA_SERVICES } from '@addons/mod/data/data.module';
// @todo import { ADDON_MOD_FEEDBACK_SERVICES } from '@addons/mod/feedback/feedback.module';
@ -290,7 +290,7 @@ export class CoreCompileProvider {
...ADDON_MESSAGES_SERVICES,
...ADDON_MOD_ASSIGN_SERVICES,
...ADDON_MOD_BOOK_SERVICES,
// @todo ...ADDON_MOD_CHAT_SERVICES,
...ADDON_MOD_CHAT_SERVICES,
...ADDON_MOD_CHOICE_SERVICES,
...ADDON_MOD_DATA_SERVICES,
// @todo ...ADDON_MOD_FEEDBACK_SERVICES,