6 Commits

Author SHA1 Message Date
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
11 changed files with 174 additions and 160 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.6", "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.6", "version": "2.0.0-preview.7",
"resolved": "https://registry.npmjs.org/@chatenium/chatenium-sdk/-/chatenium-sdk-2.0.0-preview.6.tgz", "resolved": "https://registry.npmjs.org/@chatenium/chatenium-sdk/-/chatenium-sdk-2.0.0-preview.7.tgz",
"integrity": "sha512-Coj2Hcf9AKdYloNT9y5qLL+B5CwbJq4nZhE4WnEeh8VG9AHiSuoyPK+YeTpLhS+JDUht54bQUFMXu313s824Yg==", "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.6", "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 },
], ],

View File

@@ -1,13 +1,13 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { Cache } from './cache'; import { CacheService } from './cache';
describe('Cache', () => { describe('Cache', () => {
let service: Cache; let service: CacheService;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({}); TestBed.configureTestingModule({});
service = TestBed.inject(Cache); service = TestBed.inject(CacheService);
}); });
it('should be created', () => { it('should be created', () => {

View File

@@ -4,7 +4,7 @@ import { Contact } from 'chatenium-sdk-preview';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class Cache { export class CacheService {
contacts = signal<Contact[]>([]) contacts = signal<Contact[]>([])
contactsState = signal<LoadState>(LoadState.CLEAN_LOADING) contactsState = signal<LoadState>(LoadState.CLEAN_LOADING)
} }

View File

@@ -66,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")) {

View File

@@ -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',
@@ -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

@@ -6,9 +6,9 @@ import {Oimg} from '../elements/oimg/oimg';
import {Router, RouterLink} from '@angular/router'; import {Router, RouterLink} from '@angular/router';
import {TranslatePipe} from '@ngx-translate/core'; import {TranslatePipe} from '@ngx-translate/core';
import {LoadStatus, ServiceManager} from '../../service-manager'; import {LoadStatus, ServiceManager} from '../../service-manager';
import { Contact, createContactWrapper } from 'chatenium-sdk-preview'; import { Contact } from 'chatenium-sdk-preview';
import { CHATENIUM_SDK } from '../../chatenium.token'; import { CHATENIUM_SDK } from '../../chatenium.token';
import { Cache, LoadState } from '../../cache'; import { CacheService, LoadState } from '../../cache';
import { Avatar } from '../elements/avatar/avatar'; import { Avatar } from '../elements/avatar/avatar';
@Component({ @Component({
@@ -21,7 +21,7 @@ export class ContactList implements OnInit {
SDK = inject(CHATENIUM_SDK); SDK = inject(CHATENIUM_SDK);
idb = inject(IndexedDB); idb = inject(IndexedDB);
router = inject(Router); router = inject(Router);
cache = inject(Cache); cache = inject(CacheService);
notification = inject(TuiNotificationService); notification = inject(TuiNotificationService);
serviceManager = inject(ServiceManager); serviceManager = inject(ServiceManager);
breakpoint = inject(TUI_BREAKPOINT); breakpoint = inject(TUI_BREAKPOINT);
@@ -30,8 +30,12 @@ export class ContactList implements OnInit {
if (this.cache.contactsState() != LoadState.LOADED) { if (this.cache.contactsState() != LoadState.LOADED) {
try { try {
const contacts = (await this.idb.getAll('contacts')) as Contact[]; const contacts = (await this.idb.getAll('contacts')) as Contact[];
this.cache.contacts.set(contacts); if (contacts.length > 0) {
this.cache.contactsState.set(LoadState.CACHE_UPDATING); this.cache.contacts.set(contacts);
this.cache.contactsState.set(LoadState.CACHE_UPDATING);
} else {
console.log("Found no contacts in cache")
}
} catch (e) { } catch (e) {
console.warn(`Contacts cache load failed: ${e}. Skipping cache load...`); console.warn(`Contacts cache load failed: ${e}. Skipping cache load...`);
} }
@@ -44,8 +48,8 @@ export class ContactList implements OnInit {
return return
} }
this.cache.contacts.set(data); this.cache.contacts.set(data);
this.cache.contactsState.set(LoadState.LOADED);
console.log(`Successfully fetched ${data.length} contacts`); console.log(`Successfully fetched ${data.length} contacts`);
this.cache.contactsState.set(LoadState.LOADED);
} catch (e) { } catch (e) {
console.error(e); console.error(e);
this.serviceManager.chatsStatus.set(LoadStatus.error); this.serviceManager.chatsStatus.set(LoadStatus.error);

View File

@@ -1,28 +1,32 @@
<main [class.mobile]="breakpoint() == 'mobile'"> <main [class.mobile]="breakpoint() == 'mobile'">
@defer (when store) { @defer (when handler) {
<navbar backButtonDest="/chat"> @if (chatData != null) {
<div class="data"> <navbar backButtonDest="/chat">
<oimg [src]="store.chatData().pfp" height="50px" width="50px" [radius]="15"></oimg> <div class="data">
<div class="chat-data"> <avatar [src]="chatData.pfp" height="50px" width="50px" [radius]="15" [name]="chatData.username"></avatar>
@if (store.chatData().displayName == "") { <div class="chat-data">
<span class="main-name">{{'@'+store.chatData().username}}</span> @if (chatData.displayName == "") {
} @else { <span class="main-name">{{ '@' + chatData.username }}</span>
<span class="main-name">{{store.chatData().displayName}}</span> } @else {
<span class="alt-name">{{'@'+store.chatData().username}}</span> <span class="main-name">{{ chatData.displayName }}</span>
} <span class="alt-name">{{ '@' + 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.messagesStatus() == LoadStatus.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

@@ -15,63 +15,66 @@ import {FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUp
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema'; import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';
import {MessagesViewModel} from '../elements/messages/messages-viewmodel'; import {MessagesViewModel} from '../elements/messages/messages-viewmodel';
import {v4 as uuidv4} from 'uuid'; import {v4 as uuidv4} from 'uuid';
import { CHATENIUM_SDK } from '../../chatenium.token';
import { Contact, createDMWrapper, DirectMessagingApi, WrappedDMHandler } from 'chatenium-sdk-preview';
import { CacheService } from '../../cache';
import { Avatar } from '../elements/avatar/avatar';
import { JsonPipe } from '@angular/common';
@Component({ @Component({
selector: 'app-dm', selector: 'app-dm',
imports: [ imports: [Navbar, Oimg, TuiButton, TuiIcon, MessageBox, Messages, Avatar, JsonPipe],
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);
indexedDb = inject(IndexedDB);
breakpoint = inject(TUI_BREAKPOINT);
chatid = "" handler: WrappedDMHandler<DirectMessagingApi> | null = null;
chatData: Contact | null = null;
chatid = '';
get store(): DmStorage { get store(): DmStorage {
return this.serviceManager.dmServices()[this.chatid] return this.serviceManager.dmServices()[this.chatid];
} }
async sendMessage(message: string, files: FileDataWithPreview[] | null) { async sendMessage(message: string, files: FileDataWithPreview[] | null) {
if (!files && message.trim() == "") return 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,118 +84,131 @@ 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) => [
message: message, ...value,
chatid: this.chatid, {
files: attachments, message: message,
replyTo: "", chatid: this.chatid,
author: session.userData.userid, files: attachments,
seen: false, replyTo: '',
msgid: tempMsgId, author: session.userData.userid,
forwardedFrom: "", seen: false,
isEdited: false, msgid: tempMsgId,
sent_at: {T: 0, I: 0}, forwardedFrom: '',
replyToId: "", isEdited: false,
forwardedFromName: "" sent_at: { T: 0, I: 0 },
}]) replyToId: '',
forwardedFromName: '',
},
]);
const respMessage = await this.store.service.sendMessage(tempMsgId, message, null, null, files, <FileUploadProgressListener>{ const respMessage = await this.store.service.sendMessage(
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => { tempMsgId,
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone) message,
} null,
}) null,
this.updateTempMessage(tempMsgId, respMessage) files,
this.scrollToBottom("smooth") <FileUploadProgressListener>{
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone);
},
},
);
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);
} }
} }
} }
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) console.log(tempMsgId, fileId, allChunks, chunksDone);
this.store.messages.update(messages => this.store.messages.update((messages) =>
messages.map(m => { 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 => this.store.messages.update((messages) =>
messages.map(m => { 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;
}) }),
}; };
}) }),
); );
} }
@@ -203,9 +219,9 @@ export class Dm implements OnInit {
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;
} }
} }
@@ -213,39 +229,45 @@ export class Dm implements OnInit {
} }
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.chatid = 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]) { this.chatData = chatData;
this.handler = createDMWrapper(this.SDK.directMessaging, chatData.contactId);
console.log(`Finished initializing chat: ${contactId}`);
/*if (!this.serviceManager.dmServices()[contactId]) {
const newStore = { const newStore = {
chatData: signal<Chat>(chatData), chatData: signal<Chat>(chatData),
messages: signal<Message[]>([]), messages: signal<Message[]>([]),
messagesStatus: signal<LoadStatus>(LoadStatus.loading), messagesStatus: signal<LoadStatus>(LoadStatus.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( newStore.service = new DMService(
session.userData.userid, session.userData.userid,
session.token, session.token,
chatid, contactId,
this.indexedDb.getApi(), this.indexedDb.getApi(),
(action, data) => newStore.wsListener(action, data) (action, data) => newStore.wsListener(action, data)
); );
this.serviceManager.dmServices()[chatid] = newStore; this.serviceManager.dmServices()[contactId] = newStore;
const currentStore = this.serviceManager.dmServices()[chatid]; const currentStore = this.serviceManager.dmServices()[contactId];
try { try {
const messagesCache = await currentStore.service.getQuick(); const messagesCache = await currentStore.service.getQuick();
currentStore.messages.set(messagesCache); currentStore.messages.set(messagesCache);
@@ -262,7 +284,7 @@ export class Dm implements OnInit {
await currentStore.service.joinWebSocketRoom(); await currentStore.service.joinWebSocketRoom();
} else { } else {
this.restoreScrollState() this.restoreScrollState()
} }*/
}); });
} }

View File

@@ -91,7 +91,6 @@ 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.`,
); );
console.log(data.accessToken)
this.sessionReady.set(true); this.sessionReady.set(true);
} catch (e) { } catch (e) {
console.error(e); console.error(e);