New chat integration:

* refactoring
* cleaning
* using peertubeHelpers to get authent info when available
This commit is contained in:
John Livingston 2024-03-26 15:38:22 +01:00
parent 4cf2cd3ac8
commit b6478f0f9e
No known key found for this signature in database
GPG Key ID: B17B5640CE66CDBC
5 changed files with 82 additions and 37 deletions

View File

@ -46,7 +46,9 @@ async function registerConfiguration (clientOptions: RegisterClientOptions): Pro
converseRoot.classList.add('theme-peertube') converseRoot.classList.add('theme-peertube')
container.append(converseRoot) container.append(converseRoot)
window.initConverse(converseJSParams, 'embedded') const authHeader = peertubeHelpers.getAuthHeader()
window.initConverse(converseJSParams, 'peertube-fullpage', authHeader ?? null)
} catch (err) { } catch (err) {
console.error('[peertube-plugin-livechat] ' + (err as string)) console.error('[peertube-plugin-livechat] ' + (err as string))
rootEl.innerText = await peertubeHelpers.translate(LOC_NOT_FOUND) rootEl.innerText = await peertubeHelpers.translate(LOC_NOT_FOUND)

View File

@ -1,6 +1,7 @@
import type { InitConverseJSParams } from 'shared/lib/types' import type { InitConverseJSParams } from 'shared/lib/types'
import { computeAutoColors } from './colors' import { computeAutoColors } from './colors'
// FIXME
// declare global { // declare global {
// interface Window { // interface Window {
// converse?: { // converse?: {
@ -12,6 +13,7 @@ import { computeAutoColors } from './colors'
// } // }
// } // }
// FIXME: better declaration
declare global { declare global {
interface Window { interface Window {
converse?: any converse?: any

View File

@ -24,9 +24,24 @@ declare global {
} }
} }
/**
* ChatIncludeMode:
* - chat-only: the chat is on a full page, without Peertube
* - peertube-fullpage: the chat is embedded in Peertube, in a full custom page
* - peertube-video: the chat is embedded in Peertube, beside a video
*/
type ChatIncludeMode = 'chat-only' | 'peertube-fullpage' | 'peertube-video'
/**
* Init ConverseJS
* @param initConverseParams ConverseJS init Params
* @param chatIncludeMode How the chat is included in the html page
* @param peertubeAuthHeader when embedded in Peertube, we can get the header from peertubeHelpers
*/
window.initConverse = async function initConverse ( window.initConverse = async function initConverse (
initConverseParams: InitConverseJSParams, initConverseParams: InitConverseJSParams,
viewMode: 'fullscreen' | 'embedded' = 'fullscreen' chatIncludeMode: ChatIncludeMode = 'chat-only',
peertubeAuthHeader?: { [header: string]: string } | null
): Promise<void> { ): Promise<void> {
// First, fixing relative websocket urls. // First, fixing relative websocket urls.
if (initConverseParams.localWebsocketServiceUrl?.startsWith('/')) { if (initConverseParams.localWebsocketServiceUrl?.startsWith('/')) {
@ -50,13 +65,13 @@ window.initConverse = async function initConverse (
const isInIframe = inIframe() const isInIframe = inIframe()
initDom(initConverseParams, isInIframe) initDom(initConverseParams, isInIframe)
const params = defaultConverseParams(initConverseParams, isInIframe) const params = defaultConverseParams(initConverseParams, isInIframe)
params.view_mode = viewMode params.view_mode = chatIncludeMode === 'chat-only' ? 'fullscreen' : 'embedded'
params.allow_url_history_change = viewMode === 'fullscreen' params.allow_url_history_change = chatIncludeMode === 'chat-only'
let isAuthenticated: boolean = false let isAuthenticated: boolean = false
let isRemoteWithNicknameSet: boolean = false let isRemoteWithNicknameSet: boolean = false
const auth = await getLocalAuthentInfos(authenticationUrl) const auth = await getLocalAuthentInfos(authenticationUrl, peertubeAuthHeader)
if (auth) { if (auth) {
if (!isRemoteChat) { if (!isRemoteChat) {
localRoomAuthenticatedParams(initConverseParams, auth, params) localRoomAuthenticatedParams(initConverseParams, auth, params)
@ -93,28 +108,29 @@ window.initConverse = async function initConverse (
} }
try { try {
// TODO: disable this when on the new full page. if (chatIncludeMode === 'chat-only') {
converse.plugins.add('livechatWindowTitlePlugin', { converse.plugins.add('livechatWindowTitlePlugin', {
dependencies: ['converse-muc-views'], dependencies: ['converse-muc-views'],
overrides: { overrides: {
ChatRoomView: { ChatRoomView: {
requestUpdate: function (this: any): any { requestUpdate: function (this: any): any {
console.log('[livechatWindowTitlePlugin] updating the document title.') console.log('[livechatWindowTitlePlugin] updating the document title.')
try { try {
if (this.model?.getDisplayName) { if (this.model?.getDisplayName) {
const title = this.model.getDisplayName() const title = this.model.getDisplayName()
if (document.title !== title) { if (document.title !== title) {
document.title = title document.title = title
}
} }
} catch (err) {
console.error('[livechatWindowTitlePlugin] Failed updating the window title', err)
} }
} catch (err) { return this.__super__.requestUpdate.apply(this)
console.error('[livechatWindowTitlePlugin] Failed updating the window title', err)
} }
return this.__super__.requestUpdate.apply(this)
} }
} }
} })
}) }
converse.plugins.add('converse-slow-mode', slowModePlugin) converse.plugins.add('converse-slow-mode', slowModePlugin)

View File

@ -15,7 +15,8 @@
<div id="conversejs-bg" class="theme-peertube"></div> <div id="conversejs-bg" class="theme-peertube"></div>
<script type="text/javascript"> <script type="text/javascript">
initConverse( initConverse(
{INIT_CONVERSE_PARAMS} {INIT_CONVERSE_PARAMS},
'chat-only'
) )
</script> </script>
</body> </body>

View File

@ -3,7 +3,13 @@ interface AuthentInfos {
password: string password: string
nickname?: string nickname?: string
} }
async function getLocalAuthentInfos (authenticationUrl: string): Promise<false | AuthentInfos> {
interface AuthHeader { [key: string]: string }
async function getLocalAuthentInfos (
authenticationUrl: string,
peertubeAuthHeader?: AuthHeader | null
): Promise<false | AuthentInfos> {
try { try {
if (authenticationUrl === '') { if (authenticationUrl === '') {
console.error('Missing authenticationUrl') console.error('Missing authenticationUrl')
@ -13,25 +19,43 @@ async function getLocalAuthentInfos (authenticationUrl: string): Promise<false |
console.error('Your browser has not the fetch api, we cant log you in') console.error('Your browser has not the fetch api, we cant log you in')
return false return false
} }
if (!window.localStorage) {
// FIXME: is the Peertube token always in localStorage? if (peertubeAuthHeader === null) {
console.error('Your browser has no localStorage, we cant log you in') console.info('User is not logged in.')
return false return false
} }
const tokenType = window.localStorage.getItem('token_type') ?? ''
const accessToken = window.localStorage.getItem('access_token') ?? '' if (peertubeAuthHeader === undefined) { // parameter not given.
const refreshToken = window.localStorage.getItem('refresh_token') ?? '' // We must be in a page without PeertubeHelpers, so we must get authent token manualy.
if (tokenType === '' && accessToken === '' && refreshToken === '') { if (!window.localStorage) {
console.info('User seems not to be logged in.') // FIXME: is the Peertube token always in localStorage?
return false console.error('Your browser has no localStorage, we cant log you in')
return false
}
const tokenType = window.localStorage.getItem('token_type') ?? ''
const accessToken = window.localStorage.getItem('access_token') ?? ''
const refreshToken = window.localStorage.getItem('refresh_token') ?? ''
if (tokenType === '' && accessToken === '' && refreshToken === '') {
console.info('User seems not to be logged in.')
return false
}
peertubeAuthHeader = {
Authorization: tokenType + ' ' + accessToken
}
} }
const response = await window.fetch(authenticationUrl, { const response = await window.fetch(authenticationUrl, {
method: 'GET', method: 'GET',
headers: new Headers({ headers: new Headers(
Authorization: tokenType + ' ' + accessToken, Object.assign(
'content-type': 'application/json;charset=UTF-8' {},
}) peertubeAuthHeader,
{
'content-type': 'application/json;charset=UTF-8'
}
)
)
}) })
if (!response.ok) { if (!response.ok) {