From 44b88a87385adc75cac7f35819f04d9fc93a73c3 Mon Sep 17 00:00:00 2001 From: Milad Raeisi Date: Wed, 2 Oct 2024 17:52:43 +0400 Subject: [PATCH] Fix YouTube video rendering issue in chat --- .../conversation/conversation.component.ts | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/app/components/chat/conversation/conversation.component.ts b/src/app/components/chat/conversation/conversation.component.ts index fd49f2d4..d313e503 100644 --- a/src/app/components/chat/conversation/conversation.component.ts +++ b/src/app/components/chat/conversation/conversation.component.ts @@ -29,6 +29,7 @@ import { PickerComponent } from '@ctrl/ngx-emoji-mart'; import { AngorConfigService } from '@angor/services/config'; import { GifDialogComponent } from 'app/shared/gif-dialog/gif-dialog.component'; import { MatDialog } from '@angular/material/dialog'; +import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Component({ selector: 'chat-conversation', @@ -74,7 +75,8 @@ export class ConversationComponent implements OnInit, OnDestroy { private _angorMediaWatcherService: AngorMediaWatcherService, private _ngZone: NgZone, private _angorConfigService: AngorConfigService, - public dialog: MatDialog + public dialog: MatDialog, + private sanitizer: DomSanitizer ) { const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition; @@ -158,27 +160,30 @@ export class ConversationComponent implements OnInit, OnDestroy { }); } - - parseContent(content: string): string { + parseContent(content: string): SafeHtml { const urlRegex = /(https?:\/\/[^\s]+)/g; - return content.replace(urlRegex, (url) => { + const cleanedContent = content.replace(/["]+/g, ''); + const parsedContent = cleanedContent.replace(urlRegex, (url) => { if (url.match(/\.(jpeg|jpg|gif|png|bmp|svg|webp|tiff)$/) != null) { return `Image`; } else if (url.match(/\.(mp4|webm)$/) != null) { return ``; } else if (url.match(/(youtu\.be\/|youtube\.com\/watch\?v=)/)) { - let videoId = url.split('v=')[1] || url.split('youtu.be/')[1]; - const ampersandPosition = videoId.indexOf('&'); - if (ampersandPosition !== -1) { - videoId = videoId.substring(0, ampersandPosition); + let videoId; + if (url.includes('youtu.be/')) { + videoId = url.split('youtu.be/')[1]; + } else if (url.includes('watch?v=')) { + const urlParams = new URLSearchParams(url.split('?')[1]); + videoId = urlParams.get('v'); } - return ``; + return ``; } else { - return `${url}`; + return `${url}`; } }).replace(/\n/g, '
'); - } + return this.sanitizer.bypassSecurityTrustHtml(parsedContent); + } @HostListener('input') @HostListener('ngModelChange')