Add display of a limited set of public chats

This commit is contained in:
SondreB 2023-05-28 20:49:37 +02:00
parent 6ba07dd615
commit a29dc1100c
No known key found for this signature in database
GPG Key ID: D6CC44C75005FDBF
16 changed files with 323 additions and 15 deletions

View File

@ -87,14 +87,15 @@
<mat-icon [matBadgeHidden]="(ui.unreadNotifications$ | async) == 0" [matBadge]="ui.unreadNotifications$ | async">notifications</mat-icon>
<span *ngIf="displayLabels">{{ 'App.Notifications' | translate }}</span>
</a>
<!-- <a [routerLink]="['/chat']" mat-menu-item (click)="toggleMenu()" [routerLinkActiveOptions]="{ exact: true }" routerLinkActive="active">
<a [routerLink]="['/chat']" mat-menu-item (click)="toggleMenu()" [routerLinkActiveOptions]="{ exact: true }" routerLinkActive="active">
<mat-icon>chat</mat-icon>
<span *ngIf="displayLabels">Channels</span>
<span *ngIf="displayLabels">Chats</span>
</a>
<a [routerLink]="['/m']" mat-menu-item (click)="toggleMenu()" [routerLinkActiveOptions]="{ exact: true }" routerLinkActive="active">
<mat-icon matBadge="2">mail</mat-icon>
<span *ngIf="displayLabels">Messages</span>
</a> -->
</a>
<a [routerLink]="['/people']" mat-menu-item (click)="toggleMenu()" [routerLinkActiveOptions]="{ exact: true }" routerLinkActive="active">
<mat-icon>people</mat-icon>
<span *ngIf="displayLabels">{{ 'App.People' | translate }}</span>

View File

@ -154,6 +154,7 @@ import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field';
import { DragScrollModule } from 'ngx-drag-scroll';
import { ZappersListDialogComponent } from './shared/zappers-list-dialog/zappers-list-dialog.component';
import { ExampleComponent } from './example/example';
import { MessageListComponent } from './shared/message-list/message-list.component';
@NgModule({
declarations: [
AppComponent,
@ -245,7 +246,8 @@ import { ExampleComponent } from './example/example';
TagsComponent,
BadgeComponent,
ZappersListDialogComponent,
ExampleComponent
ExampleComponent,
MessageListComponent
],
imports: [
HttpClientModule,

View File

@ -1,4 +1,47 @@
<mat-sidenav-container class="drawer-container" autosize>
<mat-nav-list>
<div class="search">
<mat-form-field appearance="fill" class="input-full-width">
<input matInput type="text" placeholder="Search..." />
<mat-icon matSuffix>search</mat-icon>
</mat-form-field>
</div>
<ng-container *ngFor="let chat of ui.chats$ | async; let lastItem = last">
<mat-list-item>
<img alt="" matListItemAvatar [src]="chat.picture" />
<h4 mat-line>{{ chat.name }}</h4>
<p mat-line class="last-message">{{ chat.about }}</p>
<!-- <span *ngIf="chat.lastMessageLength" [matBadge]="chat.lastMessageLength" matBadgeOverlap="false" matBadgePosition="above before" matBadgeColor="warn"></span> -->
</mat-list-item>
<!-- <app-chat-item [routerLink]="['/m', chat.id]" [chat]="chat"></app-chat-item> -->
<mat-divider *ngIf="!lastItem"></mat-divider>
</ng-container>
<!-- <ng-container *ngFor="let event of chatService.chats2$ | async; let lastItem = last">
<app-chat-item [routerLink]="['/m', '5f432a9f39b58ff132fc0a4c8af10d42efd917d8076f68bb7f2f91ed7d4f6a41']" [event]="event"></app-chat-item>
<mat-divider *ngIf="!lastItem"></mat-divider>
</ng-container> -->
</mat-nav-list>
<!-- <div *ngFor="let chat of chatService.chats3">{{ chat.pubkey }} : {{ chat.content }}</div> -->
<!-- <div *ngIf="chatService.uniqueChats$ | async as chats">
<div *ngFor="let chat of chats">{{ chat.pubkey }} : {{ chat.content }}</div>
</div> -->
<!-- <div *ngIf="chats$ | async as chats">
<div *ngFor="let chat of chats">{{ chat.id }} : {{ chat.name }}</div>
</div> -->
<!-- <button (click)="add()">Add</button>
<button (click)="reset()">Reset</button>
<button (click)="chatService.download()">Download</button> -->
<!-- <app-chat-list (openChatSidebar)="open.chatSideBar($event)"></app-chat-list> -->
<!-- <mat-sidenav-container class="drawer-container" autosize>
<mat-tab-group mat-align-tabs="center">
<mat-tab label="Messages">
<app-chat-list (openChatSidebar)="open.chatSideBar($event)"></app-chat-list>
@ -25,4 +68,4 @@
</mat-toolbar>
<app-user-profile (openChatWindow)="open.chatSideBar($event)"></app-user-profile>
</mat-sidenav>
</mat-sidenav-container>
</mat-sidenav-container> -->

View File

@ -29,3 +29,20 @@
.spacer {
flex: 1;
}
.form {
padding: 16px 16px 0 16px;
}
.input-full-width {
position: relative;
margin: auto;
}
.search {
position: sticky;
top: 0;
padding: 10px;
z-index: 999;
}

View File

@ -1,6 +1,10 @@
import { Component, ChangeDetectorRef, ViewChild, ViewEncapsulation } from '@angular/core';
import { MatSidenav } from '@angular/material/sidenav';
import { ApplicationState } from '../services/applicationstate';
import { ChatService } from '../services/chat.service';
import { RelayService } from '../services/relay';
import { Kind } from 'nostr-tools';
import { UIService } from '../services/ui';
@Component({
selector: 'app-chat',
templateUrl: './chat.html',
@ -10,7 +14,10 @@ import { ApplicationState } from '../services/applicationstate';
export class ChatComponent {
@ViewChild('chatSidebar', { static: false }) chatSidebar!: MatSidenav;
@ViewChild('userSidebar', { static: false }) userSidebar!: MatSidenav;
constructor(private appState: ApplicationState) {}
subscription: any;
constructor(private appState: ApplicationState, private chatService: ChatService, private relayService: RelayService, public ui: UIService) {}
sidebarTitles = {
user: '',
chat: '',
@ -29,8 +36,13 @@ export class ChatComponent {
};
async ngOnInit() {
this.ui.clearChats();
this.appState.updateTitle('Chat');
this.appState.goBack = true;
this.appState.actions = [];
this.subscription = this.relayService.subscribe([{ kinds: [Kind.ChannelCreation, Kind.ChannelMetadata], limit: 10 }]).id;
// this.chatService.downloadChatRooms();
}
}

View File

@ -51,6 +51,42 @@ export class ChatService {
subscriptions: Subscription[] = [];
downloadChatRooms() {
debugger;
// this.chats2 = [];
this.#chats = [];
this.dataService
.downloadEventsByQuery([{ kinds: [40, 41] }], 3000)
.pipe(
finalize(async () => {
debugger;
for (let index = 0; index < this.#chats.length; index++) {
const event = this.#chats[index];
const content = await this.nostr.decrypt(event.pubkey, event.content);
event.content = content;
console.log('DECRYPTED EVENT:', event);
}
})
)
.subscribe(async (event) => {
if (this.#chats.findIndex((e) => e.id === event.id) > -1) {
return;
}
// const gt = globalThis as any;
// const content = await gt.nostr.nip04.decrypt(event.pubkey, event.content);
// event.content = content;
this.#chats.unshift(event);
// this.chats2.push(event);
// this.#chatsChanged2.next(this.chats2);
});
// this.subscriptions.push(this.dataService.downloadEventsByQuery([{}]));
}
download() {
// this.chats2 = [];
this.#chats = [];

View File

@ -582,7 +582,6 @@ export class DataService {
downloadFromRelay(filters: Filter[], relay: NostrRelay, requestTimeout = 10000): Observable<NostrEventDocument> {
return new Observable<NostrEventDocument>((observer: Observer<NostrEventDocument>) => {
const sub = relay.sub([...filters], {}) as NostrSubscription;
// relay.subscriptions.push(sub);
sub.on('event', (originalEvent: any) => {
const event = this.eventService.processEvent(originalEvent);
@ -599,8 +598,6 @@ export class DataService {
});
return () => {
// console.log('downloadFromRelay:finished:unsub');
// When the observable is finished, this return function is called.
sub.unsub();
};
}).pipe(
@ -608,7 +605,7 @@ export class DataService {
catchError((error) => {
console.warn('The observable was timed out.');
return of();
}) // Simply return undefined when the timeout is reached.
})
);
}

View File

@ -331,6 +331,12 @@ export interface CustomObjectModel {
formatted?: string;
}
export interface NostrEventChat extends NostrEvent {
about: string;
name: string;
picture: string;
}
export class ChatModel {
'id': number;
'targetUserId': number;

View File

@ -427,6 +427,14 @@ export class RelayService {
this.zapUi.addZap(event);
}
if (event.kind == Kind.ChannelCreation) {
this.ui.putChat(event);
}
if (event.kind == Kind.ChannelMetadata) {
this.ui.putChatMetadata(event);
}
if (response.subscription) {
const sub = this.subs.get(response.subscription);
if (sub) {

View File

@ -3,7 +3,7 @@ import { ActivatedRoute } from '@angular/router';
import { Kind } from 'nostr-tools';
import { BehaviorSubject, map, Observable, filter, flatMap, mergeMap, concatMap, tap, take, single, takeWhile, from, of } from 'rxjs';
import { EventService } from './event';
import { EmojiEnum, LoadMoreOptions, NostrEvent, NostrEventDocument, NostrProfileDocument, NotificationModel, ThreadEntry } from './interfaces';
import { EmojiEnum, LoadMoreOptions, NostrEvent, NostrEventChat, NostrEventDocument, NostrProfileDocument, NotificationModel, ThreadEntry } from './interfaces';
import { OptionsService } from './options';
import { ProfileService } from './profile';
import { ZapService } from './zap.service';
@ -26,6 +26,7 @@ export class UIService {
rootEventsView: [] as NostrEventDocument[],
replyEventsView: [] as NostrEventDocument[],
reactions: new Map<string, ThreadEntry>(),
chats: [] as NostrEventChat[],
};
viewCounts = {
@ -156,6 +157,14 @@ export class UIService {
// return this.#eventsChanged.asObservable().pipe(map((data) => data.sort((a, b) => (a.created_at > b.created_at ? -1 : 1))));
}
chats: NostrEventChat[] = [];
#chatsChanged: BehaviorSubject<NostrEventChat[]> = new BehaviorSubject<NostrEventChat[]>(this.chats);
get chats$(): Observable<NostrEventChat[]> {
return this.#chatsChanged.asObservable();
}
#loadMore: BehaviorSubject<LoadMoreOptions | undefined> = new BehaviorSubject<LoadMoreOptions | undefined>(undefined);
get loadMore$(): Observable<LoadMoreOptions | undefined> {
@ -285,6 +294,69 @@ export class UIService {
this.triggerUnreadNotifications();
}
putChat(event: NostrEvent) {
const index = this.chats.findIndex((n) => n.id == event.id);
if (index == -1) {
const chat = event as NostrEventChat;
const parsed = JSON.parse(chat.content);
chat.picture = parsed.picture;
chat.name = parsed.name;
chat.about = parsed.about;
this.chats.push(chat);
this.#chatsChanged.next(this.chats);
}
// if (index == -1) {
// this.#notifications.unshift(notification);
// this.#notifications = this.#notifications.sort((a, b) => {
// return a.created < b.created ? 1 : -1;
// });
// } else {
// this.#notifications[index] = notification;
// }
// this.#activityFeed = this.#notifications.slice(0, 5);
// this.triggerUnreadNotifications();
}
putChatMetadata(event: NostrEvent) {
const channelId = this.eventService.lastETag(event);
if (!channelId) {
console.debug('This channel metadata does not have eTag:', event);
return;
}
// Find the existing chat creation, but verify both channel ID and the public key.
const index = this.chats.findIndex((n) => n.id == channelId && n.pubkey == event.pubkey);
// TODO: We are subscribing to both 40 and 41 at the same time and we are receiving 41 (metadata updates)
// before some of the 40 (create) events, meaning we'll never show the latest metadata for certain chats.
if (index == -1) {
return;
}
this.chats[index].content = event.content;
this.#chatsChanged.next(this.chats);
// if (index == -1) {
// this.#notifications.unshift(notification);
// this.#notifications = this.#notifications.sort((a, b) => {
// return a.created < b.created ? 1 : -1;
// });
// } else {
// this.#notifications[index] = notification;
// }
// this.#activityFeed = this.#notifications.slice(0, 5);
// this.triggerUnreadNotifications();
}
viewEventsStart = 0;
viewEventsCount = 5;
@ -709,6 +781,7 @@ export class UIService {
this.#lists.followingEventsView = [];
this.#lists.reactions = new Map<string, ThreadEntry>();
this.#lists.chats = [];
this.#notifications = [];
this.#activityFeed = [];
@ -766,6 +839,10 @@ export class UIService {
this.previousFeedSinceValue = 0;
}
clearChats() {
this.#lists.chats = [];
}
// #parentEventId: string | undefined = undefined;
// get parentEventId() {

View File

@ -9,7 +9,7 @@ import { ChatModel, NostrEventDocument } from 'src/app/services/interfaces';
})
export class ChatItemComponent {
@Output() openChatSidebar: EventEmitter<string> = new EventEmitter();
@Input() chat!: ChatModel;
@Input() chat!: ChatModel | any;
@Input() event!: NostrEventDocument;
constructor(private service: ChatService) {}

View File

@ -18,8 +18,7 @@ export class ChatListComponent implements OnInit {
constructor(public chatService: ChatService) {}
ngOnInit() {
this.chatService.download();
// this.chatService.download();
// this.chatService.uniqueChats$.subscribe((data) => {
// console.log('YEEH!', data);
// });

View File

@ -0,0 +1,35 @@
<mat-nav-list>
<div class="search">
<mat-form-field appearance="fill" class="input-full-width">
<input matInput type="text" placeholder="Search...">
<mat-icon matSuffix>search</mat-icon>
</mat-form-field>
</div>
<ng-container *ngFor="let chat of chatService.chats$ | async; let lastItem = last">
<app-chat-item [routerLink]="['/m', chat.id]" [chat]="chat"></app-chat-item>
<mat-divider *ngIf="!lastItem"></mat-divider>
</ng-container>
<!-- <ng-container *ngFor="let event of chatService.chats2$ | async; let lastItem = last">
<app-chat-item [routerLink]="['/m', '5f432a9f39b58ff132fc0a4c8af10d42efd917d8076f68bb7f2f91ed7d4f6a41']" [event]="event"></app-chat-item>
<mat-divider *ngIf="!lastItem"></mat-divider>
</ng-container> -->
</mat-nav-list>
<div *ngFor="let chat of chatService.chats3">{{ chat.pubkey }} : {{ chat.content }}</div>
<!-- <div *ngIf="chatService.uniqueChats$ | async as chats">
<div *ngFor="let chat of chats">{{ chat.pubkey }} : {{ chat.content }}</div>
</div> -->
<!-- <div *ngIf="chats$ | async as chats">
<div *ngFor="let chat of chats">{{ chat.id }} : {{ chat.name }}</div>
</div> -->
<button (click)="add()">Add</button>
<button (click)="reset()">Reset</button>
<button (click)="chatService.download()">Download</button>

View File

@ -0,0 +1,15 @@
.form {
padding: 16px 16px 0 16px;
}
.input-full-width {
position: relative;
margin: auto;
}
.search {
position: sticky;
top: 0;
padding: 10px;
z-index: 999;
}

View File

@ -0,0 +1,25 @@
// import {async, ComponentFixture, TestBed} from '@angular/core/testing';
// import {ChatListComponent} from './chat-list.component';
// describe('ChatListComponent', () => {
// let component: ChatListComponent;
// let fixture: ComponentFixture<ChatListComponent>;
// beforeEach(async(() => {
// TestBed.configureTestingModule({
// declarations: [ChatListComponent]
// })
// .compileComponents();
// }));
// beforeEach(() => {
// fixture = TestBed.createComponent(ChatListComponent);
// component = fixture.componentInstance;
// fixture.detectChanges();
// });
// it('should create', () => {
// expect(component).toBeTruthy();
// });
// });

View File

@ -0,0 +1,35 @@
import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { from, Observable, of } from 'rxjs';
import { ChatService } from 'src/app/services/chat.service';
interface ChatModel {
id: string;
name: string;
}
@Component({
selector: 'app-message-list',
templateUrl: './message-list.component.html',
styleUrls: ['./message-list.component.scss'],
})
export class MessageListComponent implements OnInit {
@Output() openChatSidebar: EventEmitter<string> = new EventEmitter();
constructor(public chatService: ChatService) {}
ngOnInit() {
this.chatService.download();
// this.chatService.uniqueChats$.subscribe((data) => {
// console.log('YEEH!', data);
// });
}
add() {
// this.#chats.unshift({ id: '123', name: 'Yes!' });
}
reset() {
// this.#chats = [];
}
}