Skip to content

Commit

Permalink
Refactor chat service, profile component and relay service; update st…
Browse files Browse the repository at this point in the history
…orage service methods and add new ones; remove console logs
  • Loading branch information
miladsoft committed Nov 12, 2024
1 parent 952c65e commit 2b72947
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 34 deletions.
2 changes: 1 addition & 1 deletion src/app/components/chat/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class ChatService implements OnDestroy {
) {

this._metadataQueueService.processingStatus$.subscribe((status) => {
console.log('Processing status:', status);

});

}
Expand Down
6 changes: 1 addition & 5 deletions src/app/components/profile/profile.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -599,16 +599,12 @@
>
<span class="mr-1">Read More ...</span>
</button>

</div>


</div>

</angor-card>
}

<div class="mt-10 m-auto flex justify-center">
<div *ngIf="hasMorePosts" class="mt-4 m-auto flex justify-center">
<button mat-raised-button color="primary" (click)="loadNextPage()" [disabled]="loading">
{{ loading ? 'Loading...' : 'Load More Posts' }}
</button>
Expand Down
80 changes: 59 additions & 21 deletions src/app/components/profile/profile.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ export class ProfileComponent implements OnInit, OnDestroy {

subscriptionId: string;

public hasMorePosts: boolean = true;

followersList: ContactEvent[] = [];
followingList: ContactEvent[] = [];
Expand All @@ -154,7 +155,7 @@ export class ProfileComponent implements OnInit, OnDestroy {
private _clipboard: Clipboard,
private parseContent: ParseContentService
) {
}
}

async ngOnInit(): Promise<void> {
this.initializeTheme();
Expand Down Expand Up @@ -208,36 +209,78 @@ export class ProfileComponent implements OnInit, OnDestroy {
return hexPattern.test(pubkey);
}




private async loadInitialPosts(): Promise<void> {
this.loading = true;
let attemptCount = 0;
const maxAttempts = 5;
const delay = 3000; // 3 seconds

try {
await this._storageService.loadPosts(this.currentPage);
while (attemptCount < maxAttempts) {
const additionalPosts = await this._storageService.getPostsByPubKeysWithPagination(
[this.routePubKey],
this.currentPage,
10
);

if (additionalPosts.length > 0) {
this.posts = [...this.posts, ...additionalPosts];
this.posts.sort((a, b) => b.created_at - a.created_at);
break; // Stop retrying if posts are loaded
} else {
attemptCount++;
if (attemptCount < maxAttempts) {
await this.delay(delay);
}
}
}

// If no posts loaded after retries, assume there are no more posts to load
this.hasMorePosts = this.posts.length > 0;
if (!this.hasMorePosts) {
console.log('This user has no posts.');
}
} catch (error) {
console.error('Error loading posts:', error);
} finally {
this.loading = false;
}

this._changeDetectorRef.detectChanges();
}


private subscribeToNewPosts(): void {
if (this.isCurrentUserProfile) {
this._storageService.posts$.subscribe((newPost) => {
if (newPost && !this.posts.some((p) => p.id === newPost.id)) {
this.posts.push(newPost);
this.posts.sort((a, b) => b.created_at - a.created_at);
this._changeDetectorRef.detectChanges();
}
});
}
else
{

}

private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}





private subscribeToNewPosts(): void {
if (!this.isCurrentUserProfile) {
const filters: Filter[] = [
{ authors: [this.routePubKey], kinds: [1] },
];
this.subscriptionId = this._subscriptionService.addSubscriptions(filters, async (event: NostrEvent) => {
if (!this.isReply(event)) {
this._storageService.savePost(event);
}
});
}
}

private isReply(event: NostrEvent): boolean {
const replyTags = event.tags.filter(
(tag) => tag[0] === 'e' || tag[0] === 'p'
);
return replyTags.length > 0;
}
loadNextPage(): void {
if (this.loading) return;
this.currentPage++;
Expand Down Expand Up @@ -340,16 +383,13 @@ export class ProfileComponent implements OnInit, OnDestroy {
this.followersList.push(contactEvent);
this.followersCount++;
this.totalContacts++;
console.log(this.followersCount);

this._changeDetectorRef.detectChanges();

} else {
// Add to following list
this.followingList.push(contactEvent);
this.followingCount++;
this.totalContacts++;
console.log(this.followingCount);
this._changeDetectorRef.detectChanges();


Expand All @@ -374,11 +414,9 @@ export class ProfileComponent implements OnInit, OnDestroy {

if (this.isFollowing) {
await this._socialService.unfollow(routePubKey);
console.log(`Unfollowed ${routePubKey}`);

} else {
await this._socialService.follow(routePubKey);
console.log(`Followed ${routePubKey}`);
}

this.isFollowing = !this.isFollowing;
Expand Down
2 changes: 1 addition & 1 deletion src/app/services/relay.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class RelayService implements OnDestroy {
const storedRelays = JSON.parse(localStorage.getItem('nostrRelays') || '[]');
const defaultRelays: Relay[] = [
{ url: 'wss://relay.primal.net', connected: false, retries: 0, retryTimeout: null, accessType: 'read-write' },
{ url: 'wss://relay.damus.io', connected: false, retries: 0, retryTimeout: null, accessType: 'read-write' },
{ url: 'wss://nos.lol', connected: false, retries: 0, retryTimeout: null, accessType: 'read-write' },
{ url: 'wss://relay.angor.io', connected: false, retries: 0, retryTimeout: null, accessType: 'read-write' },
{ url: 'wss://relay2.angor.io', connected: false, retries: 0, retryTimeout: null, accessType: 'read-write' }
];
Expand Down
33 changes: 27 additions & 6 deletions src/app/services/storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -501,8 +501,6 @@ export class StorageService {
}
}



async getAllPosts(limit = 10): Promise<any[]> {
try {
const events: any[] = [];
Expand All @@ -520,6 +518,26 @@ export class StorageService {
}
}

async getPostsByPubKeysWithPagination(pubKeys: string[], page: number, limit: number = 10): Promise<any[]> {
try {
const events: any[] = [];

const offset = (page - 1) * limit;

await this.postsStore.iterate<any, void>((event) => {
if (pubKeys.includes(event.pubkey) && event.kind === 1) {
events.push(event);
}
});

return events
.sort((a, b) => b.created_at - a.created_at)
.slice(offset, offset + limit);
} catch (error) {
console.error('Error retrieving events for pubKeys with pagination:', error);
return [];
}
}

// ------------------- MyLikes Methods -------------------
async saveLike(like: any): Promise<void> {
Expand Down Expand Up @@ -731,11 +749,13 @@ export class StorageService {
}
}

async loadPostsFromDB(limit = 10, offset = 0): Promise<any[]> {
async loadPostsFromDB(pubKeys: string[], limit = 10, offset = 0): Promise<any[]> {
try {
const events: any[] = [];
await this.postsStore.iterate<any, void>((event) => {
events.push(event);
if (pubKeys.includes(event.pubkey)) {
events.push(event);
}
});

return events
Expand All @@ -747,10 +767,10 @@ export class StorageService {
}
}

async loadPosts(page: number): Promise<void> {
async loadPosts(pubKeys: string[], page: number): Promise<any> {
const limit = 10;
const offset = (page - 1) * limit;
const postsFromDB = await this.loadPostsFromDB(limit, offset);
const postsFromDB = await this.loadPostsFromDB(pubKeys, limit, offset);

if (postsFromDB.length > 0) {
postsFromDB.forEach((post) => {
Expand All @@ -759,6 +779,7 @@ export class StorageService {
}
}


private async loadAllMyLikesFromDB(): Promise<void> {
try {
const likes = await this.getAllMyLikes();
Expand Down

0 comments on commit 2b72947

Please sign in to comment.