Refactoring: merge video-watch scope into common.

In order to be able to use lit in videowatch related code, we have to
merge these scopes.
This commit is contained in:
John Livingston
2024-06-13 16:36:16 +02:00
parent f1e9d1dfec
commit 990ff2385a
15 changed files with 519 additions and 446 deletions

View File

@ -2,10 +2,43 @@
//
// SPDX-License-Identifier: AGPL-3.0-only
import type { SettingEntries } from '@peertube/peertube-types'
import type { RegisterClientOptions } from '@peertube/peertube-types/client/types'
import { logger as loggerFunction } from '../../../utils/logger'
export interface PtContext {
ptOptions: RegisterClientOptions
// We precise some of the settings in SettingsEntries, to faciliate some type checking.
export type LiveChatSettings = SettingEntries & {
'chat-per-live-video': boolean
'chat-all-lives': boolean
'chat-all-non-lives': boolean
'chat-videos-list': string
'federation-no-remote-chat': boolean
'chat-style': string | undefined
}
export class PtContext {
public readonly ptOptions: RegisterClientOptions
public readonly logger: typeof loggerFunction
private _settings: LiveChatSettings | undefined
constructor (
ptOptions: RegisterClientOptions,
logger: typeof loggerFunction
) {
this.ptOptions = ptOptions
this.logger = logger
}
/**
* Returns the livechat settings.
* Keep them in cache after first request.
*/
public async getSettings (): Promise<LiveChatSettings> {
if (!this._settings) {
this._settings = await this.ptOptions.peertubeHelpers.getSettings() as LiveChatSettings
}
return this._settings
}
}
let context: PtContext
@ -18,7 +51,8 @@ export function getPtContext (): PtContext {
}
export function initPtContext (ptOptions: RegisterClientOptions): void {
context = {
ptOptions
}
context = new PtContext(
ptOptions,
loggerFunction
)
}

View File

@ -5,7 +5,7 @@
import { html } from 'lit'
import { customElement, property, state } from 'lit/decorators.js'
import { unsafeHTML } from 'lit/directives/unsafe-html.js'
import { helpButtonSVG } from '../../../videowatch/buttons'
import { helpButtonSVG } from '../../videowatch/buttons'
import { Task } from '@lit/task'
import { localizedHelpUrl } from '../../../utils/help'
import { ptTr } from '../directives/translation'

View File

@ -0,0 +1,73 @@
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
//
// SPDX-License-Identifier: AGPL-3.0-only
import type { SVGButton } from './buttons'
import { logger } from '../../utils/logger'
interface displayButtonOptionsBase {
buttonContainer: HTMLElement
name: string
label: string
icon?: SVGButton
additionalClasses?: string[]
}
interface displayButtonOptionsCallback extends displayButtonOptionsBase {
callback: () => void | boolean | Promise<void>
}
interface displayButtonOptionsHref extends displayButtonOptionsBase {
href: string
targetBlank?: boolean
}
type displayButtonOptions = displayButtonOptionsCallback | displayButtonOptionsHref
function displayButton (dbo: displayButtonOptions): void {
const button = document.createElement('a')
button.classList.add(
'orange-button', 'peertube-button-link',
'peertube-plugin-livechat-button',
'peertube-plugin-livechat-button-' + dbo.name
)
if (dbo.additionalClasses) {
for (let i = 0; i < dbo.additionalClasses.length; i++) {
button.classList.add(dbo.additionalClasses[i])
}
}
if ('callback' in dbo) {
button.onclick = dbo.callback
}
if ('href' in dbo) {
button.href = dbo.href
}
if (('targetBlank' in dbo) && dbo.targetBlank) {
button.target = '_blank'
}
if (dbo.icon) {
try {
const svg = dbo.icon()
const tmp = document.createElement('span')
tmp.innerHTML = svg.trim()
const svgDom = tmp.firstChild
if (svgDom) {
button.prepend(svgDom)
}
} catch (err) {
logger.error('Failed to generate the ' + dbo.name + ' button: ' + (err as string))
}
button.setAttribute('title', dbo.label)
} else {
button.textContent = dbo.label
}
dbo.buttonContainer.append(button)
}
export type {
displayButtonOptions
}
export {
displayButton
}

View File

@ -0,0 +1,141 @@
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
//
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable max-len */
type SVGButton = () => string
const closeSVG: SVGButton = () => {
// This content comes from the file assets/images/bye.svg, after svgo cleaning.
// To get the formated content, you can do:
// xmllint dist/client/images/bye.svg --format
// Then replace the main color by «currentColor»
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 4.233 4.233">
<rect
style="
fill:currentColor;
stroke:currentColor;stroke-width:.529167;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1
"
width="4.223" height=".427" x=".882" y="-.213" transform="rotate(45)" ry=".213"
/>
<rect
style="
fill:currentColor;
stroke:currentColor;stroke-width:.529167;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1
"
width="4.223" height=".427" x="-2.112" y="2.78" transform="scale(-1 1) rotate(45)" ry=".213"
/>
</svg>`
}
const openChatSVG: SVGButton = () => {
// This content comes from the file assets/images/talking.svg, after svgo cleaning.
// To get the formated content, you can do:
// xmllint dist/client/images/talking.svg --format
// Note: it was highly simplified in this file.
return `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 8.467 8.467">
<path style="fill:transparent;stroke-width:.187325" d="M.838.848h2.643v1.861H.838zM4.896 4.38h2.451v.875H4.896z"/>
<path
d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2ZM9 11H7V9h2zm4 0h-2V9h2zm4 0h-2V9h2z"
style="fill:currentColor;" transform="matrix(-.18741 0 0 .18741 8.493 3.004)"
/>
<path
d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2ZM6 9h12v2H6Zm8 5H6v-2h8zm4-6H6V6h12z"
style="fill:currentColor;" transform="scale(.18741)"
/>
</svg>`
}
const openBlankChatSVG: SVGButton = () => {
// This content comes from the file assets/images/new-window.svg, after svgo cleaning.
// To get the formated content, you can do:
// xmllint dist/client/images/new-window.svg --format
// Then replace the main color by «currentColor»
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 4.233 4.233">
<g
transform="matrix(.45208 0 0 .45208 -.526 1.335)"
style="stroke-width:1.00021;stroke-miterlimit:4;stroke-dasharray:none"
>
<path
style="
opacity:.998;fill:none;fill-opacity:1;
stroke:currentColor;stroke-width:1.17052322;stroke-miterlimit:4;
stroke-dasharray:none;stroke-opacity:1
"
d="
m8.674.744.012 1.266v2.199a.94.94 0 0 1-.943.942H3.345a.94.94
0 0 1-.942-.942V-.19a.94.94 0 0 1 .942-.943h2.2l1.255.016
"
/>
<rect
style="
opacity:.998;fill:currentColor;fill-opacity:1;
stroke:currentColor;stroke-width:1.17223459;stroke-miterlimit:4;
stroke-dasharray:none;stroke-opacity:1
"
width="5.632" height=".569"
x="-6.185" y="4.854" transform="scale(-1.03747 .96108) rotate(45)" ry=".285"
/>
<path
style="
opacity:.998;fill:currentColor;fill-opacity:1;
stroke:currentColor;stroke-width:1.30528;stroke-miterlimit:4;
stroke-dasharray:none;stroke-opacity:1
"
d="m5.15.374 1.091-1.89L7.333.373Z"
transform="scale(.89676) rotate(45 9.536 3.618)"
/>
</g>
</svg>`
}
const shareChatUrlSVG: SVGButton = () => {
// This content comes from the file assets/images/url.svg, after svgo cleaning.
// To get the formated content, you can do:
// xmllint dist/client/images/url.svg --format
// Then replace the color by `currentColor`
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 4.233 4.233">
<g style="stroke-width:1.17052;stroke-miterlimit:4;stroke-dasharray:none">
<path style="opacity:.998;fill:none;fill-opacity:1;stroke:currentColor;stroke-width:1.17052;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="m6.556-.435 1.132-1.132c.269-.268.618-.351.784-.186L9.867-.357c.166.165.083.515-.186.784L7.418 2.69c-.269.269-.618.352-.784.186l-.698-.697-.39-.407" transform="matrix(.45208 0 0 .45208 -.73 1.423)"/>
<path style="opacity:.998;fill:none;fill-opacity:1;stroke:currentColor;stroke-width:1.17052;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M6.038 3.505 4.906 4.637c-.268.268-.618.351-.784.186L2.727 3.427c-.166-.165-.083-.515.186-.784L5.176.38c.27-.269.619-.352.784-.186l.698.697.39.407" transform="matrix(.45208 0 0 .45208 -.73 1.423)"/>
</g>
</svg>
`
}
const helpButtonSVG: SVGButton = () => {
// This content comes from the file assets/images/help.svg, after svgo cleaning.
// To get the formated content, you can do:
// xmllint dist/client/images/url.svg --format
// Then replace the color by `currentColor`
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 4.233 4.233">
<path style="display:inline;opacity:.998;fill:none;fill-opacity:1;stroke:currentColor;stroke-width:.529167;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M1.48 1.583V.86c0-.171.085-.31.19-.31h.893c.106 0 .19.139.19.31v.838c0 .171-.107.219-.19.284l-.404.314c-.136.106-.219.234-.221.489l-.003.247"/>
<path style="display:inline;fill:currentColor;stroke-width:.235169" d="M1.67 3.429h.529v.597H1.67z"/>
</svg>
`
}
const promoteSVG: SVGButton = () => {
// This content comes from the file assets/images/moderator.svg, after svgo cleaning.
// To get the formated content, you can do:
// xmllint dist/client/images/moderator.svg --format
// Then replace the color by `currentColor`
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 4.233 4.233">
<g style="stroke-width:1.00021;stroke-miterlimit:4;stroke-dasharray:none">
<path style="opacity:.998;fill:none;fill-opacity:1;stroke:currentColor;stroke-width:1.17052;stroke-linecap:butt;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M2.943 1.626V-.34a.94.94 0 0 1 .942-.943l1.962-.023 1.961.01a.94.94 0 0 1 .942.942v1.968S7.126 4.746 5.847 4.767c-1.28.02-2.904-3.14-2.904-3.14Z" transform="matrix(.45208 0 0 .45208 -.526 1.335)"/>
</g>
</svg>
`
}
export {
closeSVG,
openChatSVG,
openBlankChatSVG,
shareChatUrlSVG,
helpButtonSVG,
promoteSVG
}
export type {
SVGButton
}

View File

@ -0,0 +1,376 @@
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
//
// SPDX-License-Identifier: AGPL-3.0-only
import type { Video } from '@peertube/peertube-types'
import type { InitConverseJSParams } from 'shared/lib/types'
import { getPtContext, LiveChatSettings } from '../lib/contexts/peertube'
import { videoHasWebchat, videoHasRemoteWebchat } from 'shared/lib/video'
import { displayButton, displayButtonOptions } from './button'
import {
closeSVG, openBlankChatSVG, openChatSVG, shareChatUrlSVG, helpButtonSVG, promoteSVG
} from './buttons'
import { shareChatUrl } from './share'
import { isAnonymousUser, guessIsMine, guessIamIModerator } from '../../utils/user'
import { localizedHelpUrl } from '../../utils/help'
import { getBaseRoute } from '../../utils/uri'
import { displayConverseJS } from '../../utils/conversejs'
let savedMyPluginFlexGrow: string | undefined
/**
* Initialize the chat for the current video
* @param video the video
*/
async function initChat (video: Video): Promise<void> {
const ptContext = getPtContext()
const logger = ptContext.logger
savedMyPluginFlexGrow = undefined
if (!video) {
logger.error('No video provided')
return
}
const placeholder = document.getElementById('plugin-placeholder-player-next')
if (!placeholder) {
logger.error('The required placeholder div is not present in the DOM.')
return
}
let container = placeholder.querySelector('#peertube-plugin-livechat-container')
if (container) {
logger.log('The chat seems already initialized...')
return
}
container = document.createElement('div')
container.setAttribute('id', 'peertube-plugin-livechat-container')
container.setAttribute('peertube-plugin-livechat-state', 'initializing')
container.setAttribute('peertube-plugin-livechat-current-url', window.location.href)
placeholder.append(container)
try {
const settings = await ptContext.getSettings()
logger.log('Checking if this video should have a chat...')
if (settings['chat-no-anonymous'] === true && isAnonymousUser(ptContext.ptOptions)) {
logger.log('No chat for anonymous users')
return
}
if (!videoHasWebchat(settings, video) && !videoHasRemoteWebchat(settings, video)) {
logger.log('This video has no webchat')
return
}
let showShareUrlButton: boolean = false
let showPromote: boolean = false
if (video.isLocal) { // No need for shareButton on remote chats.
const chatShareUrl = settings['chat-share-url'] ?? ''
if (chatShareUrl === 'everyone') {
showShareUrlButton = true
} else if (chatShareUrl === 'owner') {
showShareUrlButton = guessIsMine(ptContext.ptOptions, video)
} else if (chatShareUrl === 'owner+moderators') {
showShareUrlButton = guessIsMine(ptContext.ptOptions, video) || guessIamIModerator(ptContext.ptOptions)
}
if (guessIamIModerator(ptContext.ptOptions)) {
showPromote = true
}
}
await _insertChatDom(
container as HTMLElement,
video,
settings,
!!settings['chat-open-blank'],
showShareUrlButton,
showPromote
)
if (settings['chat-auto-display']) {
await _openChat(video)
} else if (container) {
container.setAttribute('peertube-plugin-livechat-state', 'closed')
}
} catch (err) {
logger.error('initChat has failed')
logger.error(err as string)
}
}
/**
* Insert the chat in the DOM.
* @param container
* @param video
* @param settings
* @param showOpenBlank
* @param showShareUrlButton
* @param showPromote
*/
async function _insertChatDom (
container: HTMLElement,
video: Video,
settings: LiveChatSettings,
showOpenBlank: boolean,
showShareUrlButton: boolean,
showPromote: boolean
): Promise<void> {
const ptContext = getPtContext()
const peertubeHelpers = ptContext.ptOptions.peertubeHelpers
const logger = ptContext.logger
logger.log('Adding livechat in the DOM...')
const viewersDocumentationHelpUrl = await localizedHelpUrl(ptContext.ptOptions, {
page: 'documentation/user/viewers'
})
const p = new Promise<void>((resolve) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.all([
peertubeHelpers.translate(LOC_OPEN_CHAT),
peertubeHelpers.translate(LOC_OPEN_CHAT_NEW_WINDOW),
peertubeHelpers.translate(LOC_CLOSE_CHAT),
peertubeHelpers.translate(LOC_SHARE_CHAT_LINK),
peertubeHelpers.translate(LOC_ONLINE_HELP),
peertubeHelpers.translate(LOC_PROMOTE)
]).then(labels => {
const labelOpen = labels[0]
const labelOpenBlank = labels[1]
const labelClose = labels[2]
const labelShareUrl = labels[3]
const labelHelp = labels[4]
const labelPromote = labels[5]
const buttonContainer = document.createElement('div')
buttonContainer.classList.add('peertube-plugin-livechat-buttons')
container.append(buttonContainer)
// Here are buttons that are magically merged
const groupButtons: displayButtonOptions[] = []
groupButtons.push({
buttonContainer,
name: 'open',
label: labelOpen,
callback: () => {
_openChat(video).then(() => {}, () => {})
},
icon: openChatSVG,
additionalClasses: []
})
if (showOpenBlank) {
groupButtons.push({
buttonContainer,
name: 'openblank',
label: labelOpenBlank,
callback: () => {
_closeChat()
window.open('/p/livechat/room?room=' + encodeURIComponent(video.uuid))
},
icon: openBlankChatSVG,
additionalClasses: []
})
}
if (showShareUrlButton) {
groupButtons.push({
buttonContainer,
name: 'shareurl',
label: labelShareUrl,
callback: () => {
shareChatUrl(ptContext.ptOptions, settings, video).then(() => {}, () => {})
},
icon: shareChatUrlSVG,
additionalClasses: []
})
}
if (showPromote) {
groupButtons.push({
buttonContainer,
name: 'promote',
label: labelPromote,
callback: async () => {
try {
// First we must get the room JID (can be video.uuid@ or channel.id@)
const response = await fetch(
getBaseRoute(ptContext.ptOptions) + '/api/configuration/room/' +
encodeURIComponent(video.uuid),
{
method: 'GET',
headers: peertubeHelpers.getAuthHeader()
}
)
const converseJSParams: InitConverseJSParams = await (response).json()
if (converseJSParams.isRemoteChat) {
throw new Error('Cant promote on remote chat.')
}
const roomJIDLocalPart = converseJSParams.room.replace(/@.*$/, '')
await fetch(
getBaseRoute(ptContext.ptOptions) + '/api/promote/' + encodeURIComponent(roomJIDLocalPart),
{
method: 'PUT',
headers: peertubeHelpers.getAuthHeader()
}
)
} catch (err) {
console.error(err)
}
},
icon: promoteSVG,
additionalClasses: []
})
}
groupButtons.push({
buttonContainer,
name: 'help',
label: labelHelp,
href: viewersDocumentationHelpUrl,
targetBlank: true,
icon: helpButtonSVG,
additionalClasses: []
})
// If more than one groupButtons:
// - the first must have class 'peertube-plugin-livechat-multi-button-main'
// - middle ones must have 'peertube-plugin-livechat-multi-button-secondary'
// - the last must have 'peertube-plugin-livechat-multi-button-last-secondary'
if (groupButtons.length > 1) {
groupButtons[0].additionalClasses?.push('peertube-plugin-livechat-multi-button-main')
for (let i = 1; i < groupButtons.length - 1; i++) { // middle
groupButtons[i].additionalClasses?.push('peertube-plugin-livechat-multi-button-secondary')
}
groupButtons[groupButtons.length - 1]
.additionalClasses?.push('peertube-plugin-livechat-multi-button-last-secondary')
}
for (const button of groupButtons) {
displayButton(button)
}
displayButton({
buttonContainer,
name: 'close',
label: labelClose,
callback: () => _closeChat(),
icon: closeSVG
})
resolve()
})
})
return p
}
async function _openChat (video: Video): Promise<void | false> {
const ptContext = getPtContext()
const peertubeHelpers = ptContext.ptOptions.peertubeHelpers
const logger = ptContext.logger
const settings = await ptContext.getSettings()
if (!video) {
logger.log('No video.')
return false
}
logger.info(`Trying to load the chat for video ${video.uuid}.`)
// here the room key is always the video uuid, a backend API will translate to channel id if relevant.
const roomkey = video.uuid
if (!roomkey) {
logger.error('Can\'t get room xmpp addr')
return false
}
const additionalStyles = settings['chat-style'] ?? ''
logger.info('Opening the chat...')
const container = document.getElementById('peertube-plugin-livechat-container')
try {
if (!container) {
logger.error('Cant found the livechat container.')
return false
}
if (container.getElementsByTagName('converse-root').length) {
logger.error('Seems that there is already a ConverseJS in the container.')
return false
}
if (additionalStyles) {
container.setAttribute('style', additionalStyles)
}
container.setAttribute('peertube-plugin-livechat-state', 'open')
// Hacking styles...
_hackStyles(true)
// Loading converseJS...
await displayConverseJS(ptContext.ptOptions, container, roomkey, 'peertube-video', false)
} catch (err) {
// Displaying an error page.
if (container) {
const message = document.createElement('div')
message.classList.add('peertube-plugin-livechat-error-message')
message.innerText = await peertubeHelpers.translate(LOC_CHATROOM_NOT_ACCESSIBLE)
container.append(message)
container.querySelectorAll(
'.livechat-spinner, converse-root'
).forEach(dom => dom.remove())
}
_hackStyles(false)
}
}
function _closeChat (): void {
const logger = getPtContext().logger
const container = document.getElementById('peertube-plugin-livechat-container')
if (!container) {
logger.error('Can\'t close livechat, container not found.')
return
}
// Disconnecting ConverseJS
if (window.converse?.livechatDisconnect) { window.converse.livechatDisconnect() }
// Removing from the DOM
container.querySelectorAll(
'converse-root, .livechat-spinner, .peertube-plugin-livechat-error-message'
).forEach(dom => dom.remove())
container.setAttribute('peertube-plugin-livechat-state', 'closed')
// Un-Hacking styles...
_hackStyles(false)
}
function _hackStyles (on: boolean): void {
try {
document.querySelectorAll('.peertube-plugin-livechat-buttons').forEach(buttons => {
if (on) {
buttons.classList.add('peertube-plugin-livechat-buttons-open')
} else {
buttons.classList.remove('peertube-plugin-livechat-buttons-open')
}
})
const myPluginPlaceholder: HTMLElement | null = document.querySelector('my-plugin-placeholder')
if (on) {
// Saving current style attributes and maximazing space for the chat
if (myPluginPlaceholder) {
savedMyPluginFlexGrow = myPluginPlaceholder.style.flexGrow // Should be "", but can be anything else.
myPluginPlaceholder.style.flexGrow = '1'
}
} else {
// restoring values...
if (savedMyPluginFlexGrow !== undefined && myPluginPlaceholder) {
myPluginPlaceholder.style.flexGrow = savedMyPluginFlexGrow
}
}
} catch (err) {
getPtContext().logger.error(`Failed hacking styles: '${err as string}'`)
}
}
export {
initChat
}

View File

@ -0,0 +1,34 @@
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
//
// SPDX-License-Identifier: AGPL-3.0-only
import type { Video } from '@peertube/peertube-types'
import { getPtContext } from '../lib/contexts/peertube'
import { initChat } from './chat'
interface VideoWatchLoadedHookOptions {
videojs: any
video: Video
playlist?: any
}
export async function registerVideoWatch (): Promise<void> {
const ptContext = getPtContext()
ptContext.ptOptions.registerHook({
target: 'action:video-watch.video.loaded',
handler: ({
video,
playlist
}: VideoWatchLoadedHookOptions) => {
if (!video) {
ptContext.logger.error('No video argument in hook action:video-watch.video.loaded')
return
}
if (playlist) {
ptContext.logger.info('We are in a playlist, we will not use the webchat')
return
}
initChat(video).then(() => {}, () => {})
}
})
}

View File

@ -0,0 +1,425 @@
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
//
// SPDX-License-Identifier: AGPL-3.0-only
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
import type { Video } from '@peertube/peertube-types'
import { helpButtonSVG } from './buttons'
import { logger } from '../../utils/logger'
import { getIframeUri, getXMPPAddr, UriOptions } from './uri'
import { isAutoColorsAvailable } from 'shared/lib/autocolors'
import { localizedHelpUrl } from '../../utils/help'
interface ShareForm {
shareString: HTMLInputElement
openButton: HTMLButtonElement
copyButton: HTMLButtonElement
readonly: HTMLInputElement
withscroll: HTMLInputElement
transparent: HTMLInputElement
readonlyOptions: HTMLElement
autoColors?: HTMLInputElement
generateIframe: HTMLInputElement
divTips: HTMLElement
radioProtocolWeb?: HTMLInputElement
radioProtocolXMPP?: HTMLInputElement
divWebOptions: HTMLDivElement
}
async function shareChatUrl (registerOptions: RegisterClientOptions, settings: any, video: Video): Promise<void> {
const peertubeHelpers = registerOptions.peertubeHelpers
const streamersHelpUrl = await localizedHelpUrl(registerOptions, {
page: 'documentation/user/streamers'
})
const [
labelShare,
labelWeb,
labelXMPP,
labelXMPPTips,
labelReadonly,
labelWithscroll,
labelTransparent,
labelOBSTips,
labelCopy,
labelCopied,
labelError,
labelOpen,
labelAutocolors,
labelGenerateIframe,
labelChatFor,
labelHelp
] = await Promise.all([
peertubeHelpers.translate(LOC_SHARE_CHAT_LINK),
peertubeHelpers.translate(LOC_WEB),
peertubeHelpers.translate(LOC_CONNECT_USING_XMPP),
peertubeHelpers.translate(LOC_CONNECT_USING_XMPP_HELP),
peertubeHelpers.translate(LOC_READ_ONLY),
peertubeHelpers.translate(LOC_SHOW_SCROLLBARR),
peertubeHelpers.translate(LOC_TRANSPARENT_BACKGROUND),
peertubeHelpers.translate(LOC_TIPS_FOR_STREAMERS),
peertubeHelpers.translate(LOC_COPY),
peertubeHelpers.translate(LOC_LINK_COPIED),
peertubeHelpers.translate(LOC_ERROR),
peertubeHelpers.translate(LOC_OPEN),
peertubeHelpers.translate(LOC_USE_CURRENT_THEME_COLOR),
peertubeHelpers.translate(LOC_GENERATE_IFRAME),
peertubeHelpers.translate(LOC_CHAT_FOR_LIVE_STREAM),
peertubeHelpers.translate(LOC_ONLINE_HELP)
])
const defaultUri = getIframeUri(registerOptions, settings, video)
if (!defaultUri) {
return
}
let form: ShareForm | undefined
function renderContent (container: HTMLElement): void {
if (!form) {
container.childNodes.forEach(child => container.removeChild(child))
container.classList.add('peertube-plugin-livechat-shareurl-modal')
const divShareString = document.createElement('div')
divShareString.classList.add('livechat-shareurl-copy')
const shareString = document.createElement('input')
shareString.setAttribute('type', 'text')
shareString.setAttribute('readonly', '')
shareString.setAttribute('autocomplete', 'off')
shareString.setAttribute('placeholder', '')
shareString.classList.add('form-control', 'readonly')
divShareString.append(shareString)
const copyButton = document.createElement('button')
copyButton.classList.add('btn', 'btn-outline-secondary', 'text-uppercase')
copyButton.textContent = labelCopy
divShareString.append(copyButton)
const openButton = document.createElement('button')
openButton.classList.add('btn', 'btn-outline-secondary', 'text-uppercase')
openButton.textContent = labelOpen
divShareString.append(openButton)
const helpButton = document.createElement('a')
helpButton.href = streamersHelpUrl
helpButton.target = '_blank'
helpButton.innerHTML = helpButtonSVG()
helpButton.title = labelHelp
helpButton.classList.add('orange-button', 'peertube-button-link', 'peertube-plugin-livechat-button')
divShareString.append(helpButton)
container.append(divShareString)
let radioProtocolWeb
let radioProtocolXMPP
if (settings['prosody-room-allow-s2s']) {
const protocolContainer = document.createElement('div')
protocolContainer.classList.add('livechat-shareurl-protocol')
radioProtocolWeb = document.createElement('input')
radioProtocolWeb.setAttribute('type', 'radio')
radioProtocolWeb.setAttribute('value', 'web')
radioProtocolWeb.setAttribute('name', 'protocol')
const radioProtocolWebLabel = document.createElement('label')
radioProtocolWebLabel.textContent = labelWeb
radioProtocolWebLabel.prepend(radioProtocolWeb)
protocolContainer.append(radioProtocolWebLabel)
radioProtocolXMPP = document.createElement('input')
radioProtocolXMPP.setAttribute('type', 'radio')
radioProtocolXMPP.setAttribute('value', 'xmpp')
radioProtocolXMPP.setAttribute('name', 'protocol')
const radioProtocolXMPPLabel = document.createElement('label')
radioProtocolXMPPLabel.textContent = labelXMPP
radioProtocolXMPPLabel.prepend(radioProtocolXMPP)
protocolContainer.append(radioProtocolXMPPLabel)
container.append(protocolContainer)
}
const divTips = document.createElement('div')
divTips.textContent = ''
divTips.classList.add('livechat-shareurl-tips')
container.append(divTips)
const divWebOptions = document.createElement('div')
divWebOptions.classList.add('livechat-shareurl-web-options')
container.append(divWebOptions)
const readonly = document.createElement('input')
readonly.setAttribute('type', 'checkbox')
const readonlyLabelEl = document.createElement('label')
readonlyLabelEl.textContent = labelReadonly
readonlyLabelEl.prepend(readonly)
divWebOptions.append(readonlyLabelEl)
const readonlyOptions = document.createElement('div')
readonlyOptions.classList.add('livechat-shareurl-web-options-readonly')
divWebOptions.append(readonlyOptions)
const withscroll = document.createElement('input')
withscroll.setAttribute('type', 'checkbox')
const withscrollLabelEl = document.createElement('label')
withscrollLabelEl.textContent = labelWithscroll
withscrollLabelEl.prepend(withscroll)
readonlyOptions.append(withscrollLabelEl)
const transparent = document.createElement('input')
transparent.setAttribute('type', 'checkbox')
const transparentLabelEl = document.createElement('label')
transparentLabelEl.textContent = labelTransparent
transparentLabelEl.prepend(transparent)
readonlyOptions.append(transparentLabelEl)
let autoColors
if (isAutoColorsAvailable(settings['converse-theme'])) {
const label = document.createElement('label')
label.innerText = labelAutocolors
autoColors = document.createElement('input')
autoColors.setAttribute('type', 'checkbox')
label.prepend(autoColors)
divWebOptions.append(label)
}
const generateIframe = document.createElement('input')
generateIframe.setAttribute('type', 'checkbox')
const generateIframeLabelEl = document.createElement('label')
generateIframeLabelEl.textContent = labelGenerateIframe
generateIframeLabelEl.prepend(generateIframe)
divWebOptions.append(generateIframeLabelEl)
if (radioProtocolWeb) {
radioProtocolWeb.onclick = () => {
renderContent(container)
}
}
if (radioProtocolXMPP) {
radioProtocolXMPP.onclick = () => {
renderContent(container)
}
}
readonly.onclick = () => {
renderContent(container)
}
withscroll.onclick = () => {
renderContent(container)
}
transparent.onclick = () => {
renderContent(container)
}
if (autoColors) {
autoColors.onclick = () => {
renderContent(container)
}
}
generateIframe.onclick = () => {
renderContent(container)
}
shareString.onclick = () => {
shareString.select()
shareString.setSelectionRange(0, 99999) /* For mobile devices */
}
copyButton.onclick = () => {
shareString.select()
shareString.setSelectionRange(0, 99999) /* For mobile devices */
navigator.clipboard.writeText(shareString.value).then(() => {
peertubeHelpers.notifier.success(labelCopied)
}, () => {
peertubeHelpers.notifier.error(labelError)
})
}
openButton.onclick = () => {
const uri = shareString.getAttribute('open-uri') ?? shareString.value
// Don't open the url if it is an iframe!
if (uri.startsWith('http') || uri.startsWith('xmpp')) {
window.open(uri)
}
}
form = {
shareString,
copyButton,
openButton,
readonly,
withscroll,
transparent,
readonlyOptions,
autoColors,
generateIframe,
radioProtocolWeb,
radioProtocolXMPP,
divWebOptions,
divTips
}
restore(form)
}
// Saving the form state, to restore each time the modal is opened.
save(form)
const uriOptions: UriOptions = {
ignoreAutoColors: form.autoColors ? !form.autoColors.checked : true,
permanent: true
}
if (form.radioProtocolXMPP?.checked) {
// To minimize the height gap between the 2 modes,
// and prevent the dialog to resize and move too much,
// we use visibility instead of display
form.divTips.textContent = labelXMPPTips
form.divWebOptions.style.visibility = 'hidden'
} else {
form.divTips.textContent = labelOBSTips
form.divWebOptions.style.visibility = 'visible'
}
if (form.readonly.checked) {
if (form.withscroll.checked) {
uriOptions.readonly = true
} else {
uriOptions.readonly = 'noscroll'
}
if (form.transparent.checked) {
uriOptions.transparent = true
}
form.withscroll.disabled = false
form.transparent.disabled = false
form.readonlyOptions.classList.remove('livechat-shareurl-web-options-readonly-disabled')
} else {
form.withscroll.disabled = true
form.transparent.disabled = true
form.readonlyOptions.classList.add('livechat-shareurl-web-options-readonly-disabled')
}
let shareStringValue
let shareStringOpen: string | undefined
if (!form.radioProtocolXMPP?.checked) {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
if (form.readonly?.checked || form.autoColors?.checked || form.generateIframe?.checked) {
shareStringValue = getIframeUri(registerOptions, settings, video, uriOptions)
if (form.generateIframe.checked) {
form.openButton.disabled = true
if (shareStringValue) {
// To properly escape all attributes, we are constructing an HTMLIframeElement
const iframe = document.createElement('iframe')
iframe.setAttribute('src', shareStringValue)
iframe.setAttribute('title', labelChatFor + ' ' + video.name)
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts allow-popups allow-forms')
iframe.setAttribute('width', '560')
iframe.setAttribute('height', '315')
iframe.setAttribute('frameborder', '0')
shareStringValue = iframe.outerHTML
}
} else {
form.openButton.disabled = false
}
} else {
shareStringValue = window.location.protocol +
'//' +
window.location.host +
'/p/livechat/room?room=' +
encodeURIComponent(video.uuid)
}
} else {
// we must generate a XMPP room address
// form.openButton.disabled = true
const addr = getXMPPAddr(registerOptions, settings, video)
shareStringValue = addr?.jid
shareStringOpen = addr?.uri
}
form.shareString.setAttribute('value', shareStringValue ?? '')
if (shareStringOpen) {
form.shareString.setAttribute('open-uri', shareStringOpen)
} else {
form.shareString.removeAttribute('open-uri')
}
}
function save (form: ShareForm): void {
if (!window.localStorage) {
return
}
const v = {
version: 1, // in case we add incompatible values in a near feature
readonly: !!form.readonly.checked,
withscroll: !!form.withscroll.checked,
transparent: !!form.transparent.checked,
autocolors: !!form.autoColors?.checked,
generateIframe: !!form.generateIframe.checked,
protocol: !form.radioProtocolWeb || form.radioProtocolWeb.checked ? 'web' : 'xmpp'
}
window.localStorage.setItem('peertube-plugin-livechat-shareurl', JSON.stringify(v))
}
function restore (form: ShareForm): void {
if (!window.localStorage) {
return
}
const s = window.localStorage.getItem('peertube-plugin-livechat-shareurl')
if (!s) {
return
}
let v: any
try {
v = JSON.parse(s)
if (!v || (typeof v !== 'object') || v.version !== 1) {
return
}
form.readonly.checked = !!v.readonly
form.withscroll.checked = !!v.withscroll
form.transparent.checked = !!v.transparent
if (form.autoColors) {
form.autoColors.checked = !!v.autocolors
}
form.generateIframe.checked = !!v.generateIframe
if (form.radioProtocolXMPP && v.protocol === 'xmpp') {
form.radioProtocolXMPP.checked = true
} else if (form.radioProtocolWeb) {
form.radioProtocolWeb.checked = true
}
} catch (err) {
logger.error(err as string)
}
}
logger.info('Opening the share modal...')
const observer = new MutationObserver(mutations => {
for (const { addedNodes } of mutations) {
addedNodes.forEach(node => {
if ((node as HTMLElement).localName === 'ngb-modal-window') {
logger.info('Detecting a new modal, checking if this is the good one...')
if (!(node as HTMLElement).querySelector) { return }
const title = (node as HTMLElement).querySelector('.modal-title')
if (!(title?.textContent === labelShare)) {
return
}
logger.info('Yes, it is the good modal!')
observer.disconnect()
const modalBodyElem: HTMLElement | null = (node as HTMLElement).querySelector('.modal-body')
if (!modalBodyElem) {
logger.error('Modal has no body... Dont know how to fill it.')
return
}
renderContent(modalBodyElem)
}
})
}
})
observer.observe(document.body, {
childList: true
})
peertubeHelpers.showModal({
title: labelShare,
content: `<p>${defaultUri ?? ''}</p>`, // incase the observer is broken...
close: true
})
// just in case, remove the observer after a timeout, if not already done...
setTimeout(() => {
observer.disconnect()
}, 1000)
}
export {
shareChatUrl
}

View File

@ -0,0 +1,95 @@
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
//
// SPDX-License-Identifier: AGPL-3.0-only
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
import type { Video } from '@peertube/peertube-types'
import { AutoColors, isAutoColorsAvailable } from 'shared/lib/autocolors'
import { getBaseRoute } from '../../utils/uri'
import { logger } from '../../utils/logger'
import { computeAutoColors } from '../../utils/colors'
interface UriOptions {
readonly?: boolean | 'noscroll'
transparent?: boolean
ignoreAutoColors?: boolean
permanent?: boolean
}
function getIframeUri (
registerOptions: RegisterClientOptions, settings: any, video: Video, uriOptions: UriOptions = {}
): string | null {
if (!settings) {
logger.error('Settings are not initialized, too soon to compute the iframeUri')
return null
}
let iframeUriStr = getBaseRoute(registerOptions, uriOptions.permanent)
iframeUriStr += '/webchat/room/' + encodeURIComponent(video.uuid)
const iFrameUri = new URL(iframeUriStr, window.location.origin)
if (
!uriOptions.ignoreAutoColors &&
settings['converse-autocolors'] &&
isAutoColorsAvailable(settings['converse-theme'])
) {
logger.info('We have to try to compute autocolors.')
try {
const autocolors = computeAutoColors()
if (autocolors) {
for (const p in autocolors) {
iFrameUri.searchParams.set('_ac_' + p, autocolors[p as keyof AutoColors])
}
}
} catch (err) {
logger.error(`Failed computing autocolors: '${err as string}'`)
}
}
if (uriOptions.readonly) {
iFrameUri.searchParams.set('_readonly', (typeof uriOptions.readonly === 'string') ? uriOptions.readonly : 'true')
}
if (uriOptions.transparent) {
iFrameUri.searchParams.set('_transparent', 'true')
}
iframeUriStr = iFrameUri.href
return iframeUriStr
}
interface XMPPAddr {
uri: string
jid: string
}
function getXMPPAddr (
registerOptions: RegisterClientOptions, settings: any, video: Video
): XMPPAddr | null {
// returns something like xmpp:256896ac-199a-4dab-bb3a-4fd916140272@room.instance.tdl?join
if (!settings['prosody-room-allow-s2s']) {
return null
}
let uuid: string
if (settings['prosody-room-type'] === 'channel') {
uuid = 'channel.' + video.channel.id.toString()
} else {
uuid = video.uuid.toString()
}
const hostname = window.location.hostname
const jid = uuid + '@room.' + hostname
return {
jid,
uri: 'xmpp:' + jid + '?join'
}
}
export type {
UriOptions
}
export {
getIframeUri,
getXMPPAddr
}