Compare commits
23 Commits
3.0-beta9
...
277bbc14d9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
277bbc14d9 | ||
|
|
05e24d768a | ||
|
|
eaa355e40e | ||
|
|
8fc0da520c | ||
|
|
7149ebad10 | ||
|
|
34752b446c | ||
|
|
c18a8c14ca | ||
|
|
bc8501d74c | ||
|
|
76d96067d0 | ||
|
|
aa3494eac0 | ||
|
|
e386608e59 | ||
|
|
56d6065eef | ||
|
|
aa811bff1b | ||
|
|
b4ff8356ab | ||
|
|
f836df391b | ||
|
|
1988c0a61e | ||
|
|
043a97ada5 | ||
|
|
3ef5387b8d | ||
|
|
086d27c9a4 | ||
|
|
eeee9d5154 | ||
| aa3e1de412 | |||
| f9518a9164 | |||
| 3ed025ee61 |
@@ -24,6 +24,11 @@
|
||||
"glob": "**/*",
|
||||
"input": "public"
|
||||
},
|
||||
{
|
||||
"glob": "**/*",
|
||||
"input": "node_modules/@taiga-ui/icons/src",
|
||||
"output": "assets/taiga-ui/icons"
|
||||
},
|
||||
{
|
||||
"glob": "**/*",
|
||||
"input": "node_modules/@taiga-ui/icons/src",
|
||||
|
||||
4600
package-lock.json
generated
4600
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
21
package.json
21
package.json
@@ -25,17 +25,21 @@
|
||||
"@fortawesome/free-solid-svg-icons": "^7.1.0",
|
||||
"@ngx-translate/core": "^17.0.0",
|
||||
"@ngx-translate/http-loader": "^17.0.0",
|
||||
"@taiga-ui/addon-charts": "^5.1.0",
|
||||
"@taiga-ui/addon-mobile": "^5.1.0",
|
||||
"@taiga-ui/addon-table": "^5.1.0",
|
||||
"@taiga-ui/cdk": "^5.1.0",
|
||||
"@taiga-ui/core": "^5.1.0",
|
||||
"@taiga-ui/addon-charts": "^5.25.0",
|
||||
"@taiga-ui/addon-commerce": "^5.25.0",
|
||||
"@taiga-ui/addon-doc": "^5.25.0",
|
||||
"@taiga-ui/addon-mobile": "^5.25.0",
|
||||
"@taiga-ui/addon-table": "^5.25.0",
|
||||
"@taiga-ui/cdk": "^5.25.0",
|
||||
"@taiga-ui/core": "^5.25.0",
|
||||
"@taiga-ui/i18n": "^5.2.0",
|
||||
"@taiga-ui/icons": "^5.1.0",
|
||||
"@taiga-ui/kit": "^5.1.0",
|
||||
"@taiga-ui/layout": "^5.1.0",
|
||||
"@taiga-ui/icons": "^5.25.0",
|
||||
"@taiga-ui/kit": "^5.25.0",
|
||||
"@taiga-ui/layout": "^5.25.0",
|
||||
"chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.7",
|
||||
"libphonenumber-js": "^1.12.41",
|
||||
"ngx-cookie-service": "^21.3.1",
|
||||
"ngx-device-detector": "^11.0.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
"uuid": "^13.0.0"
|
||||
@@ -44,6 +48,7 @@
|
||||
"@angular/build": "^21.2.6",
|
||||
"@angular/cli": "^21.2.6",
|
||||
"@angular/compiler-cli": "^21.2.0",
|
||||
"@types/google.accounts": "^0.0.18",
|
||||
"jsdom": "^28.0.0",
|
||||
"less": "^4.6.4",
|
||||
"prettier": "^3.8.1",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "Chatenium Nexum 3.0 Beta 9 (April 19, 2026)",
|
||||
"version": "Chatenium Nexum 3.0 Beta 11 (October 4, 2026)",
|
||||
"ok": "Ok",
|
||||
"back": "Back",
|
||||
"aChatProgram": "A messaging platform that you can trust.",
|
||||
@@ -79,7 +79,9 @@
|
||||
"microsoftStoreDesc": "Start testing the application on your Windows computer via the Microsoft Store!"
|
||||
},
|
||||
"signIn": {
|
||||
"formTitle": "Sign in",
|
||||
"initial": {
|
||||
"formTitle": "Welcome back!",
|
||||
"formSubtitle": "Sign in with your Chatenium account.",
|
||||
"mainInput": {
|
||||
"label": "Username, email or phone number",
|
||||
"placeholder": "bob, bob@example.com, +36201234567"
|
||||
@@ -87,15 +89,59 @@
|
||||
"password": {
|
||||
"label": "Password"
|
||||
},
|
||||
"emailButton": "Sign in with email code",
|
||||
"smsButton": "Sign in with SMS code",
|
||||
"signInButton": "Sign in",
|
||||
"signInButton": "Sign in"
|
||||
},
|
||||
"methodChoose": {
|
||||
"formTitle": "Choose a verification method",
|
||||
"formSubtitle": "Based on your security settings, more than 1 verification method may be required.",
|
||||
"formTitleAlt": "Choose another verification method",
|
||||
"formSubtitleAlt": "Because of your security settings, multiple verification methods are required",
|
||||
"methods": {
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"desc": "Use your password to verify your identity"
|
||||
},
|
||||
"mail": {
|
||||
"title": "E-mail",
|
||||
"desc": "Use a one-time e-mail code to verify your identity"
|
||||
},
|
||||
"sms": {
|
||||
"title": "SMS",
|
||||
"desc": "Use a one-time SMS code to verify your identity"
|
||||
},
|
||||
"google": {
|
||||
"title": "Google",
|
||||
"desc": "Use your linked Google account to verify your identity"
|
||||
},
|
||||
"apple": {
|
||||
"title": "Apple",
|
||||
"desc": "Use your linked Apple account to verify your identity"
|
||||
}
|
||||
}
|
||||
},
|
||||
"anyAuth": {
|
||||
"verifyButton": "Verify identity"
|
||||
},
|
||||
"passwordAuth": {
|
||||
"formTitle": "Password authentication",
|
||||
"formSubtitle": "Enter your password below",
|
||||
"errors": {
|
||||
"unameMailPhoneRequired": "Username, email or phone number is required",
|
||||
"passwordRequired": "Password is required",
|
||||
"passwordIncorrect": "Password is incorrect"
|
||||
}
|
||||
},
|
||||
"emailAuth": {
|
||||
"formTitle": "E-mail authentication",
|
||||
"formSubtitle": "Enter your one-time e-mail code below",
|
||||
"errors": {
|
||||
"passwordRequired": "Code is required",
|
||||
"passwordIncorrect": "Code is incorrect"
|
||||
},
|
||||
"emailCode": {
|
||||
"label": "E-mail code"
|
||||
}
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"userSettingsDialog": {
|
||||
"label": "Settings",
|
||||
@@ -218,8 +264,8 @@
|
||||
"changeLogDialog": {
|
||||
"label": "Chatenium has been updated",
|
||||
"changeLog": {
|
||||
"1": "Started implementing user settings, Privacy & Security is now available.",
|
||||
"2": "Enabled Chatenium Pictures on mobile devices."
|
||||
"1": "The network UI have been merged with the left side navigation panel.",
|
||||
"2": "Categories and channels now have a threaded UI to align with recent changes"
|
||||
}
|
||||
},
|
||||
"chatnav": {
|
||||
|
||||
@@ -1,37 +1,39 @@
|
||||
import {provideTaiga} from '@taiga-ui/core';
|
||||
import {ApplicationConfig, provideBrowserGlobalErrorListeners, isDevMode} from '@angular/core';
|
||||
import {provideRouter, withRouterConfig} from '@angular/router';
|
||||
import { provideTaiga } from '@taiga-ui/core';
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners, isDevMode } from '@angular/core';
|
||||
import { provideRouter, withRouterConfig } from '@angular/router';
|
||||
|
||||
import {routes} from './app.routes';
|
||||
import {provideTranslateService} from '@ngx-translate/core';
|
||||
import {provideTranslateHttpLoader} from '@ngx-translate/http-loader';
|
||||
import {provideServiceWorker} from '@angular/service-worker';
|
||||
import {tuiInputPhoneInternationalOptionsProvider} from '@taiga-ui/kit';
|
||||
import {defer} from 'rxjs';
|
||||
import { routes } from './app.routes';
|
||||
import { provideTranslateService } from '@ngx-translate/core';
|
||||
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
|
||||
import { provideServiceWorker } from '@angular/service-worker';
|
||||
import { tuiInputPhoneInternationalOptionsProvider } from '@taiga-ui/kit';
|
||||
import { defer } from 'rxjs';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes, withRouterConfig({
|
||||
paramsInheritanceStrategy: "always"
|
||||
})),
|
||||
provideRouter(
|
||||
routes,
|
||||
withRouterConfig({
|
||||
paramsInheritanceStrategy: 'always',
|
||||
}),
|
||||
),
|
||||
provideTaiga(),
|
||||
provideTranslateService({
|
||||
fallbackLang: "en",
|
||||
lang: "hu",
|
||||
fallbackLang: 'en',
|
||||
lang: 'en',
|
||||
loader: provideTranslateHttpLoader({
|
||||
prefix: "/i18n/",
|
||||
suffix: ".json"
|
||||
})
|
||||
prefix: '/i18n/',
|
||||
suffix: '.json',
|
||||
}),
|
||||
}),
|
||||
provideServiceWorker('ngsw-worker.js', {
|
||||
enabled: !isDevMode(),
|
||||
registrationStrategy: 'registerWhenStable:30000'
|
||||
registrationStrategy: 'registerWhenStable:30000',
|
||||
}),
|
||||
tuiInputPhoneInternationalOptionsProvider({
|
||||
metadata: defer(async () =>
|
||||
import('libphonenumber-js/max/metadata').then((m) => m.default),
|
||||
),
|
||||
metadata: defer(async () => import('libphonenumber-js/max/metadata').then((m) => m.default)),
|
||||
}),
|
||||
provideTaiga(),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,30 +1,29 @@
|
||||
import {Routes} from '@angular/router';
|
||||
import {SignIn} from './signin/signin';
|
||||
import {Chat} from './chat/chat';
|
||||
import {Dm} from './chat/dm/dm';
|
||||
import {noAuthGuard} from './guards/no-auth-guard';
|
||||
import {authNeededGuard} from './guards/auth-needed-guard';
|
||||
import {Homepage} from './homepage/homepage';
|
||||
import {Privacy} from './privacy/privacy';
|
||||
import {TOS} from './tos/tos';
|
||||
import {Network} from './chat/network/network';
|
||||
import {Text} from './chat/network/channel/text/text';
|
||||
import {See} from './chat/picture/see/see';
|
||||
import { Routes } from '@angular/router';
|
||||
import { SignIn } from './signin/signin';
|
||||
import { Chat } from './chat/chat';
|
||||
import { Dm } from './chat/dm/dm';
|
||||
import { noAuthGuard } from './guards/no-auth-guard';
|
||||
import { authNeededGuard } from './guards/auth-needed-guard';
|
||||
import { Homepage } from './homepage/homepage';
|
||||
import { Privacy } from './privacy/privacy';
|
||||
import { TOS } from './tos/tos';
|
||||
import { Network } from './chat/network/network';
|
||||
import { Text } from './chat/network/channel/text/text';
|
||||
import { See } from './chat/picture/see/see';
|
||||
|
||||
export const routes: Routes = [
|
||||
{path: '', component: Homepage},
|
||||
{path: 'privacy', component: Privacy},
|
||||
{path: 'tos', component: TOS},
|
||||
{path: 'signin', component: SignIn, canActivate: [noAuthGuard]},
|
||||
{ path: '', component: Homepage },
|
||||
{ path: 'privacy', component: Privacy },
|
||||
{ path: 'tos', component: TOS },
|
||||
{ path: 'signin', component: SignIn, canActivate: [noAuthGuard] },
|
||||
{
|
||||
path: 'chat', component: Chat, canActivate: [authNeededGuard], children: [
|
||||
{path: 'dm/:chatid', component: Dm},
|
||||
{path: 'picture/:uploaderId', component: See},
|
||||
{
|
||||
path: 'network/:networkId', component: Network, children: [
|
||||
{path: ":categoryId/:channelId", component: Text}
|
||||
]
|
||||
},
|
||||
]
|
||||
path: 'chat',
|
||||
component: Chat,
|
||||
canActivate: [authNeededGuard],
|
||||
children: [
|
||||
{ path: 'dm/:contactId', component: Dm },
|
||||
{ path: 'picture/:uploaderId', component: See },
|
||||
{ path: 'network/:networkId/:categoryId/:channelId', component: Text },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { TuiRoot } from '@taiga-ui/core';
|
||||
import {Component, inject, OnInit, signal} from '@angular/core';
|
||||
import { Component, inject, OnInit, signal } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { environment as env } from '../environments/environment';
|
||||
import {environment, SDKConfig} from '@chatenium/chatenium-sdk/core/environment';
|
||||
import {IndexedDB} from './storage/indexed-db';
|
||||
import { environment, SDKConfig } from '@chatenium/chatenium-sdk/core/environment';
|
||||
import { IndexedDB } from './storage/indexed-db';
|
||||
import { SessionManager } from './session-manager';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [RouterOutlet, TuiRoot],
|
||||
imports: [RouterOutlet, TuiRoot, TuiRoot],
|
||||
templateUrl: './app.html',
|
||||
styleUrl: './app.scss',
|
||||
})
|
||||
export class App implements OnInit {
|
||||
indexedDb = inject(IndexedDB)
|
||||
indexedDb = inject(IndexedDB);
|
||||
sessionManager = inject(SessionManager);
|
||||
|
||||
protected readonly title = signal('Chatenium-On-Web');
|
||||
|
||||
@@ -22,5 +24,8 @@ export class App implements OnInit {
|
||||
apiUrl: env.api_url,
|
||||
wsUrl: env.ws_url,
|
||||
});
|
||||
this.indexedDb.openDatabase().then(() => {
|
||||
this.sessionManager.loadSessions();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
16
src/app/cache.spec.ts
Normal file
16
src/app/cache.spec.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { CacheService } from './cache';
|
||||
|
||||
describe('Cache', () => {
|
||||
let service: CacheService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(CacheService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
31
src/app/cache.ts
Normal file
31
src/app/cache.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Injectable, signal, WritableSignal } from '@angular/core';
|
||||
import { MessagesViewModel } from './chat/elements/messages/messages-viewmodel';
|
||||
import { MessageBoxViewModel } from './chat/elements/message-box/message-box-viewmodel';
|
||||
import {WrappedDMHandler, DirectMessagingApi, Contact, Message} from "chatenium-sdk-preview"
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CacheService {
|
||||
contacts = signal<Contact[]>([]);
|
||||
contactsState = signal<LoadState>(LoadState.CLEAN_LOADING);
|
||||
|
||||
dms = signal<Record<string, DmStorage>>({});
|
||||
}
|
||||
|
||||
export enum LoadState {
|
||||
CLEAN_LOADING,
|
||||
CACHE_UPDATING,
|
||||
LOADED,
|
||||
ERROR,
|
||||
}
|
||||
|
||||
export interface DmStorage {
|
||||
handler: WrappedDMHandler<DirectMessagingApi>;
|
||||
messages: WritableSignal<Message[]>;
|
||||
messagesState: WritableSignal<LoadState>;
|
||||
messagesVm: MessagesViewModel;
|
||||
chatData: WritableSignal<Contact>;
|
||||
messageBox: MessageBoxViewModel;
|
||||
wsListener: (action: string, message: string) => void;
|
||||
}
|
||||
@@ -11,50 +11,53 @@
|
||||
</button>
|
||||
</ng-template>
|
||||
|
||||
<ng-template [(tuiDialog)]="userSettingsOpen" [tuiDialogOptions]="{closable: false, appearance: 'taiga big'}" class="user-settings">
|
||||
<user-settings (close)="userSettingsOpen.set(false)"/>
|
||||
<ng-template [(tuiDialog)]="userSettingsOpen" [tuiDialogOptions]="{closable: false, appearance: 'taiga big'}"
|
||||
class="user-settings">
|
||||
<user-settings (close)="userSettingsOpen.set(false)" />
|
||||
</ng-template>
|
||||
|
||||
@if (serviceManager.currentSession() == null) {
|
||||
@if (!sessionManager.sessionReady()) {
|
||||
<main style="width: 100%; height: 100svh; display: flex; justify-content: center; align-items: center;">
|
||||
<tui-loader size="xl"/>
|
||||
<tui-loader size="xl" />
|
||||
</main>
|
||||
} @else {
|
||||
@if (breakpoint() != "mobile") {
|
||||
<main id="layout" tuiGroup [collapsed]="true">
|
||||
<main id="layout" tuiGroup [collapsed]="true" [class.expanded]="expandedSidenav()">
|
||||
<aside id="chatnav">
|
||||
<aside>
|
||||
<tui-segmented id="mode_switcher" [(activeItemIndex)]="navigationActiveIndex">
|
||||
<button>
|
||||
<tui-icon icon="@tui.message-circle"/>
|
||||
<button (click)="expandedSidenav.set(false)">
|
||||
<tui-icon icon="@tui.message-circle" />
|
||||
</button>
|
||||
<button>
|
||||
<tui-icon icon="@tui.network"/>
|
||||
<tui-icon icon="@tui.network" />
|
||||
</button>
|
||||
<button>
|
||||
<tui-icon icon="@tui.image"/>
|
||||
<button (click)="expandedSidenav.set(false)">
|
||||
<tui-icon icon="@tui.image" />
|
||||
</button>
|
||||
</tui-segmented>
|
||||
|
||||
<button id="bottom_btn" tuiButton [appearance]="userSettingsOpen() ? 'primary' : 'flat'" (click)="userSettingsOpen.set(true)">
|
||||
<tui-icon icon="@tui.cog"/>
|
||||
<button id="bottom_btn" tuiButton [appearance]="userSettingsOpen() ? 'primary' : 'flat'"
|
||||
(click)="userSettingsOpen.set(true)">
|
||||
<tui-icon icon="@tui.cog" />
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<main>
|
||||
@switch (navigationActiveIndex) {
|
||||
@case (0) {
|
||||
<app-dm-list [token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></app-dm-list>
|
||||
}
|
||||
<app-contact-list></app-contact-list>
|
||||
} <!--
|
||||
@case (1) {
|
||||
<network-list [token]="serviceManager.currentSession()!.token"
|
||||
<network-list
|
||||
[(expandedSidenav)]="expandedSidenav"
|
||||
[token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></network-list>
|
||||
}
|
||||
@case (2) {
|
||||
<app-picture-list [token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></app-picture-list>
|
||||
}
|
||||
}-->
|
||||
}
|
||||
</main>
|
||||
</aside>
|
||||
@@ -63,15 +66,15 @@
|
||||
<div id="content_tint">
|
||||
@if (router.url.startsWith("/chat/dm") || router.url.startsWith("/chat/picture")) {
|
||||
<!-- To ensure data is loaded -->
|
||||
@defer (when serviceManager.chatsStatus() != LoadStatus.loading) {
|
||||
<router-outlet/>
|
||||
@defer (when cache.contactsState() != LoadState.CLEAN_LOADING) {
|
||||
<router-outlet />
|
||||
}
|
||||
} @else if (router.url.startsWith("/chat/network")) {
|
||||
@defer (when serviceManager.networksStatus() != LoadStatus.loading) {
|
||||
<router-outlet/>
|
||||
<router-outlet />
|
||||
}
|
||||
} @else {
|
||||
<router-outlet/>
|
||||
<router-outlet />
|
||||
}
|
||||
</div>
|
||||
</main>
|
||||
@@ -81,13 +84,16 @@
|
||||
@if (!routerOutletActive()) {
|
||||
<div id="navigation">
|
||||
<div id="navigation_content">
|
||||
<!--
|
||||
@switch (navigationActiveIndex) {
|
||||
@case (0) {
|
||||
<app-dm-list [token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></app-dm-list>
|
||||
<app-contact-list [token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></app-contact-list>
|
||||
}
|
||||
@case (1) {
|
||||
<network-list [token]="serviceManager.currentSession()!.token"
|
||||
<network-list
|
||||
[(expandedSidenav)]="expandedSidenav"
|
||||
[token]="serviceManager.currentSession()!.token"
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></network-list>
|
||||
}
|
||||
@case (2) {
|
||||
@@ -95,9 +101,10 @@
|
||||
[userid]="serviceManager.currentSession()!.userData.userid"></app-picture-list>
|
||||
}
|
||||
@case (3) {
|
||||
<user-settings/>
|
||||
<user-settings />
|
||||
}
|
||||
}
|
||||
-->
|
||||
</div>
|
||||
|
||||
<nav tuiTabBar [(activeItemIndex)]="navigationActiveIndex">
|
||||
@@ -120,14 +127,14 @@
|
||||
@if (router.url.startsWith("/chat/dm") || router.url.startsWith("/chat/picture")) {
|
||||
<!-- To ensure data is loaded -->
|
||||
@defer (when serviceManager.chatsStatus() != LoadStatus.loading) {
|
||||
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)"/>
|
||||
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)" />
|
||||
}
|
||||
} @else if (router.url.startsWith("/chat/network")) {
|
||||
@defer (when serviceManager.networksStatus() != LoadStatus.loading) {
|
||||
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)"/>
|
||||
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)" />
|
||||
}
|
||||
} @else {
|
||||
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)"/>
|
||||
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)" />
|
||||
}
|
||||
</main>
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
#layout {
|
||||
transition: 0.3s ease;
|
||||
display: grid;
|
||||
grid-template-columns: 350px minmax(0, 1fr);
|
||||
height: 100svh;
|
||||
overflow: hidden;
|
||||
|
||||
&.expanded {
|
||||
grid-template-columns: 450px minmax(0, 1fr) !important;
|
||||
}
|
||||
|
||||
#chatnav {
|
||||
display: grid;
|
||||
@@ -44,11 +48,12 @@
|
||||
}
|
||||
|
||||
main {
|
||||
overflow-y: scroll;
|
||||
overflow-x: hidden;
|
||||
background: var(--tui-background-base-alt);
|
||||
border-radius: 20px 0 0 20px;
|
||||
margin: 10px 0 10px 10px;
|
||||
padding: 15px;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,9 @@ import {Component, computed, inject, OnInit, signal} from '@angular/core';
|
||||
import {isActive, IsActiveMatchOptions, Router, RouterOutlet} from '@angular/router';
|
||||
import {TuiSegmented} from '@taiga-ui/kit';
|
||||
import {TUI_BREAKPOINT, TuiAppearance, TuiButton, TuiDialog, TuiGroup, TuiIcon, TuiLoader} from '@taiga-ui/core';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import {LoadStatus, ServiceManager} from '../service-manager';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {DmList} from './dm-list/dm-list';
|
||||
import {ContactList} from './contact-list/contact-list';
|
||||
import {JsonPipe} from '@angular/common';
|
||||
import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler';
|
||||
import {TranslatePipe, TranslateService} from '@ngx-translate/core';
|
||||
@@ -16,6 +15,8 @@ import {PictureList} from './picture-list/picture-list';
|
||||
import {UserSettings} from './user-settings/user-settings';
|
||||
import {AuthService} from '@chatenium/chatenium-sdk/services/authService';
|
||||
import {UserService} from '@chatenium/chatenium-sdk/services/userService';
|
||||
import { SessionManager } from '../session-manager';
|
||||
import { CacheService, LoadState } from '../cache';
|
||||
|
||||
@Component({
|
||||
selector: 'app-chat',
|
||||
@@ -25,7 +26,7 @@ import {UserService} from '@chatenium/chatenium-sdk/services/userService';
|
||||
TuiIcon,
|
||||
TuiButton,
|
||||
TuiLoader,
|
||||
DmList,
|
||||
ContactList,
|
||||
JsonPipe,
|
||||
TuiAppearance,
|
||||
TuiGroup,
|
||||
@@ -41,10 +42,14 @@ import {UserService} from '@chatenium/chatenium-sdk/services/userService';
|
||||
styleUrl: './chat.scss',
|
||||
})
|
||||
export class Chat implements OnInit {
|
||||
serviceManager = inject(ServiceManager)
|
||||
indexedDb = inject(IndexedDB)
|
||||
breakpoint = inject(TUI_BREAKPOINT)
|
||||
router = inject(Router)
|
||||
sessionManager = inject(SessionManager);
|
||||
serviceManager = inject(ServiceManager);
|
||||
cache = inject(CacheService);
|
||||
indexedDb = inject(IndexedDB);
|
||||
breakpoint = inject(TUI_BREAKPOINT);
|
||||
router = inject(Router);
|
||||
|
||||
expandedSidenav = signal(false)
|
||||
|
||||
routerOutletActive = signal(false)
|
||||
userSettingsOpen = signal(false)
|
||||
@@ -83,24 +88,6 @@ export class Chat implements OnInit {
|
||||
this.navigationActiveIndex = 2
|
||||
}
|
||||
|
||||
this.indexedDb.openDatabase().then(async () => {
|
||||
const session = await this.serviceManager.sessionManager.loadPreferredSession()
|
||||
this.serviceManager.currentSession.set(session)
|
||||
this.serviceManager.currentSessionHandler = new UserService(session.userData.userid, session.token, this.indexedDb.getApi())
|
||||
await WebSocketHandler.getInstance().connect(session.userData.userid, session.token)
|
||||
try {
|
||||
console.log("Updating sessions...")
|
||||
const sessions = await this.serviceManager.sessionManager.loadSessions()
|
||||
console.log("Updating sessions: saved sessions loaded...")
|
||||
await this.serviceManager.sessionManager.updateSessions(sessions)
|
||||
const session = await this.serviceManager.sessionManager.loadPreferredSession()
|
||||
console.log("Updating sessions succeeded: updating sessions...")
|
||||
this.serviceManager.currentSession.set(session)
|
||||
} catch (e) {
|
||||
console.warn("Session update failed, skipping...", e)
|
||||
}
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
const latestRead = localStorage.getItem("changeLogLastRead")
|
||||
if (latestRead != environment.version) {
|
||||
@@ -112,4 +99,5 @@ export class Chat implements OnInit {
|
||||
protected readonly LoadStatus = LoadStatus;
|
||||
protected readonly localStorage = localStorage;
|
||||
protected readonly environment = environment;
|
||||
protected readonly LoadState = LoadState;
|
||||
}
|
||||
|
||||
31
src/app/chat/contact-list/contact-list.html
Normal file
31
src/app/chat/contact-list/contact-list.html
Normal file
@@ -0,0 +1,31 @@
|
||||
<button disabled tuiButton appearance="secondary" iconStart="@tui.mail-plus">
|
||||
{{ "chat.chatnav.dmList.newChat"|translate }}
|
||||
</button>
|
||||
@if (cache.contactsState() == LoadState.CACHE_UPDATING) {
|
||||
<div id="loader">
|
||||
<tui-loader/>
|
||||
{{ "updating"|translate }}
|
||||
</div>
|
||||
}
|
||||
@for (contact of cache.contacts(); track contact.contactId) {
|
||||
<button [class.enlarge]="breakpoint() == 'mobile'" tuiButton
|
||||
[appearance]="router.url == '/chat/dm/' + contact.contactId ? 'primary' : 'flat'"
|
||||
[routerLink]="'/chat/dm/' + contact.contactId">
|
||||
<avatar height="35px" width="35px" [radius]="10" [src]="contact.pfp" [name]="contact.username"></avatar>
|
||||
<div class="info">
|
||||
@if (contact.displayName == "") {
|
||||
<span>{{ '@' + contact.username }}</span>
|
||||
} @else {
|
||||
<span>{{ contact.displayName }}</span>
|
||||
}
|
||||
@if (contact.latestMessage) {
|
||||
<span class="latest_message">
|
||||
@if (contact.latestMessage.isAuthor) {
|
||||
{{ "chat.chatnav.dmList.messageBox.latestMessage.you"|translate }}
|
||||
}
|
||||
{{ contact.latestMessage.message }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { DmList } from './dm-list';
|
||||
import { ContactList } from './contact-list';
|
||||
|
||||
describe('PictureList', () => {
|
||||
let component: DmList;
|
||||
let fixture: ComponentFixture<DmList>;
|
||||
let component: ContactList;
|
||||
let fixture: ComponentFixture<ContactList>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [DmList],
|
||||
imports: [ContactList],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(DmList);
|
||||
fixture = TestBed.createComponent(ContactList);
|
||||
component = fixture.componentInstance;
|
||||
await fixture.whenStable();
|
||||
});
|
||||
65
src/app/chat/contact-list/contact-list.ts
Normal file
65
src/app/chat/contact-list/contact-list.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import {Component, inject, input, OnInit} from '@angular/core';
|
||||
import {ChatService} from '@chatenium/chatenium-sdk/services/chatService';
|
||||
import {IndexedDB} from '../../storage/indexed-db';
|
||||
import { TUI_BREAKPOINT, TuiButton, TuiLoader, TuiNotificationService } from '@taiga-ui/core';
|
||||
import {Oimg} from '../elements/oimg/oimg';
|
||||
import {Router, RouterLink} from '@angular/router';
|
||||
import {TranslatePipe} from '@ngx-translate/core';
|
||||
import {LoadStatus, ServiceManager} from '../../service-manager';
|
||||
import { Contact } from 'chatenium-sdk-preview';
|
||||
import { CHATENIUM_SDK } from '../../chatenium.token';
|
||||
import { CacheService, LoadState } from '../../cache';
|
||||
import { Avatar } from '../elements/avatar/avatar';
|
||||
|
||||
@Component({
|
||||
selector: 'app-contact-list',
|
||||
imports: [TuiButton, Oimg, RouterLink, TranslatePipe, TuiLoader, Avatar],
|
||||
templateUrl: './contact-list.html',
|
||||
styleUrl: './contact-list.scss',
|
||||
})
|
||||
export class ContactList implements OnInit {
|
||||
SDK = inject(CHATENIUM_SDK);
|
||||
idb = inject(IndexedDB);
|
||||
router = inject(Router);
|
||||
cache = inject(CacheService);
|
||||
notification = inject(TuiNotificationService);
|
||||
serviceManager = inject(ServiceManager);
|
||||
breakpoint = inject(TUI_BREAKPOINT);
|
||||
|
||||
async ngOnInit() {
|
||||
if (this.cache.contactsState() != LoadState.LOADED) {
|
||||
try {
|
||||
const contacts = (await this.idb.getAll('contacts')) as Contact[];
|
||||
if (contacts.length > 0) {
|
||||
this.cache.contacts.set(contacts);
|
||||
this.cache.contactsState.set(LoadState.CACHE_UPDATING);
|
||||
} else {
|
||||
console.log("Found no contacts in cache")
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`Contacts cache load failed: ${e}. Skipping cache load...`);
|
||||
}
|
||||
try {
|
||||
const resp = await this.SDK.contacts.getContacts();
|
||||
const data = resp.data as Contact[];
|
||||
if (data == null) {
|
||||
console.log("No contacts were fetched - user possibly has 0 contacts")
|
||||
this.cache.contactsState.set(LoadState.LOADED);
|
||||
return
|
||||
}
|
||||
this.cache.contacts.set(data);
|
||||
console.log(`Successfully fetched ${data.length} contacts`);
|
||||
this.cache.contactsState.set(LoadState.LOADED);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
this.serviceManager.chatsStatus.set(LoadStatus.error);
|
||||
this.notification
|
||||
.open(`Loading contacts failed: ${e}`, { appearance: 'negative' })
|
||||
.subscribe();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected readonly LoadStatus = LoadStatus;
|
||||
protected readonly LoadState = LoadState;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
<button disabled tuiButton appearance="secondary" iconStart="@tui.mail-plus">
|
||||
{{ "chat.chatnav.dmList.newChat"|translate }}
|
||||
</button>
|
||||
@if (serviceManager.chatsStatus() == LoadStatus.updating) {
|
||||
<div id="loader">
|
||||
<tui-loader/>
|
||||
{{ "updating"|translate }}
|
||||
</div>
|
||||
}
|
||||
@for (chat of serviceManager.chats(); track chat.chatid) {
|
||||
<button [class.enlarge]="breakpoint() == 'mobile'" tuiButton
|
||||
[appearance]="router.url == '/chat/dm/' + chat.chatid ? 'primary' : 'flat'"
|
||||
[routerLink]="'/chat/dm/' + chat.chatid">
|
||||
<oimg [src]="chat.pfp" height="35px" width="35px" [radius]="10"></oimg>
|
||||
<div class="info">
|
||||
@if (chat.displayName == "") {
|
||||
<span>{{ '@' + chat.username }}</span>
|
||||
} @else {
|
||||
<span>{{ chat.displayName }}</span>
|
||||
}
|
||||
@if (chat.latestMessage) {
|
||||
<span class="latest_message">
|
||||
@if (chat.latestMessage.isAuthor) {
|
||||
{{ "chat.chatnav.dmList.messageBox.latestMessage.you"|translate }}
|
||||
}
|
||||
{{ chat.latestMessage.message }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import {Component, inject, input, OnInit} from '@angular/core';
|
||||
import {ChatService} from '@chatenium/chatenium-sdk/services/chatService';
|
||||
import {IndexedDB} from '../../storage/indexed-db';
|
||||
import {TUI_BREAKPOINT, TuiButton, TuiLoader} from '@taiga-ui/core';
|
||||
import {Oimg} from '../elements/oimg/oimg';
|
||||
import {Router, RouterLink} from '@angular/router';
|
||||
import {TranslatePipe} from '@ngx-translate/core';
|
||||
import {LoadStatus, ServiceManager} from '../../service-manager';
|
||||
|
||||
@Component({
|
||||
selector: 'app-dm-list',
|
||||
imports: [
|
||||
TuiButton,
|
||||
Oimg,
|
||||
RouterLink,
|
||||
TranslatePipe,
|
||||
TuiLoader
|
||||
],
|
||||
templateUrl: './dm-list.html',
|
||||
styleUrl: './dm-list.scss',
|
||||
})
|
||||
export class DmList implements OnInit {
|
||||
userid = input<string>("")
|
||||
token = input<string>("")
|
||||
|
||||
indexedDb = inject(IndexedDB)
|
||||
router = inject(Router)
|
||||
serviceManager = inject(ServiceManager)
|
||||
breakpoint = inject(TUI_BREAKPOINT)
|
||||
|
||||
async ngOnInit() {
|
||||
this.serviceManager.chatService = new ChatService(this.userid(), this.token(), this.indexedDb.getApi(), () => {})
|
||||
if (this.serviceManager.chatsStatus() != LoadStatus.loaded) {
|
||||
try {
|
||||
this.serviceManager.chats.set(await this.serviceManager.chatService.getQuick())
|
||||
this.serviceManager.chatsStatus.set(LoadStatus.updating)
|
||||
} catch (e) {
|
||||
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
|
||||
}
|
||||
try {
|
||||
this.serviceManager.chats.set(await this.serviceManager.chatService.get())
|
||||
this.serviceManager.chatsStatus.set(LoadStatus.loaded)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
this.serviceManager.chatsStatus.set(LoadStatus.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected readonly LoadStatus = LoadStatus;
|
||||
}
|
||||
@@ -2,27 +2,29 @@
|
||||
@defer (when store) {
|
||||
<navbar backButtonDest="/chat">
|
||||
<div class="data">
|
||||
<oimg [src]="store.chatData().pfp" height="50px" width="50px" [radius]="15"></oimg>
|
||||
<avatar [src]="this.store.chatData().pfp" height="50px" width="50px" [radius]="15" [name]="this.store.chatData().username"></avatar>
|
||||
<div class="chat-data">
|
||||
@if (store.chatData().displayName == "") {
|
||||
<span class="main-name">{{'@'+store.chatData().username}}</span>
|
||||
@if (this.store.chatData().displayName == "") {
|
||||
<span class="main-name">{{ '@' + this.store.chatData().username }}</span>
|
||||
} @else {
|
||||
<span class="main-name">{{store.chatData().displayName}}</span>
|
||||
<span class="alt-name">{{'@'+store.chatData().username}}</span>
|
||||
<span class="main-name">{{ this.store.chatData().displayName }}</span>
|
||||
<span class="alt-name">{{ '@' + this.store.chatData().username }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="items-right">
|
||||
<button tuiButton appearance="flat" disabled>
|
||||
<tui-icon icon="@tui.phone"/>
|
||||
<tui-icon icon="@tui.phone" />
|
||||
</button>
|
||||
</div>
|
||||
</navbar>
|
||||
|
||||
<messages (scrollend)="handleMessagesScroll($event)" [loading]="store.messagesStatus() == LoadStatus.loading" [messageBoxViewModel]="store.messageBox" [messages]="store.messages()" id="scrollContainer" (onDelete)="deleteMessage($event)"/>
|
||||
<messages (scrollend)="handleMessagesScroll($event)" [loading]="store.messagesState() == LoadState.CLEAN_LOADING"
|
||||
[messageBoxViewModel]="store.messageBox" [messages]="store.messages()" id="scrollContainer"
|
||||
(onDelete)="deleteMessage($event)" />
|
||||
|
||||
<message-box [viewModel]="store.messageBox"/>
|
||||
<message-box [viewModel]="store.messageBox" />
|
||||
}
|
||||
|
||||
</main>
|
||||
|
||||
@@ -1,78 +1,88 @@
|
||||
import {Component, inject, OnInit, signal} from '@angular/core';
|
||||
import {DmStorage, LoadStatus, ServiceManager} from '../../service-manager';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {DMService} from '@chatenium/chatenium-sdk/services/dmService';
|
||||
import {IndexedDB} from '../../storage/indexed-db';
|
||||
import {Navbar} from '../elements/navbar/navbar';
|
||||
import {Oimg} from '../elements/oimg/oimg';
|
||||
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';
|
||||
import {FileDataWithPreview, MessageBox} from '../elements/message-box/message-box';
|
||||
import {Messages} from '../elements/messages/messages';
|
||||
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
|
||||
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
|
||||
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel';
|
||||
import {FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema';
|
||||
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';
|
||||
import {MessagesViewModel} from '../elements/messages/messages-viewmodel';
|
||||
import {v4 as uuidv4} from 'uuid';
|
||||
import { Component, inject, OnInit, signal } from '@angular/core';
|
||||
import { LoadStatus, ServiceManager } from '../../service-manager';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { IndexedDB } from '../../storage/indexed-db';
|
||||
import { Navbar } from '../elements/navbar/navbar';
|
||||
import { TUI_BREAKPOINT, TuiButton, TuiIcon, TuiNotificationService } from '@taiga-ui/core';
|
||||
import { FileDataWithPreview, MessageBox } from '../elements/message-box/message-box';
|
||||
import { CHATENIUM_SDK } from '../../chatenium.token';
|
||||
import {
|
||||
Contact,
|
||||
createDMWrapper,
|
||||
DirectMessagingApi,
|
||||
Message,
|
||||
WrappedDMHandler,
|
||||
} from 'chatenium-sdk-preview';
|
||||
import { CacheService, DmStorage, LoadState } from '../../cache';
|
||||
import { Avatar } from '../elements/avatar/avatar';
|
||||
import { MessageBoxViewModel } from '../elements/message-box/message-box-viewmodel';
|
||||
import { MessagesViewModel } from '../elements/messages/messages-viewmodel';
|
||||
import { Messages } from '../elements/messages/messages';
|
||||
|
||||
@Component({
|
||||
selector: 'app-dm',
|
||||
imports: [
|
||||
Navbar,
|
||||
Oimg,
|
||||
TuiButton,
|
||||
TuiIcon,
|
||||
MessageBox,
|
||||
Messages
|
||||
],
|
||||
imports: [Navbar, TuiButton, TuiIcon, MessageBox, Avatar, Messages],
|
||||
templateUrl: './dm.html',
|
||||
styleUrl: './dm.scss',
|
||||
})
|
||||
export class Dm implements OnInit {
|
||||
serviceManager = inject(ServiceManager)
|
||||
route = inject(ActivatedRoute)
|
||||
indexedDb = inject(IndexedDB)
|
||||
breakpoint = inject(TUI_BREAKPOINT)
|
||||
SDK = inject(CHATENIUM_SDK);
|
||||
cache = inject(CacheService);
|
||||
serviceManager = inject(ServiceManager);
|
||||
route = inject(ActivatedRoute);
|
||||
notification = inject(TuiNotificationService);
|
||||
indexedDb = inject(IndexedDB);
|
||||
breakpoint = inject(TUI_BREAKPOINT);
|
||||
|
||||
chatid = ""
|
||||
contactId = '';
|
||||
|
||||
get store(): DmStorage {
|
||||
return this.serviceManager.dmServices()[this.chatid]
|
||||
return this.cache.dms()[this.contactId];
|
||||
}
|
||||
|
||||
async sendMessage(message: string, files: FileDataWithPreview[] | null) {
|
||||
if (!files && message.trim() == "") return
|
||||
this.scrollToBottom("smooth")
|
||||
console.log('sendMessage', message, files);
|
||||
try {
|
||||
const resp = await this.store.handler.sendMessage({
|
||||
content: message,
|
||||
});
|
||||
const data = resp.data as Message;
|
||||
console.log(data);
|
||||
} catch (e) {
|
||||
this.notification.open(`Failed sending DM: ${e}`, { appearance: 'negative' }).subscribe();
|
||||
console.error(e);
|
||||
}
|
||||
/*
|
||||
if (!files && message.trim() == '') return;
|
||||
|
||||
const session = this.serviceManager.currentSession();
|
||||
if (session != null) {
|
||||
const editedMessage = this.store.messageBox.editingMessage()
|
||||
const editedMessage = this.store.messageBox.editingMessage();
|
||||
if (editedMessage) {
|
||||
const storedMsg = this.store.messages().find(m => m.msgid == editedMessage.messageId)
|
||||
const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg))
|
||||
const storedMsg = this.store.messages().find((m) => m.msgid == editedMessage.messageId);
|
||||
const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg));
|
||||
if (storedMsg) {
|
||||
storedMsg.message = message
|
||||
storedMsg.message = message;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.store.service.editMessage(editedMessage.messageId, message)
|
||||
await this.store.service.editMessage(editedMessage.messageId, message);
|
||||
} catch (e) {
|
||||
if (storedMsg) {
|
||||
storedMsg.message = originalMessage.message
|
||||
storedMsg.message = originalMessage.message;
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
let attachments: Attachment[] = []
|
||||
files?.forEach(file => {
|
||||
const extraMetaData: Record<string, any> = {}
|
||||
extraMetaData["thumbnailMetaData"] = file.videoThumbnail ?? ""
|
||||
extraMetaData["progressShown"] = true
|
||||
extraMetaData["totalChunks"] = 0
|
||||
extraMetaData["uploadedChunks"] = 0
|
||||
let attachments: Attachment[] = [];
|
||||
files?.forEach((file) => {
|
||||
const extraMetaData: Record<string, any> = {};
|
||||
extraMetaData['thumbnailMetaData'] = file.videoThumbnail ?? '';
|
||||
extraMetaData['progressShown'] = true;
|
||||
extraMetaData['totalChunks'] = 0;
|
||||
extraMetaData['uploadedChunks'] = 0;
|
||||
|
||||
attachments.push({
|
||||
fileName: file.name,
|
||||
@@ -82,180 +92,222 @@ export class Dm implements OnInit {
|
||||
path: file.blob,
|
||||
height: file.height,
|
||||
width: file.width,
|
||||
extraMetaData: extraMetaData
|
||||
})
|
||||
})
|
||||
extraMetaData: extraMetaData,
|
||||
});
|
||||
});
|
||||
|
||||
const tempMsgId = uuidv4()
|
||||
this.store.messages.update(value => [...value, {
|
||||
const tempMsgId = uuidv4();
|
||||
this.store.messages.update((value) => [
|
||||
...value,
|
||||
{
|
||||
message: message,
|
||||
chatid: this.chatid,
|
||||
files: attachments,
|
||||
replyTo: "",
|
||||
replyTo: '',
|
||||
author: session.userData.userid,
|
||||
seen: false,
|
||||
msgid: tempMsgId,
|
||||
forwardedFrom: "",
|
||||
forwardedFrom: '',
|
||||
isEdited: false,
|
||||
sent_at: {T: 0, I: 0},
|
||||
replyToId: "",
|
||||
forwardedFromName: ""
|
||||
}])
|
||||
sent_at: { T: 0, I: 0 },
|
||||
replyToId: '',
|
||||
forwardedFromName: '',
|
||||
},
|
||||
]);
|
||||
|
||||
this.scrollToBottom("smooth")
|
||||
|
||||
const respMessage = await this.store.service.sendMessage(tempMsgId, message, null, null, files, <FileUploadProgressListener>{
|
||||
const respMessage = await this.store.service.sendMessage(
|
||||
tempMsgId,
|
||||
message,
|
||||
null,
|
||||
null,
|
||||
files,
|
||||
<FileUploadProgressListener>{
|
||||
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
|
||||
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone)
|
||||
}
|
||||
})
|
||||
this.updateTempMessage(tempMsgId, respMessage)
|
||||
}
|
||||
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone);
|
||||
},
|
||||
},
|
||||
);
|
||||
this.updateTempMessage(tempMsgId, respMessage);
|
||||
this.scrollToBottom('smooth');
|
||||
}*/
|
||||
}
|
||||
|
||||
async deleteMessage(messageId: string) {
|
||||
const i = this.store.messages().findIndex(m => m.msgid == messageId)
|
||||
/*const i = this.store.messages().findIndex((m) => m.msgid == messageId);
|
||||
if (i != -1) {
|
||||
const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]))
|
||||
this.store.messages().splice(i, 1)
|
||||
const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]));
|
||||
this.store.messages().splice(i, 1);
|
||||
try {
|
||||
await this.store.service.deleteMessages([messageId])
|
||||
await this.store.service.deleteMessages([messageId]);
|
||||
} catch (e) {
|
||||
this.store.messages().splice(i, 0, originalMessage)
|
||||
this.store.messages().splice(i, 0, originalMessage);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
async loadMessages() {
|
||||
try {
|
||||
const resp = await this.store.handler.getMessages(0);
|
||||
const data = resp.data as Message[];
|
||||
console.log(
|
||||
`Successfully fetched ${data.length} message(s) in DM ${this.store.chatData().contactId}`,
|
||||
);
|
||||
console.log(data);
|
||||
this.store.messages.set(data);
|
||||
this.store.messagesState.set(LoadState.LOADED);
|
||||
} catch (e) {
|
||||
this.notification
|
||||
.open('Loading direct messages failed.', { appearance: 'negative' })
|
||||
.subscribe();
|
||||
}
|
||||
}
|
||||
|
||||
restoreScrollState(): void {
|
||||
setTimeout(() => {
|
||||
const scrollContainer = <HTMLDivElement>document.querySelector('#scrollContainer');
|
||||
scrollContainer.scroll({
|
||||
top:
|
||||
this.store.messagesVm.scrollBarStatus() == -1
|
||||
? scrollContainer.scrollHeight
|
||||
: this.store.messagesVm.scrollBarStatus(),
|
||||
left: 0,
|
||||
behavior: 'instant',
|
||||
});
|
||||
|
||||
if (this.store.messagesVm.scrollBarStatus() == -1) {
|
||||
this.store.messagesVm.scrollBarStatus.set(scrollContainer.scrollHeight);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
scrollToBottom(anim: 'instant' | 'smooth'): void {
|
||||
setTimeout(() => {
|
||||
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
|
||||
const scrollContainer = <HTMLDivElement>document.querySelector('#scrollContainer');
|
||||
scrollContainer.scroll({
|
||||
top: this.store.messagesVm.scrollBarStatus() == -1 ? scrollContainer.scrollHeight : this.store.messagesVm.scrollBarStatus(),
|
||||
top: scrollContainer.scrollHeight,
|
||||
left: 0,
|
||||
behavior: anim
|
||||
behavior: anim,
|
||||
});
|
||||
|
||||
if (this.store.messagesVm.scrollBarStatus() == -1) {
|
||||
this.store.messagesVm.scrollBarStatus.set(scrollContainer.scrollHeight)
|
||||
}
|
||||
}, 0)
|
||||
}, 0);
|
||||
}
|
||||
|
||||
handleMessagesScroll(e: any) {
|
||||
this.store.messagesVm.scrollBarStatus.set(e.target.scrollTop)
|
||||
this.store.messagesVm.scrollBarStatus.set(e.target.scrollTop);
|
||||
}
|
||||
|
||||
uploadProgressUpdate(tempMsgId: string, fileId: string, allChunks: number, chunksDone: number) {
|
||||
console.log(tempMsgId, fileId, allChunks, chunksDone)
|
||||
this.store.messages.update(messages =>
|
||||
messages.map(m => {
|
||||
/*
|
||||
console.log(tempMsgId, fileId, allChunks, chunksDone);
|
||||
this.store.messages.update((messages) =>
|
||||
messages.map((m) => {
|
||||
if (m.msgid !== tempMsgId) return m;
|
||||
|
||||
return {
|
||||
...m,
|
||||
files: m.files.map(f => {
|
||||
files: m.files.map((f) => {
|
||||
if (f.fileId !== fileId) return f;
|
||||
return {
|
||||
...f,
|
||||
extraMetaData: {
|
||||
...f.extraMetaData,
|
||||
totalChunks: allChunks,
|
||||
uploadedChunks: chunksDone
|
||||
}
|
||||
uploadedChunks: chunksDone,
|
||||
},
|
||||
};
|
||||
})
|
||||
}),
|
||||
};
|
||||
})
|
||||
);
|
||||
}),
|
||||
);*/
|
||||
}
|
||||
|
||||
updateTempMessage(tempMsgId: string, message: Message) {
|
||||
this.store.messages.update(messages =>
|
||||
messages.map(m => {
|
||||
/*
|
||||
this.store.messages.update((messages) =>
|
||||
messages.map((m) => {
|
||||
if (m.msgid !== tempMsgId) return m;
|
||||
|
||||
return {
|
||||
...m,
|
||||
msgid: message.msgid,
|
||||
sent_at: message.sent_at,
|
||||
files: m.files.map(f => {
|
||||
f.extraMetaData["progressShown"] = false
|
||||
return f
|
||||
})
|
||||
files: m.files.map((f) => {
|
||||
f.extraMetaData['progressShown'] = false;
|
||||
return f;
|
||||
}),
|
||||
};
|
||||
})
|
||||
);
|
||||
}),
|
||||
);*/
|
||||
}
|
||||
|
||||
// The chatid parameter ensures isolation
|
||||
onWsListen(action: string, message: string, chatid: string) {
|
||||
/*
|
||||
const data = JSON.parse(message);
|
||||
if (data.chatid === chatid) {
|
||||
const targetStore = this.serviceManager.dmServices()[chatid];
|
||||
if (targetStore) {
|
||||
switch (action) {
|
||||
case "newMessage":
|
||||
targetStore.messages.update(messages => [...messages, data]);
|
||||
this.scrollToBottom("smooth")
|
||||
case 'newMessage':
|
||||
targetStore.messages.update((messages) => [...messages, data]);
|
||||
this.scrollToBottom('smooth');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.route.params.subscribe(async params => {
|
||||
const chatid = params['chatid'];
|
||||
this.chatid = chatid;
|
||||
console.log(`Loading chat ${chatid}...`)
|
||||
this.route.params.subscribe(async (params) => {
|
||||
const contactId = params['contactId'];
|
||||
this.contactId = contactId;
|
||||
console.log(`Loading DM chat ${contactId}...`);
|
||||
|
||||
const session = this.serviceManager.currentSession();
|
||||
const chatData = this.serviceManager.chats().find(c => c.chatid === chatid);
|
||||
const chatData = this.cache.contacts().find((c) => c.contactId === contactId);
|
||||
|
||||
if (!session || !chatData) {
|
||||
return
|
||||
if (!chatData) {
|
||||
console.warn(
|
||||
`Unable to find chat data with the provided contactId: ${contactId}, skipping load.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.serviceManager.dmServices()[chatid]) {
|
||||
const newStore = {
|
||||
chatData: signal<Chat>(chatData),
|
||||
if (!this.cache.dms()[contactId]) {
|
||||
console.log(`No store yet, creating service store for DM: ${contactId}`);
|
||||
this.cache.dms()[contactId] = {
|
||||
handler: createDMWrapper(this.SDK.directMessaging, chatData.contactId),
|
||||
chatData: signal<Contact>(chatData),
|
||||
messages: signal<Message[]>([]),
|
||||
messagesStatus: signal<LoadStatus>(LoadStatus.loading),
|
||||
messagesState: signal<LoadState>(LoadState.CLEAN_LOADING),
|
||||
messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)),
|
||||
messagesVm: new MessagesViewModel(),
|
||||
wsListener: (action, data) => this.onWsListen(action, data, chatid),
|
||||
wsListener: (action, data) => this.onWsListen(action, data, contactId),
|
||||
} as DmStorage;
|
||||
|
||||
newStore.service = new DMService(
|
||||
session.userData.userid,
|
||||
session.token,
|
||||
chatid,
|
||||
this.indexedDb.getApi(),
|
||||
(action, data) => newStore.wsListener(action, data)
|
||||
);
|
||||
|
||||
this.serviceManager.dmServices()[chatid] = newStore;
|
||||
|
||||
const currentStore = this.serviceManager.dmServices()[chatid];
|
||||
await this.loadMessages();
|
||||
/*
|
||||
const currentStore = this.serviceManager.dmServices()[contactId];
|
||||
try {
|
||||
const messagesCache = await currentStore.service.getQuick();
|
||||
currentStore.messages.set(messagesCache);
|
||||
this.store.messagesStatus.set(LoadStatus.updating)
|
||||
this.scrollToBottom("instant")
|
||||
this.restoreScrollState()
|
||||
} catch (e) {
|
||||
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
|
||||
}
|
||||
const messages = await currentStore.service.get();
|
||||
currentStore.messages.set(messages);
|
||||
this.store.messagesStatus.set(LoadStatus.loaded)
|
||||
this.scrollToBottom("instant")
|
||||
this.restoreScrollState()
|
||||
|
||||
await currentStore.service.joinWebSocketRoom();
|
||||
} else {
|
||||
this.scrollToBottom("instant")
|
||||
this.restoreScrollState()
|
||||
}*/
|
||||
}
|
||||
console.log(`Finished initializing chat: ${contactId}`);
|
||||
});
|
||||
}
|
||||
|
||||
protected readonly LoadStatus = LoadStatus;
|
||||
protected readonly LoadState = LoadState;
|
||||
}
|
||||
|
||||
3
src/app/chat/elements/avatar/avatar.html
Normal file
3
src/app/chat/elements/avatar/avatar.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<div class="avatar" [style]="'width: '+width()+'; height: '+height()+'; background-color: '+stringToHexColor(name())+'; border-radius: '+radius()+'px;'">
|
||||
<span>{{name()[0]}}</span>
|
||||
</div>
|
||||
6
src/app/chat/elements/avatar/avatar.scss
Normal file
6
src/app/chat/elements/avatar/avatar.scss
Normal file
@@ -0,0 +1,6 @@
|
||||
.avatar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
}
|
||||
22
src/app/chat/elements/avatar/avatar.spec.ts
Normal file
22
src/app/chat/elements/avatar/avatar.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { Avatar } from './avatar';
|
||||
|
||||
describe('Avatar', () => {
|
||||
let component: Avatar;
|
||||
let fixture: ComponentFixture<Avatar>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [Avatar],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(Avatar);
|
||||
component = fixture.componentInstance;
|
||||
await fixture.whenStable();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
||||
29
src/app/chat/elements/avatar/avatar.ts
Normal file
29
src/app/chat/elements/avatar/avatar.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Component, input } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'avatar',
|
||||
imports: [],
|
||||
templateUrl: './avatar.html',
|
||||
styleUrl: './avatar.scss',
|
||||
})
|
||||
export class Avatar {
|
||||
height = input.required<string>();
|
||||
width = input.required<string>();
|
||||
src = input<string>();
|
||||
name = input.required<string>();
|
||||
radius = input.required<number>();
|
||||
|
||||
PALETTE = ['#ff6b6b', '#ffd166', '#06d6a0', '#4cc9f0', '#b56576', '#f78c6b'];
|
||||
|
||||
/**
|
||||
* Picks 1 color from a few for avatar background
|
||||
* @param str
|
||||
*/
|
||||
stringToHexColor(str: string): string {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
hash = str.charCodeAt(i) + ((hash << 5) - hash);
|
||||
}
|
||||
return this.PALETTE[Math.abs(hash) % this.PALETTE.length];
|
||||
}
|
||||
}
|
||||
@@ -12,5 +12,5 @@ export class MessageBoxViewModel {
|
||||
message = signal<string>("")
|
||||
files = signal<FileDataWithPreview[]>([])
|
||||
dialogOpen = signal<boolean>(false)
|
||||
editingMessage = signal<{messageId: string, message: string} | null >(null)
|
||||
editingMessage = signal<{messageId: string, content: string|undefined} | null >(null)
|
||||
}
|
||||
|
||||
@@ -55,11 +55,11 @@
|
||||
@if (viewModel().editingMessage()) {
|
||||
<tui-icon icon="@tui.pencil"></tui-icon>
|
||||
<span>{{"chat.elements.messageBox.editMessageLabel"|translate}}</span>
|
||||
@if (viewModel().editingMessage()!.message == "") {
|
||||
@if (viewModel().editingMessage()!.content == "") {
|
||||
<tui-icon icon="@tui.paperclip"></tui-icon>
|
||||
<span>{{"chat.elements.messageBox.attachments"|translate}}</span>
|
||||
} @else {
|
||||
<span style="width: 300px" tuiScrollable tuiFade>{{viewModel().editingMessage()!.message}}</span>
|
||||
<span style="width: 300px" tuiScrollable tuiFade>{{viewModel().editingMessage()!.content}}</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -13,24 +13,24 @@
|
||||
}
|
||||
} @else {
|
||||
@if (serviceManager.currentSession != null) {
|
||||
@for (message of messages(); track message.msgid; let i = $index) {
|
||||
@for (message of messages(); track message.messageId; let i = $index) {
|
||||
<div
|
||||
class="message"
|
||||
[class.author]="
|
||||
messageAsDm(message).author == serviceManager.currentSession()!.userData.userid ||
|
||||
messageAsNetwork(message).author.userid == serviceManager.currentSession()!.userData.userid
|
||||
messageAsDm(message).author.userId == sessionManager.userData()?.userId ||
|
||||
messageAsNetwork(message).author.userId == sessionManager.userData()?.userId
|
||||
"
|
||||
[class.chained_start]="isMessageStartOfChain(i)"
|
||||
[class.chained_middle]="isMessageMiddleInChain(i)"
|
||||
[class.chained_end]="isMessageEndOfChain(i)"
|
||||
>
|
||||
<div class="above">
|
||||
<span>{{ message.sent_at.T * 1000 | date: 'HH:mm' }}</span>
|
||||
<span>{{ message.sentAt | date: 'HH:mm' }}</span>
|
||||
</div>
|
||||
<div class="bubble" tuiDropdownContext [tuiDropdown]="messageContextMenu">
|
||||
<span class="message-text">{{ message.message }}</span>
|
||||
<masonry style="max-height: 300px">
|
||||
@for (file of filterExpressedMedia(message.files); track file) {
|
||||
<span class="message-text">{{ message.content }}</span>
|
||||
<!-- <masonry style="max-height: 300px">
|
||||
@for (file of filterExpressedMedia(message.attachments); track file) {
|
||||
<div style="position:relative;">
|
||||
@if (file.extraMetaData && Object.keys(file.extraMetaData).length > 0) {
|
||||
@if (file.extraMetaData['progressShown']) {
|
||||
@@ -75,7 +75,7 @@
|
||||
<span>{{ file.fileName }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>-->
|
||||
</div>
|
||||
<div class="below"></div>
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
tuiOption
|
||||
type="button"
|
||||
iconEnd="@tui.pencil"
|
||||
(click)="messageBoxViewModel().editingMessage.set({message: message.message, messageId: message.msgid}); messageBoxViewModel().message.set(message.message);"
|
||||
(click)="messageBoxViewModel().editingMessage.set({content: message.content, messageId: message.messageId}); messageBoxViewModel().message.set(message.content??'');"
|
||||
>
|
||||
{{ "chat.elements.messages.contextMenu.edit" | translate }}
|
||||
</button>
|
||||
@@ -95,7 +95,7 @@
|
||||
tuiOption
|
||||
type="button"
|
||||
iconEnd="@tui.trash"
|
||||
(click)="onDelete.emit(message.msgid)"
|
||||
(click)="onDelete.emit(message.messageId)"
|
||||
>
|
||||
{{ "chat.elements.messages.contextMenu.delete" | translate }}
|
||||
</button>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import {Component, EventEmitter, inject, input, Output} from '@angular/core';
|
||||
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
|
||||
import {Message as NetworkMessage} from '@chatenium/chatenium-sdk/domain/textChannelService.schema'
|
||||
import {ServiceManager} from '../../../service-manager';
|
||||
import {DatePipe} from '@angular/common';
|
||||
import {Masonry} from '../masonry/masonry';
|
||||
import {VideoPlayer} from '../video-player/video-player';
|
||||
import { Component, EventEmitter, inject, input, Output } from '@angular/core';
|
||||
import { Message, ThreadMessage, Attachment, ThreadMessageAttachment } from 'chatenium-sdk-preview';
|
||||
import { ServiceManager } from '../../../service-manager';
|
||||
import { DatePipe } from '@angular/common';
|
||||
import { Masonry } from '../masonry/masonry';
|
||||
import { VideoPlayer } from '../video-player/video-player';
|
||||
import {
|
||||
TuiButton,
|
||||
TuiDataListComponent,
|
||||
@@ -12,13 +11,12 @@ import {
|
||||
TuiDropdownContext,
|
||||
TuiGroup,
|
||||
TuiIcon,
|
||||
TuiOption
|
||||
TuiOption,
|
||||
} from '@taiga-ui/core';
|
||||
import {TranslatePipe} from '@ngx-translate/core';
|
||||
import {MessageBoxViewModel} from '../message-box/message-box-viewmodel';
|
||||
import {FileDataWithPreview} from '../message-box/message-box';
|
||||
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';
|
||||
import {TuiProgressCircle, TuiSkeleton} from '@taiga-ui/kit';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
import { MessageBoxViewModel } from '../message-box/message-box-viewmodel';
|
||||
import { TuiProgressCircle, TuiSkeleton } from '@taiga-ui/kit';
|
||||
import { SessionManager } from '../../../session-manager';
|
||||
|
||||
@Component({
|
||||
selector: 'messages',
|
||||
@@ -35,27 +33,28 @@ import {TuiProgressCircle, TuiSkeleton} from '@taiga-ui/kit';
|
||||
TuiGroup,
|
||||
TuiIcon,
|
||||
TuiProgressCircle,
|
||||
TuiSkeleton
|
||||
TuiSkeleton,
|
||||
],
|
||||
templateUrl: './messages.html',
|
||||
styleUrl: './messages.scss',
|
||||
})
|
||||
export class Messages {
|
||||
serviceManager = inject(ServiceManager)
|
||||
serviceManager = inject(ServiceManager);
|
||||
sessionManager = inject(SessionManager);
|
||||
|
||||
messages = input.required<Message[] | NetworkMessage[]>()
|
||||
messageBoxViewModel = input.required<MessageBoxViewModel>()
|
||||
loading = input(false)
|
||||
messages = input.required<Message[] | ThreadMessage[]>();
|
||||
messageBoxViewModel = input.required<MessageBoxViewModel>();
|
||||
loading = input(false);
|
||||
|
||||
@Output() onDelete = new EventEmitter<string>()
|
||||
@Output() onDelete = new EventEmitter<string>();
|
||||
|
||||
/**
|
||||
* Helps code readability by specifying what type of messages are being processed.
|
||||
* Example: messageAsDm(message).author == userid -- We are specifying that we are handling dm messages
|
||||
* @param message
|
||||
*/
|
||||
messageAsDm(message: Message | NetworkMessage) {
|
||||
return message == undefined ? <Message>{author: "no"} : message as Message
|
||||
messageAsDm(message: Message | ThreadMessage) {
|
||||
return message as Message;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,8 +62,8 @@ export class Messages {
|
||||
Example: messageAsNetwork(message).author.userid == userid -- We are specifying that we are handling network messages
|
||||
* @param message
|
||||
*/
|
||||
messageAsNetwork(message: Message | NetworkMessage) {
|
||||
return message == undefined ? <NetworkMessage>{author: {userid: "no"}} : message as NetworkMessage
|
||||
messageAsNetwork(message: Message | ThreadMessage) {
|
||||
return message as ThreadMessage;
|
||||
}
|
||||
|
||||
isMessageStartOfChain(i: number) {
|
||||
@@ -76,16 +75,17 @@ export class Messages {
|
||||
// is author == last msg's author
|
||||
if (prev) {
|
||||
if (
|
||||
(typeof message.author === 'string' && this.messageAsDm(prev).author !== this.messageAsDm(message).author) &&
|
||||
this.messageAsNetwork(prev).author.userid !== this.messageAsNetwork(message).author.userid
|
||||
typeof message.author === 'string' &&
|
||||
this.messageAsDm(prev).author.userId !== this.messageAsDm(message).author.userId &&
|
||||
this.messageAsNetwork(prev).author.userId !== this.messageAsNetwork(message).author.userId
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// same author but time gap between this and prev msg
|
||||
if (
|
||||
Math.abs(message.sent_at.T - prev.sent_at.T) >= 60
|
||||
) {
|
||||
const currMsgDate = new Date(message.sentAt);
|
||||
const prevMsgDate = new Date(prev.sentAt);
|
||||
if (Math.abs(currMsgDate.getDate() - prevMsgDate.getDate()) >= 60_000) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -100,12 +100,14 @@ export class Messages {
|
||||
const prev = this.messages()[i - 1];
|
||||
|
||||
// message must be from the same author and have little time gap between
|
||||
const currMsgDate = new Date(message.sentAt);
|
||||
const prevMsgDate = new Date(prev.sentAt);
|
||||
return (
|
||||
(
|
||||
(typeof message.author === 'string' && this.messageAsDm(prev).author == this.messageAsDm(message).author) ||
|
||||
this.messageAsNetwork(prev).author.userid == this.messageAsNetwork(message).author.userid
|
||||
) &&
|
||||
Math.abs(message.sent_at.T - prev.sent_at.T) <= 60
|
||||
((typeof message.author === 'string' &&
|
||||
this.messageAsDm(prev).author == this.messageAsDm(message).author) ||
|
||||
this.messageAsNetwork(prev).author.userId ==
|
||||
this.messageAsNetwork(message).author.userId) &&
|
||||
Math.abs(currMsgDate.getDate() - prevMsgDate.getDate()) <= 60_000
|
||||
);
|
||||
}
|
||||
|
||||
@@ -118,19 +120,20 @@ export class Messages {
|
||||
|
||||
const next = this.messages()[i + 1];
|
||||
|
||||
const currMsgDate = new Date(message.sentAt);
|
||||
const nextMsgDate = new Date(next.sentAt);
|
||||
// First condition: next author is different
|
||||
if (next) {
|
||||
if (
|
||||
(typeof message.author === 'string' && this.messageAsDm(next).author != this.messageAsDm(message).author) ||
|
||||
this.messageAsNetwork(next).author.userid != this.messageAsNetwork(message).author.userid
|
||||
(typeof message.author === 'string' &&
|
||||
this.messageAsDm(next).author != this.messageAsDm(message).author) ||
|
||||
this.messageAsNetwork(next).author.userId != this.messageAsNetwork(message).author.userId
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// same author but time gap between this and next msg
|
||||
if (
|
||||
Math.abs(message.sent_at.T - next.sent_at.T) >= 60
|
||||
) {
|
||||
if (Math.abs(currMsgDate.getDate() - nextMsgDate.getDate()) >= 60) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -139,12 +142,16 @@ export class Messages {
|
||||
return i + 1 === this.messages().length;
|
||||
}
|
||||
|
||||
filterExpressedMedia(files: Attachment[]) {
|
||||
return files.filter(f => f.type == "image" || f.type == "video")
|
||||
filterExpressedMedia(files: Attachment[] | ThreadMessageAttachment[] | undefined) {
|
||||
return files
|
||||
? files.filter((f) => f.mimeType.startsWith('image') || f.mimeType.startsWith('video'))
|
||||
: [];
|
||||
}
|
||||
|
||||
filterNonExpressedMedia(files: Attachment[]) {
|
||||
return files.filter(f => f.type != "image" && f.type != "video")
|
||||
filterNonExpressedMedia(files: Attachment[] | ThreadMessageAttachment[] | undefined) {
|
||||
return files
|
||||
? files.filter((f) => f.mimeType.startsWith('image') || f.mimeType.startsWith('video'))
|
||||
: [];
|
||||
}
|
||||
|
||||
protected readonly Object = Object;
|
||||
|
||||
@@ -1,19 +1,35 @@
|
||||
<button disabled tuiButton appearance="secondary" iconStart="@tui.plus">
|
||||
<div id="holder" [class.networkActive]="selectedNetwork() != null">
|
||||
<div id="networks">
|
||||
<button disabled tuiButton appearance="secondary" iconStart="@tui.plus">
|
||||
{{ "chat.chatnav.networkList.newNetwork"|translate }}
|
||||
</button>
|
||||
@if (serviceManager.networksStatus() == LoadStatus.updating) {
|
||||
</button>
|
||||
@if (serviceManager.networksStatus() == LoadStatus.updating) {
|
||||
<div id="loader">
|
||||
<tui-loader />
|
||||
{{"updating"|translate}}
|
||||
</div>
|
||||
}
|
||||
@for (network of serviceManager.networks(); track network.networkId) {
|
||||
}
|
||||
|
||||
@for (network of serviceManager.networks(); track network.networkId) {
|
||||
<button [class.enlarge]="breakpoint() == 'mobile'" tuiButton
|
||||
[appearance]="router.url.startsWith('/chat/network/' + network.networkId) ? 'primary' : 'flat'"
|
||||
[routerLink]="'/chat/network/' + network.networkId">
|
||||
appearance="flat"
|
||||
(click)="selectNetwork(network)">
|
||||
<oimg [src]="network.picture" height="35px" width="35px" [radius]="10"></oimg>
|
||||
<div class="info">
|
||||
<span>{{ network.name }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
<div id="network">
|
||||
<div style="display: flex; align-items: center; gap: 1rem;">
|
||||
<button tuiButton appearance="secondary" iconStart="@tui.arrow-left" (click)="selectNetwork(null)"></button>
|
||||
@if (selectedNetwork() != null) {
|
||||
<oimg [src]="selectedNetwork()!.picture" height="35px" width="35px" [radius]="15"></oimg>
|
||||
<h3>{{ selectedNetwork()!.name }}</h3>
|
||||
}
|
||||
</div>
|
||||
<network [network]="selectedNetwork()!"></network>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,31 @@
|
||||
:host {
|
||||
#holder {
|
||||
position: relative;
|
||||
|
||||
&.networkActive {
|
||||
#networks {
|
||||
transform: translateX(100px);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
#network {
|
||||
pointer-events: all;
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
|
||||
network {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#networks {
|
||||
transition: 0.3s;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
@@ -25,4 +52,17 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#network {
|
||||
pointer-events: none;
|
||||
transform: translateX(-100px);
|
||||
opacity: 0;
|
||||
transition: 0.2s;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Component, inject, input, OnInit} from '@angular/core';
|
||||
import { Component, inject, input, model, OnInit, signal } from '@angular/core';
|
||||
import {IndexedDB} from '../../storage/indexed-db';
|
||||
import {Router, RouterLink} from '@angular/router';
|
||||
import {LoadStatus, ServiceManager} from '../../service-manager';
|
||||
@@ -6,43 +6,53 @@ import {TUI_BREAKPOINT, TuiButton, TuiLoader} from '@taiga-ui/core';
|
||||
import {NetworkService} from '@chatenium/chatenium-sdk/services/networkService';
|
||||
import {Oimg} from '../elements/oimg/oimg';
|
||||
import {TranslatePipe} from '@ngx-translate/core';
|
||||
import { Network as NetworkData } from '@chatenium/chatenium-sdk/domain/networkService.schema';
|
||||
import { Network } from '../network/network';
|
||||
|
||||
@Component({
|
||||
selector: 'network-list',
|
||||
imports: [
|
||||
Oimg,
|
||||
TranslatePipe,
|
||||
TuiButton,
|
||||
RouterLink,
|
||||
TuiLoader
|
||||
],
|
||||
imports: [Oimg, TranslatePipe, TuiButton, TuiLoader, Network],
|
||||
templateUrl: './network-list.html',
|
||||
styleUrl: './network-list.scss',
|
||||
})
|
||||
export class NetworkList implements OnInit {
|
||||
userid = input<string>("")
|
||||
token = input<string>("")
|
||||
userid = input<string>('');
|
||||
token = input<string>('');
|
||||
expandedSidenav = model.required<boolean>();
|
||||
|
||||
indexedDb = inject(IndexedDB)
|
||||
router = inject(Router)
|
||||
serviceManager = inject(ServiceManager)
|
||||
breakpoint = inject(TUI_BREAKPOINT)
|
||||
selectedNetwork = signal<NetworkData | null>(null);
|
||||
|
||||
indexedDb = inject(IndexedDB);
|
||||
router = inject(Router);
|
||||
serviceManager = inject(ServiceManager);
|
||||
breakpoint = inject(TUI_BREAKPOINT);
|
||||
|
||||
selectNetwork(network: NetworkData | null) {
|
||||
this.selectedNetwork.set(network);
|
||||
this.expandedSidenav.set(network !== null);
|
||||
}
|
||||
|
||||
async ngOnInit() {
|
||||
this.serviceManager.networkService = new NetworkService(this.userid(), this.token(), "", this.indexedDb.getApi(), () => {})
|
||||
this.serviceManager.networkService = new NetworkService(
|
||||
this.userid(),
|
||||
this.token(),
|
||||
'',
|
||||
this.indexedDb.getApi(),
|
||||
() => {},
|
||||
);
|
||||
if (this.serviceManager.networksStatus() != LoadStatus.loaded) {
|
||||
try {
|
||||
this.serviceManager.networks.set(await this.serviceManager.networkService.getQuick())
|
||||
this.serviceManager.networksStatus.set(LoadStatus.updating)
|
||||
this.serviceManager.networks.set(await this.serviceManager.networkService.getQuick());
|
||||
this.serviceManager.networksStatus.set(LoadStatus.updating);
|
||||
} catch (e) {
|
||||
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
|
||||
console.warn(`Cache load failed: ${e}. Skipping cache load...`);
|
||||
}
|
||||
try {
|
||||
this.serviceManager.networks.set(await this.serviceManager.networkService.get())
|
||||
this.serviceManager.networksStatus.set(LoadStatus.loaded)
|
||||
this.serviceManager.networks.set(await this.serviceManager.networkService.get());
|
||||
this.serviceManager.networksStatus.set(LoadStatus.loaded);
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
this.serviceManager.networksStatus.set(LoadStatus.error)
|
||||
console.error(e);
|
||||
this.serviceManager.networksStatus.set(LoadStatus.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {Component, inject, signal} from '@angular/core';
|
||||
import {DmStorage, LoadStatus, ServiceManager, TextChannelStorage} from '../../../../service-manager';
|
||||
import {LoadStatus, ServiceManager, TextChannelStorage} from '../../../../service-manager';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {IndexedDB} from '../../../../storage/indexed-db';
|
||||
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';
|
||||
@@ -116,14 +116,13 @@ export class Text {
|
||||
forwardedFromName: ""
|
||||
}])
|
||||
|
||||
this.scrollToBottom("smooth")
|
||||
|
||||
const respMessage = await this.store.service.sendMessage(tempMsgId, message, null, null, files, <FileUploadProgressListener>{
|
||||
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
|
||||
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone)
|
||||
}
|
||||
})
|
||||
this.updateTempMessage(tempMsgId, respMessage)
|
||||
this.scrollToBottom("smooth")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +140,7 @@ export class Text {
|
||||
}
|
||||
}
|
||||
|
||||
scrollToBottom(anim: 'instant' | 'smooth'): void {
|
||||
restoreScrollState() {
|
||||
setTimeout(() => {
|
||||
if (!this.store) {
|
||||
return
|
||||
@@ -150,7 +149,7 @@ export class Text {
|
||||
scrollContainer.scroll({
|
||||
top: this.store.messagesVm.scrollBarStatus() == -1 ? scrollContainer.scrollHeight : this.store.messagesVm.scrollBarStatus(),
|
||||
left: 0,
|
||||
behavior: anim
|
||||
behavior: "instant"
|
||||
});
|
||||
|
||||
if (this.store.messagesVm.scrollBarStatus() == -1) {
|
||||
@@ -159,6 +158,17 @@ export class Text {
|
||||
}, 0)
|
||||
}
|
||||
|
||||
scrollToBottom(anim: 'instant' | 'smooth'): void {
|
||||
setTimeout(() => {
|
||||
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
|
||||
scrollContainer.scroll({
|
||||
top: scrollContainer.scrollHeight,
|
||||
left: 0,
|
||||
behavior: anim
|
||||
});
|
||||
}, 0)
|
||||
}
|
||||
|
||||
handleMessagesScroll(e: any) {
|
||||
if (!this.store) return
|
||||
this.store.messagesVm.scrollBarStatus.set(e.target.scrollTop)
|
||||
@@ -282,7 +292,7 @@ export class Text {
|
||||
try {
|
||||
const messagesCache = await currentStore.service.getQuick();
|
||||
currentStore.messages.set(messagesCache);
|
||||
this.scrollToBottom("instant")
|
||||
this.restoreScrollState()
|
||||
currentStore.messagesStatus.set(LoadStatus.updating)
|
||||
} catch (e) {
|
||||
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
|
||||
@@ -290,11 +300,11 @@ export class Text {
|
||||
const messages = await currentStore.service.get();
|
||||
currentStore.messages.set(messages);
|
||||
currentStore.messagesStatus.set(LoadStatus.loaded)
|
||||
this.scrollToBottom("instant")
|
||||
this.restoreScrollState()
|
||||
|
||||
await currentStore.service.joinWebSocketRoom();
|
||||
} else {
|
||||
this.scrollToBottom("instant")
|
||||
this.restoreScrollState()
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,57 +1,19 @@
|
||||
@defer(when store) {
|
||||
<div id="layout" [class.routerOutletActive]="routerOutletActive()" [class.hideNetworkNav]="routerOutletActive() && breakpoint() == 'desktopSmall'">
|
||||
<div id="router">
|
||||
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)"></router-outlet>
|
||||
</div>
|
||||
@defer (when store) {
|
||||
<div id="layout" [class.routerOutletActive]="routerOutletActive()"
|
||||
[class.hideNetworkNav]="routerOutletActive() && breakpoint() == 'desktopSmall'">
|
||||
<div id="network-data">
|
||||
<navbar backButtonDest="/chat" dataAlignment="center">
|
||||
<div class="data">
|
||||
<oimg [src]="store.networkData().picture" height="50px" width="50px" [radius]="15"></oimg>
|
||||
<h2>{{store.networkData().name}}</h2>
|
||||
</div>
|
||||
|
||||
<div class="items-right"></div>
|
||||
</navbar>
|
||||
|
||||
<tui-tabs [(activeItemIndex)]="tabActiveIndex">
|
||||
<button
|
||||
iconStart="@tui.hash"
|
||||
tuiTab
|
||||
type="button"
|
||||
>
|
||||
{{"chat.network.tabs.channels"|translate}}
|
||||
</button>
|
||||
|
||||
<button
|
||||
disabled
|
||||
iconStart="@tui.users"
|
||||
tuiTab
|
||||
type="button"
|
||||
>
|
||||
{{"chat.network.tabs.members"|translate}}
|
||||
</button>
|
||||
|
||||
<button
|
||||
iconStart="@tui.cog"
|
||||
tuiTab
|
||||
type="button"
|
||||
>
|
||||
{{"chat.network.tabs.settings"|translate}}
|
||||
</button>
|
||||
</tui-tabs>
|
||||
|
||||
<br/>
|
||||
|
||||
@switch (tabActiveIndex) {
|
||||
@case (0) {
|
||||
<main tuiGroup orientation="vertical" style="width: 100%">
|
||||
<main tuiGroup orientation="vertical" style="width: 100%; height: 80svh">
|
||||
@for (category of store.networkData().categories; track category) {
|
||||
<div class="category">
|
||||
<h2>{{category.name}}</h2>
|
||||
<h2>{{ category.name }}</h2>
|
||||
|
||||
<div tuiGroup orientation="vertical" style="width: 100%">
|
||||
<div class="channels">
|
||||
@for (channel of category.channels; track channel) {
|
||||
<button tuiButton class="channel" [appearance]="router.url.endsWith(channel.channelId) ? 'primary' : 'secondary'" [disabled]="channel.type != 'message'" [routerLink]="'/chat/network/'+store.networkData().networkId+'/'+category.categoryId+'/'+channel.channelId">
|
||||
<div class="channel">
|
||||
<button tuiButton
|
||||
[appearance]="router.url.endsWith(channel.channelId) ? 'secondary' : 'flat'"
|
||||
[disabled]="channel.type != 'message'"
|
||||
[routerLink]="'/chat/network/'+store.networkData().networkId+'/'+category.categoryId+'/'+channel.channelId">
|
||||
@switch (channel.type) {
|
||||
@case ("message") {
|
||||
<tui-icon icon="@tui.hash"></tui-icon>
|
||||
@@ -63,20 +25,19 @@
|
||||
<tui-icon icon="@tui.audio-lines"></tui-icon>
|
||||
}
|
||||
}
|
||||
<span>{{channel.name}}</span>
|
||||
<span>{{ channel.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</main>
|
||||
}
|
||||
@case (2) {
|
||||
<!-- @case (2) {
|
||||
<main id="settings">
|
||||
<network-settings [networkStore]="this.store"></network-settings>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
}-->
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
overflow-y: scroll;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 0 100%;
|
||||
overflow-x: hidden;
|
||||
padding: 15px;
|
||||
transition: 0.2s;
|
||||
@@ -13,20 +11,6 @@
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
&.routerOutletActive {
|
||||
overflow-y: hidden;
|
||||
padding: 0;
|
||||
grid-template-columns: 1fr 300px;
|
||||
|
||||
#router {
|
||||
background: var(--tui-background-neutral-1);
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 15px;
|
||||
}
|
||||
}
|
||||
|
||||
&.hideNetworkNav {
|
||||
grid-template-columns: 1fr;
|
||||
|
||||
@@ -38,7 +22,6 @@
|
||||
}
|
||||
|
||||
.category {
|
||||
background: var(--tui-background-base-alt);
|
||||
width: 100%;
|
||||
padding: 15px;
|
||||
|
||||
@@ -46,6 +29,31 @@
|
||||
display: flex;
|
||||
justify-content: start;
|
||||
}
|
||||
|
||||
.channels {
|
||||
position: relative;
|
||||
padding-left: 24px; /* Space for the line and spacing */
|
||||
border-left: 2px solid var(--tui-background-neutral-1-hover); /* Main vertical track */
|
||||
margin-left: 8px; /* Shifts child tracks slightly right */
|
||||
|
||||
.channel {
|
||||
height: 50px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.channel::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: -26px; /* Reaches backward to snap to the parent track */
|
||||
top: 10px; /* Aligns horizontally with the center of the user header */
|
||||
width: 22px; /* Defines width of the horizontal curve */
|
||||
height: 14px; /* Defines height of the vertical curve drop */
|
||||
|
||||
border-left: 2px solid var(--tui-background-neutral-1-hover);
|
||||
border-bottom: 2px solid var(--tui-background-neutral-1-hover);
|
||||
border-bottom-left-radius: 8px; /* Creates the smooth curved bend */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#settings {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {Component, inject, OnInit, signal} from '@angular/core';
|
||||
import { Component, effect, inject, input, OnInit, signal } from '@angular/core';
|
||||
import {ActivatedRoute, Router, RouterLink, RouterOutlet} from '@angular/router';
|
||||
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
|
||||
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
|
||||
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel';
|
||||
import {DmStorage, NetworkStorage, ServiceManager} from '../../service-manager';
|
||||
import {NetworkStorage, ServiceManager} from '../../service-manager';
|
||||
import {DMService} from '@chatenium/chatenium-sdk/services/dmService';
|
||||
import {Network as NetworkData} from "@chatenium/chatenium-sdk/domain/networkService.schema"
|
||||
import {NetworkService} from '@chatenium/chatenium-sdk/services/networkService';
|
||||
@@ -15,9 +15,10 @@ import {TuiTab, TuiTabsHorizontal, TuiTabsWithMore} from '@taiga-ui/kit';
|
||||
import {TuiItem} from '@taiga-ui/cdk';
|
||||
import {TranslatePipe} from '@ngx-translate/core';
|
||||
import {Settings} from './settings/settings';
|
||||
import { toObservable } from '@angular/core/rxjs-interop';
|
||||
|
||||
@Component({
|
||||
selector: 'app-network',
|
||||
selector: 'network',
|
||||
imports: [
|
||||
RouterOutlet,
|
||||
Navbar,
|
||||
@@ -31,59 +32,61 @@ import {Settings} from './settings/settings';
|
||||
TuiTab,
|
||||
TranslatePipe,
|
||||
TuiTabsHorizontal,
|
||||
Settings
|
||||
Settings,
|
||||
],
|
||||
templateUrl: './network.html',
|
||||
styleUrl: './network.scss',
|
||||
})
|
||||
export class Network implements OnInit {
|
||||
serviceManager = inject(ServiceManager)
|
||||
route = inject(ActivatedRoute)
|
||||
indexedDb = inject(IndexedDB)
|
||||
breakpoint = inject(TUI_BREAKPOINT)
|
||||
router = inject(Router)
|
||||
export class Network {
|
||||
serviceManager = inject(ServiceManager);
|
||||
route = inject(ActivatedRoute);
|
||||
indexedDb = inject(IndexedDB);
|
||||
breakpoint = inject(TUI_BREAKPOINT);
|
||||
router = inject(Router);
|
||||
|
||||
tabActiveIndex = 2
|
||||
|
||||
routerOutletActive = signal(false)
|
||||
|
||||
networkId = ""
|
||||
get store() {
|
||||
return this.serviceManager.networkServices()[this.networkId]
|
||||
constructor() {
|
||||
effect(() => {
|
||||
if (this.network()) {
|
||||
this.setupNetwork();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.route.params.subscribe(async params => {
|
||||
console.log("Loading network...")
|
||||
const networkId = params['networkId'];
|
||||
this.networkId = networkId;
|
||||
network = input.required<NetworkData>();
|
||||
|
||||
routerOutletActive = signal(false);
|
||||
|
||||
get store() {
|
||||
return this.serviceManager.networkServices()[this.network().networkId];
|
||||
}
|
||||
|
||||
setupNetwork() {
|
||||
console.log(`Setting up NetworkView for ${this.network().networkId}`);
|
||||
const session = this.serviceManager.currentSession();
|
||||
const networkData = this.serviceManager.networks().find(c => c.networkId === networkId);
|
||||
|
||||
if (!session || !networkData) {
|
||||
console.warn(`Initialization deferred for ${networkId}: Session or NetworkData missing.`);
|
||||
if (!session) {
|
||||
console.warn(
|
||||
`Initialization deferred for ${this.network().networkId}: Session or NetworkData missing.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.serviceManager.networkServices()[networkId]) {
|
||||
if (!this.serviceManager.networkServices()[this.network().networkId]) {
|
||||
const newStore = {
|
||||
networkData: signal<NetworkData>(networkData),
|
||||
networkData: signal<NetworkData>(this.network()),
|
||||
textChannels: signal({}),
|
||||
wsListener: (action, data) => {
|
||||
},
|
||||
wsListener: (action, data) => {},
|
||||
} as NetworkStorage;
|
||||
|
||||
newStore.service = new NetworkService(
|
||||
session.userData.userid,
|
||||
session.token,
|
||||
networkId,
|
||||
this.network().networkId,
|
||||
this.indexedDb.getApi(),
|
||||
(action, data) => newStore.wsListener(action, data)
|
||||
(action, data) => newStore.wsListener(action, data),
|
||||
);
|
||||
|
||||
this.serviceManager.networkServices()[networkId] = newStore;
|
||||
this.serviceManager.networkServices()[this.network().networkId] = newStore;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {Component, inject, signal} from '@angular/core';
|
||||
import {DmStorage, PictureStorage, ServiceManager} from '../../../service-manager';
|
||||
import {PictureStorage, ServiceManager} from '../../../service-manager';
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {IndexedDB} from '../../../storage/indexed-db';
|
||||
import {TUI_BREAKPOINT, TuiButton, TuiDialog, TuiIcon} from '@taiga-ui/core';
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
</button>
|
||||
|
||||
@if (serviceManager.currentSession()!.userData.emailSet) {
|
||||
<button tuiButton appearance="outline" tuiAppearanceMode="invalid" iconStart="@tui.x" [disabled]="!serviceManager.currentSession()!.userData.phoneSet && !serviceManager.currentSession()!.userData.phoneSet"
|
||||
<button tuiButton appearance="outline" tuiAppearanceMode="invalid" iconStart="@tui.x" [disabled]="!serviceManager.currentSession()!.userData.phoneSet && !serviceManager.currentSession()!.userData.passwordSet"
|
||||
(click)="openChangeEmailDialog(true)"
|
||||
style="color: var(--tui-text-negative)">
|
||||
{{ "chat.userSettingsDialog.security.removeMail"|translate }}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
{{ "chat.userSettingsDialog.security.label"|translate }}
|
||||
</p>
|
||||
<div id="options" tuiGroup orientation="vertical">
|
||||
<user-settings-security-password/>
|
||||
<user-settings-security-email/>
|
||||
<user-settings-security-phone/>
|
||||
<user-settings-security-password style="overflow: hidden"/>
|
||||
<user-settings-security-email style="overflow: hidden"/>
|
||||
<user-settings-security-phone style="overflow: hidden"/>
|
||||
</div>
|
||||
|
||||
12
src/app/chatenium.token.ts
Normal file
12
src/app/chatenium.token.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
import { environment } from '../environments/environment';
|
||||
import { ChateniumClient } from 'chatenium-sdk-preview';
|
||||
|
||||
export const CHATENIUM_SDK = new InjectionToken<ChateniumClient>('CHATENIUM_SDK', {
|
||||
providedIn: 'root',
|
||||
factory: () => {
|
||||
return new ChateniumClient({
|
||||
baseUrl: environment.api_url,
|
||||
});
|
||||
},
|
||||
});
|
||||
16
src/app/google-oauth.spec.ts
Normal file
16
src/app/google-oauth.spec.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { GoogleOAuth } from './google-oauth';
|
||||
|
||||
describe('GoogleOAuth', () => {
|
||||
let service: GoogleOAuth;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(GoogleOAuth);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
30
src/app/google-oauth.ts
Normal file
30
src/app/google-oauth.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { inject, Injectable, NgZone } from '@angular/core';
|
||||
import { Subject } from 'rxjs';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class GoogleOAuth {
|
||||
private ngZone = inject(NgZone);
|
||||
private codeClient?: google.accounts.oauth2.CodeClient;
|
||||
private codeSubject = new Subject<string>();
|
||||
|
||||
readonly code$ = this.codeSubject.asObservable();
|
||||
|
||||
init(clientId: string): void {
|
||||
this.codeClient = google.accounts.oauth2.initCodeClient({
|
||||
client_id: clientId,
|
||||
scope: 'openid email profile',
|
||||
ux_mode: 'popup',
|
||||
callback: (response) => {
|
||||
if (response.code) {
|
||||
this.ngZone.run(() => this.codeSubject.next(response.code));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openSignIn(): void {
|
||||
this.codeClient?.requestCode();
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,18 @@
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {inject} from '@angular/core';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {Keyring} from '../storage/keyring';
|
||||
import {KeyValue} from '../storage/key-value';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import { SessionManager } from '../session-manager';
|
||||
|
||||
export const authNeededGuard: CanActivateFn = (route, state) => {
|
||||
const indexedDb = inject(IndexedDB)
|
||||
const keyring = inject(Keyring)
|
||||
const keyValue = inject(KeyValue)
|
||||
const router = inject(Router)
|
||||
const sessionManager = inject(SessionManager);
|
||||
const idb = inject(IndexedDB);
|
||||
const router = inject(Router);
|
||||
|
||||
indexedDb.openDatabase().then(async () => {
|
||||
const sessionManager = new SessionManager(indexedDb.getApi(), keyring.getApi(), keyValue.getApi());
|
||||
const sessions = await sessionManager.loadSessions()
|
||||
|
||||
if (sessions.length == 0) {
|
||||
router.navigate(['/signin'])
|
||||
idb.openDatabase().then(async () => {
|
||||
if (!sessionManager.quickSignInCheck()) {
|
||||
await router.navigate(['/chat']);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import {inject} from '@angular/core';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {Keyring} from '../storage/keyring';
|
||||
import {KeyValue} from '../storage/key-value';
|
||||
import { SessionManager } from '../session-manager';
|
||||
|
||||
export const noAuthGuard: CanActivateFn = async (route, state) => {
|
||||
const indexedDb = inject(IndexedDB)
|
||||
const keyring = inject(Keyring)
|
||||
const keyValue = inject(KeyValue)
|
||||
const sessionManager = inject(SessionManager);
|
||||
const idb = inject(IndexedDB);
|
||||
const router = inject(Router)
|
||||
|
||||
indexedDb.openDatabase().then(async () => {
|
||||
const sessionManager = new SessionManager(indexedDb.getApi(), keyring.getApi(), keyValue.getApi());
|
||||
const sessions = await sessionManager.loadSessions()
|
||||
|
||||
if (sessions.length != 0) {
|
||||
router.navigate(['/chat'])
|
||||
idb.openDatabase().then(async () => {
|
||||
if (sessionManager.quickSignInCheck()) {
|
||||
await router.navigate(['/chat'])
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ export class ServiceManager {
|
||||
// Services for individual networks
|
||||
networkServices = signal<Record<string, NetworkStorage>>({})
|
||||
|
||||
dmServices = signal<Record<string, DmStorage>>({})
|
||||
//dmServices = signal<Record<string, DmStorage>>({})
|
||||
pictureServices = signal<Record<string, PictureStorage>>({})
|
||||
}
|
||||
|
||||
@@ -53,16 +53,6 @@ export enum LoadStatus {
|
||||
updating = 3,
|
||||
}
|
||||
|
||||
export interface DmStorage {
|
||||
service: DMService
|
||||
messages: WritableSignal<Message[]>
|
||||
messagesStatus: WritableSignal<LoadStatus>
|
||||
messagesVm: MessagesViewModel
|
||||
chatData: WritableSignal<Chat>
|
||||
messageBox: MessageBoxViewModel
|
||||
wsListener: (action: string, message: string) => void
|
||||
}
|
||||
|
||||
export interface PictureStorage {
|
||||
service: PictureService
|
||||
albums: WritableSignal<Album[]>
|
||||
|
||||
16
src/app/session-manager.spec.ts
Normal file
16
src/app/session-manager.spec.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { SessionManager } from './session-manager';
|
||||
|
||||
describe('SessionManager', () => {
|
||||
let service: SessionManager;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
service = TestBed.inject(SessionManager);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
});
|
||||
102
src/app/session-manager.ts
Normal file
102
src/app/session-manager.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { inject, Injectable, signal } from '@angular/core';
|
||||
import { IndexedDB } from './storage/indexed-db';
|
||||
import { CookieService } from 'ngx-cookie-service';
|
||||
import { CHATENIUM_SDK } from './chatenium.token';
|
||||
import { PersonalUserData, SuccessfulAuthResp } from 'chatenium-sdk-preview';
|
||||
import { TuiNotificationService } from '@taiga-ui/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SessionManager {
|
||||
private SDK = inject(CHATENIUM_SDK);
|
||||
private idb = inject(IndexedDB);
|
||||
private cookie = inject(CookieService);
|
||||
private notification = inject(TuiNotificationService);
|
||||
|
||||
public userData = signal<PersonalUserData|undefined>(undefined);
|
||||
public sessionReady = signal(false); // Helps with timing session loading
|
||||
|
||||
async addSession(refreshToken: string, accessToken: string, userId: string) {
|
||||
const date = new Date();
|
||||
date.setFullYear(date.getFullYear() + 5);
|
||||
this.cookie.set(`token_${userId}`, refreshToken, {
|
||||
expires: date,
|
||||
path: '/',
|
||||
secure: true,
|
||||
sameSite: 'Strict',
|
||||
});
|
||||
|
||||
this.SDK.addHeader('Authorization', accessToken);
|
||||
try {
|
||||
const resp = await this.SDK.account.getPersonalUserData();
|
||||
const data = resp.data as PersonalUserData;
|
||||
this.idb.putObject('userData', data, data.userId);
|
||||
} catch (error) {
|
||||
this.notification
|
||||
.open('PersonalUserData fetch failed. Did header refresh fail?', { appearance: 'negative' })
|
||||
.subscribe();
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async loadSessions() {
|
||||
const cookies = this.cookie.getAll();
|
||||
for (const [key, value] of Object.entries(cookies)) {
|
||||
if (key.startsWith('token')) {
|
||||
const userId = key.split('_')[1];
|
||||
const userData = (await this.idb.get('userData', userId)) as PersonalUserData;
|
||||
console.log(`Found saved session for ID: ${userId} Username: ${userData.displayName}`);
|
||||
this.userData.set(userData);
|
||||
await this.rotateTokenPair();
|
||||
break; // For the moment, the client just loads the first session saved
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quickly checks saved cookies and determines if the user is signed-in or not
|
||||
*/
|
||||
quickSignInCheck(): boolean {
|
||||
const cookies = this.cookie.getAll();
|
||||
for (const [key, value] of Object.entries(cookies)) {
|
||||
if (key.startsWith('token')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async rotateTokenPair() {
|
||||
const userData = this.userData();
|
||||
|
||||
if (userData != undefined) {
|
||||
const refreshToken = this.cookie.get(`token_${userData.userId}`);
|
||||
|
||||
try {
|
||||
const resp = await this.SDK.auth.rotateTokenPair(refreshToken);
|
||||
const data = resp.data as SuccessfulAuthResp;
|
||||
|
||||
const date = new Date();
|
||||
date.setFullYear(date.getFullYear() + 5);
|
||||
this.cookie.set(`token_${data.userId}`, data.refreshToken, {
|
||||
expires: date,
|
||||
path: '/',
|
||||
secure: true,
|
||||
sameSite: 'Strict',
|
||||
});
|
||||
|
||||
this.SDK.addHeader('Authorization', data.accessToken);
|
||||
console.log(
|
||||
`Successfully rotated token pair for ID: ${userData.userId} Username: ${userData.username}. This session is now ready to be used.`,
|
||||
);
|
||||
this.sessionReady.set(true);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
} else {
|
||||
console.error('Token refresh failed - No user data loaded');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,163 @@
|
||||
<main id="holder">
|
||||
<form [formGroup]="signInForm" tuiAppearance="floating">
|
||||
@switch (page()) {
|
||||
@case ('initial') {
|
||||
<form [formGroup]="signInForm" tuiAppearance="floating" id="initial" animate.enter="slide-in-right"
|
||||
animate.leave="slide-out-left">
|
||||
<header>
|
||||
<h1>{{"signIn.formTitle"|translate}}</h1>
|
||||
<h1>{{ "signIn.initial.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.initial.formSubtitle"|translate }}</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<tui-textfield iconStart="@tui.user">
|
||||
<label tuiLabel>{{"signIn.mainInput.label"|translate}}</label>
|
||||
<label tuiLabel>{{ "signIn.initial.mainInput.label"|translate }}</label>
|
||||
|
||||
<input (input)="checkAuthMethods(signInForm.controls['unameMailPhone'].value)" formControlName="unameMailPhone" tuiInput placeholder="{{'signIn.mainInput.placeholder'|translate}}">
|
||||
<input (input)="checkAuthMethods(signInForm.controls['unameMailPhone'].value)"
|
||||
formControlName="unameMailPhone" tuiInput
|
||||
placeholder="{{'signIn.initial.mainInput.placeholder'|translate}}">
|
||||
</tui-textfield>
|
||||
@if (signInForm.controls["unameMailPhone"].dirty) {
|
||||
@if (signInForm.controls["unameMailPhone"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.errors.unameMailPhoneRequired'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
|
||||
<tui-textfield iconStart="@tui.key">
|
||||
<label tuiLabel>{{"signIn.password.label"|translate}}</label>
|
||||
<input formControlName="password" [disabled]="!methods().password" type="password" tuiInput>
|
||||
<tui-icon tuiPassword></tui-icon>
|
||||
</tui-textfield>
|
||||
@if (signInForm.controls["password"].dirty) {
|
||||
@if (signInForm.controls["password"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.errors.passwordRequired'|translate"></tui-error>
|
||||
} @else if (signInForm.controls["password"].hasError("incorrect")) {
|
||||
<tui-error [error]="'signIn.errors.passwordIncorrect'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
|
||||
<div id="methods">
|
||||
<button [disabled]="!methods().email" iconStart="@tui.mail-open" appearance="secondary" tuiButton disabled>{{'signIn.emailButton'|translate}}</button>
|
||||
<button [disabled]="!methods().sms" iconStart="@tui.phone" appearance="secondary" tuiButton disabled>{{'signIn.smsButton'|translate}}</button>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<button (click)="passwordSignIn(signInForm.controls['unameMailPhone'].value, signInForm.controls['password'].value)" [disabled]="signInForm.invalid || !methods().password" tuiButton>
|
||||
{{'signIn.signInButton'|translate}}
|
||||
<button (click)="startChallenge(signInForm.controls['unameMailPhone'].value)"
|
||||
[disabled]="signInForm.invalid && false || pendingAction()" tuiButton>
|
||||
{{ 'signIn.initial.signInButton'|translate }}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
}
|
||||
@case ('methodChoose') {
|
||||
<form id="methodChoose" animate.enter="slide-in-right" animate.leave="slide-out-left">
|
||||
<header>
|
||||
@if (isMultistep()) {
|
||||
<h1>{{ "signIn.methodChoose.formTitleAlt"|translate }}</h1>
|
||||
<span>{{ "signIn.methodChoose.formSubtitleAlt"|translate }}</span>
|
||||
} @else {
|
||||
<h1>{{ "signIn.methodChoose.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.methodChoose.formSubtitle"|translate }}</span>
|
||||
}
|
||||
</header>
|
||||
|
||||
<main tuiGroup orientation="vertical" style="gap: 0">
|
||||
@if (challenge != null) {
|
||||
@if (challenge()!.factorsTracker["PASSWORD"] != null) {
|
||||
<button [disabled]="challenge()!.factorsTracker['PASSWORD'].status == 'SUCCESS'" type="button" tuiButton
|
||||
appearance="secondary" class="method" (click)="this.page.set('passwordAuth')">
|
||||
<tui-icon icon="@tui.key"></tui-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.password.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.password.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
@if (challenge()!.factorsTracker["EMAIL"] != null) {
|
||||
<button type="button"
|
||||
[disabled]="challenge()!.factorsTracker['EMAIL'].status == 'SUCCESS' || pendingAction()" tuiButton
|
||||
appearance="secondary" class="method" (click)="this.requestCredential('EMAIL')">
|
||||
<tui-icon icon="@tui.mail"></tui-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.mail.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.mail.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
<button tuiButton appearance="secondary" class="method">
|
||||
<tui-icon icon="@tui.phone"></tui-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.sms.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.sms.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
@if (challenge()!.factorsTracker["GOOGLE"] != null) {
|
||||
<button type="button" tuiButton appearance="secondary" class="method"
|
||||
(click)="this.googleOAuth.openSignIn();" [disabled]="challenge()!.factorsTracker['GOOGLE'].status == 'SUCCESS' || pendingAction()">
|
||||
<fa-icon [icon]="faGoogle" style="font-size: 25px; margin-left: -5px"></fa-icon>
|
||||
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.google.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.google.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
<button tuiButton appearance="secondary" class="method">
|
||||
<fa-icon [icon]="faApple" style="font-size: 30px; margin-left: -7px"></fa-icon>
|
||||
<div>
|
||||
<span class="title">{{ "signIn.methodChoose.methods.apple.title"|translate }}</span>
|
||||
<span class="desc">{{ "signIn.methodChoose.methods.apple.desc"|translate }}</span>
|
||||
</div>
|
||||
</button>
|
||||
}
|
||||
</main>
|
||||
</form>
|
||||
}
|
||||
@case ('passwordAuth') {
|
||||
<form [formGroup]="authForm" tuiAppearance="floating" id="passwordAuth" animate.enter="slide-in-right"
|
||||
animate.leave="slide-out-left">
|
||||
<header>
|
||||
<h1>{{ "signIn.passwordAuth.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.passwordAuth.formSubtitle"|translate }}</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<tui-textfield iconStart="@tui.key">
|
||||
<label tuiLabel>{{ "signIn.initial.password.label"|translate }}</label>
|
||||
<input formControlName="method" type="password" tuiInput>
|
||||
<tui-icon tuiPassword></tui-icon>
|
||||
</tui-textfield>
|
||||
@if (authForm.controls["method"].dirty) {
|
||||
@if (authForm.controls["method"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.passwordAuth.errors.passwordRequired'|translate"></tui-error>
|
||||
} @else if (authForm.controls["method"].hasError("incorrect")) {
|
||||
<tui-error [error]="'signIn.passwordAuth.errors.passwordIncorrect'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<button (click)="verifyMethod('PASSWORD', authForm.controls['method'].value)"
|
||||
[disabled]="authForm.invalid && false || pendingAction()" tuiButton>
|
||||
{{ 'signIn.anyAuth.verifyButton'|translate }}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
}
|
||||
@case ('emailAuth') {
|
||||
<form [formGroup]="authForm" tuiAppearance="floating" id="emailAuth" animate.enter="slide-in-right"
|
||||
animate.leave="slide-out-left">
|
||||
<header>
|
||||
<h1>{{ "signIn.emailAuth.formTitle"|translate }}</h1>
|
||||
<span>{{ "signIn.emailAuth.formSubtitle"|translate }}</span>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<tui-textfield iconStart="@tui.mail">
|
||||
<label tuiLabel>{{ "signIn.emailAuth.emailCode.label"|translate }}</label>
|
||||
<input formControlName="method" type="number" tuiInput>
|
||||
</tui-textfield>
|
||||
@if (authForm.controls["method"].dirty) {
|
||||
@if (authForm.controls["method"].hasError("required")) {
|
||||
<tui-error [error]="'signIn.emailAuth.errors.passwordRequired'|translate"></tui-error>
|
||||
} @else if (authForm.controls["method"].hasError("incorrect")) {
|
||||
<tui-error [error]="'signIn.emailAuth.errors.passwordIncorrect'|translate"></tui-error>
|
||||
}
|
||||
}
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<button (click)="verifyMethod('EMAIL', authForm.controls['method'].value)"
|
||||
[disabled]="authForm.invalid && false || pendingAction()" tuiButton>
|
||||
{{ 'signIn.anyAuth.verifyButton'|translate }}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
}
|
||||
@case ('ok') {
|
||||
<h1>Received Chtn identity token, auth flow finished</h1>
|
||||
}
|
||||
}
|
||||
</main>
|
||||
|
||||
@@ -4,9 +4,28 @@
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
|
||||
.slide-in-right {
|
||||
animation: slideInRight 250ms ease-out forwards;
|
||||
}
|
||||
|
||||
.slide-out-left {
|
||||
animation: slideOutLeft 200ms ease-in forwards;
|
||||
}
|
||||
|
||||
@keyframes slideInRight {
|
||||
from { opacity: 0; transform: translateX(-8px); }
|
||||
to { opacity: 1; transform: translateX(0); }
|
||||
}
|
||||
|
||||
@keyframes slideOutLeft {
|
||||
from { opacity: 1; transform: translateX(0); }
|
||||
to { opacity: 0; transform: translateX(8px); }
|
||||
}
|
||||
|
||||
form {
|
||||
width: 50%;
|
||||
height: 45%;
|
||||
position: absolute;
|
||||
width: 35%;
|
||||
max-height: 65%;
|
||||
border-radius: 35px;
|
||||
background: var(--tui-background-base-alt);
|
||||
padding: 20px;
|
||||
@@ -14,21 +33,51 @@
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
|
||||
main {
|
||||
header {
|
||||
align-self: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
margin-bottom: 35px;
|
||||
margin-top: 25px;
|
||||
|
||||
#methods {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 10px;
|
||||
h1 {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
footer {
|
||||
margin-top: 30px;
|
||||
margin-top: 10px;
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#initial main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
#methodChoose main .method {
|
||||
width: 100%;
|
||||
height: 65px;
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
justify-content: start;
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-weight: normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,37 @@
|
||||
import {Component, inject, OnInit, signal} from '@angular/core';
|
||||
import {TuiAppearance, TuiButton, TuiError, TuiErrorDirective, TuiIcon, TuiInput, TuiTextfield} from '@taiga-ui/core';
|
||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
||||
import {
|
||||
TuiAlertService,
|
||||
TuiAppearance,
|
||||
TuiButton,
|
||||
TuiError,
|
||||
TuiErrorDirective,
|
||||
TuiGroup,
|
||||
TuiIcon,
|
||||
TuiInput,
|
||||
TuiNotificationService,
|
||||
TuiTextfield,
|
||||
} from '@taiga-ui/core';
|
||||
import {TranslatePipe} from '@ngx-translate/core';
|
||||
import {TuiButtonGroup, TuiPassword} from '@taiga-ui/kit';
|
||||
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {AuthService} from '@chatenium/chatenium-sdk/services/authService';
|
||||
import {AuthMethods} from '@chatenium/chatenium-sdk/domain/authService.schema';
|
||||
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
|
||||
import {ServiceManager} from '../service-manager';
|
||||
import {IndexedDB} from '../storage/indexed-db';
|
||||
import {PublicUserData} from '@chatenium/chatenium-sdk/domain/common.schema';
|
||||
import {Router} from '@angular/router';
|
||||
import { CHATENIUM_SDK } from '../chatenium.token';
|
||||
import { AuthChallenge, Challenge, SignInReq, SuccessfulAuthResp } from 'chatenium-sdk-preview';
|
||||
import { TuiItemGroup } from '@taiga-ui/layout';
|
||||
import { faApple, faGoogle } from '@fortawesome/free-brands-svg-icons';
|
||||
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
|
||||
import { JsonPipe } from '@angular/common';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { GoogleOAuth } from '../google-oauth';
|
||||
import { environment } from '../../environments/environment';
|
||||
import { SessionManager } from '../session-manager';
|
||||
import { Platform } from '@angular/cdk/platform';
|
||||
import { DeviceDetectorService } from 'ngx-device-detector';
|
||||
|
||||
@Component({
|
||||
selector: 'app-signin',
|
||||
@@ -19,49 +41,77 @@ import {Router} from '@angular/router';
|
||||
TuiTextfield,
|
||||
TuiInput,
|
||||
TuiButton,
|
||||
TuiButtonGroup,
|
||||
TuiPassword,
|
||||
TuiIcon,
|
||||
ReactiveFormsModule,
|
||||
TuiErrorDirective,
|
||||
TuiError
|
||||
TuiError,
|
||||
TuiGroup,
|
||||
FaIconComponent,
|
||||
JsonPipe,
|
||||
],
|
||||
templateUrl: './signin.html',
|
||||
styleUrl: './signin.scss',
|
||||
})
|
||||
export class SignIn implements OnInit {
|
||||
indexedDb = inject(IndexedDB)
|
||||
router = inject(Router)
|
||||
SDK = inject(CHATENIUM_SDK);
|
||||
googleOAuth = inject(GoogleOAuth);
|
||||
sessionManager = inject(SessionManager);
|
||||
device = inject(DeviceDetectorService);
|
||||
notification = inject(TuiNotificationService);
|
||||
|
||||
service = new AuthService()
|
||||
serviceManager = new ServiceManager()
|
||||
methods = signal<AuthMethods>({sms: false, email: false, password: false})
|
||||
private googleSub?: Subscription;
|
||||
|
||||
private clickEvent = signal(0)
|
||||
challengeApi: AuthChallenge | null = null;
|
||||
challenge = signal<Challenge | null>(null);
|
||||
|
||||
indexedDb = inject(IndexedDB);
|
||||
router = inject(Router);
|
||||
|
||||
service = new AuthService();
|
||||
serviceManager = new ServiceManager();
|
||||
methods = signal<AuthMethods>({ sms: false, email: false, password: false });
|
||||
|
||||
pendingAction = signal(false);
|
||||
page = signal<'initial' | 'methodChoose' | 'passwordAuth' | 'emailAuth' | 'smsAuth' | 'ok'>(
|
||||
'initial',
|
||||
);
|
||||
isMultistep = signal(false);
|
||||
|
||||
signInForm = new FormGroup({
|
||||
unameMailPhone: new FormControl('', {
|
||||
validators: [Validators.required]
|
||||
validators: [Validators.required],
|
||||
}),
|
||||
password: new FormControl('', {
|
||||
validators: [Validators.required]
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
authForm = new FormGroup({
|
||||
method: new FormControl('', {
|
||||
validators: [Validators.required],
|
||||
}),
|
||||
});
|
||||
|
||||
timeoutId: any;
|
||||
|
||||
async checkAuthMethods(unameMailPhone: string | null) {
|
||||
console.log("Called")
|
||||
console.log('Called');
|
||||
clearTimeout(this.timeoutId);
|
||||
|
||||
this.timeoutId = setTimeout(async () => {
|
||||
this.methods.set({sms: false, password: false, email: false})
|
||||
this.methods.set(await this.service.getAuthMethods(unameMailPhone ?? ""))
|
||||
}, 500)
|
||||
this.methods.set({ sms: false, password: false, email: false });
|
||||
this.methods.set(await this.service.getAuthMethods(unameMailPhone ?? ''));
|
||||
}, 500);
|
||||
}
|
||||
|
||||
async passwordSignIn(unameMailPhone: string | null, password: string | null) {
|
||||
async startChallenge(identity: string | null) {
|
||||
this.pendingAction.set(true);
|
||||
try {
|
||||
const fetchResp = await this.SDK.auth.getIdFromIdentity(identity ?? '');
|
||||
const challenge = new AuthChallenge(this.SDK.auth);
|
||||
const resp = await challenge.start('AUTH:SIGNIN', fetchResp.data.userId);
|
||||
this.challenge.set(resp);
|
||||
this.challengeApi = challenge;
|
||||
this.pendingAction.set(false);
|
||||
this.page.set('methodChoose');
|
||||
/*
|
||||
const resp = await this.service.loginPasswordAuth(unameMailPhone ?? "", password ?? "")
|
||||
this.serviceManager.sessionManager.addSession(<PublicUserData>{
|
||||
pfp: resp.pfp,
|
||||
@@ -71,13 +121,101 @@ export class SignIn implements OnInit {
|
||||
}, resp.token)
|
||||
console.log("Logged in")
|
||||
this.router.navigate(["/chat"])
|
||||
*/
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
this.signInForm.controls['password'].setErrors({incorrect: true})
|
||||
console.error(e);
|
||||
this.signInForm.controls['unameMailPhone'].setErrors({ incorrect: true });
|
||||
this.pendingAction.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.indexedDb.openDatabase()
|
||||
async verifyMethod(methodName: string, credential: string | null) {
|
||||
this.pendingAction.set(true);
|
||||
if (this.challengeApi != null) {
|
||||
try {
|
||||
const resp = await this.challengeApi.verifyFactor(methodName, String(credential) ?? '');
|
||||
this.challenge.set(resp);
|
||||
this.pendingAction.set(false);
|
||||
if (resp.authIdentityToken == null) {
|
||||
this.isMultistep.set(true);
|
||||
this.page.set('methodChoose');
|
||||
this.authForm.reset();
|
||||
} else {
|
||||
await this.signIn(resp.authIdentityToken);
|
||||
this.page.set('ok');
|
||||
}
|
||||
} catch (e) {
|
||||
this.pendingAction.set(false);
|
||||
this.authForm.controls['method'].setErrors({ incorrect: true });
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async signIn(authIdentityToken: string) {
|
||||
try {
|
||||
const resp = await this.SDK.auth.signIn(authIdentityToken, {
|
||||
os: this.device.deviceInfo().os,
|
||||
frontend: "nexum"
|
||||
})
|
||||
const data = resp.data as SuccessfulAuthResp;
|
||||
await this.sessionManager.addSession(data.refreshToken, data.accessToken, data.userId);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
this.notification.open('SignIn Failed', { appearance: "negative" }).subscribe();
|
||||
}
|
||||
}
|
||||
|
||||
async requestCredential(methodName: string) {
|
||||
this.pendingAction.set(true);
|
||||
if (this.challengeApi != null) {
|
||||
try {
|
||||
const resp = await this.challengeApi.requestCredential(methodName);
|
||||
this.challenge.set(resp);
|
||||
this.pendingAction.set(false);
|
||||
if (resp.authIdentityToken == null) {
|
||||
this.isMultistep.set(true);
|
||||
this.page.set(methodName == 'EMAIL' ? 'emailAuth' : 'smsAuth');
|
||||
}
|
||||
} catch (e) {
|
||||
this.pendingAction.set(false);
|
||||
this.authForm.controls['method'].setErrors({ incorrect: true });
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async ngOnInit(): Promise<void> {
|
||||
this.indexedDb.openDatabase();
|
||||
|
||||
this.googleSub = this.googleOAuth.code$.subscribe((code) => {
|
||||
this.verifyMethod("GOOGLE", code);
|
||||
});
|
||||
|
||||
this.waitForGoogle().then(() => {
|
||||
this.googleOAuth.init(environment.google_client_id);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.googleSub?.unsubscribe();
|
||||
}
|
||||
|
||||
private waitForGoogle(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (typeof google !== 'undefined' && google.accounts?.oauth2) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
if (typeof google !== 'undefined' && google.accounts?.oauth2) {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
|
||||
protected readonly faGoogle = faGoogle;
|
||||
protected readonly faApple = faApple;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {DatabaseAPI} from '@chatenium/chatenium-sdk/storage/database';
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class IndexedDB {
|
||||
private dbVersion = 3
|
||||
private dbVersion = 4
|
||||
private db: IDBDatabase | null = null
|
||||
|
||||
getApi(): DatabaseAPI {
|
||||
@@ -30,12 +30,12 @@ export class IndexedDB {
|
||||
|
||||
request.onupgradeneeded = (e: IDBVersionChangeEvent) => {
|
||||
const db = (e.target as IDBOpenDBRequest).result;
|
||||
db.createObjectStore('sessions', { keyPath: 'id' })
|
||||
db.createObjectStore('chats', { keyPath: 'id' })
|
||||
db.createObjectStore('networks', { keyPath: 'id' })
|
||||
db.createObjectStore('userData', { keyPath: 'id' })
|
||||
db.createObjectStore('contacts', { keyPath: 'id' })
|
||||
db.createObjectStore('cascades', { keyPath: 'id' })
|
||||
db.createObjectStore('files', { keyPath: 'id' })
|
||||
db.createObjectStore('messages', { keyPath: 'id' })
|
||||
db.createObjectStore('networkmessages', { keyPath: 'id' })
|
||||
db.createObjectStore('threadMessages', { keyPath: 'id' })
|
||||
db.createObjectStore('pictures', { keyPath: 'id' })
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ export class IndexedDB {
|
||||
});
|
||||
}
|
||||
|
||||
get(storeName: string, key: string): Promise<string> {
|
||||
get(storeName: string, key: string): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.db) {
|
||||
const transaction = this.db.transaction([storeName], "readonly");
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
export const environment = {
|
||||
version: "3.0-beta9",
|
||||
api_url: "http://localhost:3000",
|
||||
cdn_url: "http://localhost:4000",
|
||||
ws_url: "ws://localhost:3000",
|
||||
version: '3.0-beta11',
|
||||
api_url: 'http://localhost:3000',
|
||||
cdn_url: 'http://localhost:4000',
|
||||
ws_url: 'ws://localhost:3000',
|
||||
// Google OAuth
|
||||
google_client_id: '21430884719-vjmecc7ofnfp82hmb22hba323gr4r7p7.apps.googleusercontent.com',
|
||||
};
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
export const environment = {
|
||||
version: "3.0-beta9",
|
||||
api_url: "https://api.chatenium.hu",
|
||||
cdn_url: "https://cdn.chatenium.hu",
|
||||
ws_url: "wss://api.chatenium.hu",
|
||||
version: '3.0-beta11',
|
||||
api_url: 'https://api.chatenium.hu',
|
||||
cdn_url: 'https://cdn.chatenium.hu',
|
||||
ws_url: 'wss://api.chatenium.hu',
|
||||
// Google OAuth
|
||||
google_client_id: '21430884719-vjmecc7ofnfp82hmb22hba323gr4r7p7.apps.googleusercontent.com',
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||
<link rel="manifest" href="manifest.webmanifest">
|
||||
<script src="https://accounts.google.com/gsi/client" async defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
/* You can add global styles to this file, and also import other style files */
|
||||
|
||||
.drag-active * {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/app",
|
||||
"types": []
|
||||
"types": ["google.accounts"]
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
|
||||
Reference in New Issue
Block a user