17 Commits

Author SHA1 Message Date
Noel Maróti
277bbc14d9 Small changes + cleanup 2026-11-29 18:25:55 +01:00
Noel Maróti
05e24d768a Ported MessagesView to V3 2026-11-29 18:25:33 +01:00
Noel Maróti
eaa355e40e Updated MessageBox to align with schema changes 2026-11-29 18:25:26 +01:00
Noel Maróti
8fc0da520c Updated DmComponent (partially) to V3 2026-11-29 18:25:06 +01:00
Noel Maróti
7149ebad10 Re-implemented DmStore in V3 2026-11-29 18:24:50 +01:00
Noel Maróti
34752b446c Minor changes 2026-11-29 11:50:17 +01:00
Noel Maróti
c18a8c14ca Updated 'chatid' parameter to 'contactId' 2026-11-29 11:50:08 +01:00
Noel Maróti
bc8501d74c Renamed Cache to CacheService to prevent name collisions 2026-11-29 11:49:55 +01:00
Noel Maróti
76d96067d0 Removed old redundant initializers 2026-11-29 11:49:41 +01:00
Noel Maróti
aa3494eac0 Updated DM chat initialization to use V3 API and V2 SDK 2026-11-29 11:49:15 +01:00
Noel Maróti
e386608e59 Updated Chatenium SDK 2026-11-29 11:48:16 +01:00
Noel Maróti
56d6065eef Minor update 2026-11-28 07:14:03 +01:00
Noel Maróti
aa811bff1b Added new variable to help with timing 2026-11-28 07:13:50 +01:00
Noel Maróti
b4ff8356ab Updated Chatenium SDK 2026-11-28 07:13:39 +01:00
Noel Maróti
f836df391b Renamed DmList to ContactList and updated logic to V3 2026-11-28 07:13:31 +01:00
Noel Maróti
1988c0a61e New singleton to hold cache globally in-memory 2026-11-28 07:13:18 +01:00
Noel Maróti
043a97ada5 New component (WIP) to handle avatar image loading, blurHash display and monogram avatar generation for accounts without PFPs (now possible in API/v3) 2026-11-28 07:13:00 +01:00
28 changed files with 484 additions and 335 deletions

8
package-lock.json generated
View File

@@ -33,7 +33,7 @@
"@taiga-ui/icons": "^5.25.0", "@taiga-ui/icons": "^5.25.0",
"@taiga-ui/kit": "^5.25.0", "@taiga-ui/kit": "^5.25.0",
"@taiga-ui/layout": "^5.25.0", "@taiga-ui/layout": "^5.25.0",
"chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.4", "chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.7",
"libphonenumber-js": "^1.12.41", "libphonenumber-js": "^1.12.41",
"ngx-cookie-service": "^21.3.1", "ngx-cookie-service": "^21.3.1",
"ngx-device-detector": "^11.0.0", "ngx-device-detector": "^11.0.0",
@@ -5919,9 +5919,9 @@
}, },
"node_modules/chatenium-sdk-preview": { "node_modules/chatenium-sdk-preview": {
"name": "@chatenium/chatenium-sdk", "name": "@chatenium/chatenium-sdk",
"version": "2.0.0-preview.4", "version": "2.0.0-preview.7",
"resolved": "https://registry.npmjs.org/@chatenium/chatenium-sdk/-/chatenium-sdk-2.0.0-preview.4.tgz", "resolved": "https://registry.npmjs.org/@chatenium/chatenium-sdk/-/chatenium-sdk-2.0.0-preview.7.tgz",
"integrity": "sha512-mPmyKdZZpwSGkW94LTqQ5zfZiOUgPZRLem0XO3h+9vrQ7L5Wy2RCwnu8HtO+DnTXszQQv6DXH0EvFSVL3H/MpA==", "integrity": "sha512-ZeUt/od2IkYyHh/h4TGsvdEaDkLZ1lPEN6qrZEhPs5E0EZFg+a8IXi3p/Jt8nZuSW4mmXNkU+53WS5tn4zhoOA==",
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
"dependencies": { "dependencies": {
"@openapitools/openapi-generator-cli": "^2.42.0" "@openapitools/openapi-generator-cli": "^2.42.0"

View File

@@ -36,7 +36,7 @@
"@taiga-ui/icons": "^5.25.0", "@taiga-ui/icons": "^5.25.0",
"@taiga-ui/kit": "^5.25.0", "@taiga-ui/kit": "^5.25.0",
"@taiga-ui/layout": "^5.25.0", "@taiga-ui/layout": "^5.25.0",
"chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.4", "chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.7",
"libphonenumber-js": "^1.12.41", "libphonenumber-js": "^1.12.41",
"ngx-cookie-service": "^21.3.1", "ngx-cookie-service": "^21.3.1",
"ngx-device-detector": "^11.0.0", "ngx-device-detector": "^11.0.0",

View File

@@ -21,7 +21,7 @@ export const routes: Routes = [
component: Chat, component: Chat,
canActivate: [authNeededGuard], canActivate: [authNeededGuard],
children: [ children: [
{ path: 'dm/:chatid', component: Dm }, { path: 'dm/:contactId', component: Dm },
{ path: 'picture/:uploaderId', component: See }, { path: 'picture/:uploaderId', component: See },
{ path: 'network/:networkId/:categoryId/:channelId', component: Text }, { path: 'network/:networkId/:categoryId/:channelId', component: Text },
], ],

16
src/app/cache.spec.ts Normal file
View 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
View 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;
}

View File

@@ -16,7 +16,7 @@
<user-settings (close)="userSettingsOpen.set(false)" /> <user-settings (close)="userSettingsOpen.set(false)" />
</ng-template> </ng-template>
@if (sessionManager.userData() == undefined) { @if (!sessionManager.sessionReady()) {
<main style="width: 100%; height: 100svh; display: flex; justify-content: center; align-items: center;"> <main style="width: 100%; height: 100svh; display: flex; justify-content: center; align-items: center;">
<tui-loader size="xl" /> <tui-loader size="xl" />
</main> </main>
@@ -44,11 +44,10 @@
</aside> </aside>
<main> <main>
<!-- @switch (navigationActiveIndex) { @switch (navigationActiveIndex) {
@case (0) { @case (0) {
<app-dm-list [token]="serviceManager.currentSession()!.token" <app-contact-list></app-contact-list>
[userid]="serviceManager.currentSession()!.userData.userid"></app-dm-list> } <!--
}
@case (1) { @case (1) {
<network-list <network-list
[(expandedSidenav)]="expandedSidenav" [(expandedSidenav)]="expandedSidenav"
@@ -58,8 +57,8 @@
@case (2) { @case (2) {
<app-picture-list [token]="serviceManager.currentSession()!.token" <app-picture-list [token]="serviceManager.currentSession()!.token"
[userid]="serviceManager.currentSession()!.userData.userid"></app-picture-list> [userid]="serviceManager.currentSession()!.userData.userid"></app-picture-list>
}
}--> }-->
}
</main> </main>
</aside> </aside>
@@ -67,7 +66,7 @@
<div id="content_tint"> <div id="content_tint">
@if (router.url.startsWith("/chat/dm") || router.url.startsWith("/chat/picture")) { @if (router.url.startsWith("/chat/dm") || router.url.startsWith("/chat/picture")) {
<!-- To ensure data is loaded --> <!-- To ensure data is loaded -->
@defer (when serviceManager.chatsStatus() != LoadStatus.loading) { @defer (when cache.contactsState() != LoadState.CLEAN_LOADING) {
<router-outlet /> <router-outlet />
} }
} @else if (router.url.startsWith("/chat/network")) { } @else if (router.url.startsWith("/chat/network")) {
@@ -88,8 +87,8 @@
<!-- <!--
@switch (navigationActiveIndex) { @switch (navigationActiveIndex) {
@case (0) { @case (0) {
<app-dm-list [token]="serviceManager.currentSession()!.token" <app-contact-list [token]="serviceManager.currentSession()!.token"
[userid]="serviceManager.currentSession()!.userData.userid"></app-dm-list> [userid]="serviceManager.currentSession()!.userData.userid"></app-contact-list>
} }
@case (1) { @case (1) {
<network-list <network-list

View File

@@ -4,7 +4,7 @@ import {TuiSegmented} from '@taiga-ui/kit';
import {TUI_BREAKPOINT, TuiAppearance, TuiButton, TuiDialog, TuiGroup, TuiIcon, TuiLoader} from '@taiga-ui/core'; import {TUI_BREAKPOINT, TuiAppearance, TuiButton, TuiDialog, TuiGroup, TuiIcon, TuiLoader} from '@taiga-ui/core';
import {LoadStatus, ServiceManager} from '../service-manager'; import {LoadStatus, ServiceManager} from '../service-manager';
import {IndexedDB} from '../storage/indexed-db'; 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 {JsonPipe} from '@angular/common';
import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler'; import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler';
import {TranslatePipe, TranslateService} from '@ngx-translate/core'; import {TranslatePipe, TranslateService} from '@ngx-translate/core';
@@ -16,6 +16,7 @@ import {UserSettings} from './user-settings/user-settings';
import {AuthService} from '@chatenium/chatenium-sdk/services/authService'; import {AuthService} from '@chatenium/chatenium-sdk/services/authService';
import {UserService} from '@chatenium/chatenium-sdk/services/userService'; import {UserService} from '@chatenium/chatenium-sdk/services/userService';
import { SessionManager } from '../session-manager'; import { SessionManager } from '../session-manager';
import { CacheService, LoadState } from '../cache';
@Component({ @Component({
selector: 'app-chat', selector: 'app-chat',
@@ -25,7 +26,7 @@ import { SessionManager } from '../session-manager';
TuiIcon, TuiIcon,
TuiButton, TuiButton,
TuiLoader, TuiLoader,
DmList, ContactList,
JsonPipe, JsonPipe,
TuiAppearance, TuiAppearance,
TuiGroup, TuiGroup,
@@ -42,10 +43,11 @@ import { SessionManager } from '../session-manager';
}) })
export class Chat implements OnInit { export class Chat implements OnInit {
sessionManager = inject(SessionManager); sessionManager = inject(SessionManager);
serviceManager = inject(ServiceManager) serviceManager = inject(ServiceManager);
indexedDb = inject(IndexedDB) cache = inject(CacheService);
breakpoint = inject(TUI_BREAKPOINT) indexedDb = inject(IndexedDB);
router = inject(Router) breakpoint = inject(TUI_BREAKPOINT);
router = inject(Router);
expandedSidenav = signal(false) expandedSidenav = signal(false)
@@ -86,24 +88,6 @@ export class Chat implements OnInit {
this.navigationActiveIndex = 2 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(() => { setTimeout(() => {
const latestRead = localStorage.getItem("changeLogLastRead") const latestRead = localStorage.getItem("changeLogLastRead")
if (latestRead != environment.version) { if (latestRead != environment.version) {
@@ -115,4 +99,5 @@ export class Chat implements OnInit {
protected readonly LoadStatus = LoadStatus; protected readonly LoadStatus = LoadStatus;
protected readonly localStorage = localStorage; protected readonly localStorage = localStorage;
protected readonly environment = environment; protected readonly environment = environment;
protected readonly LoadState = LoadState;
} }

View 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>
}

View File

@@ -1,17 +1,17 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DmList } from './dm-list'; import { ContactList } from './contact-list';
describe('PictureList', () => { describe('PictureList', () => {
let component: DmList; let component: ContactList;
let fixture: ComponentFixture<DmList>; let fixture: ComponentFixture<ContactList>;
beforeEach(async () => { beforeEach(async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [DmList], imports: [ContactList],
}).compileComponents(); }).compileComponents();
fixture = TestBed.createComponent(DmList); fixture = TestBed.createComponent(ContactList);
component = fixture.componentInstance; component = fixture.componentInstance;
await fixture.whenStable(); await fixture.whenStable();
}); });

View 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;
}

View File

@@ -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>
}

View File

@@ -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;
}

View File

@@ -2,27 +2,29 @@
@defer (when store) { @defer (when store) {
<navbar backButtonDest="/chat"> <navbar backButtonDest="/chat">
<div class="data"> <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"> <div class="chat-data">
@if (store.chatData().displayName == "") { @if (this.store.chatData().displayName == "") {
<span class="main-name">{{'@'+store.chatData().username}}</span> <span class="main-name">{{ '@' + this.store.chatData().username }}</span>
} @else { } @else {
<span class="main-name">{{store.chatData().displayName}}</span> <span class="main-name">{{ this.store.chatData().displayName }}</span>
<span class="alt-name">{{'@'+store.chatData().username}}</span> <span class="alt-name">{{ '@' + this.store.chatData().username }}</span>
} }
</div> </div>
</div> </div>
<div class="items-right"> <div class="items-right">
<button tuiButton appearance="flat" disabled> <button tuiButton appearance="flat" disabled>
<tui-icon icon="@tui.phone"/> <tui-icon icon="@tui.phone" />
</button> </button>
</div> </div>
</navbar> </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> </main>

View File

@@ -1,77 +1,88 @@
import {Component, inject, OnInit, signal} from '@angular/core'; import { Component, inject, OnInit, signal } from '@angular/core';
import {DmStorage, LoadStatus, ServiceManager} from '../../service-manager'; import { LoadStatus, ServiceManager } from '../../service-manager';
import {ActivatedRoute} from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import {DMService} from '@chatenium/chatenium-sdk/services/dmService'; import { IndexedDB } from '../../storage/indexed-db';
import {IndexedDB} from '../../storage/indexed-db'; import { Navbar } from '../elements/navbar/navbar';
import {Navbar} from '../elements/navbar/navbar'; import { TUI_BREAKPOINT, TuiButton, TuiIcon, TuiNotificationService } from '@taiga-ui/core';
import {Oimg} from '../elements/oimg/oimg'; import { FileDataWithPreview, MessageBox } from '../elements/message-box/message-box';
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core'; import { CHATENIUM_SDK } from '../../chatenium.token';
import {FileDataWithPreview, MessageBox} from '../elements/message-box/message-box'; import {
import {Messages} from '../elements/messages/messages'; Contact,
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema'; createDMWrapper,
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema'; DirectMessagingApi,
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel'; Message,
import {FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema'; WrappedDMHandler,
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema'; } from 'chatenium-sdk-preview';
import {MessagesViewModel} from '../elements/messages/messages-viewmodel'; import { CacheService, DmStorage, LoadState } from '../../cache';
import {v4 as uuidv4} from 'uuid'; 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({ @Component({
selector: 'app-dm', selector: 'app-dm',
imports: [ imports: [Navbar, TuiButton, TuiIcon, MessageBox, Avatar, Messages],
Navbar,
Oimg,
TuiButton,
TuiIcon,
MessageBox,
Messages
],
templateUrl: './dm.html', templateUrl: './dm.html',
styleUrl: './dm.scss', styleUrl: './dm.scss',
}) })
export class Dm implements OnInit { export class Dm implements OnInit {
serviceManager = inject(ServiceManager) SDK = inject(CHATENIUM_SDK);
route = inject(ActivatedRoute) cache = inject(CacheService);
indexedDb = inject(IndexedDB) serviceManager = inject(ServiceManager);
breakpoint = inject(TUI_BREAKPOINT) route = inject(ActivatedRoute);
notification = inject(TuiNotificationService);
indexedDb = inject(IndexedDB);
breakpoint = inject(TUI_BREAKPOINT);
chatid = "" contactId = '';
get store(): DmStorage { get store(): DmStorage {
return this.serviceManager.dmServices()[this.chatid] return this.cache.dms()[this.contactId];
} }
async sendMessage(message: string, files: FileDataWithPreview[] | null) { async sendMessage(message: string, files: FileDataWithPreview[] | null) {
if (!files && message.trim() == "") return 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(); const session = this.serviceManager.currentSession();
if (session != null) { if (session != null) {
const editedMessage = this.store.messageBox.editingMessage() const editedMessage = this.store.messageBox.editingMessage();
if (editedMessage) { if (editedMessage) {
const storedMsg = this.store.messages().find(m => m.msgid == editedMessage.messageId) const storedMsg = this.store.messages().find((m) => m.msgid == editedMessage.messageId);
const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg)) const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg));
if (storedMsg) { if (storedMsg) {
storedMsg.message = message storedMsg.message = message;
} }
try { try {
await this.store.service.editMessage(editedMessage.messageId, message) await this.store.service.editMessage(editedMessage.messageId, message);
} catch (e) { } catch (e) {
if (storedMsg) { if (storedMsg) {
storedMsg.message = originalMessage.message storedMsg.message = originalMessage.message;
} }
} }
return return;
} }
let attachments: Attachment[] = [] let attachments: Attachment[] = [];
files?.forEach(file => { files?.forEach((file) => {
const extraMetaData: Record<string, any> = {} const extraMetaData: Record<string, any> = {};
extraMetaData["thumbnailMetaData"] = file.videoThumbnail ?? "" extraMetaData['thumbnailMetaData'] = file.videoThumbnail ?? '';
extraMetaData["progressShown"] = true extraMetaData['progressShown'] = true;
extraMetaData["totalChunks"] = 0 extraMetaData['totalChunks'] = 0;
extraMetaData["uploadedChunks"] = 0 extraMetaData['uploadedChunks'] = 0;
attachments.push({ attachments.push({
fileName: file.name, fileName: file.name,
@@ -81,171 +92,200 @@ export class Dm implements OnInit {
path: file.blob, path: file.blob,
height: file.height, height: file.height,
width: file.width, width: file.width,
extraMetaData: extraMetaData extraMetaData: extraMetaData,
}) });
}) });
const tempMsgId = uuidv4() const tempMsgId = uuidv4();
this.store.messages.update(value => [...value, { this.store.messages.update((value) => [
...value,
{
message: message, message: message,
chatid: this.chatid, chatid: this.chatid,
files: attachments, files: attachments,
replyTo: "", replyTo: '',
author: session.userData.userid, author: session.userData.userid,
seen: false, seen: false,
msgid: tempMsgId, msgid: tempMsgId,
forwardedFrom: "", forwardedFrom: '',
isEdited: false, isEdited: false,
sent_at: {T: 0, I: 0}, sent_at: { T: 0, I: 0 },
replyToId: "", replyToId: '',
forwardedFromName: "" forwardedFromName: '',
}]) },
]);
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) => { fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone) this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone);
} },
}) },
this.updateTempMessage(tempMsgId, respMessage) );
this.scrollToBottom("smooth") this.updateTempMessage(tempMsgId, respMessage);
} this.scrollToBottom('smooth');
}*/
} }
async deleteMessage(messageId: string) { 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) { if (i != -1) {
const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i])) const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]));
this.store.messages().splice(i, 1) this.store.messages().splice(i, 1);
try { try {
await this.store.service.deleteMessages([messageId]) await this.store.service.deleteMessages([messageId]);
} catch (e) { } 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 { restoreScrollState(): void {
setTimeout(() => { setTimeout(() => {
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer") const scrollContainer = <HTMLDivElement>document.querySelector('#scrollContainer');
scrollContainer.scroll({ scrollContainer.scroll({
top: this.store.messagesVm.scrollBarStatus() == -1 ? scrollContainer.scrollHeight : this.store.messagesVm.scrollBarStatus(), top:
this.store.messagesVm.scrollBarStatus() == -1
? scrollContainer.scrollHeight
: this.store.messagesVm.scrollBarStatus(),
left: 0, left: 0,
behavior: "instant" behavior: 'instant',
}); });
if (this.store.messagesVm.scrollBarStatus() == -1) { if (this.store.messagesVm.scrollBarStatus() == -1) {
this.store.messagesVm.scrollBarStatus.set(scrollContainer.scrollHeight) this.store.messagesVm.scrollBarStatus.set(scrollContainer.scrollHeight);
} }
}, 0) }, 0);
} }
scrollToBottom(anim: 'instant' | 'smooth'): void { scrollToBottom(anim: 'instant' | 'smooth'): void {
setTimeout(() => { setTimeout(() => {
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer") const scrollContainer = <HTMLDivElement>document.querySelector('#scrollContainer');
scrollContainer.scroll({ scrollContainer.scroll({
top: scrollContainer.scrollHeight, top: scrollContainer.scrollHeight,
left: 0, left: 0,
behavior: anim behavior: anim,
}); });
}, 0) }, 0);
} }
handleMessagesScroll(e: any) { 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) { uploadProgressUpdate(tempMsgId: string, fileId: string, allChunks: number, chunksDone: number) {
console.log(tempMsgId, fileId, allChunks, chunksDone) /*
this.store.messages.update(messages => console.log(tempMsgId, fileId, allChunks, chunksDone);
messages.map(m => { this.store.messages.update((messages) =>
messages.map((m) => {
if (m.msgid !== tempMsgId) return m; if (m.msgid !== tempMsgId) return m;
return { return {
...m, ...m,
files: m.files.map(f => { files: m.files.map((f) => {
if (f.fileId !== fileId) return f; if (f.fileId !== fileId) return f;
return { return {
...f, ...f,
extraMetaData: { extraMetaData: {
...f.extraMetaData, ...f.extraMetaData,
totalChunks: allChunks, totalChunks: allChunks,
uploadedChunks: chunksDone uploadedChunks: chunksDone,
} },
}; };
}) }),
}; };
}) }),
); );*/
} }
updateTempMessage(tempMsgId: string, message: Message) { 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; if (m.msgid !== tempMsgId) return m;
return { return {
...m, ...m,
msgid: message.msgid, msgid: message.msgid,
sent_at: message.sent_at, sent_at: message.sent_at,
files: m.files.map(f => { files: m.files.map((f) => {
f.extraMetaData["progressShown"] = false f.extraMetaData['progressShown'] = false;
return f return f;
}) }),
}; };
}) }),
); );*/
} }
// The chatid parameter ensures isolation // The chatid parameter ensures isolation
onWsListen(action: string, message: string, chatid: string) { onWsListen(action: string, message: string, chatid: string) {
/*
const data = JSON.parse(message); const data = JSON.parse(message);
if (data.chatid === chatid) { if (data.chatid === chatid) {
const targetStore = this.serviceManager.dmServices()[chatid]; const targetStore = this.serviceManager.dmServices()[chatid];
if (targetStore) { if (targetStore) {
switch (action) { switch (action) {
case "newMessage": case 'newMessage':
targetStore.messages.update(messages => [...messages, data]); targetStore.messages.update((messages) => [...messages, data]);
this.scrollToBottom("smooth") this.scrollToBottom('smooth');
break; break;
} }
} }
} }*/
} }
ngOnInit() { ngOnInit() {
this.route.params.subscribe(async params => { this.route.params.subscribe(async (params) => {
const chatid = params['chatid']; const contactId = params['contactId'];
this.chatid = chatid; this.contactId = contactId;
console.log(`Loading chat ${chatid}...`) console.log(`Loading DM chat ${contactId}...`);
const session = this.serviceManager.currentSession(); const chatData = this.cache.contacts().find((c) => c.contactId === contactId);
const chatData = this.serviceManager.chats().find(c => c.chatid === chatid);
if (!session || !chatData) { if (!chatData) {
return console.warn(
`Unable to find chat data with the provided contactId: ${contactId}, skipping load.`,
);
return;
} }
if (!this.serviceManager.dmServices()[chatid]) { if (!this.cache.dms()[contactId]) {
const newStore = { console.log(`No store yet, creating service store for DM: ${contactId}`);
chatData: signal<Chat>(chatData), this.cache.dms()[contactId] = {
handler: createDMWrapper(this.SDK.directMessaging, chatData.contactId),
chatData: signal<Contact>(chatData),
messages: signal<Message[]>([]), messages: signal<Message[]>([]),
messagesStatus: signal<LoadStatus>(LoadStatus.loading), messagesState: signal<LoadState>(LoadState.CLEAN_LOADING),
messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)), messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)),
messagesVm: new MessagesViewModel(), messagesVm: new MessagesViewModel(),
wsListener: (action, data) => this.onWsListen(action, data, chatid), wsListener: (action, data) => this.onWsListen(action, data, contactId),
} as DmStorage; } as DmStorage;
newStore.service = new DMService( await this.loadMessages();
session.userData.userid, /*
session.token, const currentStore = this.serviceManager.dmServices()[contactId];
chatid,
this.indexedDb.getApi(),
(action, data) => newStore.wsListener(action, data)
);
this.serviceManager.dmServices()[chatid] = newStore;
const currentStore = this.serviceManager.dmServices()[chatid];
try { try {
const messagesCache = await currentStore.service.getQuick(); const messagesCache = await currentStore.service.getQuick();
currentStore.messages.set(messagesCache); currentStore.messages.set(messagesCache);
@@ -262,9 +302,12 @@ export class Dm implements OnInit {
await currentStore.service.joinWebSocketRoom(); await currentStore.service.joinWebSocketRoom();
} else { } else {
this.restoreScrollState() this.restoreScrollState()
}*/
} }
console.log(`Finished initializing chat: ${contactId}`);
}); });
} }
protected readonly LoadStatus = LoadStatus; protected readonly LoadStatus = LoadStatus;
protected readonly LoadState = LoadState;
} }

View 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>

View File

@@ -0,0 +1,6 @@
.avatar {
display: flex;
align-items: center;
justify-content: center;
color: white;
}

View 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();
});
});

View 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];
}
}

View File

@@ -12,5 +12,5 @@ export class MessageBoxViewModel {
message = signal<string>("") message = signal<string>("")
files = signal<FileDataWithPreview[]>([]) files = signal<FileDataWithPreview[]>([])
dialogOpen = signal<boolean>(false) dialogOpen = signal<boolean>(false)
editingMessage = signal<{messageId: string, message: string} | null >(null) editingMessage = signal<{messageId: string, content: string|undefined} | null >(null)
} }

View File

@@ -55,11 +55,11 @@
@if (viewModel().editingMessage()) { @if (viewModel().editingMessage()) {
<tui-icon icon="@tui.pencil"></tui-icon> <tui-icon icon="@tui.pencil"></tui-icon>
<span>{{"chat.elements.messageBox.editMessageLabel"|translate}}</span> <span>{{"chat.elements.messageBox.editMessageLabel"|translate}}</span>
@if (viewModel().editingMessage()!.message == "") { @if (viewModel().editingMessage()!.content == "") {
<tui-icon icon="@tui.paperclip"></tui-icon> <tui-icon icon="@tui.paperclip"></tui-icon>
<span>{{"chat.elements.messageBox.attachments"|translate}}</span> <span>{{"chat.elements.messageBox.attachments"|translate}}</span>
} @else { } @else {
<span style="width: 300px" tuiScrollable tuiFade>{{viewModel().editingMessage()!.message}}</span> <span style="width: 300px" tuiScrollable tuiFade>{{viewModel().editingMessage()!.content}}</span>
} }
} }
</div> </div>

View File

@@ -13,24 +13,24 @@
} }
} @else { } @else {
@if (serviceManager.currentSession != null) { @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 <div
class="message" class="message"
[class.author]=" [class.author]="
messageAsDm(message).author == serviceManager.currentSession()!.userData.userid || messageAsDm(message).author.userId == sessionManager.userData()?.userId ||
messageAsNetwork(message).author.userid == serviceManager.currentSession()!.userData.userid messageAsNetwork(message).author.userId == sessionManager.userData()?.userId
" "
[class.chained_start]="isMessageStartOfChain(i)" [class.chained_start]="isMessageStartOfChain(i)"
[class.chained_middle]="isMessageMiddleInChain(i)" [class.chained_middle]="isMessageMiddleInChain(i)"
[class.chained_end]="isMessageEndOfChain(i)" [class.chained_end]="isMessageEndOfChain(i)"
> >
<div class="above"> <div class="above">
<span>{{ message.sent_at.T * 1000 | date: 'HH:mm' }}</span> <span>{{ message.sentAt | date: 'HH:mm' }}</span>
</div> </div>
<div class="bubble" tuiDropdownContext [tuiDropdown]="messageContextMenu"> <div class="bubble" tuiDropdownContext [tuiDropdown]="messageContextMenu">
<span class="message-text">{{ message.message }}</span> <span class="message-text">{{ message.content }}</span>
<masonry style="max-height: 300px"> <!-- <masonry style="max-height: 300px">
@for (file of filterExpressedMedia(message.files); track file) { @for (file of filterExpressedMedia(message.attachments); track file) {
<div style="position:relative;"> <div style="position:relative;">
@if (file.extraMetaData && Object.keys(file.extraMetaData).length > 0) { @if (file.extraMetaData && Object.keys(file.extraMetaData).length > 0) {
@if (file.extraMetaData['progressShown']) { @if (file.extraMetaData['progressShown']) {
@@ -75,7 +75,7 @@
<span>{{ file.fileName }}</span> <span>{{ file.fileName }}</span>
</div> </div>
} }
</div> </div>-->
</div> </div>
<div class="below"></div> <div class="below"></div>
@@ -85,7 +85,7 @@
tuiOption tuiOption
type="button" type="button"
iconEnd="@tui.pencil" 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 }} {{ "chat.elements.messages.contextMenu.edit" | translate }}
</button> </button>
@@ -95,7 +95,7 @@
tuiOption tuiOption
type="button" type="button"
iconEnd="@tui.trash" iconEnd="@tui.trash"
(click)="onDelete.emit(message.msgid)" (click)="onDelete.emit(message.messageId)"
> >
{{ "chat.elements.messages.contextMenu.delete" | translate }} {{ "chat.elements.messages.contextMenu.delete" | translate }}
</button> </button>

View File

@@ -1,10 +1,9 @@
import {Component, EventEmitter, inject, input, Output} from '@angular/core'; import { Component, EventEmitter, inject, input, Output } from '@angular/core';
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema'; import { Message, ThreadMessage, Attachment, ThreadMessageAttachment } from 'chatenium-sdk-preview';
import {Message as NetworkMessage} from '@chatenium/chatenium-sdk/domain/textChannelService.schema' import { ServiceManager } from '../../../service-manager';
import {ServiceManager} from '../../../service-manager'; import { DatePipe } from '@angular/common';
import {DatePipe} from '@angular/common'; import { Masonry } from '../masonry/masonry';
import {Masonry} from '../masonry/masonry'; import { VideoPlayer } from '../video-player/video-player';
import {VideoPlayer} from '../video-player/video-player';
import { import {
TuiButton, TuiButton,
TuiDataListComponent, TuiDataListComponent,
@@ -12,13 +11,12 @@ import {
TuiDropdownContext, TuiDropdownContext,
TuiGroup, TuiGroup,
TuiIcon, TuiIcon,
TuiOption TuiOption,
} from '@taiga-ui/core'; } from '@taiga-ui/core';
import {TranslatePipe} from '@ngx-translate/core'; import { TranslatePipe } from '@ngx-translate/core';
import {MessageBoxViewModel} from '../message-box/message-box-viewmodel'; import { MessageBoxViewModel } from '../message-box/message-box-viewmodel';
import {FileDataWithPreview} from '../message-box/message-box'; import { TuiProgressCircle, TuiSkeleton } from '@taiga-ui/kit';
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema'; import { SessionManager } from '../../../session-manager';
import {TuiProgressCircle, TuiSkeleton} from '@taiga-ui/kit';
@Component({ @Component({
selector: 'messages', selector: 'messages',
@@ -35,27 +33,28 @@ import {TuiProgressCircle, TuiSkeleton} from '@taiga-ui/kit';
TuiGroup, TuiGroup,
TuiIcon, TuiIcon,
TuiProgressCircle, TuiProgressCircle,
TuiSkeleton TuiSkeleton,
], ],
templateUrl: './messages.html', templateUrl: './messages.html',
styleUrl: './messages.scss', styleUrl: './messages.scss',
}) })
export class Messages { export class Messages {
serviceManager = inject(ServiceManager) serviceManager = inject(ServiceManager);
sessionManager = inject(SessionManager);
messages = input.required<Message[] | NetworkMessage[]>() messages = input.required<Message[] | ThreadMessage[]>();
messageBoxViewModel = input.required<MessageBoxViewModel>() messageBoxViewModel = input.required<MessageBoxViewModel>();
loading = input(false) 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. * 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 * Example: messageAsDm(message).author == userid -- We are specifying that we are handling dm messages
* @param message * @param message
*/ */
messageAsDm(message: Message | NetworkMessage) { messageAsDm(message: Message | ThreadMessage) {
return message == undefined ? <Message>{author: "no"} : message as Message 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 Example: messageAsNetwork(message).author.userid == userid -- We are specifying that we are handling network messages
* @param message * @param message
*/ */
messageAsNetwork(message: Message | NetworkMessage) { messageAsNetwork(message: Message | ThreadMessage) {
return message == undefined ? <NetworkMessage>{author: {userid: "no"}} : message as NetworkMessage return message as ThreadMessage;
} }
isMessageStartOfChain(i: number) { isMessageStartOfChain(i: number) {
@@ -76,16 +75,17 @@ export class Messages {
// is author == last msg's author // is author == last msg's author
if (prev) { if (prev) {
if ( if (
(typeof message.author === 'string' && this.messageAsDm(prev).author !== this.messageAsDm(message).author) && typeof message.author === 'string' &&
this.messageAsNetwork(prev).author.userid !== this.messageAsNetwork(message).author.userid this.messageAsDm(prev).author.userId !== this.messageAsDm(message).author.userId &&
this.messageAsNetwork(prev).author.userId !== this.messageAsNetwork(message).author.userId
) { ) {
return true; return true;
} }
// same author but time gap between this and prev msg // same author but time gap between this and prev msg
if ( const currMsgDate = new Date(message.sentAt);
Math.abs(message.sent_at.T - prev.sent_at.T) >= 60 const prevMsgDate = new Date(prev.sentAt);
) { if (Math.abs(currMsgDate.getDate() - prevMsgDate.getDate()) >= 60_000) {
return true; return true;
} }
} }
@@ -100,12 +100,14 @@ export class Messages {
const prev = this.messages()[i - 1]; const prev = this.messages()[i - 1];
// message must be from the same author and have little time gap between // 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 ( return (
( ((typeof message.author === 'string' &&
(typeof message.author === 'string' && this.messageAsDm(prev).author == this.messageAsDm(message).author) || this.messageAsDm(prev).author == this.messageAsDm(message).author) ||
this.messageAsNetwork(prev).author.userid == this.messageAsNetwork(message).author.userid this.messageAsNetwork(prev).author.userId ==
) && this.messageAsNetwork(message).author.userId) &&
Math.abs(message.sent_at.T - prev.sent_at.T) <= 60 Math.abs(currMsgDate.getDate() - prevMsgDate.getDate()) <= 60_000
); );
} }
@@ -118,19 +120,20 @@ export class Messages {
const next = this.messages()[i + 1]; const next = this.messages()[i + 1];
const currMsgDate = new Date(message.sentAt);
const nextMsgDate = new Date(next.sentAt);
// First condition: next author is different // First condition: next author is different
if (next) { if (next) {
if ( if (
(typeof message.author === 'string' && this.messageAsDm(next).author != this.messageAsDm(message).author) || (typeof message.author === 'string' &&
this.messageAsNetwork(next).author.userid != this.messageAsNetwork(message).author.userid this.messageAsDm(next).author != this.messageAsDm(message).author) ||
this.messageAsNetwork(next).author.userId != this.messageAsNetwork(message).author.userId
) { ) {
return true; return true;
} }
// same author but time gap between this and next msg // same author but time gap between this and next msg
if ( if (Math.abs(currMsgDate.getDate() - nextMsgDate.getDate()) >= 60) {
Math.abs(message.sent_at.T - next.sent_at.T) >= 60
) {
return true; return true;
} }
} }
@@ -139,12 +142,16 @@ export class Messages {
return i + 1 === this.messages().length; return i + 1 === this.messages().length;
} }
filterExpressedMedia(files: Attachment[]) { filterExpressedMedia(files: Attachment[] | ThreadMessageAttachment[] | undefined) {
return files.filter(f => f.type == "image" || f.type == "video") return files
? files.filter((f) => f.mimeType.startsWith('image') || f.mimeType.startsWith('video'))
: [];
} }
filterNonExpressedMedia(files: Attachment[]) { filterNonExpressedMedia(files: Attachment[] | ThreadMessageAttachment[] | undefined) {
return files.filter(f => f.type != "image" && f.type != "video") return files
? files.filter((f) => f.mimeType.startsWith('image') || f.mimeType.startsWith('video'))
: [];
} }
protected readonly Object = Object; protected readonly Object = Object;

View File

@@ -1,5 +1,5 @@
import {Component, inject, signal} from '@angular/core'; 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 {ActivatedRoute} from '@angular/router';
import {IndexedDB} from '../../../../storage/indexed-db'; import {IndexedDB} from '../../../../storage/indexed-db';
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core'; import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';

View File

@@ -3,7 +3,7 @@ import {ActivatedRoute, Router, RouterLink, RouterOutlet} from '@angular/router'
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema'; import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema'; import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel'; 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 {DMService} from '@chatenium/chatenium-sdk/services/dmService';
import {Network as NetworkData} from "@chatenium/chatenium-sdk/domain/networkService.schema" import {Network as NetworkData} from "@chatenium/chatenium-sdk/domain/networkService.schema"
import {NetworkService} from '@chatenium/chatenium-sdk/services/networkService'; import {NetworkService} from '@chatenium/chatenium-sdk/services/networkService';

View File

@@ -1,5 +1,5 @@
import {Component, inject, signal} from '@angular/core'; 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 {ActivatedRoute, Router} from '@angular/router';
import {IndexedDB} from '../../../storage/indexed-db'; import {IndexedDB} from '../../../storage/indexed-db';
import {TUI_BREAKPOINT, TuiButton, TuiDialog, TuiIcon} from '@taiga-ui/core'; import {TUI_BREAKPOINT, TuiButton, TuiDialog, TuiIcon} from '@taiga-ui/core';

View File

@@ -42,7 +42,7 @@ export class ServiceManager {
// Services for individual networks // Services for individual networks
networkServices = signal<Record<string, NetworkStorage>>({}) networkServices = signal<Record<string, NetworkStorage>>({})
dmServices = signal<Record<string, DmStorage>>({}) //dmServices = signal<Record<string, DmStorage>>({})
pictureServices = signal<Record<string, PictureStorage>>({}) pictureServices = signal<Record<string, PictureStorage>>({})
} }
@@ -53,16 +53,6 @@ export enum LoadStatus {
updating = 3, 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 { export interface PictureStorage {
service: PictureService service: PictureService
albums: WritableSignal<Album[]> albums: WritableSignal<Album[]>

View File

@@ -15,6 +15,7 @@ export class SessionManager {
private notification = inject(TuiNotificationService); private notification = inject(TuiNotificationService);
public userData = signal<PersonalUserData|undefined>(undefined); public userData = signal<PersonalUserData|undefined>(undefined);
public sessionReady = signal(false); // Helps with timing session loading
async addSession(refreshToken: string, accessToken: string, userId: string) { async addSession(refreshToken: string, accessToken: string, userId: string) {
const date = new Date(); const date = new Date();
@@ -90,6 +91,7 @@ export class SessionManager {
console.log( console.log(
`Successfully rotated token pair for ID: ${userData.userId} Username: ${userData.username}. This session is now ready to be used.`, `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) { } catch (e) {
console.error(e); console.error(e);
} }