- static async main () {
- const videoContainerId = 'video-wrapper'
- const embed = new PeerTubeEmbed(videoContainerId)
- await embed.init()
- }
-
- constructor (private videoWrapperId: string) {
- this.wrapperElement = document.getElementById(this.videoWrapperId)
- }
-
- getVideoUrl (id: string) {
- return window.location.origin + '/api/v1/videos/' + id
- }
-
- refreshFetch (url: string, options?: RequestInit) {
- return fetch(url, options)
- .then((res: Response) => {
- if (res.status !== 401) return res
-
- const refreshingTokenPromise = new Promise((resolve, reject) => {
- const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
- const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
-
- const headers = new Headers()
- headers.set('Content-Type', 'application/x-www-form-urlencoded')
-
- const data = {
- refresh_token: this.userTokens.refreshToken,
- client_id: clientId,
- client_secret: clientSecret,
- response_type: 'code',
- grant_type: 'refresh_token'
- }
-
- fetch('/api/v1/users/token', {
- headers,
- method: 'POST',
- body: objectToUrlEncoded(data)
- }).then(res => {
- if (res.status === 401) return undefined
-
- return res.json()
- }).then((obj: UserRefreshToken & { code: 'invalid_grant'}) => {
- if (!obj || obj.code === 'invalid_grant') {
- Tokens.flush()
- this.removeTokensFromHeaders()
-
- return resolve()
- }
-
- this.userTokens.accessToken = obj.access_token
- this.userTokens.refreshToken = obj.refresh_token
- this.userTokens.save()
-
- this.setHeadersFromTokens()
-
- resolve()
- })
- .catch((refreshTokenError: any) => {
- reject(refreshTokenError)
- })
- })
-
- return refreshingTokenPromise
- .catch(() => {
- Tokens.flush()
-
- this.removeTokensFromHeaders()
- }).then(() => fetch(url, {
- ...options,
- headers: this.headers
- }))
- })
- }
-
- getPlaylistUrl (id: string) {
- return window.location.origin + '/api/v1/video-playlists/' + id
- }
-
- loadVideoInfo (videoId: string): Promise<Response> {
- return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
- }
-
- loadVideoCaptions (videoId: string): Promise<Response> {
- return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
- }
-
- loadPlaylistInfo (playlistId: string): Promise<Response> {
- return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
- }
-
- loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
- const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
- url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
-
- return this.refreshFetch(url.toString(), { headers: this.headers })
- }
-
- loadConfig (): Promise<ServerConfig> {
- return this.refreshFetch('/api/v1/config')
- .then(res => res.json())
- }