Skip to content

Commit

Permalink
Update chat service
Browse files Browse the repository at this point in the history
  • Loading branch information
miladsoft committed Sep 25, 2024
1 parent 5383df1 commit a484675
Show file tree
Hide file tree
Showing 6 changed files with 151 additions and 154 deletions.
1 change: 1 addition & 0 deletions src/app/components/auth/logout/logout.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export class LogoutComponent implements OnInit, OnDestroy {
}

logout(): void {
this._signerService.clearPassword();
this._signerService.logout();
console.log("User logged out and keys removed from localStorage.");
}
Expand Down
49 changes: 24 additions & 25 deletions src/app/components/chat/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class ChatService implements OnDestroy {
private isDecrypting = false;
private recipientPublicKey: string;
private message: string;

private decryptedPrivateKey:string;
private _chat: BehaviorSubject<Chat | null> = new BehaviorSubject(null);
private _chats: BehaviorSubject<Chat[] | null> = new BehaviorSubject(null);
private _contact: BehaviorSubject<Contact | null> = new BehaviorSubject(null);
Expand Down Expand Up @@ -92,31 +92,34 @@ export class ChatService implements OnDestroy {
}
}


getContacts(): Observable<Contact[]> {
return new Observable<Contact[]>((observer) => {
this._indexedDBService.getAllUsers()
.then((cachedContacts: Contact[]) => {
if (cachedContacts.length > 0) {

cachedContacts.forEach(contact => {
if (cachedContacts && cachedContacts.length > 0) {
const validatedContacts = cachedContacts.map(contact => {
if (!contact.pubKey) {
console.error('Contact is missing pubKey:', contact);
}
contact.name = contact.name ? contact.name : 'Unknown';
return contact;
});

this._contacts.next(cachedContacts);
observer.next(cachedContacts);
this._contacts.next(validatedContacts);
observer.next(validatedContacts);
} else {
observer.next([]);
}
observer.complete();
})
.catch((error) => {
console.error('Error loading cached contacts from IndexedDB:', error);
observer.error(error);
observer.next([]);
observer.complete();
});

return () => {
console.log('Unsubscribing from contacts updates.');
};
return { unsubscribe() {} };
});
}

Expand Down Expand Up @@ -165,7 +168,7 @@ export class ChatService implements OnDestroy {
async getChats(): Promise<Observable<Chat[]>> {
const pubkey = this._signerService.getPublicKey();
const useExtension = await this._signerService.isUsingExtension();
const decryptedPrivateKey = await this._signerService.getSecretKey("123");
this.decryptedPrivateKey = await this._signerService.getDecryptedSecretKey();

const storedChats = await this._indexedDBService.getAllChats();
if (storedChats && storedChats.length > 0) {
Expand All @@ -187,7 +190,7 @@ export class ChatService implements OnDestroy {
console.error('Error updating chat contacts metadata:', error);
}
}, 0);
this.subscribeToChatList(pubkey, useExtension, decryptedPrivateKey);
this.subscribeToChatList(pubkey, useExtension, this.decryptedPrivateKey);
return this.getChatListStream();
}

Expand Down Expand Up @@ -346,7 +349,7 @@ export class ChatService implements OnDestroy {
recipientPublicKey: string
): Promise<string> {
if (useExtension) {
return await this._signerService.decryptDMWithExtension(recipientPublicKey, event.content);
return await this._signerService.decryptMessageWithExtension(recipientPublicKey, event.content);
} else {
return await this._signerService.decryptMessage(decryptedSenderPrivateKey, recipientPublicKey, event.content);
}
Expand All @@ -368,12 +371,12 @@ export class ChatService implements OnDestroy {
const decryptedMessage = await this.decryptReceivedMessage(
event,
await this._signerService.isUsingExtension(),
await this._signerService.getSecretKey("123"),
this.decryptedPrivateKey,
senderOrRecipientPubKey
);

if (decryptedMessage) {
const messageTimestamp = Math.floor(event.created_at / 1000);
const messageTimestamp = Math.floor(event.created_at );


this.addOrUpdateChatList(pubKey, decryptedMessage, messageTimestamp, isSentByMe);
Expand Down Expand Up @@ -430,11 +433,9 @@ export class ChatService implements OnDestroy {
this.recipientPublicKey = id;

const pubkeyPromise = this._signerService.getPublicKey();
const useExtensionPromise = this._signerService.isUsingExtension();
const decryptedSenderPrivateKeyPromise = this._signerService.getSecretKey('123');

return from(Promise.all([pubkeyPromise, useExtensionPromise, decryptedSenderPrivateKeyPromise])).pipe(
switchMap(([pubkey, useExtension, decryptedSenderPrivateKey]) => {
return from(Promise.all([pubkeyPromise])).pipe(
switchMap(() => {
return this.chats$.pipe(
take(1),
distinctUntilChanged(),
Expand Down Expand Up @@ -478,9 +479,7 @@ export class ChatService implements OnDestroy {

this.recipientPublicKey = contact.pubKey;

const pubkey = this._signerService.getPublicKey();
const useExtension = this._signerService.isUsingExtension();
const decryptedSenderPrivateKey = this._signerService.getSecretKey('123');


return this.chats$.pipe(
take(1),
Expand Down Expand Up @@ -536,22 +535,22 @@ export class ChatService implements OnDestroy {
if (useExtension) {
await this.handleMessageSendingWithExtension();
} else {
const decryptedSenderPrivateKey = await this._signerService.getSecretKey("123");


if (!this.isValidMessageSetup()) {
console.error('Message, sender private key, or recipient public key is not properly set.');
return;
}

const encryptedMessage = await this._signerService.encryptMessage(
decryptedSenderPrivateKey,
this.decryptedPrivateKey,
this.recipientPublicKey,
this.message
);

const messageEvent = this._signerService.getUnsignedEvent(4, [['p', this.recipientPublicKey]], encryptedMessage);

const signedEvent = this._signerService.getSignedEvent(messageEvent, decryptedSenderPrivateKey);
const signedEvent = this._signerService.getSignedEvent(messageEvent, this.decryptedPrivateKey);

const published = await this._relayService.publishEventToRelays(signedEvent);

Expand Down
12 changes: 4 additions & 8 deletions src/app/components/settings/profile/profile.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ import { RelayService } from 'app/services/relay.service';
import { SignerService } from 'app/services/signer.service';
import { UnsignedEvent, NostrEvent, finalizeEvent } from 'nostr-tools';
import { PasswordDialogComponent } from 'app/shared/password-dialog/password-dialog.component';
import { PasswordService } from 'app/services/password.service';


@Component({
selector: 'settings-profile',
templateUrl: './profile.component.html',
Expand Down Expand Up @@ -48,8 +47,7 @@ export class SettingsProfileComponent implements OnInit {
private relayService: RelayService,
private router: Router,
private dialog: MatDialog,
private password: PasswordService
) { }
) { }

ngOnInit(): void {
this.profileForm = this.fb.group({
Expand Down Expand Up @@ -99,16 +97,14 @@ export class SettingsProfileComponent implements OnInit {
this.content = JSON.stringify(profileData);

if (this.signerService.isUsingSecretKey()) {
const storedPassword = this.password.getPassword();
const storedPassword = this.signerService.getPassword();
if (storedPassword) {
try {
const privateKey = await this.signerService.getSecretKey(storedPassword);
this.signEvent(privateKey);
} catch (error) {
console.error(error);
}


} else {
const dialogRef = this.dialog.open(PasswordDialogComponent, {
width: '300px',
Expand All @@ -121,7 +117,7 @@ export class SettingsProfileComponent implements OnInit {
const privateKey = await this.signerService.getSecretKey(result.password);
this.signEvent(privateKey);
if (result.duration != 0) {
this.password.savePassword(result.password, result.duration);
this.signerService.savePassword(result.password, result.duration);
}
} catch (error) {
console.error(error);
Expand Down
8 changes: 3 additions & 5 deletions src/app/components/settings/security/security.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { PasswordService } from 'app/services/password.service';
import { SignerService } from 'app/services/signer.service';
import { SignerService } from 'app/services/signer.service';

@Component({
selector: 'settings-security',
Expand All @@ -43,8 +42,7 @@ export class SettingsSecurityComponent implements OnInit {
*/
constructor(
private _formBuilder: UntypedFormBuilder,
private _passwordService: PasswordService,
private _signerService: SignerService
private _signerService: SignerService
) {}

/**
Expand Down Expand Up @@ -80,7 +78,7 @@ export class SettingsSecurityComponent implements OnInit {
const savePassword = this.securityForm.get('savePassword')?.value;

try {
const success = await this._passwordService.changePassword(
const success = await this._signerService.changePassword(
currentPassword,
newPassword,
savePassword // Save password toggle value
Expand Down
67 changes: 0 additions & 67 deletions src/app/services/password.service.ts

This file was deleted.

Loading

0 comments on commit a484675

Please sign in to comment.