Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Rebuild thumbnail and media file architecture

Chocobozzz526f1c6df529
diff --git a/apps/peertube-cli/src/peertube-upload.ts b/apps/peertube-cli/src/peertube-upload.ts
index b71cfbbaf8..ea23757f42 100644
--- a/apps/peertube-cli/src/peertube-upload.ts
+++ b/apps/peertube-cli/src/peertube-upload.ts
@@ -11,7 +11,6 @@ type UploadOptions = {
username?: string
password?: string
thumbnail?: string
- preview?: string
file?: string
videoName?: string
category?: number
@@ -38,7 +37,6 @@ export function defineUploadProgram () {
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.option('-b, --thumbnail <thumbnailPath>', 'Thumbnail path')
- .option('--preview <previewPath>', 'Preview path')
.option('-f, --file <file>', 'Video absolute file path')
.option('-n, --video-name <name>', 'Video name')
.option('-c, --category <category_number>', 'Category number', parseInt)
@@ -105,8 +103,7 @@ async function run (options: UploadOptions) {
...baseAttributes,
fixture: options.file,
- thumbnailfile: options.thumbnail,
- previewfile: options.preview
+ thumbnailfile: options.thumbnail
}
try {
diff --git a/apps/peertube-runner/src/server/process/shared/process-vod.ts b/apps/peertube-runner/src/server/process/shared/process-vod.ts
index 99c897ebaf..6b2a70d661 100644
--- a/apps/peertube-runner/src/server/process/shared/process-vod.ts
+++ b/apps/peertube-runner/src/server/process/shared/process-vod.ts
@@ -169,7 +169,7 @@ export async function processAudioMergeTranscoding (options: ProcessOptions<Runn
let ffmpegProgress: number
let audioPath: string
- let previewPath: string
+ let thumbnailPath: string
const outputPath = join(ConfigManager.Instance.getTranscodingDirectory(), `output-${buildUUID()}.mp4`)
@@ -187,7 +187,7 @@ export async function processAudioMergeTranscoding (options: ProcessOptions<Runn
)
audioPath = await downloadInputFile({ url: payload.input.audioFileUrl, runnerToken, job })
- previewPath = await downloadInputFile({ url: payload.input.previewFileUrl, runnerToken, job })
+ thumbnailPath = await downloadInputFile({ url: payload.input.previewFileUrl, runnerToken, job })
logger.info(
`Downloaded input files ${payload.input.audioFileUrl} and ${payload.input.previewFileUrl} ` +
@@ -204,7 +204,7 @@ export async function processAudioMergeTranscoding (options: ProcessOptions<Runn
type: 'merge-audio',
audioPath,
- videoInputPath: previewPath,
+ videoInputPath: thumbnailPath,
outputPath,
@@ -227,7 +227,7 @@ export async function processAudioMergeTranscoding (options: ProcessOptions<Runn
})
} finally {
if (audioPath) await remove(audioPath)
- if (previewPath) await remove(previewPath)
+ if (thumbnailPath) await remove(thumbnailPath)
if (outputPath) await remove(outputPath)
if (updateProgressInterval) clearInterval(updateProgressInterval)
}
diff --git a/client/src/app/+about/about-follows/follower-image.component.ts b/client/src/app/+about/about-follows/follower-image.component.ts
index 9442e25383..4e4affc5e2 100644
--- a/client/src/app/+about/about-follows/follower-image.component.ts
+++ b/client/src/app/+about/about-follows/follower-image.component.ts
@@ -1,6 +1,6 @@
import { Component, OnInit, inject } from '@angular/core'
import { ServerService } from '@app/core'
-import { Actor } from '@app/shared/shared-main/account/actor.model'
+import { findAppropriateImageFileUrl } from '@root-helpers/images'
@Component({
selector: 'my-follower-image',
@@ -15,6 +15,6 @@ export class FollowerImageComponent implements OnInit {
avatarUrl: string
ngOnInit () {
- this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(this.server.getHTMLConfig().instance, 30)
+ this.avatarUrl = findAppropriateImageFileUrl(this.server.getHTMLConfig().instance.avatars, 30)
}
}
diff --git a/client/src/app/+about/about-follows/subscription-image.component.ts b/client/src/app/+about/about-follows/subscription-image.component.ts
index a0a4ea3b85..5d880226ca 100644
--- a/client/src/app/+about/about-follows/subscription-image.component.ts
+++ b/client/src/app/+about/about-follows/subscription-image.component.ts
@@ -1,6 +1,6 @@
import { Component, OnInit, inject } from '@angular/core'
import { ServerService } from '@app/core'
-import { Actor } from '@app/shared/shared-main/account/actor.model'
+import { findAppropriateImageFileUrl } from '@root-helpers/images'
@Component({
selector: 'my-subscription-image',
@@ -15,6 +15,6 @@ export class SubscriptionImageComponent implements OnInit {
avatarUrl: string
ngOnInit () {
- this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(this.server.getHTMLConfig().instance, 30)
+ this.avatarUrl = findAppropriateImageFileUrl(this.server.getHTMLConfig().instance.avatars, 30)
}
}
diff --git a/client/src/app/+about/about.component.ts b/client/src/app/+about/about.component.ts
index c04f84da9a..7d11e40df4 100644
--- a/client/src/app/+about/about.component.ts
+++ b/client/src/app/+about/about.component.ts
@@ -2,12 +2,12 @@ import { Component, OnInit, inject, viewChild } from '@angular/core'
import { RouterOutlet } from '@angular/router'
import { ServerService } from '@app/core'
import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'
-import { Actor } from '@app/shared/shared-main/account/actor.model'
import { ButtonComponent } from '@app/shared/shared-main/buttons/button.component'
import { HorizontalMenuComponent, HorizontalMenuEntry } from '@app/shared/shared-main/menu/horizontal-menu.component'
import { SupportModalComponent } from '@app/shared/shared-support-modal/support-modal.component'
import { maxBy } from '@peertube/peertube-core-utils'
import { HTMLServerConfig } from '@peertube/peertube-models'
+import { findAppropriateImageFileUrl } from '@root-helpers/images'
@Component({
selector: 'my-about',
@@ -34,7 +34,7 @@ export class AboutComponent implements OnInit {
? maxBy(this.config.instance.banners, 'width').fileUrl
: undefined
- this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(this.config.instance, 110)
+ this.avatarUrl = findAppropriateImageFileUrl(this.config.instance.avatars, 110)
this.menuEntries = [
{
diff --git a/client/src/app/+admin/config/pages/admin-config-advanced.component.html b/client/src/app/+admin/config/pages/admin-config-advanced.component.html
index 84d6e7890c..489e6e43ae 100644
--- a/client/src/app/+admin/config/pages/admin-config-advanced.component.html
+++ b/client/src/app/+admin/config/pages/admin-config-advanced.component.html
@@ -10,75 +10,6 @@
Some files are not federated, and fetched when necessary. Define their caching policies.
</div>
</div>
-
- <div class="content-col">
- <ng-container formGroupName="cache">
- <div class="form-group" formGroupName="previews">
- <label i18n for="cachePreviewsSize">Number of previews to keep in cache</label>
-
- <div class="number-with-unit">
- <input
- type="number" min="0" id="cachePreviewsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors.cache.previews.size }"
- >
- <span i18n>{getCacheSize('previews'), plural, =1 {cached image} other {cached images}}</span>
- </div>
-
- @if (formErrors.cache.previews.size) {
- <div class="form-error" role="alert">{{ formErrors.cache.previews.size }}</div>
- }
- </div>
-
- <div class="form-group" formGroupName="captions">
- <label i18n for="cacheCaptionsSize">Number of video captions to keep in cache</label>
-
- <div class="number-with-unit">
- <input
- type="number" min="0" id="cacheCaptionsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors.cache.captions.size }"
- >
- <span i18n>{getCacheSize('captions'), plural, =1 {cached caption} other {cached captions}}</span>
- </div>
-
- @if (formErrors.cache.captions.size) {
- <div class="form-error" role="alert">{{ formErrors.cache.captions.size }}</div>
- }
- </div>
-
- <div class="form-group" formGroupName="torrents">
- <label i18n for="cacheTorrentsSize">Number of video torrents to keep in cache</label>
-
- <div class="number-with-unit">
- <input
- type="number" min="0" id="cacheTorrentsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors.cache.torrents.size }"
- >
- <span i18n>{getCacheSize('torrents'), plural, =1 {cached torrent} other {cached torrents}}</span>
- </div>
-
- @if (formErrors.cache.torrents.size) {
- <div class="form-error" role="alert">{{ formErrors.cache.torrents.size }}</div>
- }
- </div>
-
- <div class="form-group" formGroupName="storyboards">
- <label i18n for="cacheTorrentsSize">Number of video storyboard images to keep in cache</label>
-
- <div class="number-with-unit">
- <input
- type="number" min="0" id="cacheStoryboardsSize" class="form-control"
- formControlName="size" [ngClass]="{ 'input-error': formErrors.cache.storyboards.size }"
- >
- <span i18n>{getCacheSize('storyboards'), plural, =1 {cached storyboard} other {cached storyboards}}</span>
- </div>
-
- @if (formErrors.cache.storyboards.size) {
- <div class="form-error" role="alert">{{ formErrors.cache.storyboards.size }}</div>
- }
- </div>
- </ng-container>
-
- </div>
</div>
<div class="pt-two-cols mt-4">
diff --git a/client/src/app/+admin/config/pages/admin-config-advanced.component.ts b/client/src/app/+admin/config/pages/admin-config-advanced.component.ts
index 877563c8e2..54503cb67c 100644
--- a/client/src/app/+admin/config/pages/admin-config-advanced.component.ts
+++ b/client/src/app/+admin/config/pages/admin-config-advanced.component.ts
@@ -3,7 +3,7 @@ import { Component, inject, OnDestroy, OnInit } from '@angular/core'
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'
import { ActivatedRoute } from '@angular/router'
import { CanComponentDeactivate } from '@app/core'
-import { CACHE_SIZE_VALIDATOR, SERVICES_TWITTER_USERNAME_VALIDATOR } from '@app/shared/form-validators/custom-config-validators'
+import { SERVICES_TWITTER_USERNAME_VALIDATOR } from '@app/shared/form-validators/custom-config-validators'
import {
BuildFormArgumentTyped,
FormDefaultTyped,
@@ -22,21 +22,6 @@ type Form = {
username: FormControl<string>
}>
}>
-
- cache: FormGroup<{
- previews: FormGroup<{
- size: FormControl<number>
- }>
- captions: FormGroup<{
- size: FormControl<number>
- }>
- torrents: FormGroup<{
- size: FormControl<number>
- }>
- storyboards: FormGroup<{
- size: FormControl<number>
- }>
- }>
}
@Component({
@@ -84,20 +69,6 @@ export class AdminConfigAdvancedComponent implements OnInit, OnDestroy, CanCompo
twitter: {
username: SERVICES_TWITTER_USERNAME_VALIDATOR
}
- },
- cache: {
- previews: {
- size: CACHE_SIZE_VALIDATOR
- },
- captions: {
- size: CACHE_SIZE_VALIDATOR
- },
- torrents: {
- size: CACHE_SIZE_VALIDATOR
- },
- storyboards: {
- size: CACHE_SIZE_VALIDATOR
- }
}
}
@@ -114,10 +85,6 @@ export class AdminConfigAdvancedComponent implements OnInit, OnDestroy, CanCompo
this.validationMessages = validationMessages
}
- getCacheSize (type: 'captions' | 'previews' | 'torrents' | 'storyboards') {
- return this.form.value.cache[type].size
- }
-
save () {
this.adminConfigService.saveAndUpdateCurrent({
currentConfig: this.customConfig,
diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.scss b/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.scss
index fead6d31ec..5591c3ac43 100644
--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.scss
+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.scss
@@ -21,6 +21,7 @@ my-select-options {
}
my-image-input {
+ // Keep it sync with image size requested by the component
width: 223px;
height: 122px;
}
diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts
index 3321303428..ffb59affc9 100644
--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts
+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts
@@ -150,7 +150,8 @@ export class MyVideoPlaylistUpdateComponent extends MyVideoPlaylistEdit implemen
videoChannelId: this.videoPlaylistToUpdate.videoChannel ? this.videoPlaylistToUpdate.videoChannel.id : null
})
- fetch(this.videoPlaylistToUpdate.thumbnailUrl)
+ // Keep it sync with image size set in the SASS file
+ fetch(this.videoPlaylistToUpdate.getThumbnailUrl(223))
.then(response => response.blob())
.then(data => {
this.form.patchValue({
diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scss b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scss
index 6a5d9a2dcd..611929375a 100644
--- a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scss
+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scss
@@ -22,5 +22,7 @@
my-video-playlist-miniature {
display: block;
+
+ // Sync wid
width: 130px;
}
diff --git a/client/src/app/+video-watch/shared/recommendations/recommended-videos.component.scss b/client/src/app/+video-watch/shared/recommendations/recommended-videos.component.scss
index 98296a41e9..d110240985 100644
--- a/client/src/app/+video-watch/shared/recommendations/recommended-videos.component.scss
+++ b/client/src/app/+video-watch/shared/recommendations/recommended-videos.component.scss
@@ -49,8 +49,10 @@ my-video-miniature {
}
.other-videos:not(.display-as-row) my-video-miniature {
- min-width: $video-thumbnail-medium-width;
- max-width: $video-thumbnail-medium-width;
+ --co-miniature-max-width: #{$video-thumbnail-medium-width};
+
+ min-width: var(--co-miniature-min-width);
+ max-width: var(--co-miniature-max-width);
}
.display-as-row {
diff --git a/client/src/app/+video-watch/video-watch.component.ts b/client/src/app/+video-watch/video-watch.component.ts
index d998e887f1..fe1ad4d5fb 100644
--- a/client/src/app/+video-watch/video-watch.component.ts
+++ b/client/src/app/+video-watch/video-watch.component.ts
@@ -870,9 +870,9 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
!video.canBypassPassword(this.authUser),
videoPassword: () => videoPassword,
- poster: video.isNSFWBlurForUser(loggedInOrAnonymousUser, this.serverConfig)
+ thumbnails: video.isNSFWBlurForUser(loggedInOrAnonymousUser, this.serverConfig)
? null
- : video.previewUrl,
+ : video.thumbnails,
nsfwWarning: video.isNSFWHiddenOrWarned(loggedInOrAnonymousUser, this.serverConfig)
? {
@@ -980,7 +980,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy {
this.peertubePlayer.disable()
if (hasPlayed || !this.video.isNSFWBlurForUser(this.authUser || this.anonymousUser, this.serverConfig)) {
- this.peertubePlayer.setPoster(this.video.previewPath)
+ this.peertubePlayer.setPoster(this.video.thumbnails)
}
}
diff --git a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.html b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.html
index 072a399420..0cd75667bb 100644
--- a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.html
+++ b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.html
@@ -22,14 +22,14 @@
</div>
@if (uploadingAudioFile) {
- <div class="form-group audio-preview">
- <label i18n for="previewfileUpload">Video background image</label>
+ <div class="form-group audio-thumbnail">
+ <label i18n for="thumbnailfileUpload">Video background image</label>
<div i18n class="audio-image-info">
Image that will be merged with your audio file.
<br />
The chosen image will be definitive and cannot be modified.
</div>
- <my-image-input i18n-inputLabel inputLabel="Edit" inputName="previewfileUpload" [(ngModel)]="audioPreviewFile"></my-image-input>
+ <my-image-input i18n-inputLabel inputLabel="Edit" inputName="thumbnailfileUpload" [(ngModel)]="audioThumbnailFile"></my-image-input>
</div>
<div class="form-group upload-audio-button">
<my-button theme="primary" [label]="getAudioUploadLabel()" icon="upload" (click)="uploadAudio()"></my-button>
diff --git a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.scss b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.scss
index 645d292204..db97fa45c8 100644
--- a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.scss
+++ b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.scss
@@ -11,7 +11,7 @@
margin-bottom: 10px;
}
- .audio-preview {
+ .audio-thumbnail {
margin: 30px 0;
my-image-input {
diff --git a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.ts b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.ts
index 61dcbe7ddb..abbca45ff6 100644
--- a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.ts
+++ b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.ts
@@ -58,7 +58,7 @@ export class VideoUploadComponent implements OnInit, OnDestroy, AfterViewInit, C
readonly videoFileInput = viewChild<ElementRef<HTMLInputElement>>('videoFileInput')
uploadingAudioFile = false
- audioPreviewFile: File
+ audioThumbnailFile: File
firstStep = true
firstStepChannelId: number
@@ -164,11 +164,11 @@ export class VideoUploadComponent implements OnInit, OnDestroy, AfterViewInit, C
this.firstStep = true
this.videoEdit = undefined
this.uploadingAudioFile = false
- this.audioPreviewFile = undefined
+ this.audioThumbnailFile = undefined
}
uploadAudio () {
- this.uploadFile(this.getInputVideoFile(), this.audioPreviewFile)
+ this.uploadFile(this.getInputVideoFile(), this.audioThumbnailFile)
}
getAudioUploadLabel () {
@@ -206,7 +206,7 @@ export class VideoUploadComponent implements OnInit, OnDestroy, AfterViewInit, C
return this.videoFileInput().nativeElement.files[0]
}
- private uploadFile (file: File, previewfile?: File) {
+ private uploadFile (file: File, thumbnailfile?: File) {
const serverConfig = this.serverService.getHTMLConfig()
this.videoEdit = VideoEdit.createFromUpload(serverConfig, {
@@ -218,7 +218,7 @@ export class VideoUploadComponent implements OnInit, OnDestroy, AfterViewInit, C
this.manageController.setConfig({ manageType: 'upload', serverConfig: this.serverService.getHTMLConfig() })
this.manageController.setVideoEdit(this.videoEdit)
- this.manageController.uploadNewVideo({ privacy: this.highestPrivacy(), file, previewfile })
+ this.manageController.uploadNewVideo({ privacy: this.highestPrivacy(), file, thumbnailfile })
this.manageController.silentRedirectOnUploading(this.route)
this.firstStep = false
diff --git a/client/src/app/+videos-publish-manage/shared-manage/common/thumbnail-manager.component.ts b/client/src/app/+videos-publish-manage/shared-manage/common/thumbnail-manager.component.ts
index c4d9cb5bc9..6f5e21b11f 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/common/thumbnail-manager.component.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/common/thumbnail-manager.component.ts
@@ -164,7 +164,7 @@ export class ThumbnailManagerComponent implements OnInit, ControlValueAccessor {
const blob: Blob = this.dataURItoBlob(dataUrl)
- const file = new File([ blob ], 'preview-file-from-frame.jpg', { type: 'image/jpeg' })
+ const file = new File([ blob ], 'thumbnail-file-from-frame.jpg', { type: 'image/jpeg' })
this.imageFile = file
diff --git a/client/src/app/+videos-publish-manage/shared-manage/common/uploaderx-form-data.ts b/client/src/app/+videos-publish-manage/shared-manage/common/uploaderx-form-data.ts
index 3392a0d8ac..4aa0ecbc91 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/common/uploaderx-form-data.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/common/uploaderx-form-data.ts
@@ -13,20 +13,18 @@ import { resolveUrl, UploaderX } from 'ngx-uploadx'
* };
*/
export class UploaderXFormData extends UploaderX {
-
async getFileUrl (): Promise<string> {
const headers = {
'X-Upload-Content-Length': this.size.toString(),
'X-Upload-Content-Type': this.file.type || 'application/octet-stream'
}
- const previewfile = this.metadata.previewfile as any as File
- delete this.metadata.previewfile
+ const thumbnailfile = this.metadata.thumbnailfile as any as File
+ delete this.metadata.thumbnailfile
const data = objectToFormData(this.metadata)
- if (previewfile !== undefined) {
- data.append('previewfile', previewfile, previewfile.name)
- data.append('thumbnailfile', previewfile, previewfile.name)
+ if (thumbnailfile !== undefined) {
+ data.append('thumbnailfile', thumbnailfile, thumbnailfile.name)
}
await this.request({
diff --git a/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts b/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts
index ce00fe0211..5dba7f7abc 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts
@@ -1,5 +1,5 @@
-import { getOriginUrl } from '@app/helpers'
-import { exists, omit, pick, secondsToTime } from '@peertube/peertube-core-utils'
+import { AuthUser } from '@app/core'
+import { exists, maxBy, omit, pick, secondsToTime } from '@peertube/peertube-core-utils'
import {
HTMLServerConfig,
LiveVideo,
@@ -28,7 +28,6 @@ import debug from 'debug'
import { Jsonify, SharedUnionFieldsDeep } from 'type-fest'
import { VideoCaptionWithPathEdit } from './video-caption-edit.model'
import { VideoChaptersEdit } from './video-chapters-edit.model'
-import { AuthUser } from '@app/core'
const debugLogger = debug('peertube:video-manage:video-edit')
@@ -37,7 +36,7 @@ export type VideoEditPrivacyType = VideoPrivacyType | typeof VideoEdit.SPECIAL_S
type CommonUpdateForm =
& Omit<
VideoUpdate,
- 'privacy' | 'videoPasswords' | 'thumbnailfile' | 'scheduleUpdate' | 'originallyPublishedAt' | 'nsfwFlags'
+ 'privacy' | 'videoPasswords' | 'previewfile' | 'scheduleUpdate' | 'originallyPublishedAt' | 'nsfwFlags'
>
& {
schedulePublicationAt?: Date
@@ -113,7 +112,7 @@ type UpdateFromAPIOptions = {
| 'aspectRatio'
| 'views'
| 'blacklisted'
- | 'previewPath'
+ | 'thumbnails'
| 'state'
| 'isLive'
>
@@ -127,7 +126,7 @@ type UpdateFromAPIOptions = {
// ---------------------------------------------------------------------------
-type CommonUpdate = Omit<VideoUpdate, 'thumbnailfile' | 'originallyPublishedAt' | 'scheduleUpdate'> & {
+type CommonUpdate = Omit<VideoUpdate, 'previewfile' | 'originallyPublishedAt' | 'scheduleUpdate'> & {
originallyPublishedAt?: string
scheduleUpdate?: {
updateAt: string
@@ -196,8 +195,8 @@ export class VideoEdit {
}
private saveStore: {
- common?: Omit<CommonUpdate, 'pluginData' | 'previewfile'>
- previewfile?: { size: number }
+ common?: Omit<CommonUpdate, 'pluginData' | 'thumbnailfile'>
+ thumbnailfile?: { size: number }
live?: LiveUpdate
playerSettings?: PlayerVideoSettings
@@ -334,7 +333,7 @@ export class VideoEdit {
this.metadata.videoSource = videoSource
}
- await this.loadPreview(video)
+ await this.loadThumbnail(video)
this.updateAfterChange()
}
@@ -396,7 +395,7 @@ export class VideoEdit {
if (saveInStore) {
const obj = buildObj({ loadPrivacy: true })
- this.saveStore.common = omit(obj, [ 'pluginData', 'previewfile' ])
+ this.saveStore.common = omit(obj, [ 'pluginData', 'thumbnailfile' ])
// Apply plugin defaults so we correctly detect changes
const pluginDefaults = this.saveStore.pluginDefaults || {}
@@ -430,16 +429,18 @@ export class VideoEdit {
}
}
- private async loadPreview (video: UpdateFromAPIOptions['video']) {
- if (!video?.previewPath) return
+ private async loadThumbnail (video: UpdateFromAPIOptions['video']) {
+ if (!video?.thumbnails || video.thumbnails.length === 0) return
+
+ const bestThumbnail = maxBy(video.thumbnails, 'width')
try {
- const response = await fetch(getOriginUrl() + video.previewPath)
+ const response = await fetch(bestThumbnail.fileUrl)
- this.common.previewfile = await response.blob()
- this.saveStore.previewfile = { size: this.common.previewfile.size }
+ this.common.thumbnailfile = await response.blob()
+ this.saveStore.thumbnailfile = { size: this.common.thumbnailfile.size }
} catch (err) {
- logger.error('Failed to fetch video preview', err)
+ logger.error('Failed to fetch video thumbnail', err)
}
}
@@ -507,7 +508,7 @@ export class VideoEdit {
if (values.support !== undefined) this.common.support = values.support
if (values.commentsPolicy !== undefined) this.common.commentsPolicy = values.commentsPolicy
if (values.downloadEnabled !== undefined) this.common.downloadEnabled = values.downloadEnabled
- if (values.previewfile !== undefined) this.common.previewfile = values.previewfile
+ if (values.thumbnailfile !== undefined) this.common.thumbnailfile = values.thumbnailfile
if (values.pluginData !== undefined) this.common.pluginData = values.pluginData
// ---------------------------------------------------------------------------
@@ -597,7 +598,7 @@ export class VideoEdit {
pluginData: this.common.pluginData,
- previewfile: this.common.previewfile,
+ thumbnailfile: this.common.thumbnailfile,
videoPassword: this.common.videoPasswords && this.common.videoPasswords.length !== 0
? this.common.videoPasswords[0]
@@ -623,7 +624,7 @@ export class VideoEdit {
return json
}
- toVideoUpdate (): Required<VideoUpdate> {
+ toVideoUpdate (): Required<Omit<VideoUpdate, 'previewfile'>> {
return {
...this.toVideoCreateOrUpdate(),
@@ -631,7 +632,7 @@ export class VideoEdit {
}
}
- toVideoCreate (overriddenPrivacy: VideoPrivacyType): Required<Omit<VideoCreate, 'generateTranscription'>> {
+ toVideoCreate (overriddenPrivacy: VideoPrivacyType): Required<Omit<VideoCreate, 'generateTranscription' | 'previewfile'>> {
return {
...this.toVideoCreateOrUpdate(),
@@ -639,7 +640,7 @@ export class VideoEdit {
}
}
- private toVideoCreateOrUpdate (): Required<SharedUnionFieldsDeep<VideoCreate | VideoUpdate>> {
+ private toVideoCreateOrUpdate (): Required<SharedUnionFieldsDeep<Omit<VideoCreate | VideoUpdate, 'previewfile'>>> {
return {
name: this.common.name,
category: this.common.category || null,
@@ -661,8 +662,7 @@ export class VideoEdit {
waitTranscoding: this.common.waitTranscoding,
commentsPolicy: this.common.commentsPolicy,
downloadEnabled: this.common.downloadEnabled,
- thumbnailfile: this.common.previewfile,
- previewfile: this.common.previewfile,
+ thumbnailfile: this.common.thumbnailfile,
scheduleUpdate: this.common.scheduleUpdate || null,
originallyPublishedAt: this.common.originallyPublishedAt || null
}
@@ -923,18 +923,18 @@ export class VideoEdit {
if (this.isNewVideo) return true
if (!this.saveStore.common) return true
- let changes = !this.areSameObjects(omit(this.common, [ 'previewfile', 'pluginData' ]), this.saveStore.common)
+ let changes = !this.areSameObjects(omit(this.common, [ 'thumbnailfile', 'pluginData' ]), this.saveStore.common)
- // Compare preview file
- if (changes !== true && (this.common.previewfile || this.saveStore.previewfile)) {
- changes = this.common.previewfile?.size !== this.saveStore.previewfile?.size
+ // Compare thumbnails
+ if (changes !== true && (this.common.thumbnailfile || this.saveStore.thumbnailfile)) {
+ changes = this.common.thumbnailfile?.size !== this.saveStore.thumbnailfile?.size
}
debugLogger('Check if has common changes', {
changes,
common: this.common,
saveCommon: this.saveStore.common,
- savePreview: this.saveStore.previewfile
+ saveThumbnail: this.saveStore.thumbnailfile
})
return changes
diff --git a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.html b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.html
index 37038e2849..c356487698 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.html
+++ b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.html
@@ -111,9 +111,9 @@
</div>
<div class="form-group">
- <label i18n for="previewfile">Thumbnail</label>
+ <label i18n for="thumbnailfile">Thumbnail</label>
- <my-thumbnail-manager id="previewfile" formControlName="previewfile" [videoEdit]="videoEdit"></my-thumbnail-manager>
+ <my-thumbnail-manager id="thumbnailfile" formControlName="thumbnailfile" [videoEdit]="videoEdit"></my-thumbnail-manager>
</div>
<div class="form-group">
diff --git a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.ts b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.ts
index 56be65b5d9..9bfd5c3150 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/main-info/video-main-info.component.ts
@@ -73,7 +73,7 @@ type Form = {
language: FormControl<string>
description: FormControl<string>
tags: FormArray<FormControl<string>>
- previewfile: FormControl<Blob>
+ thumbnailfile: FormControl<Blob>
support: FormControl<string>
schedulePublicationAt: FormControl<Date>
pluginData: FormGroup
@@ -287,7 +287,7 @@ export class VideoMainInfoComponent implements OnInit, OnDestroy {
language: VIDEO_LANGUAGE_VALIDATOR,
description: VIDEO_DESCRIPTION_VALIDATOR,
tags: VIDEO_TAGS_ARRAY_VALIDATOR,
- previewfile: null,
+ thumbnailfile: null,
support: VIDEO_SUPPORT_VALIDATOR,
schedulePublicationAt: VIDEO_SCHEDULE_PUBLICATION_AT_VALIDATOR
}
diff --git a/client/src/app/+videos-publish-manage/shared-manage/video-manage-controller.service.ts b/client/src/app/+videos-publish-manage/shared-manage/video-manage-controller.service.ts
index 4dcef4e15e..075576b3a1 100644
--- a/client/src/app/+videos-publish-manage/shared-manage/video-manage-controller.service.ts
+++ b/client/src/app/+videos-publish-manage/shared-manage/video-manage-controller.service.ts
@@ -446,7 +446,7 @@ export class VideoManageController implements OnDestroy {
uploadNewVideo (options: {
file: File
privacy: VideoPrivacyType
- previewfile?: File
+ thumbnailfile?: File
}) {
this.resetUploadState()
@@ -457,7 +457,7 @@ export class VideoManageController implements OnDestroy {
...this.videoEdit.toVideoCreate(options.privacy),
filename: options.file.name,
- previewfile: options.previewfile
+ thumbnailfile: options.thumbnailfile
}
this.resumableUploadService.handleFiles(options.file, {
diff --git a/client/src/app/shared/form-validators/custom-config-validators.ts b/client/src/app/shared/form-validators/custom-config-validators.ts
index 3ba8e74060..f1d277e893 100644
--- a/client/src/app/shared/form-validators/custom-config-validators.ts
+++ b/client/src/app/shared/form-validators/custom-config-validators.ts
@@ -22,15 +22,6 @@ export const SERVICES_TWITTER_USERNAME_VALIDATOR: BuildFormValidator = {
}
}
-export const CACHE_SIZE_VALIDATOR: BuildFormValidator = {
- VALIDATORS: [ Validators.required, Validators.min(1), Validators.pattern('[0-9]+') ],
- MESSAGES: {
- required: $localize`Cache size is required.`,
- min: $localize`Cache size must be greater than 1.`,
- pattern: $localize`Cache size must be a number.`
- }
-}
-
export const SIGNUP_LIMIT_VALIDATOR: BuildFormValidator = {
VALIDATORS: [ Validators.required, Validators.min(-1), Validators.pattern('-?[0-9]+') ],
MESSAGES: {
diff --git a/client/src/app/shared/shared-actor-image/actor-avatar.component.ts b/client/src/app/shared/shared-actor-image/actor-avatar.component.ts
index 746333c661..e68c0a867b 100644
--- a/client/src/app/shared/shared-actor-image/actor-avatar.component.ts
+++ b/client/src/app/shared/shared-actor-image/actor-avatar.component.ts
@@ -3,8 +3,8 @@ import { Component, ElementRef, OnChanges, OnInit, booleanAttribute, inject, inp
import { RouterLink } from '@angular/router'
import { objectKeysTyped } from '@peertube/peertube-core-utils'
import { ActorImage } from '@peertube/peertube-models'
+import { findAppropriateImageFileUrl } from '@root-helpers/images'
import { Account } from '../shared-main/account/account.model'
-import { Actor } from '../shared-main/account/actor.model'
import { VideoChannel } from '../shared-main/channel/video-channel.model'
export type ActorAvatarInput = {
@@ -119,7 +119,7 @@ export class ActorAvatarComponent implements OnInit, OnChanges {
}
if (this.isAccount() || this.isChannel() || this.isInstance()) {
- this.avatarUrl = Actor.GET_ACTOR_AVATAR_URL(actor, this.getSizeNumber())
+ this.avatarUrl = findAppropriateImageFileUrl(actor.avatars, this.getSizeNumber())
return
}
diff --git a/client/src/app/shared/shared-main/account/actor.model.ts b/client/src/app/shared/shared-main/account/actor.model.ts
index fbaf0c0e33..64eb0d0962 100644
--- a/client/src/app/shared/shared-main/account/actor.model.ts
+++ b/client/src/app/shared/shared-main/account/actor.model.ts
@@ -17,18 +17,6 @@ export abstract class Actor implements ServerActor {
isLocal: boolean
- static GET_ACTOR_AVATAR_URL (actor: { avatars: Pick<ActorImage, 'width' | 'fileUrl'>[] }, size?: number) {
- const avatarsAscWidth = actor.avatars.sort((a, b) => a.width - b.width)
-
- const avatar = size && avatarsAscWidth.length > 1
- ? avatarsAscWidth.find(a => a.width >= size)
- : avatarsAscWidth[avatarsAscWidth.length - 1] // Biggest one
-
- if (!avatar) return ''
-
- return avatar.fileUrl
- }
-
static CREATE_BY_STRING (accountName: string, host: string, forceHostname = false) {
const thisHost = getBackendHost()
diff --git a/client/src/app/shared/shared-main/video/video.model.ts b/client/src/app/shared/shared-main/video/video.model.ts
index 346dd2cd77..215a19a601 100644
--- a/client/src/app/shared/shared-main/video/video.model.ts
+++ b/client/src/app/shared/shared-main/video/video.model.ts
@@ -1,11 +1,12 @@
import { AuthUser } from '@app/core'
import { User } from '@app/core/users/user.model'
-import { durationToString, getAPIUrl, getOriginUrl } from '@app/helpers'
+import { durationToString, getOriginUrl } from '@app/helpers'
import { Actor } from '@app/shared/shared-main/account/actor.model'
import { buildVideoWatchPath, getAllFiles, peertubeTranslate } from '@peertube/peertube-core-utils'
import {
ActorImage,
HTMLServerConfig,
+ Thumbnail,
UserRight,
VideoConstant,
VideoFile,
@@ -49,17 +50,18 @@ export class Video implements VideoServerModel {
name: string
serverHost: string
+
thumbnailPath: string
thumbnailUrl: string
+ previewPath: string
+ previewUrl: string
+ thumbnails: Thumbnail[]
aspectRatio: number
isLive: boolean
liveSchedules: { startAt: Date | string }[]
- previewPath: string
- previewUrl: string
-
embedPath: string
embedUrl: string
@@ -153,6 +155,8 @@ export class Video implements VideoServerModel {
? hash.liveSchedules.map(schedule => ({ startAt: new Date(schedule.startAt.toString()) }))
: null
+ this.thumbnails = hash.thumbnails
+
this.duration = hash.duration
this.durationLabel = Video.buildDurationLabel(this)
@@ -163,16 +167,6 @@ export class Video implements VideoServerModel {
this.isLocal = hash.isLocal
this.name = hash.name
- this.thumbnailPath = hash.thumbnailPath
- this.thumbnailUrl = this.thumbnailPath
- ? hash.thumbnailUrl || (getAPIUrl() + hash.thumbnailPath)
- : null
-
- this.previewPath = hash.previewPath
- this.previewUrl = this.previewPath
- ? hash.previewUrl || (getAPIUrl() + hash.previewPath)
- : null
-
this.embedPath = hash.embedPath
this.embedUrl = hash.embedUrl || (getOriginUrl() + hash.embedPath)
diff --git a/client/src/app/shared/shared-tables/video-cell.component.scss b/client/src/app/shared/shared-tables/video-cell.component.scss
index c67a7ba2ad..eac9c796ac 100644
--- a/client/src/app/shared/shared-tables/video-cell.component.scss
+++ b/client/src/app/shared/shared-tables/video-cell.component.scss
@@ -3,8 +3,13 @@
@use "_mixins" as *;
@use "_miniature" as *;
+@function getWidth($height) {
+ @return math.div(16, 9) * $height;
+}
+
.root {
--co-image-height: 78px;
+ --co-image-width: #{getWidth(78px)};
display: flex;
align-items: center;
@@ -12,17 +17,19 @@
@media screen and (max-width: $mobile-view) {
--co-image-height: 64px;
+ --co-image-width: #{getWidth(64px)};
}
&.small {
--co-image-height: 45px;
+ --co-image-width: #{getWidth(45px)};
}
}
my-video-thumbnail {
display: block;
height: var(--co-image-height);
- width: calc(#{math.div(16, 9)} * var(--co-image-height));
+ width: var(--co-image-width);
& + .name {
@include margin-left(0.5rem);
diff --git a/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts b/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts
index 28b3ce0096..d66395a652 100644
--- a/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts
+++ b/client/src/app/shared/shared-thumbnail/video-thumbnail.component.ts
@@ -1,13 +1,12 @@
import { CommonModule } from '@angular/common'
-import { booleanAttribute, Component, inject, input, OnChanges, output, viewChild } from '@angular/core'
+import { booleanAttribute, Component, ElementRef, inject, input, OnChanges, output, viewChild } from '@angular/core'
import { RouterLink } from '@angular/router'
-import { ScreenService } from '@app/core'
-import { getAPIUrl } from '@app/helpers'
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'
import { Video as VideoServerModel, VideoState } from '@peertube/peertube-models'
+import { findAppropriateImageFileUrl } from '@root-helpers/images'
import { GlobalIconComponent } from '../shared-icons/global-icon.component'
-import { Video } from '../shared-main/video/video.model'
import { FromNowPipe } from '../shared-main/date/from-now.pipe'
+import { Video } from '../shared-main/video/video.model'
export type VideoThumbnailInput = Pick<
VideoServerModel,
@@ -17,10 +16,7 @@ export type VideoThumbnailInput = Pick<
| 'shortUUID'
| 'isLive'
| 'state'
- | 'previewPath'
- | 'previewUrl'
- | 'thumbnailPath'
- | 'thumbnailUrl'
+ | 'thumbnails'
| 'userHistory'
| 'originallyPublishedAt'
| 'liveSchedules'
@@ -33,7 +29,7 @@ export type VideoThumbnailInput = Pick<
imports: [ CommonModule, RouterLink, NgbTooltip, GlobalIconComponent, FromNowPipe ]
})
export class VideoThumbnailComponent implements OnChanges {
- private screenService = inject(ScreenService)
+ private el = inject(ElementRef)
readonly video = input.required<VideoThumbnailInput>()
@@ -103,11 +99,15 @@ export class VideoThumbnailComponent implements OnChanges {
const video = this.video()
if (!video) return ''
- if (this.screenService.isInMobileView()) {
- return video.previewUrl || getAPIUrl() + video.previewPath
- }
+ const computedStyle = window.getComputedStyle(this.el.nativeElement)
+
+ const cssVariable = computedStyle.getPropertyValue('--co-miniature-max-width') ||
+ computedStyle.getPropertyValue('--co-row-thumbnail-width') ||
+ computedStyle.getPropertyValue('--co-image-width')
+
+ const widthStr = cssVariable.replace('px', '').trim()
- return video.thumbnailUrl || getAPIUrl() + video.thumbnailPath
+ return findAppropriateImageFileUrl(video.thumbnails, +widthStr)
}
getProgressPercent () {
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.scss b/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.scss
index 188ec7667c..ba18b56fbf 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.scss
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-element-miniature.component.scss
@@ -1,21 +1,26 @@
-@use '_variables' as *;
-@use '_mixins' as *;
-@use '_miniature' as *;
+@use "_variables" as *;
+@use "_mixins" as *;
+@use "_miniature" as *;
$thumbnail-width: 130px;
$thumbnail-height: 72px;
+.video {
+ --co-miniature-width: #{$thumbnail-width};
+ --co-miniature-height: #{$thumbnail-height};
+}
+
my-timestamp-input {
width: 100px;
}
my-video-thumbnail {
- @include thumbnail-size-component($thumbnail-width, $thumbnail-height);
+ @include thumbnail-size-component(var(--co-miniature-width), var(--co-miniature-height));
}
.fake-thumbnail {
- width: $thumbnail-width;
- height: $thumbnail-height;
+ width: var(--co-miniature-width);
+ height: var(--co-miniature-height);
background-color: #ececec;
}
@@ -151,7 +156,6 @@ my-video-thumbnail,
}
.dropdown-menu {
-
.dropdown-item {
cursor: pointer;
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html
index dcad8009af..51ebb7b100 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.html
@@ -3,7 +3,7 @@
[internalLink]="playlistRouterLink" [href]="playlistHref" [target]="playlistTarget" inheritParentStyle="true" inheritParentDimension="true"
[title]="playlist().displayName" class="miniature-thumbnail" tabindex="-1"
>
- <img alt="" [attr.aria-label]="playlist().displayName" [attr.src]="playlist().thumbnailUrl" />
+ <img alt="" [attr.aria-label]="playlist().displayName" [attr.src]="getPlaylistThumbnailUrl()" />
<div class="miniature-playlist-info-overlay">
<ng-container i18n>{playlist().videosLength, plural, =0 {No videos} =1 {1 video} other {{{ playlist().videosLength }} videos}}</ng-container>
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scss b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scss
index b8ba0c5205..687e6582f4 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scss
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scss
@@ -93,6 +93,7 @@
}
.miniature.display-as-row {
+ // Keep it sync with image size requested by the component
--co-row-thumbnail-width: #{$video-thumbnail-width};
--co-row-thumbnail-height: #{$video-thumbnail-height};
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts
index bcc5892f52..13a6e980f6 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts
+++ b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.ts
@@ -98,4 +98,9 @@ export class VideoPlaylistMiniatureComponent implements OnInit {
this.ownerRouterLink = [ '/search/lazy-load-channel', { url: playlist.videoChannel.url } ]
return
}
+
+ getPlaylistThumbnailUrl () {
+ // Keep it sync with image size requested by the SASS file
+ return this.playlist().getThumbnailUrl(280)
+ }
}
diff --git a/client/src/app/shared/shared-video-playlist/video-playlist.model.ts b/client/src/app/shared/shared-video-playlist/video-playlist.model.ts
index 602b1efa19..686e658281 100644
--- a/client/src/app/shared/shared-video-playlist/video-playlist.model.ts
+++ b/client/src/app/shared/shared-video-playlist/video-playlist.model.ts
@@ -3,12 +3,14 @@ import { buildPlaylistWatchPath, peertubeTranslate } from '@peertube/peertube-co
import {
AccountSummary,
VideoPlaylist as ServerVideoPlaylist,
+ Thumbnail,
VideoChannelSummary,
VideoConstant,
VideoPlaylistPrivacyType,
VideoPlaylistType,
VideoPlaylistType_Type
} from '@peertube/peertube-models'
+import { findAppropriateImageFileUrl } from '@root-helpers/images'
import { Actor } from '../shared-main/account/actor.model'
export class VideoPlaylist implements ServerVideoPlaylist {
@@ -36,6 +38,8 @@ export class VideoPlaylist implements ServerVideoPlaylist {
videoChannelPosition: number
videoChannel?: VideoChannelSummary
+ thumbnails: Thumbnail[]
+
thumbnailPath: string
thumbnailUrl: string
@@ -63,12 +67,6 @@ export class VideoPlaylist implements ServerVideoPlaylist {
this.description = hash.description
this.privacy = hash.privacy
- this.thumbnailPath = hash.thumbnailPath
-
- this.thumbnailUrl = this.thumbnailPath
- ? hash.thumbnailUrl || (getAPIUrl() + hash.thumbnailPath)
- : getAPIUrl() + '/client/assets/images/default-playlist.jpg'
-
this.embedPath = hash.embedPath
this.embedUrl = hash.embedUrl || (getOriginUrl() + hash.embedPath)
@@ -95,4 +93,10 @@ export class VideoPlaylist implements ServerVideoPlaylist {
this.displayName = peertubeTranslate(this.displayName, translations)
}
}
+
+ getThumbnailUrl (width: number) {
+ const defaultUrl = getAPIUrl() + '/client/assets/images/default-playlist.jpg'
+
+ return findAppropriateImageFileUrl(this.thumbnails, width) || defaultUrl
+ }
}
diff --git a/client/src/root-helpers/images.ts b/client/src/root-helpers/images.ts
index c4b09ec3cf..adf378483a 100644
--- a/client/src/root-helpers/images.ts
+++ b/client/src/root-helpers/images.ts
@@ -1,6 +1,7 @@
+import { findAppropriateImage } from '@peertube/peertube-core-utils'
import { logger } from './logger'
-function imageToDataURL (input: File | Blob) {
+export function imageToDataURL (input: File | Blob) {
return new Promise<string>(res => {
const reader = new FileReader()
@@ -10,6 +11,6 @@ function imageToDataURL (input: File | Blob) {
})
}
-export {
- imageToDataURL
+export function findAppropriateImageFileUrl<T extends { width: number, fileUrl: string }> (images: T[], width: number) {
+ return findAppropriateImage(images, width)?.fileUrl || ''
}
diff --git a/client/src/standalone/player/src/peertube-player.ts b/client/src/standalone/player/src/peertube-player.ts
index c34610434d..538c285f0a 100644
--- a/client/src/standalone/player/src/peertube-player.ts
+++ b/client/src/standalone/player/src/peertube-player.ts
@@ -1,4 +1,5 @@
-import { buildVideoLink, decorateVideoLink, isDefaultLocale, pick } from '@peertube/peertube-core-utils'
+import { buildVideoLink, decorateVideoLink, findAppropriateImage, isDefaultLocale, pick } from '@peertube/peertube-core-utils'
+import { Thumbnail } from '@peertube/peertube-models'
import { logger } from '@root-helpers/logger'
import { PluginsManager } from '@root-helpers/plugins-manager'
import { TranslationsManager } from '@root-helpers/translations-manager'
@@ -101,7 +102,7 @@ export class PeerTubePlayer {
async load (loadOptions: PeerTubePlayerLoadOptions) {
this.currentLoadOptions = loadOptions
- this.setPoster('')
+ this.setPoster([])
this.disposeDynamicPluginsIfNeeded()
@@ -130,7 +131,7 @@ export class PeerTubePlayer {
this.player.autoplay(this.getAutoPlayValue(this.currentLoadOptions.autoplay))
if (!this.player.autoplay()) {
- this.setPoster(loadOptions.poster)
+ this.setPoster(loadOptions.thumbnails)
}
this.player.trigger('video-change')
@@ -144,15 +145,20 @@ export class PeerTubePlayer {
if (this.player) this.player.dispose()
}
- setPoster (url: string) {
+ setPoster (thumbnails: Thumbnail[]) {
// Use HTML video element to display poster
if (!this.player) {
- this.options.playerElement().poster = url
+ const playerEl = this.options.playerElement()
+
+ this.options.playerElement().poster = findAppropriateImage(thumbnails, playerEl.clientWidth || window.innerWidth)?.fileUrl || ''
return
}
// Prefer using player poster API
- this.player?.poster(url)
+ if (this.player) {
+ this.player.poster(findAppropriateImage(thumbnails, this.player.currentWidth())?.fileUrl || '')
+ }
+
this.options.playerElement().poster = ''
}
@@ -384,7 +390,10 @@ export class PeerTubePlayer {
})
}
- getVideojsOptions (): VideojsPlayerOptions {
+ private getVideojsOptions (): VideojsPlayerOptions {
+ const poster =
+ findAppropriateImage(this.currentLoadOptions.thumbnails, this.options.playerElement().clientWidth || window.innerWidth)?.fileUrl || ''
+
const html5 = {
preloadTextTracks: false,
// Prevent a bug on iOS where the text tracks added by peertube plugin are removed on play
@@ -413,7 +422,7 @@ export class PeerTubePlayer {
videoRatio: () => this.currentLoadOptions.videoRatio,
- poster: () => this.currentLoadOptions.poster,
+ poster: () => poster,
autoPlayerRatio: this.options.autoPlayerRatio
},
@@ -450,7 +459,7 @@ export class PeerTubePlayer {
autoplay: this.getAutoPlayValue(this.currentLoadOptions.autoplay),
- poster: this.currentLoadOptions.poster,
+ poster,
preload: 'none' as 'none',
inactivityTimeout: this.options.inactivityTimeout,
diff --git a/client/src/standalone/player/src/sass/shared/playlist.scss b/client/src/standalone/player/src/sass/shared/playlist.scss
index 0a22dc4cb4..985149869e 100644
--- a/client/src/standalone/player/src/sass/shared/playlist.scss
+++ b/client/src/standalone/player/src/sass/shared/playlist.scss
@@ -161,7 +161,7 @@ $playlist-menu-width: 350px;
}
img {
- width: 80px;
+ width: 80px; // Keep in sync with TS in "playlist-menu-item.ts"
height: 40px;
}
diff --git a/client/src/standalone/player/src/shared/playlist/playlist-menu-item.ts b/client/src/standalone/player/src/shared/playlist/playlist-menu-item.ts
index b159dae7c5..c32d75c558 100644
--- a/client/src/standalone/player/src/shared/playlist/playlist-menu-item.ts
+++ b/client/src/standalone/player/src/shared/playlist/playlist-menu-item.ts
@@ -1,4 +1,4 @@
-import { secondsToTime } from '@peertube/peertube-core-utils'
+import { findAppropriateImage, secondsToTime } from '@peertube/peertube-core-utils'
import { VideoPlaylistElement } from '@peertube/peertube-models'
import videojs from 'video.js'
import { PlaylistItemOptions, VideojsComponent, VideojsComponentOptions, VideojsPlayer } from '../../types'
@@ -83,7 +83,9 @@ class PlaylistMenuItem extends Component {
positionBlock.appendChild(player)
const thumbnail = super.createEl('img', {
- src: window.location.origin + videoElement.video.thumbnailPath
+ src: videoElement.video.thumbnails.length !== 0
+ ? window.location.origin + findAppropriateImage(videoElement.video.thumbnails, 80).fileUrl // Keep 80 in sync with CSS
+ : ''
})
const infoBlock = super.createEl('div', {
diff --git a/client/src/standalone/player/src/types/peertube-player-options.ts b/client/src/standalone/player/src/types/peertube-player-options.ts
index ba2c7263bf..c02168e50b 100644
--- a/client/src/standalone/player/src/types/peertube-player-options.ts
+++ b/client/src/standalone/player/src/types/peertube-player-options.ts
@@ -1,4 +1,4 @@
-import { LiveVideoLatencyModeType, PlayerMode, PlayerTheme, VideoChapter, VideoFile } from '@peertube/peertube-models'
+import { LiveVideoLatencyModeType, PlayerMode, PlayerTheme, Thumbnail, VideoChapter, VideoFile } from '@peertube/peertube-models'
import { PluginsManager } from '@root-helpers/plugins-manager'
import { PeerTubeDockPluginOptions } from '../shared/dock/peertube-dock-plugin'
import { PlaylistPluginOptions, VideoJSCaption, VideojsPlayer, VideoJSStoryboard } from './peertube-videojs-typings'
@@ -58,7 +58,8 @@ export type PeerTubePlayerLoadOptions = {
autoplay: boolean
forceAutoplay: boolean
- poster: string
+ thumbnails: Thumbnail[]
+
subtitle?: string
videoViewUrl: string
diff --git a/client/src/standalone/videos/embed.ts b/client/src/standalone/videos/embed.ts
index fc9d692774..568e10316d 100644
--- a/client/src/standalone/videos/embed.ts
+++ b/client/src/standalone/videos/embed.ts
@@ -399,7 +399,7 @@ export class PeerTubeEmbed {
this.peertubePlayer.unload()
this.peertubePlayer.disable()
- this.peertubePlayer.setPoster(video.previewPath)
+ this.peertubePlayer.setPoster(video.thumbnails)
}
private async handlePasswordError (err: PeerTubeServerError) {
diff --git a/client/src/standalone/videos/shared/player-options-builder.ts b/client/src/standalone/videos/shared/player-options-builder.ts
index ec44128530..8f7130e908 100644
--- a/client/src/standalone/videos/shared/player-options-builder.ts
+++ b/client/src/standalone/videos/shared/player-options-builder.ts
@@ -318,9 +318,9 @@ export class PlayerOptionsBuilder {
}
: undefined,
- poster: nsfwBlur
+ thumbnails: nsfwBlur
? null
- : getBackendUrl() + video.previewPath,
+ : video.thumbnails,
duration: video.duration,
videoRatio: video.aspectRatio,
diff --git a/config/default.yaml b/config/default.yaml
index b3be3bc3bc..9305794231 100644
--- a/config/default.yaml
+++ b/config/default.yaml
@@ -481,9 +481,6 @@ thumbnails:
# Minimum value is 2
frames_to_analyze: 50
- # Only two sizes are currently supported for now (not less, not more)
- # 1 size for the thumbnail (displayed in video miniatures)
- # 1 size for the preview (displayed in the video player)
sizes:
-
width: 280
@@ -528,16 +525,6 @@ download_generate_video:
# The ffmpeg process ends when users have downloaded the entire file or cancelled the download
max_parallel_downloads: 100
-cache:
- previews:
- size: 500 # Max number of previews you want to cache
- captions:
- size: 500 # Max number of video captions/subtitles you want to cache
- torrents:
- size: 500 # Max number of video torrents you want to cache
- storyboards:
- size: 500 # Max number of video storyboards you want to cache
-
admin:
# Used to generate the root user at first startup
# And to receive emails from the contact form
diff --git a/config/production.yaml.example b/config/production.yaml.example
index 273d745f07..c23d1ea9fa 100644
--- a/config/production.yaml.example
+++ b/config/production.yaml.example
@@ -479,9 +479,6 @@ thumbnails:
# Minimum value is 2
frames_to_analyze: 50
- # Only two sizes are currently supported for now (not less, not more)
- # 1 size for the thumbnail (displayed in video miniatures)
- # 1 size for the preview (displayed in the video player)
sizes:
-
width: 280
@@ -538,16 +535,6 @@ download_generate_video:
#
###############################################################################
-cache:
- previews:
- size: 500 # Max number of previews you want to cache
- captions:
- size: 500 # Max number of video captions/subtitles you want to cache
- torrents:
- size: 500 # Max number of video torrents you want to cache
- storyboards:
- size: 500 # Max number of video storyboards you want to cache
-
admin:
# Used to generate the root user at first startup
# And to receive emails from the contact form
diff --git a/package.json b/package.json
index a24c7316d8..f683adcbe4 100644
--- a/package.json
+++ b/package.json
@@ -79,8 +79,7 @@
"test": "bash ./scripts/test.sh",
"tsc": "tsc",
"tsx": "tsx",
- "update-host": "node ./dist/scripts/update-host.js",
- "update-object-storage-url": "LOGGER_LEVEL=warn node ./dist/scripts/update-object-storage-url.js"
+ "update-host": "node ./dist/scripts/update-host.js"
},
"resolutions": {
"@types/express": "4.17.9",
@@ -94,7 +93,6 @@
"@aws-sdk/lib-storage": "^3.930.0",
"@aws-sdk/s3-request-presigner": "^3.930.0",
"@commander-js/extra-typings": "^14.0.0",
- "@jimp/plugin-color": "^1.6.0",
"@misskey-dev/node-http-message-signatures": "^0.0.10",
"@node-oauth/oauth2-server": "^5.2.1",
"@opentelemetry/api": "^1.9.0",
@@ -160,7 +158,6 @@
"ip-anonymize": "^0.1.0",
"ipaddr.js": "2.2.0",
"iso-639-3": "3.0.1",
- "jimp": "^0.22.12",
"js-yaml": "^4.1.1",
"jsonld": "~8.3.3",
"jsonwebtoken": "^9.0.3",
@@ -191,6 +188,7 @@
"sanitize-html": "~2.17.0",
"sequelize": "~6.37.7",
"sequelize-typescript": "^2.1.6",
+ "sharp": "^0.34.5",
"short-uuid": "^5.2.0",
"sitemap": "^9.0.0",
"socket.io": "^4.8.1",
@@ -251,12 +249,10 @@
"eslint-config-love": "^133.0.0",
"fast-xml-parser": "^5.3.1",
"i18next-parser": "^9.3.0",
- "jpeg-js": "^0.4.4",
"jszip": "^3.10.1",
"maildev": "^2.2.1",
"mocha": "^11.7.5",
"pixelmatch": "^7.1.0",
- "pngjs": "^7.0.0",
"proxy": "^2.2.0",
"rollup": "^4.53.2",
"rollup-plugin-dts": "^6.2.3",
diff --git a/packages/core-utils/src/common/array.ts b/packages/core-utils/src/common/array.ts
index 68152d4334..8699b92db6 100644
--- a/packages/core-utils/src/common/array.ts
+++ b/packages/core-utils/src/common/array.ts
@@ -37,7 +37,6 @@ export function shuffle<T> (elements: T[]) {
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
-
;[ shuffled[i], shuffled[j] ] = [ shuffled[j], shuffled[i] ]
}
@@ -45,7 +44,7 @@ export function shuffle<T> (elements: T[]) {
}
export function sortBy<T> (obj: T[], key1: string, key2?: string): T[] {
- return obj.sort((a, b) => {
+ return [ ...obj ].sort((a, b) => {
const elem1 = key2 ? a[key1][key2] : a[key1]
const elem2 = key2 ? b[key1][key2] : b[key1]
diff --git a/packages/core-utils/src/common/image.ts b/packages/core-utils/src/common/image.ts
index ef833af278..831f9e11dd 100644
--- a/packages/core-utils/src/common/image.ts
+++ b/packages/core-utils/src/common/image.ts
@@ -1,13 +1,14 @@
-export function findAppropriateImage<T extends { width: number, height: number }> (images: T[], wantedWidth: number) {
+export function findAppropriateImage<T extends { width: number }> (images: T[], wantedWidth: number) {
+ if (!wantedWidth) throw new Error('Invalid width to find appropriate image')
if (!images || images.length === 0) return undefined
- const imagesSorted = images.sort((a, b) => a.width - b.width)
+ let candidate: T
- for (const image of imagesSorted) {
- if (image.width >= wantedWidth) {
- return image
+ for (const img of images) {
+ if (img.width >= wantedWidth && (!candidate || img.width < candidate.width)) {
+ candidate = img
}
}
- return images[images.length - 1] // Biggest one
+ return candidate || images[0]
}
diff --git a/packages/ffmpeg/src/ffmpeg-images.ts b/packages/ffmpeg/src/ffmpeg-images.ts
index 77c780bde6..d4c5922c42 100644
--- a/packages/ffmpeg/src/ffmpeg-images.ts
+++ b/packages/ffmpeg/src/ffmpeg-images.ts
@@ -10,22 +10,6 @@ export class FFmpegImage {
this.commandWrapper = new FFmpegCommandWrapper(options)
}
- processImage (options: {
- path: string
- destination: string
- newSize?: { width: number, height: number }
- }): Promise<void> {
- const { path, destination, newSize } = options
-
- const command = this.commandWrapper.buildCommand(path)
-
- if (newSize) command.size(`${newSize.width ?? '?'}x${newSize.height ?? '?'}`)
-
- command.output(destination)
-
- return this.commandWrapper.runCommand({ silent: true })
- }
-
// ---------------------------------------------------------------------------
async generateThumbnailFromVideo (options: {
diff --git a/packages/models/src/import-export/peertube-export-format/account-export.model.ts b/packages/models/src/import-export/peertube-export-format/account-export.model.ts
index 3b06a3c708..e17d7aab16 100644
--- a/packages/models/src/import-export/peertube-export-format/account-export.model.ts
+++ b/packages/models/src/import-export/peertube-export-format/account-export.model.ts
@@ -1,4 +1,4 @@
-import { UserActorImageJSON } from './actor-export.model.js'
+import { ImageExportJSON } from './image-export.model.js'
export interface AccountExportJSON {
url: string
@@ -10,7 +10,7 @@ export interface AccountExportJSON {
updatedAt: string
createdAt: string
- avatars: UserActorImageJSON[]
+ avatars: ImageExportJSON[]
archiveFiles: {
avatar: string | null
diff --git a/packages/models/src/import-export/peertube-export-format/channel-export.model.ts b/packages/models/src/import-export/peertube-export-format/channel-export.model.ts
index d5a3ebfc07..46eaa3d00b 100644
--- a/packages/models/src/import-export/peertube-export-format/channel-export.model.ts
+++ b/packages/models/src/import-export/peertube-export-format/channel-export.model.ts
@@ -1,5 +1,5 @@
import { PlayerThemeChannelSetting } from '../../player/player-theme.type.js'
-import { UserActorImageJSON } from './actor-export.model.js'
+import { ImageExportJSON } from './image-export.model.js'
export interface ChannelExportJSON {
channels: {
@@ -13,8 +13,8 @@ export interface ChannelExportJSON {
updatedAt: string
createdAt: string
- avatars: UserActorImageJSON[]
- banners: UserActorImageJSON[]
+ avatars: ImageExportJSON[]
+ banners: ImageExportJSON[]
playerSettings?: {
theme: PlayerThemeChannelSetting
diff --git a/packages/models/src/import-export/peertube-export-format/actor-export.model.ts b/packages/models/src/import-export/peertube-export-format/image-export.model.ts
similarity index 58%
rename from packages/models/src/import-export/peertube-export-format/actor-export.model.ts
rename to packages/models/src/import-export/peertube-export-format/image-export.model.ts
index e88be7132e..6f6f13f5ae 100644
--- a/packages/models/src/import-export/peertube-export-format/actor-export.model.ts
+++ b/packages/models/src/import-export/peertube-export-format/image-export.model.ts
@@ -1,5 +1,6 @@
-export interface UserActorImageJSON {
+export interface ImageExportJSON {
width: number
+ height: number
url: string
createdAt: string
updatedAt: string
diff --git a/packages/models/src/import-export/peertube-export-format/index.ts b/packages/models/src/import-export/peertube-export-format/index.ts
index 3ecec47eb3..779eb38f56 100644
--- a/packages/models/src/import-export/peertube-export-format/index.ts
+++ b/packages/models/src/import-export/peertube-export-format/index.ts
@@ -1,5 +1,4 @@
export * from './account-export.model.js'
-export * from './actor-export.model.js'
export * from './auto-tag-policies-export.js'
export * from './blocklist-export.model.js'
export * from './channel-export.model.js'
@@ -7,6 +6,7 @@ export * from './comments-export.model.js'
export * from './dislikes-export.model.js'
export * from './followers-export.model.js'
export * from './following-export.model.js'
+export * from './image-export.model.js'
export * from './likes-export.model.js'
export * from './user-settings-export.model.js'
export * from './user-video-history-export.js'
diff --git a/packages/models/src/import-export/peertube-export-format/video-export.model.ts b/packages/models/src/import-export/peertube-export-format/video-export.model.ts
index b86df22acc..c1a3219166 100644
--- a/packages/models/src/import-export/peertube-export-format/video-export.model.ts
+++ b/packages/models/src/import-export/peertube-export-format/video-export.model.ts
@@ -7,6 +7,7 @@ import {
VideoStateType,
VideoStreamingPlaylistType_Type
} from '../../videos/index.js'
+import { ImageExportJSON } from './image-export.model.js'
export interface VideoExportJSON {
videos: {
@@ -51,6 +52,7 @@ export interface VideoExportJSON {
thumbnailUrl: string
previewUrl: string
+ thumbnails: ImageExportJSON[]
views: number
diff --git a/packages/models/src/import-export/user-export.model.ts b/packages/models/src/import-export/user-export.model.ts
index 4d7b56fa84..40c18d3d3f 100644
--- a/packages/models/src/import-export/user-export.model.ts
+++ b/packages/models/src/import-export/user-export.model.ts
@@ -11,7 +11,6 @@ export interface UserExport {
// In bytes
size: number
- fileUrl: string
privateDownloadUrl: string
createdAt: string | Date
diff --git a/packages/models/src/moderation/abuse/abuse.model.ts b/packages/models/src/moderation/abuse/abuse.model.ts
index 8c24901d13..0addc60632 100644
--- a/packages/models/src/moderation/abuse/abuse.model.ts
+++ b/packages/models/src/moderation/abuse/abuse.model.ts
@@ -1,8 +1,9 @@
import { Account } from '../../actors/account.model.js'
-import { AbuseStateType } from './abuse-state.model.js'
-import { AbusePredefinedReasonsString } from './abuse-reason.model.js'
-import { VideoConstant } from '../../videos/video-constant.model.js'
import { VideoChannel } from '../../videos/channel/video-channel.model.js'
+import { Thumbnail } from '../../videos/index.js'
+import { VideoConstant } from '../../videos/video-constant.model.js'
+import { AbusePredefinedReasonsString } from './abuse-reason.model.js'
+import { AbuseStateType } from './abuse-state.model.js'
export interface AdminVideoAbuse {
id: number
@@ -17,7 +18,13 @@ export interface AdminVideoAbuse {
startAt: number | null
endAt: number | null
+ /**
+ * @deprecated use thumbnails instead
+ */
thumbnailPath?: string
+
+ thumbnails: Thumbnail[]
+
channel?: VideoChannel
countReports: number
diff --git a/packages/models/src/server/custom-config.model.ts b/packages/models/src/server/custom-config.model.ts
index 5232a33569..c23dcae090 100644
--- a/packages/models/src/server/custom-config.model.ts
+++ b/packages/models/src/server/custom-config.model.ts
@@ -106,24 +106,6 @@ export interface CustomConfig {
}
}
- cache: {
- previews: {
- size: number
- }
-
- captions: {
- size: number
- }
-
- torrents: {
- size: number
- }
-
- storyboards: {
- size: number
- }
- }
-
signup: {
enabled: boolean
limit: number
diff --git a/packages/models/src/videos/index.ts b/packages/models/src/videos/index.ts
index dd581d797b..db09843406 100644
--- a/packages/models/src/videos/index.ts
+++ b/packages/models/src/videos/index.ts
@@ -18,7 +18,7 @@ export * from './nsfw-flag.enum.js'
export * from './nsfw-policy.type.js'
export * from './storyboard.model.js'
-export * from './thumbnail.type.js'
+export * from './thumbnail/index.js'
export * from './video-constant.model.js'
export * from './video-create.model.js'
diff --git a/packages/models/src/videos/playlist/video-playlist.model.ts b/packages/models/src/videos/playlist/video-playlist.model.ts
index d0c20e4a55..f176de739e 100644
--- a/packages/models/src/videos/playlist/video-playlist.model.ts
+++ b/packages/models/src/videos/playlist/video-playlist.model.ts
@@ -1,5 +1,6 @@
import { AccountSummary } from '../../actors/index.js'
import { VideoChannelSummary } from '../channel/index.js'
+import { Thumbnail } from '../thumbnail/thumbnail.model.js'
import { VideoConstant } from '../video-constant.model.js'
import { VideoPlaylistPrivacyType } from './video-playlist-privacy.model.js'
import { VideoPlaylistType_Type } from './video-playlist-type.model.js'
@@ -17,9 +18,17 @@ export interface VideoPlaylist {
description: string
privacy: VideoConstant<VideoPlaylistPrivacyType>
+ /**
+ * @deprecated in 8.1, use thumbnails array instead
+ */
thumbnailPath: string
+ /**
+ * @deprecated in 8.1, use thumbnails array instead
+ */
thumbnailUrl?: string
+ thumbnails: Thumbnail[]
+
videosLength: number
type: VideoConstant<VideoPlaylistType_Type>
diff --git a/packages/models/src/videos/thumbnail.type.ts b/packages/models/src/videos/thumbnail.type.ts
deleted file mode 100644
index 0cb7483ec9..0000000000
--- a/packages/models/src/videos/thumbnail.type.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const ThumbnailType = {
- MINIATURE: 1,
- PREVIEW: 2
-} as const
-
-export type ThumbnailType_Type = typeof ThumbnailType[keyof typeof ThumbnailType]
diff --git a/packages/models/src/videos/thumbnail/index.ts b/packages/models/src/videos/thumbnail/index.ts
new file mode 100644
index 0000000000..3b04b2a477
--- /dev/null
+++ b/packages/models/src/videos/thumbnail/index.ts
@@ -0,0 +1 @@
+export * from './thumbnail.model.js'
diff --git a/packages/models/src/videos/thumbnail/thumbnail.model.ts b/packages/models/src/videos/thumbnail/thumbnail.model.ts
new file mode 100644
index 0000000000..ac3d25cdd5
--- /dev/null
+++ b/packages/models/src/videos/thumbnail/thumbnail.model.ts
@@ -0,0 +1,6 @@
+export interface Thumbnail {
+ height: number
+ width: number
+
+ fileUrl: string
+}
diff --git a/packages/models/src/videos/video-create-update-common.model.ts b/packages/models/src/videos/video-create-update-common.model.ts
index 20bd5d645d..7096d0a861 100644
--- a/packages/models/src/videos/video-create-update-common.model.ts
+++ b/packages/models/src/videos/video-create-update-common.model.ts
@@ -23,6 +23,7 @@ export interface VideoCreateUpdateCommon {
waitTranscoding?: boolean
channelId?: number
thumbnailfile?: Blob
+ // TODO: remove in v10, deprecated in 8.1
previewfile?: Blob
scheduleUpdate?: VideoScheduleUpdate
originallyPublishedAt?: Date | string
diff --git a/packages/models/src/videos/video-source.model.ts b/packages/models/src/videos/video-source.model.ts
index 8f9f830983..aeb3d0a814 100644
--- a/packages/models/src/videos/video-source.model.ts
+++ b/packages/models/src/videos/video-source.model.ts
@@ -10,7 +10,6 @@ export interface VideoSource {
width?: number
height?: number
- fileUrl: string
fileDownloadUrl: string
fps?: number
diff --git a/packages/models/src/videos/video-streaming-playlist.type.ts b/packages/models/src/videos/video-streaming-playlist.type.ts
index 07a2c207ff..d79fdf39d5 100644
--- a/packages/models/src/videos/video-streaming-playlist.type.ts
+++ b/packages/models/src/videos/video-streaming-playlist.type.ts
@@ -3,3 +3,5 @@ export const VideoStreamingPlaylistType = {
} as const
export type VideoStreamingPlaylistType_Type = typeof VideoStreamingPlaylistType[keyof typeof VideoStreamingPlaylistType]
+
+export type VideoStreamingPlaylistTypeString = 'hls' | 'unknown'
diff --git a/packages/models/src/videos/video.model.ts b/packages/models/src/videos/video.model.ts
index d4201a2fb6..1e2ac99245 100644
--- a/packages/models/src/videos/video.model.ts
+++ b/packages/models/src/videos/video.model.ts
@@ -1,8 +1,9 @@
import { Account, AccountSummary } from '../actors/index.js'
import { VideoChannel, VideoChannelSummary } from './channel/video-channel.model.js'
+import { VideoCommentPolicyType } from './comment/video-comment-policy.enum.js'
import { VideoFile } from './file/index.js'
-import { VideoCommentPolicyType } from './index.js'
import { LiveVideoScheduleEdit } from './live/live-video-schedule.model.js'
+import { Thumbnail } from './thumbnail/thumbnail.model.js'
import { VideoConstant } from './video-constant.model.js'
import { VideoPrivacyType } from './video-privacy.enum.js'
import { VideoScheduleUpdate } from './video-schedule-update.model.js'
@@ -37,12 +38,28 @@ export interface Video extends Partial<VideoAdditionalAttributes> {
isLive: boolean
liveSchedules?: LiveVideoScheduleEdit[]
+ /**
+ * @deprecated in 8.1, use thumbnails array instead
+ */
thumbnailPath: string
+
+ /**
+ * @deprecated in 8.1, use thumbnails array instead
+ */
thumbnailUrl?: string
+ /**
+ * @deprecated in 8.1, use thumbnails array instead
+ */
previewPath: string
+
+ /**
+ * @deprecated in 8.1, use thumbnails array instead
+ */
previewUrl?: string
+ thumbnails: Thumbnail[]
+
embedPath: string
embedUrl?: string
diff --git a/packages/server-commands/src/videos/live-command.ts b/packages/server-commands/src/videos/live-command.ts
index c71e79e2c1..fcc1475330 100644
--- a/packages/server-commands/src/videos/live-command.ts
+++ b/packages/server-commands/src/videos/live-command.ts
@@ -108,7 +108,6 @@ export class LiveCommand extends AbstractCommand {
options: OverrideCommandOptions & {
fields: Omit<LiveVideoCreate, 'channelId' | 'thumbnailfile' | 'previewfile'> & {
thumbnailfile?: string | Blob
- previewfile?: string | Blob
channelId?: number
}
}
@@ -125,7 +124,6 @@ export class LiveCommand extends AbstractCommand {
const attaches: any = {}
if (fields.thumbnailfile) attaches.thumbnailfile = fields.thumbnailfile
- if (fields.previewfile) attaches.previewfile = fields.previewfile
const body = await unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
...options,
@@ -135,7 +133,7 @@ export class LiveCommand extends AbstractCommand {
fields: {
channelId: defaultChannelId,
- ...omit(fields, [ 'thumbnailfile', 'previewfile' ])
+ ...omit(fields, [ 'thumbnailfile' ])
},
implicitToken: true,
defaultExpectedStatus: HttpStatusCode.OK_200
diff --git a/packages/server-commands/src/videos/video-imports-command.ts b/packages/server-commands/src/videos/video-imports-command.ts
index aa4e5626df..296227beac 100644
--- a/packages/server-commands/src/videos/video-imports-command.ts
+++ b/packages/server-commands/src/videos/video-imports-command.ts
@@ -5,7 +5,7 @@ import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
export class VideoImportsCommand extends AbstractCommand {
async importVideo (
options: OverrideCommandOptions & {
- attributes: Partial<VideoImportCreate> | { torrentfile?: string, previewfile?: string, thumbnailfile?: string }
+ attributes: Partial<VideoImportCreate> | { torrentfile?: string, thumbnailfile?: string }
}
) {
const { attributes } = options
@@ -21,7 +21,6 @@ export class VideoImportsCommand extends AbstractCommand {
let attaches: any = {}
if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile }
if (attributes.thumbnailfile) attaches = { thumbnailfile: attributes.thumbnailfile }
- if (attributes.previewfile) attaches = { previewfile: attributes.previewfile }
return unwrapBody<VideoImport>(this.postUploadRequest({
...options,
diff --git a/packages/server-commands/src/videos/videos-command.ts b/packages/server-commands/src/videos/videos-command.ts
index 905387b638..a309a4efb5 100644
--- a/packages/server-commands/src/videos/videos-command.ts
+++ b/packages/server-commands/src/videos/videos-command.ts
@@ -28,6 +28,7 @@ import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
fixture?: string
thumbnailfile?: string
+ // TODO: remove when previewfile is deleted from the server
previewfile?: string
}
@@ -371,10 +372,9 @@ export class VideosCommand extends AbstractCommand {
const path = '/api/v1/videos/' + id
// Upload request
- if (attributes.thumbnailfile || attributes.previewfile) {
+ if (attributes.thumbnailfile) {
const attaches: any = {}
if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
- if (attributes.previewfile) attaches.previewfile = attributes.previewfile
return this.putUploadRequest({
...options,
@@ -382,8 +382,7 @@ export class VideosCommand extends AbstractCommand {
path,
fields: options.attributes,
attaches: {
- thumbnailfile: attributes.thumbnailfile,
- previewfile: attributes.previewfile
+ thumbnailfile: attributes.thumbnailfile
},
implicitToken: true,
defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
@@ -673,16 +672,14 @@ export class VideosCommand extends AbstractCommand {
}
buildUploadFields (attributes: VideoEdit) {
- return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
+ return omit(attributes, [ 'fixture', 'thumbnailfile' ])
}
buildUploadAttaches (attributes: VideoEdit, includeFixture: boolean) {
const attaches: { [name: string]: string } = {}
- for (const key of [ 'thumbnailfile', 'previewfile' ]) {
- if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
- }
-
+ if (attributes.thumbnailfile) attaches.thumbnailfile = buildAbsoluteFixturePath(attributes.thumbnailfile)
+ if (attributes.previewfile) attaches.previewfile = buildAbsoluteFixturePath(attributes.previewfile)
if (includeFixture && attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)
return attaches
diff --git a/packages/tests/fixtures/avatar-resized-120x120.png b/packages/tests/fixtures/avatar-resized-120x120.png
index 9d84151f8e..9d68c86836 100644
Binary files a/packages/tests/fixtures/avatar-resized-120x120.png and b/packages/tests/fixtures/avatar-resized-120x120.png differ
diff --git a/packages/tests/fixtures/avatar-resized-1500x1500.png b/packages/tests/fixtures/avatar-resized-1500x1500.png
index 97135debd6..837bb4c277 100644
Binary files a/packages/tests/fixtures/avatar-resized-1500x1500.png and b/packages/tests/fixtures/avatar-resized-1500x1500.png differ
diff --git a/packages/tests/fixtures/avatar-resized-48x48.gif b/packages/tests/fixtures/avatar-resized-48x48.gif
index 5900ff12e9..b74b3dc29b 100644
Binary files a/packages/tests/fixtures/avatar-resized-48x48.gif and b/packages/tests/fixtures/avatar-resized-48x48.gif differ
diff --git a/packages/tests/fixtures/avatar-resized-600x600.png b/packages/tests/fixtures/avatar-resized-600x600.png
index 2e42135ee7..470981e375 100644
Binary files a/packages/tests/fixtures/avatar-resized-600x600.png and b/packages/tests/fixtures/avatar-resized-600x600.png differ
diff --git a/packages/tests/fixtures/banner-user-import-resized-600.jpg b/packages/tests/fixtures/banner-user-import-resized-600.jpg
index 287b803d65..7f9d407825 100644
Binary files a/packages/tests/fixtures/banner-user-import-resized-600.jpg and b/packages/tests/fixtures/banner-user-import-resized-600.jpg differ
diff --git a/packages/tests/fixtures/custom-thumbnail-2-280x157.jpg b/packages/tests/fixtures/custom-thumbnail-2-280x157.jpg
new file mode 100644
index 0000000000..ef683a446e
Binary files /dev/null and b/packages/tests/fixtures/custom-thumbnail-2-280x157.jpg differ
diff --git a/packages/tests/fixtures/custom-thumbnail-2-850x480.jpg b/packages/tests/fixtures/custom-thumbnail-2-850x480.jpg
new file mode 100644
index 0000000000..ce324163d1
Binary files /dev/null and b/packages/tests/fixtures/custom-thumbnail-2-850x480.jpg differ
diff --git a/packages/tests/fixtures/custom-thumbnail-2.jpg b/packages/tests/fixtures/custom-thumbnail-2.jpg
deleted file mode 100644
index 01abe457c8..0000000000
Binary files a/packages/tests/fixtures/custom-thumbnail-2.jpg and /dev/null differ
diff --git a/packages/tests/fixtures/custom-thumbnail-280x157.jpg b/packages/tests/fixtures/custom-thumbnail-280x157.jpg
new file mode 100644
index 0000000000..50b3edb69a
Binary files /dev/null and b/packages/tests/fixtures/custom-thumbnail-280x157.jpg differ
diff --git a/packages/tests/fixtures/custom-preview.jpg b/packages/tests/fixtures/custom-thumbnail-850x480.jpg
similarity index 100%
rename from packages/tests/fixtures/custom-preview.jpg
rename to packages/tests/fixtures/custom-thumbnail-850x480.jpg
diff --git a/packages/tests/fixtures/custom-thumbnail.jpg b/packages/tests/fixtures/custom-thumbnail.jpg
deleted file mode 100644
index ef818442d1..0000000000
Binary files a/packages/tests/fixtures/custom-thumbnail.jpg and /dev/null differ
diff --git a/packages/tests/fixtures/default-live-thumbnail.jpg b/packages/tests/fixtures/default-live-thumbnail-280x157.jpg
similarity index 100%
rename from packages/tests/fixtures/default-live-thumbnail.jpg
rename to packages/tests/fixtures/default-live-thumbnail-280x157.jpg
diff --git a/packages/tests/fixtures/default-live-preview.jpg b/packages/tests/fixtures/default-live-thumbnail-850x480.jpg
similarity index 100%
rename from packages/tests/fixtures/default-live-preview.jpg
rename to packages/tests/fixtures/default-live-thumbnail-850x480.jpg
diff --git a/packages/tests/fixtures/thumbnail-playlist-280x157.jpg b/packages/tests/fixtures/thumbnail-playlist-280x157.jpg
new file mode 100644
index 0000000000..7b3b5e521e
Binary files /dev/null and b/packages/tests/fixtures/thumbnail-playlist-280x157.jpg differ
diff --git a/packages/tests/fixtures/thumbnail-playlist.jpg b/packages/tests/fixtures/thumbnail-playlist.jpg
deleted file mode 100644
index 061f19f70a..0000000000
Binary files a/packages/tests/fixtures/thumbnail-playlist.jpg and /dev/null differ
diff --git a/packages/tests/fixtures/video_short.mp4.jpg b/packages/tests/fixtures/video_short.mp4.jpg
index 1b8ed917a9..d0cc1d691e 100644
Binary files a/packages/tests/fixtures/video_short.mp4.jpg and b/packages/tests/fixtures/video_short.mp4.jpg differ
diff --git a/packages/tests/fixtures/video_short.ogv.jpg b/packages/tests/fixtures/video_short.ogv.jpg
index a4c514d132..ccee9e3632 100644
Binary files a/packages/tests/fixtures/video_short.ogv.jpg and b/packages/tests/fixtures/video_short.ogv.jpg differ
diff --git a/packages/tests/fixtures/video_short.webm.jpg b/packages/tests/fixtures/video_short.webm.jpg
index 061f19f70a..63b0a844ab 100644
Binary files a/packages/tests/fixtures/video_short.webm.jpg and b/packages/tests/fixtures/video_short.webm.jpg differ
diff --git a/packages/tests/fixtures/video_short1-preview.webm.jpg b/packages/tests/fixtures/video_short1.webm-thumbnail-850x480.jpg
similarity index 100%
rename from packages/tests/fixtures/video_short1-preview.webm.jpg
rename to packages/tests/fixtures/video_short1.webm-thumbnail-850x480.jpg
diff --git a/packages/tests/fixtures/video_short3.webm.jpg b/packages/tests/fixtures/video_short3.webm.jpg
index f5fabefbdf..5d20c64b55 100644
Binary files a/packages/tests/fixtures/video_short3.webm.jpg and b/packages/tests/fixtures/video_short3.webm.jpg differ
diff --git a/packages/tests/src/api/check-params/runners.ts b/packages/tests/src/api/check-params/runners.ts
index da6ad7434c..b2a34bb134 100644
--- a/packages/tests/src/api/check-params/runners.ts
+++ b/packages/tests/src/api/check-params/runners.ts
@@ -387,7 +387,7 @@ describe('Test managing runners', function () {
const { jobUUID, expectedStatus, videoUUID, runnerToken, jobToken } = options
const basePath = '/api/v1/runners/jobs/' + jobUUID + '/files/videos/' + videoUUID
- const paths = [ `${basePath}/max-quality`, `${basePath}/previews/max-quality` ]
+ const paths = [ `${basePath}/max-quality`, `${basePath}/thumbnails/max-quality` ]
for (const path of paths) {
await makePostBodyRequest({ url: server.url, path, fields: { runnerToken, jobToken }, expectedStatus })
@@ -810,7 +810,7 @@ describe('Test managing runners', function () {
})
it('Should fail with an invalid vod audio merge payload', async function () {
- const attributes = { name: 'audio_with_preview', previewfile: 'custom-preview.jpg', fixture: 'sample.ogg' }
+ const attributes = { name: 'audio_with_preview', thumbnailfile: 'custom-thumbnail-big.jpg', fixture: 'sample.ogg' }
await server.videos.upload({ attributes, mode: 'legacy' })
await waitJobs([ server ])
diff --git a/packages/tests/src/api/check-params/video-playlists.ts b/packages/tests/src/api/check-params/video-playlists.ts
index e25fac56df..f3b82d3d17 100644
--- a/packages/tests/src/api/check-params/video-playlists.ts
+++ b/packages/tests/src/api/check-params/video-playlists.ts
@@ -258,7 +258,7 @@ describe('Test video playlists API validator', function () {
attributes: {
displayName: 'display name',
privacy: VideoPlaylistPrivacy.UNLISTED,
- thumbnailfile: 'custom-thumbnail.jpg',
+ thumbnailfile: 'custom-thumbnail-280x157.jpg',
videoChannelId: server.store.channel.id,
...attributes
diff --git a/packages/tests/src/api/check-params/video-studio.ts b/packages/tests/src/api/check-params/video-studio.ts
index 0e1926b886..6c2e3f7681 100644
--- a/packages/tests/src/api/check-params/video-studio.ts
+++ b/packages/tests/src/api/check-params/video-studio.ts
@@ -293,7 +293,7 @@ describe('Test video studio API validator', function () {
it('Should succeed with the correct params', async function () {
this.timeout(360000)
- await addWatermark('custom-thumbnail.jpg', HttpStatusCode.NO_CONTENT_204)
+ await addWatermark('custom-thumbnail-280x157.jpg', HttpStatusCode.NO_CONTENT_204)
await waitJobs([ server ])
})
@@ -325,8 +325,8 @@ describe('Test video studio API validator', function () {
})
it('Should fail with an invalid file', async function () {
- await addIntroOutro('add-intro', 'custom-thumbnail.jpg')
- await addIntroOutro('add-outro', 'custom-thumbnail.jpg')
+ await addIntroOutro('add-intro', 'custom-thumbnail-280x157.jpg')
+ await addIntroOutro('add-outro', 'custom-thumbnail-280x157.jpg')
})
it('Should fail with a file that does not contain video stream', async function () {
diff --git a/packages/tests/src/api/check-params/videos.ts b/packages/tests/src/api/check-params/videos.ts
index 9a7d748458..966198cf1d 100644
--- a/packages/tests/src/api/check-params/videos.ts
+++ b/packages/tests/src/api/check-params/videos.ts
@@ -486,7 +486,7 @@ describe('Test videos API validator', function () {
it('Should fail with an incorrect thumbnail file', async function () {
const fields = baseCorrectParams
const attaches = {
- thumbnailfile: buildAbsoluteFixturePath('video_short.mp4'),
+ thumbnailfile: buildAbsoluteFixturePath('video-720p.torrent'),
fixture: buildAbsoluteFixturePath('video_short.mp4')
}
@@ -506,7 +506,7 @@ describe('Test videos API validator', function () {
it('Should fail with an incorrect preview file', async function () {
const fields = baseCorrectParams
const attaches = {
- previewfile: buildAbsoluteFixturePath('video_short.mp4'),
+ previewfile: buildAbsoluteFixturePath('video-720p.torrent'),
fixture: buildAbsoluteFixturePath('video_short.mp4')
}
diff --git a/packages/tests/src/api/live/live-save-replay.ts b/packages/tests/src/api/live/live-save-replay.ts
index 6187c944cb..84c3c59297 100644
--- a/packages/tests/src/api/live/live-save-replay.ts
+++ b/packages/tests/src/api/live/live-save-replay.ts
@@ -26,8 +26,8 @@ import {
waitUntilLiveReplacedByReplayOnAllServers,
waitUntilLiveWaitingOnAllServers
} from '@peertube/peertube-server-commands'
-import { testImageGeneratedByFFmpeg } from '@tests/shared/checks.js'
import { checkLiveCleanup } from '@tests/shared/live.js'
+import { checkThumbnails as _checkVideoThumbnails } from '@tests/shared/videos.js'
import { expect } from 'chai'
import { FfmpegCommand } from 'fluent-ffmpeg'
@@ -41,7 +41,6 @@ describe('Save replay setting', function () {
replay: boolean
replaySettings?: { privacy: VideoPrivacyType }
thumbnailfile?: string
- previewfile?: string
}) {
if (liveVideoUUID) {
try {
@@ -59,8 +58,7 @@ describe('Save replay setting', function () {
saveReplay: options.replay,
replaySettings: options.replaySettings,
permanentLive: options.permanent,
- thumbnailfile: options.thumbnailfile,
- previewfile: options.previewfile
+ thumbnailfile: options.thumbnailfile
}
})
return uuid
@@ -150,12 +148,11 @@ describe('Save replay setting', function () {
}
}
- async function checkVideoThumbnail (videoId: string, thumbnailfile: string, previewfile?: string) {
+ async function checkVideoThumbnails (videoId: string, thumbnails: string[]) {
for (const server of servers) {
const video = await server.videos.get({ id: videoId })
- await testImageGeneratedByFFmpeg(server.url, thumbnailfile, video.thumbnailPath, '')
- if (previewfile) await testImageGeneratedByFFmpeg(server.url, previewfile, video.previewPath, '')
+ await _checkVideoThumbnails({ video, server, thumbnails, strict: true })
}
}
@@ -301,7 +298,7 @@ describe('Save replay setting', function () {
await checkVideosExist(liveVideoUUID, 0, HttpStatusCode.OK_200)
await checkVideoState(liveVideoUUID, VideoState.WAITING_FOR_LIVE)
await checkVideoPrivacy(liveVideoUUID, VideoPrivacy.PUBLIC)
- await checkVideoThumbnail(liveVideoUUID, 'default-live-thumbnail.jpg', 'default-live-preview.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'default-live-thumbnail-280x157.jpg', 'default-live-thumbnail-850x480.jpg' ])
})
it('Should correctly have updated the live and federated it when streaming in the live', async function () {
@@ -315,7 +312,7 @@ describe('Save replay setting', function () {
await checkVideosExist(liveVideoUUID, 1, HttpStatusCode.OK_200)
await checkVideoState(liveVideoUUID, VideoState.PUBLISHED)
await checkVideoPrivacy(liveVideoUUID, VideoPrivacy.PUBLIC)
- await checkVideoThumbnail(liveVideoUUID, 'default-live-thumbnail.jpg', 'default-live-preview.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'default-live-thumbnail-280x157.jpg', 'default-live-thumbnail-850x480.jpg' ])
})
it('Should correctly have saved the live and federated it after the streaming', async function () {
@@ -368,8 +365,7 @@ describe('Save replay setting', function () {
attributes: {
name: 'video updated',
privacy: VideoPrivacy.PUBLIC,
- thumbnailfile: 'custom-thumbnail.jpg',
- previewfile: 'custom-preview.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg'
}
})
await waitJobs(servers)
@@ -380,7 +376,7 @@ describe('Save replay setting', function () {
expect(video.isLive).to.be.false
expect(video.privacy.id).to.equal(VideoPrivacy.PUBLIC)
- await checkVideoThumbnail(liveVideoUUID, 'custom-thumbnail.jpg', 'custom-preview.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ])
}
})
@@ -437,8 +433,7 @@ describe('Save replay setting', function () {
permanent: true,
replay: true,
replaySettings: { privacy: VideoPrivacy.UNLISTED },
- thumbnailfile: 'custom-thumbnail.jpg',
- previewfile: 'custom-preview.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg'
})
await waitJobs(servers)
@@ -446,7 +441,7 @@ describe('Save replay setting', function () {
await checkVideosExist(liveVideoUUID, 0, HttpStatusCode.OK_200)
await checkVideoState(liveVideoUUID, VideoState.WAITING_FOR_LIVE)
await checkVideoPrivacy(liveVideoUUID, VideoPrivacy.PUBLIC)
- await checkVideoThumbnail(liveVideoUUID, 'custom-thumbnail.jpg', 'custom-preview.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ])
})
it('Should correctly have updated the live and federated it when streaming in the live', async function () {
@@ -518,15 +513,15 @@ describe('Save replay setting', function () {
await checkVideosExist(lastReplayUUID, 1, HttpStatusCode.OK_200)
await checkVideoState(lastReplayUUID, VideoState.PUBLISHED)
await checkVideoPrivacy(lastReplayUUID, VideoPrivacy.PUBLIC)
- await checkVideoThumbnail(lastReplayUUID, 'custom-thumbnail-from-preview.jpg', 'custom-preview.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ])
})
it('Should update the live replay thumbnail', async function () {
- await servers[0].videos.update({ id: lastReplayUUID, attributes: { thumbnailfile: 'custom-thumbnail-2.jpg' } })
+ await servers[0].videos.update({ id: lastReplayUUID, attributes: { thumbnailfile: 'custom-thumbnail-2-850x480.jpg' } })
await waitJobs(servers)
- await checkVideoThumbnail(liveVideoUUID, 'custom-thumbnail.jpg', 'custom-preview.jpg')
- await checkVideoThumbnail(lastReplayUUID, 'custom-thumbnail-2.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ])
+ await checkVideoThumbnails(lastReplayUUID, [ 'custom-thumbnail-2-280x157.jpg', 'custom-thumbnail-2-850x480.jpg' ])
})
})
@@ -676,18 +671,18 @@ describe('Save replay setting', function () {
const video = await findExternalSavedVideo(servers[0], liveVideoUUID)
lastReplayUUID = video.uuid
- await checkVideoThumbnail(liveVideoUUID, 'default-live-thumbnail.jpg', 'default-live-preview.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'default-live-thumbnail-280x157.jpg', 'default-live-thumbnail-850x480.jpg' ])
})
it('Should update the live replay thumbnail', async function () {
await servers[0].videos.update({
id: lastReplayUUID,
- attributes: { thumbnailfile: 'custom-thumbnail.jpg', previewfile: 'custom-preview.jpg' }
+ attributes: { thumbnailfile: 'custom-thumbnail-850x480.jpg' }
})
await waitJobs(servers)
- await checkVideoThumbnail(liveVideoUUID, 'default-live-thumbnail.jpg', 'default-live-preview.jpg')
- await checkVideoThumbnail(lastReplayUUID, 'custom-thumbnail.jpg', 'custom-preview.jpg')
+ await checkVideoThumbnails(liveVideoUUID, [ 'default-live-thumbnail-280x157.jpg', 'default-live-thumbnail-850x480.jpg' ])
+ await checkVideoThumbnails(lastReplayUUID, [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ])
})
})
})
diff --git a/packages/tests/src/api/live/live.ts b/packages/tests/src/api/live/live.ts
index 80cf951509..cd26029fea 100644
--- a/packages/tests/src/api/live/live.ts
+++ b/packages/tests/src/api/live/live.ts
@@ -19,7 +19,6 @@ import {
doubleFollow,
killallServers,
LiveCommand,
- makeGetRequest,
makeRawRequest,
PeerTubeServer,
sendRTMPStream,
@@ -30,9 +29,9 @@ import {
waitJobs,
waitUntilLivePublishedOnAllServers
} from '@peertube/peertube-server-commands'
-import { testImageGeneratedByFFmpeg } from '@tests/shared/checks.js'
import { testLiveVideoResolutions } from '@tests/shared/live.js'
import { SQLCommand } from '@tests/shared/sql-command.js'
+import { checkThumbnails } from '@tests/shared/videos.js'
import { expect } from 'chai'
import { basename, join } from 'path'
@@ -96,8 +95,7 @@ describe('Test live', function () {
replaySettings: { privacy: VideoPrivacy.PUBLIC },
latencyMode: LiveVideoLatencyMode.SMALL_LATENCY,
privacy: VideoPrivacy.PUBLIC,
- previewfile: 'video_short1-preview.webm.jpg',
- thumbnailfile: 'video_short1.webm.jpg'
+ thumbnailfile: 'video_short1.webm-thumbnail-850x480.jpg'
}
})
liveVideoUUID = live.uuid
@@ -127,8 +125,11 @@ describe('Test live', function () {
expect(video.downloadEnabled).to.be.false
expect(video.privacy.id).to.equal(VideoPrivacy.PUBLIC)
- await testImageGeneratedByFFmpeg(server.url, 'video_short1-preview.webm', video.previewPath)
- await testImageGeneratedByFFmpeg(server.url, 'video_short1.webm', video.thumbnailPath)
+ await checkThumbnails({
+ server,
+ video,
+ thumbnails: [ 'video_short1.webm-thumbnail-850x480.jpg', 'video_short1.webm.jpg' ]
+ })
const live = await server.live.get({ videoId: liveVideoUUID })
@@ -168,8 +169,9 @@ describe('Test live', function () {
expect(video.privacy.id).to.equal(VideoPrivacy.UNLISTED)
expect(video.nsfw).to.be.true
- await makeGetRequest({ url: server.url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: server.url, path: video.previewPath, expectedStatus: HttpStatusCode.OK_200 })
+ for (const t of video.thumbnails) {
+ await makeRawRequest({ url: t.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
}
})
diff --git a/packages/tests/src/api/object-storage/video-static-file-privacy.ts b/packages/tests/src/api/object-storage/video-static-file-privacy.ts
index 0f002793f0..162e20a02a 100644
--- a/packages/tests/src/api/object-storage/video-static-file-privacy.ts
+++ b/packages/tests/src/api/object-storage/video-static-file-privacy.ts
@@ -51,12 +51,21 @@ describe('Object storage for video static file privacy', function () {
}
}
- for (const file of getAllFiles(video)) {
- const internalFileUrl = await sqlCommand.getInternalFileUrl(file.id)
- expectStartWith(internalFileUrl, ObjectStorageCommand.getScalewayBaseUrl())
+ const internalUrls = [
+ ...video.files.map(file => {
+ return ObjectStorageCommand.getScalewayBaseUrl() +
+ `test:server-1-web-videos:private/${video.uuid}/${extractFilenameFromUrl(file.fileUrl)}`
+ }),
+
+ ...video.streamingPlaylists[0].files.map(file => {
+ return ObjectStorageCommand.getScalewayBaseUrl() +
+ `test:server-1-streaming-playlists:hls/private/${video.uuid}/${extractFilenameFromUrl(file.fileUrl)}`
+ })
+ ]
+ for (const internalUrl of internalUrls) {
const { text } = await makeRawRequest({
- url: internalFileUrl,
+ url: internalUrl,
token: server.accessToken,
expectedStatus: HttpStatusCode.FORBIDDEN_403
})
diff --git a/packages/tests/src/api/runners/runner-vod-transcoding.ts b/packages/tests/src/api/runners/runner-vod-transcoding.ts
index 5673c7c2d8..33d49fb63e 100644
--- a/packages/tests/src/api/runners/runner-vod-transcoding.ts
+++ b/packages/tests/src/api/runners/runner-vod-transcoding.ts
@@ -1,9 +1,6 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import { expect } from 'chai'
-import { readFile } from 'fs/promises'
-import { completeCheckHlsPlaylist } from '@tests/shared/streaming-playlists.js'
-import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
+import { maxBy } from '@peertube/peertube-core-utils'
import {
HttpStatusCode,
RunnerJobSuccessPayload,
@@ -16,17 +13,20 @@ import {
VODHLSTranscodingSuccess,
VODWebVideoTranscodingSuccess
} from '@peertube/peertube-models'
+import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import {
cleanupTests,
createMultipleServers,
doubleFollow,
- makeGetRequest,
makeRawRequest,
PeerTubeServer,
setAccessTokensToServers,
setDefaultVideoChannel,
waitJobs
} from '@peertube/peertube-server-commands'
+import { completeCheckHlsPlaylist } from '@tests/shared/streaming-playlists.js'
+import { expect } from 'chai'
+import { readFile } from 'fs/promises'
async function processAllJobs (server: PeerTubeServer, runnerToken: string) {
do {
@@ -435,7 +435,7 @@ describe('Test runner VOD transcoding', function () {
await servers[0].config.enableTranscoding({ hls: true, webVideo: true })
- const attributes = { name: 'audio_with_preview', previewfile: 'custom-preview.jpg', fixture: 'sample.ogg' }
+ const attributes = { name: 'audio_with_preview', thumbnailfile: 'custom-thumbnail-big.jpg', fixture: 'sample.ogg' }
const { uuid } = await servers[0].videos.upload({ attributes, mode: 'legacy' })
videoUUID = uuid
@@ -470,9 +470,9 @@ describe('Test runner VOD transcoding', function () {
const { body } = await servers[0].runnerJobs.getJobFile({ url: job.payload.input.previewFileUrl, jobToken, runnerToken })
const video = await servers[0].videos.get({ id: videoUUID })
- const { body: inputFile } = await makeGetRequest({
- url: servers[0].url,
- path: video.previewPath,
+
+ const { body: inputFile } = await makeRawRequest({
+ url: maxBy(video.thumbnails, 'width').fileUrl,
expectedStatus: HttpStatusCode.OK_200
})
diff --git a/packages/tests/src/api/search/search-index.ts b/packages/tests/src/api/search/search-index.ts
index be40dd6dcf..75a84d37fe 100644
--- a/packages/tests/src/api/search/search-index.ts
+++ b/packages/tests/src/api/search/search-index.ts
@@ -107,6 +107,7 @@ describe('Test index search', function () {
expect(video.licence.label).to.equal('Attribution - Share Alike')
expect(video.privacy.label).to.equal('Public')
expect(video.duration).to.equal(113)
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
expect(video.thumbnailUrl.startsWith('https://framatube.org/lazy-static/thumbnails')).to.be.true
expect(video.account.host).to.equal('framatube.org')
@@ -375,6 +376,7 @@ describe('Test index search', function () {
const videoPlaylist = body.data[0]
expect(videoPlaylist.url).to.equal('https://peertube2.cpy.re/videos/watch/playlist/73804a40-da9a-40c2-b1eb-2c6d9eec8f0a')
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
expect(videoPlaylist.thumbnailUrl).to.exist
expect(videoPlaylist.embedUrl).to.equal('https://peertube2.cpy.re/video-playlists/embed/fgei1ws1oa6FCaJ2qZPG29')
diff --git a/packages/tests/src/api/server/config.ts b/packages/tests/src/api/server/config.ts
index 0e077948ae..a5e5aa0e9b 100644
--- a/packages/tests/src/api/server/config.ts
+++ b/packages/tests/src/api/server/config.ts
@@ -55,11 +55,6 @@ function checkInitialConfig (server: PeerTubeServer, data: CustomConfig) {
expect(data.client.browseVideos.defaultScope).to.equal('federated')
expect(data.client.menu.login.redirectOnSingleExternalAuth).to.be.false
- expect(data.cache.previews.size).to.equal(1)
- expect(data.cache.captions.size).to.equal(1)
- expect(data.cache.torrents.size).to.equal(1)
- expect(data.cache.storyboards.size).to.equal(1)
-
expect(data.signup.enabled).to.be.true
expect(data.signup.limit).to.equal(4)
expect(data.signup.minimumAge).to.equal(16)
@@ -249,20 +244,6 @@ function buildNewCustomConfig (server: PeerTubeServer): CustomConfig {
}
}
},
- cache: {
- previews: {
- size: 2
- },
- captions: {
- size: 3
- },
- torrents: {
- size: 4
- },
- storyboards: {
- size: 5
- }
- },
signup: {
enabled: false,
limit: 5,
diff --git a/packages/tests/src/api/server/lazy-static.ts b/packages/tests/src/api/server/lazy-static.ts
index 447a2c8013..c47f327707 100644
--- a/packages/tests/src/api/server/lazy-static.ts
+++ b/packages/tests/src/api/server/lazy-static.ts
@@ -5,57 +5,139 @@ import {
cleanupTests,
createMultipleServers,
doubleFollow,
- makeGetRequest,
+ makeRawRequest,
PeerTubeServer,
setAccessTokensToServers,
+ setDefaultAccountAvatar,
+ setDefaultChannelAvatar,
waitJobs
} from '@peertube/peertube-server-commands'
-import { checkDirectoryIsEmpty } from '@tests/shared/directories.js'
+import { expect } from 'chai'
+import { join } from 'path'
-describe('Test lazy static endpoinds', function () {
+describe('Test lazy static endpoints', function () {
let servers: PeerTubeServer[]
let videoId: string
+ async function fetchRemoteData () {
+ {
+ const video = await servers[1].videos.get({ id: videoId })
+
+ for (const thumbnail of video.thumbnails) {
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+
+ const { storyboards } = await servers[1].storyboard.list({ id: video.uuid })
+
+ for (const storyboard of storyboards) {
+ await makeRawRequest({ url: storyboard.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+
+ const { data: captions } = await servers[1].captions.list({ videoId: video.uuid })
+
+ for (const caption of captions) {
+ await makeRawRequest({ url: caption.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+ }
+
+ {
+ const { data: accounts } = await servers[1].accounts.list()
+ const { data: channels } = await servers[1].channels.list()
+
+ for (const { avatars } of [ ...accounts, ...channels ]) {
+ for (const avatar of avatars) {
+ await makeRawRequest({ url: avatar.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+ }
+ }
+ }
+
+ async function checkCachedFiles (options: { populated: boolean }) {
+ if (options.populated) {
+ expect(await servers[1].servers.countFiles(join('cache', 'thumbnails'))).to.equal(2)
+ expect(await servers[1].servers.countFiles(join('cache', 'avatars'))).to.equal(2 * 4)
+ expect(await servers[1].servers.countFiles(join('cache', 'storyboards'))).to.equal(1)
+ expect(await servers[1].servers.countFiles(join('cache', 'video-captions'))).to.equal(1)
+ } else {
+ expect(await servers[1].servers.countFiles(join('cache', 'thumbnails'))).to.equal(0)
+ expect(await servers[1].servers.countFiles(join('cache', 'avatars'))).to.equal(0)
+ expect(await servers[1].servers.countFiles(join('cache', 'storyboards'))).to.equal(0)
+ expect(await servers[1].servers.countFiles(join('cache', 'video-captions'))).to.equal(0)
+ }
+ }
+
before(async function () {
this.timeout(240000)
servers = await createMultipleServers(2)
await setAccessTokensToServers(servers)
+ await setDefaultAccountAvatar(servers)
+ await setDefaultChannelAvatar(servers)
+
+ await servers[0].config.enableFileUpdate()
+
await doubleFollow(servers[0], servers[1])
- const { uuid } = await servers[0].videos.quickUpload({ name: 'video' })
+ const { uuid } = await servers[0].videos.upload({
+ attributes: {
+ name: 'video',
+ thumbnailfile: 'custom-thumbnail-big.jpg'
+ }
+ })
videoId = uuid
+ await servers[0].captions.add({
+ language: 'ar',
+ videoId: uuid,
+ fixture: 'subtitle-good1.vtt'
+ })
+
await waitJobs(servers)
})
- it('Should remove previous thumbnails/previews after an update', async function () {
+ it('Should remove previous data after an update', async function () {
this.timeout(60000)
- const fetchRemoteImages = async () => {
- const video = await servers[1].videos.get({ id: videoId })
- await makeGetRequest({ url: servers[1].url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: servers[1].url, path: video.previewPath, expectedStatus: HttpStatusCode.OK_200 })
- }
+ await checkCachedFiles({ populated: false })
+
+ await fetchRemoteData()
- await fetchRemoteImages()
+ await checkCachedFiles({ populated: true })
- // Update video
- await servers[0].videos.update({
- id: videoId,
- attributes: { thumbnailfile: 'custom-thumbnail.jpg', previewfile: 'custom-preview.jpg' }
+ // Will re-generate thumbnails and storyboard
+ await servers[0].videos.replaceSourceFile({ videoId, fixture: 'video_short_360p.mp4' })
+
+ await servers[0].captions.add({
+ language: 'ar',
+ videoId,
+ fixture: 'subtitle-good2.vtt'
})
await waitJobs(servers)
- await fetchRemoteImages()
+ await fetchRemoteData()
+ await checkCachedFiles({ populated: true })
+ })
+
+ it('Should still have files after a server restart', async function () {
+ this.timeout(60000)
+
+ await servers[0].kill()
+ await servers[0].run()
+
+ await checkCachedFiles({ populated: true })
+ })
+
+ it('Should remove the video and remove cached files', async function () {
+ this.timeout(60000)
- // Remove video
await servers[0].videos.remove({ id: videoId })
await waitJobs(servers)
- await checkDirectoryIsEmpty(servers[1], 'thumbnails')
- await checkDirectoryIsEmpty(servers[1], 'previews')
+ expect(await servers[1].servers.countFiles(join('cache', 'thumbnails'))).to.equal(0)
+ expect(await servers[1].servers.countFiles(join('cache', 'avatars'))).to.equal(2 * 4)
+ expect(await servers[1].servers.countFiles(join('cache', 'storyboards'))).to.equal(0)
+ expect(await servers[1].servers.countFiles(join('cache', 'video-captions'))).to.equal(0)
})
after(async function () {
diff --git a/packages/tests/src/api/server/services.ts b/packages/tests/src/api/server/services.ts
index c577a3695f..a934627e10 100644
--- a/packages/tests/src/api/server/services.ts
+++ b/packages/tests/src/api/server/services.ts
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+import { maxBy } from '@peertube/peertube-core-utils'
import { HttpStatusCode, Video, VideoPlaylistPrivacy } from '@peertube/peertube-models'
import {
cleanupTests,
@@ -85,14 +86,14 @@ describe('Test services', function () {
`title="${video.name}" src="http://${servers[0].host}/videos/embed/${video.shortUUID}${suffix.output}" ` +
'style="border: none" allow="fullscreen"></iframe>'
- const expectedThumbnailUrl = 'http://' + servers[0].host + video.previewPath
+ const thumbnail = maxBy(video.thumbnails, 'width')
expect(res.body.html).to.equal(expectedHtml)
expect(res.body.title).to.equal(video.name)
expect(res.body.author_name).to.equal(servers[0].store.channel.displayName)
expect(res.body.width).to.equal(560)
expect(res.body.height).to.equal(315)
- expect(res.body.thumbnail_url).to.equal(expectedThumbnailUrl)
+ expect(res.body.thumbnail_url).to.equal(thumbnail.fileUrl)
expect(res.body.thumbnail_width).to.equal(850)
expect(res.body.thumbnail_height).to.equal(480)
}
diff --git a/packages/tests/src/api/transcoding/transcoder.ts b/packages/tests/src/api/transcoding/transcoder.ts
index 9d00e5006e..4f686d1858 100644
--- a/packages/tests/src/api/transcoding/transcoder.ts
+++ b/packages/tests/src/api/transcoding/transcoder.ts
@@ -8,7 +8,7 @@ import {
cleanupTests,
createMultipleServers,
doubleFollow,
- makeGetRequest,
+ makeRawRequest,
PeerTubeServer,
setAccessTokensToServers,
waitJobs
@@ -306,7 +306,7 @@ describe('Test video transcoding', function () {
it('Should merge an audio file with the preview file', async function () {
this.timeout(60_000)
- const attributes = { name: 'audio_with_preview', previewfile: 'custom-preview.jpg', fixture: 'sample.ogg' }
+ const attributes = { name: 'audio_with_preview', thumbnailfile: 'custom-thumbnail-big.jpg', fixture: 'sample.ogg' }
await servers[1].videos.upload({ attributes, mode })
await waitJobs(servers)
@@ -319,8 +319,9 @@ describe('Test video transcoding', function () {
expect(videoDetails.files).to.have.lengthOf(1)
- await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: server.url, path: videoDetails.previewPath, expectedStatus: HttpStatusCode.OK_200 })
+ for (const t of video.thumbnails) {
+ await makeRawRequest({ url: t.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
const magnetUri = videoDetails.files[0].magnetUri
expect(magnetUri).to.contain('.mp4')
@@ -343,8 +344,9 @@ describe('Test video transcoding', function () {
expect(videoDetails.files).to.have.lengthOf(1)
- await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: server.url, path: videoDetails.previewPath, expectedStatus: HttpStatusCode.OK_200 })
+ for (const t of videoDetails.thumbnails) {
+ await makeRawRequest({ url: t.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
const magnetUri = videoDetails.files[0].magnetUri
expect(magnetUri).to.contain('.mp4')
@@ -369,7 +371,7 @@ describe('Test video transcoding', function () {
}
})
- const attributes = { name: 'audio_with_preview', previewfile: 'custom-preview.jpg', fixture: 'sample.ogg' }
+ const attributes = { name: 'audio_with_preview', thumbnailfile: 'custom-thumbnail-big.jpg', fixture: 'sample.ogg' }
const { id } = await servers[1].videos.upload({ attributes, mode })
await waitJobs(servers)
diff --git a/packages/tests/src/api/users/user-import.ts b/packages/tests/src/api/users/user-import.ts
index 1504ef32f7..29de3f6c24 100644
--- a/packages/tests/src/api/users/user-import.ts
+++ b/packages/tests/src/api/users/user-import.ts
@@ -479,8 +479,7 @@ function runTest (withObjectStorage: boolean) {
size: 23000
}
],
- thumbnailfile: 'custom-thumbnail-from-preview',
- previewfile: 'custom-preview'
+ thumbnails: [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ]
}
})
}
diff --git a/packages/tests/src/api/users/user-videos.ts b/packages/tests/src/api/users/user-videos.ts
index 24f822d786..413cd94f02 100644
--- a/packages/tests/src/api/users/user-videos.ts
+++ b/packages/tests/src/api/users/user-videos.ts
@@ -138,8 +138,7 @@ describe('Test user videos', function () {
const video = data[0]
expect(video.name).to.equal('super user video')
- expect(video.thumbnailPath).to.not.be.null
- expect(video.previewPath).to.not.be.null
+ expect(video.thumbnails).to.have.lengthOf(2)
})
it('Should be able to filter by a specific channel in my videos', async function () {
@@ -154,8 +153,7 @@ describe('Test user videos', function () {
const video = data[0]
expect(video.name).to.equal('super user video')
- expect(video.thumbnailPath).to.not.be.null
- expect(video.previewPath).to.not.be.null
+ expect(video.thumbnails).to.have.lengthOf(2)
}
{
diff --git a/packages/tests/src/api/videos/multiple-servers.ts b/packages/tests/src/api/videos/multiple-servers.ts
index d7ede11aea..f0f9320017 100644
--- a/packages/tests/src/api/videos/multiple-servers.ts
+++ b/packages/tests/src/api/videos/multiple-servers.ts
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import { wait } from '@peertube/peertube-core-utils'
+import { maxBy, wait } from '@peertube/peertube-core-utils'
import { HttpStatusCode, VideoCommentPolicy, VideoCommentThreadTree, VideoPrivacy } from '@peertube/peertube-models'
import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import {
@@ -86,47 +86,51 @@ describe('Test multiple servers', function () {
let publishedAt: string = null
await Bluebird.map(servers, async server => {
- const checkAttributes = {
- name: 'my super name for server 1',
- category: 5,
- licence: 4,
- language: 'ja',
- nsfw: true,
- description: 'my super description for server 1',
- support: 'my super support text for server 1',
- originallyPublishedAt: '2019-02-10T13:38:14.449Z',
- account: {
- name: 'root',
- host: servers[0].host
- },
- publishedAt,
- duration: 10,
- tags: [ 'tag1p1', 'tag2p1' ],
- privacy: VideoPrivacy.PUBLIC,
- commentsPolicy: VideoCommentPolicy.ENABLED,
- downloadEnabled: true,
- channel: {
- displayName: 'my channel',
- name: 'super_channel_name',
- description: 'super channel'
- },
- fixture: 'video_short1.webm',
- files: [
- {
- resolution: 720,
- height: 720,
- width: 1280,
- size: 572456
- }
- ]
- }
-
const { data } = await server.videos.list()
expect(data).to.be.an('array')
expect(data.length).to.equal(1)
const video = data[0]
- await completeVideoCheck({ server, originServer: servers[0], videoUUID: video.uuid, attributes: checkAttributes })
+ await completeVideoCheck({
+ server,
+ originServer: servers[0],
+ videoUUID: video.uuid,
+ attributes: {
+ name: 'my super name for server 1',
+ category: 5,
+ licence: 4,
+ language: 'ja',
+ nsfw: true,
+ description: 'my super description for server 1',
+ support: 'my super support text for server 1',
+ originallyPublishedAt: '2019-02-10T13:38:14.449Z',
+ account: {
+ name: 'root',
+ host: servers[0].host
+ },
+ publishedAt,
+ duration: 10,
+ tags: [ 'tag1p1', 'tag2p1' ],
+ privacy: VideoPrivacy.PUBLIC,
+ commentsPolicy: VideoCommentPolicy.ENABLED,
+ downloadEnabled: true,
+ channel: {
+ displayName: 'my channel',
+ name: 'super_channel_name',
+ description: 'super channel'
+ },
+ fixture: 'video_short1.webm',
+ files: [
+ {
+ resolution: 720,
+ height: 720,
+ width: 1280,
+ size: 572456
+ }
+ ]
+ }
+ })
+
publishedAt = video.publishedAt as string
expect(video.channel.avatars).to.have.lengthOf(4)
@@ -163,8 +167,7 @@ describe('Test multiple servers', function () {
support: 'my super support text for server 2',
tags: [ 'tag1p2', 'tag2p2', 'tag3p2' ],
fixture: 'video_short2.webm',
- thumbnailfile: 'custom-thumbnail.jpg',
- previewfile: 'custom-preview.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg'
}
await servers[1].videos.upload({ token: userAccessToken, attributes, mode: 'resumable' })
@@ -222,8 +225,7 @@ describe('Test multiple servers', function () {
size: 750000
}
],
- thumbnailfile: 'custom-thumbnail',
- previewfile: 'custom-preview'
+ thumbnails: [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ]
}
const { data } = await server.videos.list()
@@ -624,9 +626,8 @@ describe('Test multiple servers', function () {
description: 'my super description updated',
support: 'my super support text updated',
tags: [ 'tag_up_1', 'tag_up_2' ],
- thumbnailfile: 'custom-thumbnail.jpg',
- originallyPublishedAt: '2019-02-11T13:38:14.449Z',
- previewfile: 'custom-preview.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg',
+ originallyPublishedAt: '2019-02-11T13:38:14.449Z'
}
updatedAtMin = new Date()
@@ -646,42 +647,45 @@ describe('Test multiple servers', function () {
expect(new Date(videoUpdated.updatedAt)).to.be.greaterThan(updatedAtMin)
- const checkAttributes = {
- name: 'my super video updated',
- category: 10,
- licence: 7,
- language: 'fr',
- nsfw: true,
- description: 'my super description updated',
- support: 'my super support text updated',
- originallyPublishedAt: '2019-02-11T13:38:14.449Z',
- account: {
- name: 'root',
- host: servers[2].host
- },
- duration: 5,
- commentsPolicy: VideoCommentPolicy.ENABLED,
- downloadEnabled: true,
- tags: [ 'tag_up_1', 'tag_up_2' ],
- privacy: VideoPrivacy.PUBLIC,
- channel: {
- displayName: 'Main root channel',
- name: 'root_channel',
- description: ''
- },
- fixture: 'video_short3.webm',
- files: [
- {
- resolution: 720,
- height: 720,
- width: 1280,
- size: 292677
- }
- ],
- thumbnailfile: 'custom-thumbnail',
- previewfile: 'custom-preview'
- }
- await completeVideoCheck({ server, originServer: servers[2], videoUUID: videoUpdated.uuid, attributes: checkAttributes })
+ await completeVideoCheck({
+ server,
+ originServer: servers[2],
+ videoUUID: videoUpdated.uuid,
+ attributes: {
+ name: 'my super video updated',
+ category: 10,
+ licence: 7,
+ language: 'fr',
+ nsfw: true,
+ description: 'my super description updated',
+ support: 'my super support text updated',
+ originallyPublishedAt: '2019-02-11T13:38:14.449Z',
+ account: {
+ name: 'root',
+ host: servers[2].host
+ },
+ duration: 5,
+ commentsPolicy: VideoCommentPolicy.ENABLED,
+ downloadEnabled: true,
+ tags: [ 'tag_up_1', 'tag_up_2' ],
+ privacy: VideoPrivacy.PUBLIC,
+ channel: {
+ displayName: 'Main root channel',
+ name: 'root_channel',
+ description: ''
+ },
+ fixture: 'video_short3.webm',
+ files: [
+ {
+ resolution: 720,
+ height: 720,
+ width: 1280,
+ size: 292677
+ }
+ ],
+ thumbnails: [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ]
+ }
+ })
})
})
@@ -704,7 +708,7 @@ describe('Test multiple servers', function () {
this.timeout(30000)
const attributes = {
- thumbnailfile: 'custom-thumbnail.jpg'
+ thumbnailfile: 'custom-thumbnail-280x157.jpg'
}
updatedAtMin = new Date()
@@ -776,11 +780,11 @@ describe('Test multiple servers', function () {
}
})
- it('Should get the preview from each server', async function () {
+ it('Should get the best thumbnail from each server', async function () {
for (const server of servers) {
const video = await server.videos.get({ id: videoUUID })
- await testImageGeneratedByFFmpeg(server.url, 'video_short1-preview.webm', video.previewPath)
+ await testImageGeneratedByFFmpeg({ name: 'video_short1.webm-thumbnail-850x480.jpg', url: maxBy(video.thumbnails, 'width').fileUrl })
}
})
})
@@ -1054,60 +1058,61 @@ describe('Test multiple servers', function () {
const { data } = await server.videos.list()
const video = data.find(v => v.name === 'minimum parameters')
- const isLocal = server.url === servers[1].url
- const checkAttributes = {
- name: 'minimum parameters',
- category: null,
- licence: null,
- language: null,
- nsfw: false,
- description: null,
- support: null,
- account: {
- name: 'root',
- host: servers[1].host
- },
- isLocal,
- duration: 5,
- commentsPolicy: VideoCommentPolicy.ENABLED,
- downloadEnabled: true,
- tags: [],
- privacy: VideoPrivacy.PUBLIC,
- channel: {
- displayName: 'Main root channel',
- name: 'root_channel',
- description: '',
- isLocal
- },
- fixture: 'video_short.webm',
- files: [
- {
- resolution: 720,
- height: 720,
- width: 1280,
- size: 61000
+ await completeVideoCheck({
+ server,
+ originServer: servers[1],
+ videoUUID: video.uuid,
+ attributes: {
+ name: 'minimum parameters',
+ category: null,
+ licence: null,
+ language: null,
+ nsfw: false,
+ description: null,
+ support: null,
+ account: {
+ name: 'root',
+ host: servers[1].host
},
- {
- resolution: 480,
- height: 480,
- width: 854,
- size: 40000
+ duration: 5,
+ commentsPolicy: VideoCommentPolicy.ENABLED,
+ downloadEnabled: true,
+ tags: [],
+ privacy: VideoPrivacy.PUBLIC,
+ channel: {
+ displayName: 'Main root channel',
+ name: 'root_channel',
+ description: ''
},
- {
- resolution: 360,
- height: 360,
- width: 640,
- size: 32000
- },
- {
- resolution: 240,
- height: 240,
- width: 426,
- size: 23000
- }
- ]
- }
- await completeVideoCheck({ server, originServer: servers[1], videoUUID: video.uuid, attributes: checkAttributes })
+ fixture: 'video_short.webm',
+ files: [
+ {
+ resolution: 720,
+ height: 720,
+ width: 1280,
+ size: 61000
+ },
+ {
+ resolution: 480,
+ height: 480,
+ width: 854,
+ size: 40000
+ },
+ {
+ resolution: 360,
+ height: 360,
+ width: 640,
+ size: 32000
+ },
+ {
+ resolution: 240,
+ height: 240,
+ width: 426,
+ size: 23000
+ }
+ ]
+ }
+ })
})
})
})
diff --git a/packages/tests/src/api/videos/single-server.ts b/packages/tests/src/api/videos/single-server.ts
index 7a0701be0a..fe5634eee0 100644
--- a/packages/tests/src/api/videos/single-server.ts
+++ b/packages/tests/src/api/videos/single-server.ts
@@ -1,10 +1,7 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import { expect } from 'chai'
import { wait } from '@peertube/peertube-core-utils'
import { Video, VideoCommentPolicy, VideoPrivacy } from '@peertube/peertube-models'
-import { checkVideoFilesWereRemoved, completeVideoCheck } from '@tests/shared/videos.js'
-import { testImageGeneratedByFFmpeg } from '@tests/shared/checks.js'
import {
cleanupTests,
createSingleServer,
@@ -14,6 +11,8 @@ import {
setDefaultChannelAvatar,
waitJobs
} from '@peertube/peertube-server-commands'
+import { checkVideoFilesWereRemoved, checkThumbnails, completeVideoCheck } from '@tests/shared/videos.js'
+import { expect } from 'chai'
describe('Test a single server', function () {
function runSuite (mode: 'legacy' | 'resumable') {
@@ -266,8 +265,7 @@ describe('Test a single server', function () {
videosListBase = data
for (const video of data) {
- const videoName = video.name.replace(' name', '')
- await testImageGeneratedByFFmpeg(server.url, videoName, video.thumbnailPath)
+ await checkThumbnails({ video, server, thumbnails: [ video.name.replace(' name', '') + '.jpg' ], strict: false })
}
})
diff --git a/packages/tests/src/api/videos/video-channels.ts b/packages/tests/src/api/videos/video-channels.ts
index c89016b1f7..e02a8591cd 100644
--- a/packages/tests/src/api/videos/video-channels.ts
+++ b/packages/tests/src/api/videos/video-channels.ts
@@ -292,7 +292,12 @@ describe('Test video channels', function () {
for (const avatar of videoChannel.avatars) {
avatarUrls[server.port] = avatar.fileUrl
await testImage({ url: avatarUrls[server.port], name: `avatar-resized-${avatar.width}x${avatar.width}.png` })
- await testFileExistsOnFSOrNot(server, 'avatars', basename(avatarUrls[server.port]), true)
+
+ if (i === 0) {
+ await testFileExistsOnFSOrNot(server, 'avatars', basename(avatarUrls[server.port]), true)
+ } else {
+ await testFileExistsOnFSOrNot(server, 'avatars', basename(avatarUrls[server.port]), false)
+ }
const row = await sqlCommands[i].getActorImage(basename(avatarUrls[server.port]))
@@ -325,7 +330,12 @@ describe('Test video channels', function () {
for (const banner of videoChannel.banners) {
bannerUrls[server.port] = banner.fileUrl
await testImage({ url: bannerUrls[server.port], name: `banner-resized-${banner.width}.jpg` })
- await testFileExistsOnFSOrNot(server, 'avatars', basename(bannerUrls[server.port]), true)
+
+ if (i === 0) {
+ await testFileExistsOnFSOrNot(server, 'avatars', basename(bannerUrls[server.port]), true)
+ } else {
+ await testFileExistsOnFSOrNot(server, 'avatars', basename(bannerUrls[server.port]), false)
+ }
const row = await sqlCommands[i].getActorImage(basename(bannerUrls[server.port]))
expect(expectedSizes.some(({ height, width }) => row.height === height && row.width === width)).to.equal(true)
diff --git a/packages/tests/src/api/videos/video-comments.ts b/packages/tests/src/api/videos/video-comments.ts
index dbccf5a749..43c57db39b 100644
--- a/packages/tests/src/api/videos/video-comments.ts
+++ b/packages/tests/src/api/videos/video-comments.ts
@@ -456,6 +456,8 @@ describe('Test video comments', function () {
video1 = await server.videos.quickUpload({ name: 'video on server 1' })
video2 = await server2.videos.quickUpload({ name: 'video on server 2' })
+ await waitJobs([ server, server2 ])
+
await server2.comments.createThread({ videoId: video1.uuid, text: 'comment on server 2' })
await server2.comments.createThread({ videoId: video2.uuid, text: 'comment on server 2' })
diff --git a/packages/tests/src/api/videos/video-imports.ts b/packages/tests/src/api/videos/video-imports.ts
index 06efa45ea3..fa268dfd96 100644
--- a/packages/tests/src/api/videos/video-imports.ts
+++ b/packages/tests/src/api/videos/video-imports.ts
@@ -15,9 +15,9 @@ import {
} from '@peertube/peertube-server-commands'
import { DeepPartial } from '@peertube/peertube-typescript-utils'
import { testCaptionFile } from '@tests/shared/captions.js'
-import { testImageGeneratedByFFmpeg } from '@tests/shared/checks.js'
import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'
import { SQLCommand } from '@tests/shared/sql-command.js'
+import { checkThumbnails } from '@tests/shared/videos.js'
import { expect } from 'chai'
import { pathExists, remove } from 'fs-extra/esm'
import { readdir } from 'fs/promises'
@@ -73,7 +73,7 @@ async function checkVideoServer2 (server: PeerTubeServer, id: number | string) {
expect(video.description).to.equal('my super description')
expect(video.tags).to.deep.equal([ 'supertag1', 'supertag2' ])
- await testImageGeneratedByFFmpeg(server.url, 'custom-thumbnail', video.thumbnailPath)
+ await checkThumbnails({ server, video, thumbnails: [ 'custom-thumbnail-280x157.jpg', 'custom-thumbnail-850x480.jpg' ] })
expect(video.files).to.have.lengthOf(1)
@@ -123,22 +123,20 @@ describe('Test video imports', function () {
expect(video.name).to.equal('small video - youtube')
- {
- try {
- expect(video.thumbnailPath).to.match(new RegExp(`^/lazy-static/thumbnails/.+.webp$`))
- expect(video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.webp$`))
- } catch {
- expect(video.thumbnailPath).to.match(new RegExp(`^/lazy-static/thumbnails/.+.jpg$`))
- expect(video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.jpg$`))
- }
+ const extension = video.thumbnails[0].fileUrl.endsWith('.webp')
+ ? '.webp'
+ : '.jpg'
+
+ const pathRegexp = new RegExp(`^/lazy-static/thumbnails/.+.${extension}$`)
+ const urlRegexp = new RegExp(`^${servers[0].url}/lazy-static/thumbnails/.+.${extension}$`)
- // FIXME: re-enable when we'll support webp pixel match
- // const suffix = mode === 'yt-dlp'
- // ? '_yt_dlp'
- // : ''
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ expect(video.thumbnailPath).to.match(pathRegexp)
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ expect(video.previewPath).to.match(pathRegexp)
- // await testImageGeneratedByFFmpeg(servers[0].url, 'video_import_thumbnail' + suffix, video.thumbnailPath)
- // await testImageGeneratedByFFmpeg(servers[0].url, 'video_import_preview' + suffix, video.previewPath)
+ for (const thumbnail of video.thumbnails) {
+ expect(thumbnail.fileUrl).to.match(urlRegexp)
}
const bodyCaptions = await servers[0].captions.list({ videoId: video.id })
@@ -341,7 +339,7 @@ describe('Test video imports', function () {
name: 'my super name',
description: 'my super description',
tags: [ 'supertag1', 'supertag2' ],
- thumbnailfile: 'custom-thumbnail.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg'
}
})
expect(video.name).to.equal('my super name')
diff --git a/packages/tests/src/api/videos/video-playlist-thumbnails.ts b/packages/tests/src/api/videos/video-playlist-thumbnails.ts
index d79c92f723..ea55f961f8 100644
--- a/packages/tests/src/api/videos/video-playlist-thumbnails.ts
+++ b/packages/tests/src/api/videos/video-playlist-thumbnails.ts
@@ -1,7 +1,5 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import { expect } from 'chai'
-import { testImageGeneratedByFFmpeg } from '@tests/shared/checks.js'
import { VideoPlaylistPrivacy } from '@peertube/peertube-models'
import {
cleanupTests,
@@ -12,6 +10,8 @@ import {
setDefaultVideoChannel,
waitJobs
} from '@peertube/peertube-server-commands'
+import { checkThumbnails } from '@tests/shared/videos.js'
+import { expect } from 'chai'
describe('Playlist thumbnail', function () {
let servers: PeerTubeServer[] = []
@@ -83,7 +83,8 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithoutThumbnail(server)
- await testImageGeneratedByFFmpeg(server.url, 'thumbnail-playlist', p.thumbnailPath)
+
+ await checkThumbnails({ server, playlist: p, thumbnails: [ 'thumbnail-playlist-280x157.jpg' ] })
}
})
@@ -95,7 +96,7 @@ describe('Playlist thumbnail', function () {
displayName: 'playlist with thumbnail',
privacy: VideoPlaylistPrivacy.PUBLIC,
videoChannelId: servers[1].store.channel.id,
- thumbnailfile: 'custom-thumbnail.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg'
}
})
playlistWithThumbnailId = created.id
@@ -110,7 +111,8 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithThumbnail(server)
- await testImageGeneratedByFFmpeg(server.url, 'custom-thumbnail', p.thumbnailPath)
+
+ await checkThumbnails({ server, playlist: p, thumbnails: [ 'custom-thumbnail-280x157.jpg' ] })
}
})
@@ -135,7 +137,8 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithoutThumbnail(server)
- await testImageGeneratedByFFmpeg(server.url, 'thumbnail-playlist', p.thumbnailPath)
+
+ await checkThumbnails({ server, playlist: p, thumbnails: [ 'thumbnail-playlist-280x157.jpg' ] })
}
})
@@ -160,7 +163,8 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithThumbnail(server)
- await testImageGeneratedByFFmpeg(server.url, 'custom-thumbnail', p.thumbnailPath)
+
+ await checkThumbnails({ server, playlist: p, thumbnails: [ 'custom-thumbnail-280x157.jpg' ] })
}
})
@@ -176,7 +180,8 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithoutThumbnail(server)
- await testImageGeneratedByFFmpeg(server.url, 'thumbnail-playlist', p.thumbnailPath)
+
+ await checkThumbnails({ server, playlist: p, thumbnails: [ 'thumbnail-playlist-280x157.jpg' ] })
}
})
@@ -192,11 +197,12 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithThumbnail(server)
- await testImageGeneratedByFFmpeg(server.url, 'custom-thumbnail', p.thumbnailPath)
+
+ await checkThumbnails({ server, playlist: p, thumbnails: [ 'custom-thumbnail-280x157.jpg' ] })
}
})
- it('Should the thumbnail when we delete the last element', async function () {
+ it('Should delete the thumbnail when we delete the last element', async function () {
this.timeout(30000)
await servers[1].playlists.removeElement({
@@ -208,7 +214,9 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithoutThumbnail(server)
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
expect(p.thumbnailPath).to.be.null
+ expect(p.thumbnails).to.have.lengthOf(0)
}
})
@@ -224,7 +232,8 @@ describe('Playlist thumbnail', function () {
for (const server of servers) {
const p = await getPlaylistWithThumbnail(server)
- await testImageGeneratedByFFmpeg(server.url, 'custom-thumbnail', p.thumbnailPath)
+
+ await checkThumbnails({ server, playlist: p, thumbnails: [ 'custom-thumbnail-280x157.jpg' ] })
}
})
diff --git a/packages/tests/src/api/videos/video-playlists.ts b/packages/tests/src/api/videos/video-playlists.ts
index e112fe8cf7..623392026c 100644
--- a/packages/tests/src/api/videos/video-playlists.ts
+++ b/packages/tests/src/api/videos/video-playlists.ts
@@ -24,8 +24,8 @@ import {
setDefaultVideoChannel,
waitJobs
} from '@peertube/peertube-server-commands'
-import { testImageGeneratedByFFmpeg } from '@tests/shared/checks.js'
import { checkPlaylistFilesWereRemoved } from '@tests/shared/video-playlists.js'
+import { checkThumbnails } from '@tests/shared/videos.js'
import { expect } from 'chai'
async function checkPlaylistElementType (
@@ -138,7 +138,7 @@ describe('Test video playlists', function () {
displayName: 'my normal playlist',
privacy: VideoPlaylistPrivacy.PUBLIC,
description: 'my super description',
- thumbnailfile: 'custom-thumbnail.jpg',
+ thumbnailfile: 'custom-thumbnail-280x157.jpg',
videoChannelId: servers[0].store.channel.id
}
})
@@ -231,7 +231,7 @@ describe('Test video playlists', function () {
displayName: 'my super playlist',
privacy: VideoPlaylistPrivacy.PUBLIC,
description: 'my super description',
- thumbnailfile: 'custom-thumbnail.jpg',
+ thumbnailfile: 'custom-thumbnail-280x157.jpg',
videoChannelId: servers[0].store.channel.id
}
})
@@ -288,7 +288,7 @@ describe('Test video playlists', function () {
attributes: {
displayName: 'playlist 3',
privacy: VideoPlaylistPrivacy.PUBLIC,
- thumbnailfile: 'custom-thumbnail.jpg',
+ thumbnailfile: 'custom-thumbnail-280x157.jpg',
videoChannelId: servers[1].store.channel.id
}
})
@@ -315,11 +315,20 @@ describe('Test video playlists', function () {
const playlist2 = body.data.find(p => p.displayName === 'playlist 2')
expect(playlist2).to.not.be.undefined
- await testImageGeneratedByFFmpeg(server.url, 'thumbnail-playlist', playlist2.thumbnailPath)
+
+ await checkThumbnails({
+ server,
+ thumbnails: [ 'thumbnail-playlist-280x157.jpg' ],
+ playlist: playlist2
+ })
const playlist3 = body.data.find(p => p.displayName === 'playlist 3')
expect(playlist3).to.not.be.undefined
- await testImageGeneratedByFFmpeg(server.url, 'custom-thumbnail', playlist3.thumbnailPath)
+ await checkThumbnails({
+ server,
+ thumbnails: [ 'custom-thumbnail-280x157.jpg' ],
+ playlist: playlist3
+ })
}
const body = await servers[2].playlists.list({ start: 0, count: 5 })
@@ -337,7 +346,12 @@ describe('Test video playlists', function () {
const playlist2 = body.data.find(p => p.displayName === 'playlist 2')
expect(playlist2).to.not.be.undefined
- await testImageGeneratedByFFmpeg(servers[2].url, 'thumbnail-playlist', playlist2.thumbnailPath)
+
+ await checkThumbnails({
+ server: servers[2],
+ thumbnails: [ 'thumbnail-playlist-280x157.jpg' ],
+ playlist: playlist2
+ })
expect(body.data.find(p => p.displayName === 'playlist 3')).to.not.be.undefined
})
@@ -655,7 +669,7 @@ describe('Test video playlists', function () {
displayName: 'playlist 3 updated',
description: 'description updated',
privacy: VideoPlaylistPrivacy.UNLISTED,
- thumbnailfile: 'custom-thumbnail.jpg',
+ thumbnailfile: 'custom-thumbnail-280x157.jpg',
videoChannelId: servers[1].store.channel.id
},
playlistId: playlistServer2Id2
@@ -1533,7 +1547,7 @@ describe('Test video playlists', function () {
displayName: 'playlist 0 updated',
description: 'description updated',
privacy: VideoPlaylistPrivacy.UNLISTED,
- thumbnailfile: 'custom-thumbnail.jpg',
+ thumbnailfile: 'custom-thumbnail-280x157.jpg',
videoChannelId: channelId1
}
})
diff --git a/packages/tests/src/api/videos/video-source.ts b/packages/tests/src/api/videos/video-source.ts
index 7eece60fc3..bbd157e4a9 100644
--- a/packages/tests/src/api/videos/video-source.ts
+++ b/packages/tests/src/api/videos/video-source.ts
@@ -8,7 +8,6 @@ import {
cleanupTests,
createMultipleServers,
doubleFollow,
- makeGetRequest,
makeRawRequest,
setAccessTokensToServers,
setDefaultAccountAvatar,
@@ -263,8 +262,9 @@ describe('Test video source management', function () {
// Grab old paths to ensure we'll regenerate
- previousUrls.push(video.previewPath)
- previousUrls.push(video.thumbnailPath)
+ for (const thumbnail of video.thumbnails) {
+ previousUrls.push(thumbnail.fileUrl)
+ }
for (const file of files) {
previousUrls.push(file.fileUrl)
@@ -309,11 +309,11 @@ describe('Test video source management', function () {
const files = getAllFiles(video)
expect(files).to.have.lengthOf(4 * 2)
- expect(previousUrls).to.not.include(server.url + video.previewPath)
- expect(previousUrls).to.not.include(server.url + video.thumbnailPath)
+ for (const thumbnail of video.thumbnails) {
+ expect(previousUrls).to.not.include(thumbnail.fileUrl)
- await makeGetRequest({ url: server.url, path: video.previewPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: server.url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
for (const file of files) {
expect(previousUrls).to.not.include(file.fileUrl)
@@ -373,23 +373,22 @@ describe('Test video source management', function () {
const { uuid } = await servers[0].videos.upload({
attributes: {
name: 'custom miniatures',
- thumbnailfile: 'custom-thumbnail.jpg',
- previewfile: 'custom-preview.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg'
}
})
await waitJobs(servers)
- const previousPaths: string[] = []
+ const previousUrls: string[] = []
for (const server of servers) {
const video = await server.videos.get({ id: uuid })
- previousPaths.push(video.previewPath)
- previousPaths.push(video.thumbnailPath)
+ for (const thumbnail of video.thumbnails) {
+ previousUrls.push(thumbnail.fileUrl)
- await makeGetRequest({ url: server.url, path: video.previewPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: server.url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
}
await servers[0].videos.replaceSourceFile({ videoId: uuid, fixture: 'video_short_360p.mp4' })
@@ -398,11 +397,11 @@ describe('Test video source management', function () {
for (const server of servers) {
const video = await server.videos.get({ id: uuid })
- expect(previousPaths).to.include(video.previewPath)
- expect(previousPaths).to.include(video.thumbnailPath)
+ for (const thumbnail of video.thumbnails) {
+ expect(previousUrls).to.include(thumbnail.fileUrl)
- await makeGetRequest({ url: server.url, path: video.previewPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: server.url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
}
})
diff --git a/packages/tests/src/cli/house-keeping.ts b/packages/tests/src/cli/house-keeping.ts
index 8d67bea6fa..a35030693d 100644
--- a/packages/tests/src/cli/house-keeping.ts
+++ b/packages/tests/src/cli/house-keeping.ts
@@ -6,7 +6,6 @@ import {
cleanupTests,
createMultipleServers,
doubleFollow,
- makeGetRequest,
makeRawRequest,
setAccessTokensToServers,
setDefaultAccountAvatar,
@@ -14,6 +13,7 @@ import {
waitJobs
} from '@peertube/peertube-server-commands'
import { expect } from 'chai'
+import { join } from 'path'
describe('House keeping CLI', function () {
let servers: PeerTubeServer[]
@@ -28,9 +28,23 @@ describe('House keeping CLI', function () {
async function fetchRemoteData () {
{
const { data } = await servers[0].videos.list()
+
for (const video of data) {
- await makeGetRequest({ url: servers[0].url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- await makeGetRequest({ url: servers[0].url, path: video.previewPath, expectedStatus: HttpStatusCode.OK_200 })
+ for (const thumbnail of video.thumbnails) {
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+
+ const { storyboards } = await servers[0].storyboard.list({ id: video.uuid })
+
+ for (const storyboard of storyboards) {
+ await makeRawRequest({ url: storyboard.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+
+ const { data: captions } = await servers[0].captions.list({ videoId: video.uuid })
+
+ for (const caption of captions) {
+ await makeRawRequest({ url: caption.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
}
}
@@ -46,6 +60,27 @@ describe('House keeping CLI', function () {
}
}
+ async function checkLocalFiles () {
+ expect(await servers[0].servers.countFiles('thumbnails')).to.equal(2) // 2 images sizes per video
+ expect(await servers[0].servers.countFiles('avatars')).to.equal(2 * 4) // 4 versions of 1 account and 1 channel
+ expect(await servers[0].servers.countFiles('storyboards')).to.equal(1)
+ expect(await servers[0].servers.countFiles('captions')).to.equal(1)
+ }
+
+ async function checkCachedFiles (options: { populated: boolean }) {
+ if (options.populated) {
+ expect(await servers[0].servers.countFiles(join('cache', 'thumbnails'))).to.equal(2)
+ expect(await servers[0].servers.countFiles(join('cache', 'avatars'))).to.equal(2 * 4)
+ expect(await servers[0].servers.countFiles(join('cache', 'storyboards'))).to.equal(1)
+ expect(await servers[0].servers.countFiles(join('cache', 'video-captions'))).to.equal(1)
+ } else {
+ expect(await servers[0].servers.countFiles(join('cache', 'thumbnails'))).to.equal(0)
+ expect(await servers[0].servers.countFiles(join('cache', 'avatars'))).to.equal(0)
+ expect(await servers[0].servers.countFiles(join('cache', 'storyboards'))).to.equal(0)
+ expect(await servers[0].servers.countFiles(join('cache', 'video-captions'))).to.equal(0)
+ }
+ }
+
before(async function () {
this.timeout(360000)
@@ -58,7 +93,13 @@ describe('House keeping CLI', function () {
await servers[1].config.enableMinimumTranscoding()
for (const server of servers) {
- await server.videos.quickUpload({ name: 'video' })
+ const { uuid } = await server.videos.quickUpload({ name: 'video' })
+
+ await server.captions.add({
+ language: 'ar',
+ videoId: uuid,
+ fixture: 'subtitle-good1.vtt'
+ })
}
await waitJobs(servers)
@@ -69,10 +110,11 @@ describe('House keeping CLI', function () {
it('Should have remote files locally', async function () {
this.timeout(120000)
- await fetchRemoteData()
+ await checkLocalFiles()
+ await checkCachedFiles({ populated: false })
- expect(await servers[0].servers.countFiles('thumbnails')).to.equal(2)
- expect(await servers[0].servers.countFiles('avatars')).to.equal((2 + 2) * 4) // 2 accounts and 2 channels in 4 versions
+ await fetchRemoteData()
+ await checkCachedFiles({ populated: true })
})
it('Should remove remote files', async function () {
@@ -82,13 +124,11 @@ describe('House keeping CLI', function () {
await runHouseKeeping('--delete-remote-files')
await servers[0].run()
- expect(await servers[0].servers.countFiles('thumbnails')).to.equal(1)
- expect(await servers[0].servers.countFiles('avatars')).to.equal((1 + 1) * 4) // 1 account and 1 channel in 4 versions
+ await checkLocalFiles()
+ await checkCachedFiles({ populated: false })
await fetchRemoteData()
-
- expect(await servers[0].servers.countFiles('thumbnails')).to.equal(2)
- expect(await servers[0].servers.countFiles('avatars')).to.equal((2 + 2) * 4) // 2 accounts and 2 channels in 4 versions
+ await checkCachedFiles({ populated: true })
})
after(async function () {
diff --git a/packages/tests/src/cli/index.ts b/packages/tests/src/cli/index.ts
index fb3bb39af9..d5d1e03c87 100644
--- a/packages/tests/src/cli/index.ts
+++ b/packages/tests/src/cli/index.ts
@@ -9,4 +9,3 @@ import './prune-storage'
import './regenerate-thumbnails'
import './reset-password'
import './update-host'
-import './update-object-storage-url.js'
diff --git a/packages/tests/src/cli/prune-storage.ts b/packages/tests/src/cli/prune-storage.ts
index c7c6042fb1..ace9d80272 100644
--- a/packages/tests/src/cli/prune-storage.ts
+++ b/packages/tests/src/cli/prune-storage.ts
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-import { getAllFiles, wait } from '@peertube/peertube-core-utils'
+import { getAllFiles } from '@peertube/peertube-core-utils'
import { FileStorage, HttpStatusCode, HttpStatusCodeType, VideoPlaylistPrivacy, VideoPrivacy } from '@peertube/peertube-models'
import { areMockObjectStorageTestsDisabled, buildUUID } from '@peertube/peertube-node-utils'
import {
@@ -10,7 +10,6 @@ import {
cleanupTests,
createMultipleServers,
doubleFollow,
- killallServers,
makeRawRequest,
setAccessTokensToServers,
setDefaultVideoChannel,
@@ -40,9 +39,9 @@ describe('Test prune storage CLI', function () {
for (const server of servers) {
await server.videos.quickUpload({ name: 'video 1', privacy: VideoPrivacy.PUBLIC })
- await server.videos.quickUpload({ name: 'video 2', privacy: VideoPrivacy.PUBLIC })
+ const { uuid } = await server.videos.quickUpload({ name: 'video 2', privacy: VideoPrivacy.PUBLIC })
- const { uuid } = await server.videos.quickUpload({ name: 'video 3', privacy: VideoPrivacy.PRIVATE })
+ await server.videos.quickUpload({ name: 'video 3', privacy: VideoPrivacy.PRIVATE })
await server.captions.add({
language: 'ar',
@@ -57,7 +56,7 @@ describe('Test prune storage CLI', function () {
displayName: 'playlist',
privacy: VideoPlaylistPrivacy.PUBLIC,
videoChannelId: server.store.channel.id,
- thumbnailfile: 'custom-thumbnail.jpg'
+ thumbnailfile: 'custom-thumbnail-280x157.jpg'
}
})
}
@@ -69,29 +68,6 @@ describe('Test prune storage CLI', function () {
}
await doubleFollow(servers[0], servers[1])
-
- // Lazy load the remote avatars
- {
- const account = await servers[0].accounts.get({ accountName: 'root@' + servers[1].host })
-
- for (const avatar of account.avatars) {
- await makeRawRequest({ url: avatar.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
- }
- }
-
- {
- const account = await servers[1].accounts.get({ accountName: 'root@' + servers[0].host })
- for (const avatar of account.avatars) {
- await makeRawRequest({ url: avatar.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
- }
- }
-
- await wait(1000)
-
- await waitJobs(servers)
- await killallServers(servers)
-
- await wait(1000)
})
describe('On filesystem', function () {
@@ -105,48 +81,99 @@ describe('Test prune storage CLI', function () {
}
}
- async function assertCountAreOkay () {
- for (const server of servers) {
- const videosCount = await server.servers.countFiles('web-videos')
- expect(videosCount).to.equal(5) // 2 videos with 2 resolutions + private directory
+ async function checkLocalFilesCount () {
+ const server = servers[0]
- const privateVideosCount = await server.servers.countFiles('web-videos/private')
- expect(privateVideosCount).to.equal(2)
+ const videosCount = await server.servers.countFiles('web-videos')
+ expect(videosCount).to.equal(5) // 2 videos with 2 resolutions + private directory
- const torrentsCount = await server.servers.countFiles('torrents')
- expect(torrentsCount).to.equal(12)
+ const privateVideosCount = await server.servers.countFiles('web-videos/private')
+ expect(privateVideosCount).to.equal(2)
- const previewsCount = await server.servers.countFiles('previews')
- expect(previewsCount).to.equal(3)
+ const torrentsCount = await server.servers.countFiles('torrents')
+ expect(torrentsCount).to.equal(12)
- const thumbnailsCount = await server.servers.countFiles('thumbnails')
- expect(thumbnailsCount).to.equal(5) // 3 local videos, 1 local playlist, 2 remotes videos (lazy downloaded) and 1 remote playlist
+ const thumbnailsCount = await server.servers.countFiles('thumbnails')
+ // 6 of 3 local videos (2 sizes for each)
+ // 1 local playlist
+ expect(thumbnailsCount).to.equal(7)
- const avatarsCount = await server.servers.countFiles('avatars')
- expect(avatarsCount).to.equal(8)
+ const avatarsCount = await server.servers.countFiles('avatars')
+ expect(avatarsCount).to.equal(4)
- const hlsRootCount = await server.servers.countFiles(join('streaming-playlists', 'hls'))
- expect(hlsRootCount).to.equal(3) // 2 videos + private directory
+ const hlsRootCount = await server.servers.countFiles(join('streaming-playlists', 'hls'))
+ expect(hlsRootCount).to.equal(3) // 2 videos + private directory
- const hlsPrivateRootCount = await server.servers.countFiles(join('streaming-playlists', 'hls', 'private'))
- expect(hlsPrivateRootCount).to.equal(1)
+ const hlsPrivateRootCount = await server.servers.countFiles(join('streaming-playlists', 'hls', 'private'))
+ expect(hlsPrivateRootCount).to.equal(1)
- const originalVideoFilesCount = await server.servers.countFiles(join('original-video-files'))
- expect(originalVideoFilesCount).to.equal(3)
+ const originalVideoFilesCount = await server.servers.countFiles('original-video-files')
+ expect(originalVideoFilesCount).to.equal(3)
- const storyboardsCount = await server.servers.countFiles(join('storyboards'))
- expect(storyboardsCount).to.equal(3)
+ const storyboardsCount = await server.servers.countFiles('storyboards')
+ expect(storyboardsCount).to.equal(3)
- const captionsCount = await server.servers.countFiles(join('captions'))
- expect(captionsCount).to.equal(1)
+ const captionsCount = await server.servers.countFiles('captions')
+ expect(captionsCount).to.equal(1)
- const userExportFilesCount = await server.servers.countFiles(join('tmp-persistent'))
- expect(userExportFilesCount).to.equal(1)
- }
+ const userExportFilesCount = await server.servers.countFiles('tmp-persistent')
+ expect(userExportFilesCount).to.equal(1)
+ }
+
+ async function checkCacheFilesCountBeforeLazyLoad () {
+ expect(await servers[0].servers.countFiles(join('cache', 'avatars'))).to.equal(0)
+ expect(await servers[0].servers.countFiles(join('cache', 'storyboards'))).to.equal(0)
+ expect(await servers[0].servers.countFiles(join('cache', 'thumbnails'))).to.equal(0)
+ expect(await servers[0].servers.countFiles(join('cache', 'video-captions'))).to.equal(0)
+ }
+
+ async function checkCacheFilesCountAfterLazyLoad () {
+ expect(await servers[0].servers.countFiles(join('cache', 'avatars'))).to.equal(4)
+ expect(await servers[0].servers.countFiles(join('cache', 'storyboards'))).to.equal(2)
+ expect(await servers[0].servers.countFiles(join('cache', 'thumbnails'))).to.equal(4)
+ expect(await servers[0].servers.countFiles(join('cache', 'video-captions'))).to.equal(1)
}
it('Should have the files on the disk', async function () {
- await assertCountAreOkay()
+ await checkLocalFilesCount()
+ await checkCacheFilesCountBeforeLazyLoad()
+ })
+
+ it('Should lazy load remote files', async function () {
+ // Lazy load remote avatars
+ {
+ const account = await servers[0].accounts.get({ accountName: 'root@' + servers[1].host })
+
+ for (const avatar of account.avatars) {
+ await makeRawRequest({ url: avatar.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+ }
+
+ // Lazy load video captions, storyboards and thumbnails
+ {
+ const { data: videos } = await servers[0].videos.list()
+ expect(videos).to.have.lengthOf(4)
+
+ for (const video of videos) {
+ const { data: captions } = await servers[0].captions.list({ videoId: video.uuid })
+ const { storyboards } = await servers[0].storyboard.list({ id: video.uuid })
+
+ for (const caption of captions) {
+ await makeRawRequest({ url: caption.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+
+ for (const storyboard of storyboards) {
+ await makeRawRequest({ url: storyboard.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+
+ for (const thumbnail of video.thumbnails) {
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
+ }
+ }
+
+ await checkLocalFilesCount()
+ await checkCacheFilesCountAfterLazyLoad()
})
it('Should create some dirty files', async function () {
@@ -178,7 +205,7 @@ describe('Test prune storage CLI', function () {
badNames['torrents'] = [ n1, n2 ]
}
- for (const name of [ 'thumbnails', 'previews', 'avatars', 'storyboards' ]) {
+ for (const name of [ 'thumbnails', 'avatars', 'storyboards' ]) {
const base = servers[0].servers.buildDirectory(name)
const n1 = buildUUID() + '.png'
@@ -244,7 +271,8 @@ describe('Test prune storage CLI', function () {
})
it('Should have removed files', async function () {
- await assertCountAreOkay()
+ await checkLocalFilesCount()
+ await checkCacheFilesCountAfterLazyLoad()
for (const directory of Object.keys(badNames)) {
for (const name of badNames[directory]) {
@@ -307,6 +335,7 @@ describe('Test prune storage CLI', function () {
await objectStorage.prepareDefaultMockBuckets()
+ await servers[0].kill()
await servers[0].run(objectStorage.getDefaultMockConfig({ proxifyPrivateFiles: false }))
{
diff --git a/packages/tests/src/cli/regenerate-thumbnails.ts b/packages/tests/src/cli/regenerate-thumbnails.ts
index 9767749155..895ee1154f 100644
--- a/packages/tests/src/cli/regenerate-thumbnails.ts
+++ b/packages/tests/src/cli/regenerate-thumbnails.ts
@@ -1,28 +1,24 @@
-import { expect } from 'chai'
-import { writeFile } from 'fs/promises'
-import { basename, join } from 'path'
-import { HttpStatusCode, Video } from '@peertube/peertube-models'
+import { minBy, wait } from '@peertube/peertube-core-utils'
+import { HttpStatusCode, Thumbnail, Video } from '@peertube/peertube-models'
import {
cleanupTests,
createMultipleServers,
doubleFollow,
- makeGetRequest,
+ makeRawRequest,
PeerTubeServer,
setAccessTokensToServers,
waitJobs
} from '@peertube/peertube-server-commands'
+import { expect } from 'chai'
+import { writeFile } from 'fs/promises'
+import { basename, join } from 'path'
-async function testThumbnail (server: PeerTubeServer, videoId: number | string) {
+async function testCurrentThumbnail (server: PeerTubeServer, videoId: number | string) {
const video = await server.videos.get({ id: videoId })
- const requests = [
- makeGetRequest({ url: server.url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 }),
- makeGetRequest({ url: server.url, path: video.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- ]
-
- for (const req of requests) {
- const res = await req
- expect(res.body).to.not.have.lengthOf(0)
+ for (const thumbnail of video.thumbnails) {
+ const { body } = await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ expect(body).to.not.have.lengthOf(0)
}
}
@@ -33,8 +29,13 @@ describe('Test regenerate thumbnails CLI', function () {
let video2: Video
let remoteVideo: Video
- let thumbnail1Path: string
- let thumbnailRemotePath: string
+ let localSmallestThumbnailPath: string
+ let remoteSmallestThumbnailPath: string
+
+ function isTruncatedThumbnail (thumbnail: Thumbnail) {
+ return basename(thumbnail.fileUrl) === basename(localSmallestThumbnailPath) ||
+ basename(thumbnail.fileUrl) === basename(remoteSmallestThumbnailPath)
+ }
before(async function () {
this.timeout(60000)
@@ -48,7 +49,8 @@ describe('Test regenerate thumbnails CLI', function () {
const videoUUID1 = (await servers[0].videos.quickUpload({ name: 'video 1' })).uuid
video1 = await servers[0].videos.get({ id: videoUUID1 })
- thumbnail1Path = join(servers[0].servers.buildDirectory('thumbnails'), basename(video1.thumbnailPath))
+ const smallestThumbnail = minBy(video1.thumbnails, 'width')
+ localSmallestThumbnailPath = join(join(servers[0].servers.buildDirectory('thumbnails'), basename(smallestThumbnail.fileUrl)))
const videoUUID2 = (await servers[0].videos.quickUpload({ name: 'video 2' })).uuid
video2 = await servers[0].videos.get({ id: videoUUID2 })
@@ -60,60 +62,95 @@ describe('Test regenerate thumbnails CLI', function () {
remoteVideo = await servers[0].videos.get({ id: videoUUID })
- // Load remote thumbnail on disk
- await makeGetRequest({ url: servers[0].url, path: remoteVideo.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
+ // Load remote thumbnails on disk
+ for (const thumbnail of remoteVideo.thumbnails) {
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ }
- thumbnailRemotePath = join(servers[0].servers.buildDirectory('thumbnails'), basename(remoteVideo.thumbnailPath))
+ const smallestThumbnail = minBy(remoteVideo.thumbnails, 'width')
+ remoteSmallestThumbnailPath = join(
+ servers[0].servers.buildDirectory(join('cache', 'thumbnails')),
+ basename(smallestThumbnail.fileUrl)
+ )
}
- await writeFile(thumbnail1Path, '')
- await writeFile(thumbnailRemotePath, '')
+ await writeFile(localSmallestThumbnailPath, '')
+ await writeFile(remoteSmallestThumbnailPath, '')
})
it('Should have empty thumbnails', async function () {
- {
- const res = await makeGetRequest({ url: servers[0].url, path: video1.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- expect(res.body).to.have.lengthOf(0)
- }
-
- {
- const res = await makeGetRequest({ url: servers[0].url, path: video2.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- expect(res.body).to.not.have.lengthOf(0)
+ for (const thumbnail of [ ...video1.thumbnails, ...remoteVideo.thumbnails ]) {
+ const { body } = await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+
+ if (isTruncatedThumbnail(thumbnail)) {
+ expect(body).to.have.lengthOf(0)
+ } else {
+ expect(body).to.not.have.lengthOf(0)
+ }
}
- {
- const res = await makeGetRequest({ url: servers[0].url, path: remoteVideo.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- expect(res.body).to.have.lengthOf(0)
+ for (const thumbnail of video2.thumbnails) {
+ const { body } = await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+ expect(body).to.not.have.lengthOf(0)
}
})
it('Should regenerate local thumbnails from the CLI', async function () {
- this.timeout(15000)
-
await servers[0].cli.execWithEnv(`npm run regenerate-thumbnails`)
})
it('Should have generated new thumbnail files', async function () {
- await testThumbnail(servers[0], video1.uuid)
- await testThumbnail(servers[0], video2.uuid)
+ await testCurrentThumbnail(servers[0], video1.uuid)
+ await testCurrentThumbnail(servers[0], video2.uuid)
+ })
- const res = await makeGetRequest({ url: servers[0].url, path: remoteVideo.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- expect(res.body).to.have.lengthOf(0)
+ it('Should have deleted old local thumbnail files', async function () {
+ for (const thumbnail of [ ...video1.thumbnails, ...video2.thumbnails ]) {
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
+ }
})
- it('Should have deleted old thumbnail files', async function () {
- {
- await makeGetRequest({ url: servers[0].url, path: video1.thumbnailPath, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
+ it('Should regenerate remote thumbnails', async function () {
+ await servers[1].cli.execWithEnv(`npm run regenerate-thumbnails`)
+ })
+
+ it('Should still have cached remote thumbnails on server 1', async function () {
+ for (const thumbnail of remoteVideo.thumbnails) {
+ const { body } = await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
+
+ if (isTruncatedThumbnail(thumbnail)) {
+ expect(body).to.have.lengthOf(0)
+ } else {
+ expect(body).to.not.have.lengthOf(0)
+ }
}
+ })
- {
- await makeGetRequest({ url: servers[0].url, path: video2.thumbnailPath, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
+ it('Should refresh the video and remove previous cached thumbnails', async function () {
+ await wait(10000)
+
+ await servers[0].videos.get({ id: remoteVideo.uuid }) // Refresh remote video thumbnails
+ await waitJobs(servers)
+
+ for (const thumbnail of remoteVideo.thumbnails) {
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
}
+ })
- {
- const res = await makeGetRequest({ url: servers[0].url, path: remoteVideo.thumbnailPath, expectedStatus: HttpStatusCode.OK_200 })
- expect(res.body).to.have.lengthOf(0)
+ it('Should have the appropriate thumbnails count', async function () {
+ expect(await servers[0].servers.countFiles('thumbnails')).to.equal(4)
+ expect(await servers[0].servers.countFiles('cache/thumbnails')).to.equal(0)
+ })
+
+ it('Should re-cache thumbnails on server 1', async function () {
+ const remoteVideoRefreshed = await servers[0].videos.get({ id: remoteVideo.uuid })
+
+ for (const thumbnail of remoteVideoRefreshed.thumbnails) {
+ await makeRawRequest({ url: thumbnail.fileUrl, expectedStatus: HttpStatusCode.OK_200 })
}
+
+ expect(await servers[0].servers.countFiles('thumbnails')).to.equal(4)
+ expect(await servers[0].servers.countFiles('cache/thumbnails')).to.equal(2)
})
after(async function () {
diff --git a/packages/tests/src/cli/update-object-storage-url.ts b/packages/tests/src/cli/update-object-storage-url.ts
deleted file mode 100644
index 7692109627..0000000000
--- a/packages/tests/src/cli/update-object-storage-url.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
-
-import { getHLS } from '@peertube/peertube-core-utils'
-import { VideoDetails } from '@peertube/peertube-models'
-import { areMockObjectStorageTestsDisabled } from '@peertube/peertube-node-utils'
-import {
- ObjectStorageCommand,
- PeerTubeServer,
- cleanupTests,
- createSingleServer,
- setAccessTokensToServers,
- waitJobs
-} from '@peertube/peertube-server-commands'
-import { expectStartWith } from '@tests/shared/checks.js'
-import { expect } from 'chai'
-
-describe('Update object storage URL CLI', function () {
- if (areMockObjectStorageTestsDisabled()) return
-
- let server: PeerTubeServer
- let uuid: string
- const objectStorage = new ObjectStorageCommand()
-
- function runUpdate (from: string, to: string) {
- const env = server.cli.getEnv()
- const command = `echo y | ${env} npm run update-object-storage-url -- --from "${from}" --to "${to}"`
-
- return server.cli.execWithEnv(command, objectStorage.getDefaultMockConfig())
- }
-
- before(async function () {
- this.timeout(360000)
-
- server = await createSingleServer(1, objectStorage.getDefaultMockConfig())
- await setAccessTokensToServers([ server ])
-
- await objectStorage.prepareDefaultMockBuckets()
-
- await server.config.enableMinimumTranscoding({ keepOriginal: true })
-
- const video = await server.videos.quickUpload({ name: 'video' })
- uuid = video.uuid
-
- await server.captions.add({ language: 'ar', videoId: uuid, fixture: 'subtitle-good1.vtt' })
- await server.captions.add({ language: 'zh', videoId: uuid, fixture: 'subtitle-good1.vtt' })
-
- await waitJobs([ server ])
- })
-
- it('Should update video URLs', async function () {
- this.timeout(120000)
-
- const check = async (options: {
- baseUrl: string
- newBaseUrl: string
- urlGetter: (video: VideoDetails) => Promise<string[]> | string[]
- }) => {
- const { baseUrl, newBaseUrl, urlGetter } = options
-
- const oldVideo = await server.videos.get({ id: uuid })
- const oldFileUrls = await urlGetter(oldVideo)
-
- for (const url of oldFileUrls) {
- expectStartWith(url, baseUrl)
- }
-
- await runUpdate(baseUrl, newBaseUrl)
-
- const newVideo = await server.videos.get({ id: uuid })
-
- const shouldBe = oldFileUrls.map(f => f.replace(baseUrl, newBaseUrl))
- expect(await urlGetter(newVideo)).to.have.members(shouldBe)
- }
-
- await check({
- baseUrl: objectStorage.getMockWebVideosBaseUrl(),
- newBaseUrl: 'https://web-video.example.com/',
- urlGetter: video => video.files.map(f => f.fileUrl)
- })
-
- await check({
- baseUrl: objectStorage.getMockPlaylistBaseUrl(),
- newBaseUrl: 'https://streaming-playlists.example.com/',
- urlGetter: video => {
- const hls = getHLS(video)
-
- return [
- ...hls.files.map(f => f.fileUrl),
-
- hls.playlistUrl,
- hls.segmentsSha256Url
- ]
- }
- })
-
- await check({
- baseUrl: objectStorage.getMockOriginalFileBaseUrl(),
- newBaseUrl: 'https://original-file.example.com/',
- urlGetter: async video => {
- const source = await server.videos.getSource({ id: video.uuid })
-
- return [ source.fileUrl ]
- }
- })
-
- await check({
- baseUrl: objectStorage.getMockCaptionFileBaseUrl(),
- newBaseUrl: 'https://captions.example.com/',
- urlGetter: async video => {
- const { data } = await server.captions.list({ videoId: video.uuid })
-
- return data.map(c => c.fileUrl)
- }
- })
- })
-
- it('Should update user export URLs', async function () {
- this.timeout(120000)
-
- const user = await server.users.getMyInfo()
-
- await server.userExports.request({ userId: user.id, withVideoFiles: false })
- await waitJobs([ server ])
-
- {
- const { data } = await server.userExports.list({ userId: user.id })
- expectStartWith(data[0].fileUrl, objectStorage.getMockUserExportBaseUrl())
- }
-
- await runUpdate(objectStorage.getMockUserExportBaseUrl(), 'https://user-export.example.com/')
-
- {
- const { data } = await server.userExports.list({ userId: user.id })
- expectStartWith(data[0].fileUrl, 'https://user-export.example.com/')
- }
- })
-
- after(async function () {
- await objectStorage.cleanupMock()
-
- await cleanupTests([ server ])
- })
-})
diff --git a/packages/tests/src/client/jsonld.ts b/packages/tests/src/client/jsonld.ts
index 4b3d955876..9733779522 100644
--- a/packages/tests/src/client/jsonld.ts
+++ b/packages/tests/src/client/jsonld.ts
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+import { maxBy } from '@peertube/peertube-core-utils'
import { HttpStatusCode, VideoCreateResult, VideoPlaylistCreateResult, VideoPrivacy } from '@peertube/peertube-models'
import {
PeerTubeServer,
@@ -108,13 +109,15 @@ describe('Test JSONLD HTML tags', function () {
const video = await server.videos.get({ id: publicVideo.uuid })
const jsonld = await getJSONLD(server, getWatchVideoBasePaths()[0] + publicVideo.uuid)
+ const thumbnailUrl = maxBy(video.thumbnails, 'width').fileUrl
+
expect(jsonld).to.deep.equal({
'@context': 'http://schema.org',
'@type': 'VideoObject',
'name': 'simple public video',
'description': '',
- 'image': server.url + video.previewPath,
- 'thumbnailUrl': server.url + video.previewPath,
+ 'image': thumbnailUrl,
+ thumbnailUrl,
'duration': 'PT' + video.duration + 'S',
'url': server.url + '/w/' + publicVideo.shortUUID,
'embedUrl': server.url + '/videos/embed/' + publicVideo.shortUUID,
@@ -210,6 +213,7 @@ describe('Test JSONLD HTML tags', function () {
for (const server of servers) {
const jsonld = await getJSONLD(server, getWatchPlaylistBasePaths()[0] + publicPlaylist.uuid)
const playlist = await server.playlists.get({ playlistId: publicPlaylist.uuid })
+ const thumbnailUrl = maxBy(playlist.thumbnails, 'width').fileUrl
expect(jsonld).to.deep.equal({
'@context': 'http://schema.org',
@@ -220,8 +224,8 @@ describe('Test JSONLD HTML tags', function () {
'numberOfItems': 1,
'embedUrl': server.url + playlist.embedPath,
- 'image': server.url + playlist.thumbnailPath,
- 'thumbnailUrl': server.url + playlist.thumbnailPath,
+ 'image': thumbnailUrl,
+ thumbnailUrl,
'author': {
'@type': 'Organization',
diff --git a/packages/tests/src/plugins/plugin-helpers.ts b/packages/tests/src/plugins/plugin-helpers.ts
index 494c6257e8..0c041282ab 100644
--- a/packages/tests/src/plugins/plugin-helpers.ts
+++ b/packages/tests/src/plugins/plugin-helpers.ts
@@ -2,7 +2,7 @@
import { expect } from 'chai'
import { pathExists } from 'fs-extra/esm'
-import { HttpStatusCode, ThumbnailType } from '@peertube/peertube-models'
+import { HttpStatusCode } from '@peertube/peertube-models'
import {
cleanupTests,
createMultipleServers,
@@ -44,7 +44,6 @@ describe('Test plugin helpers', function () {
})
describe('Logger', function () {
-
it('Should have logged things', async function () {
await servers[0].servers.waitUntilLog(servers[0].host + ' peertube-plugin-test-four', 1, false)
await servers[0].servers.waitUntilLog('Hello world from plugin four', 1)
@@ -52,14 +51,12 @@ describe('Test plugin helpers', function () {
})
describe('Database', function () {
-
it('Should have made a query', async function () {
await servers[0].servers.waitUntilLog(`root email is admin${servers[0].internalServerNumber}@example.com`)
})
})
describe('Config', function () {
-
it('Should have the correct webserver url', async function () {
await servers[0].servers.waitUntilLog(`server url is ${servers[0].url}`)
})
@@ -89,14 +86,12 @@ describe('Test plugin helpers', function () {
})
describe('Server', function () {
-
it('Should get the server actor', async function () {
await servers[0].servers.waitUntilLog('server actor name is peertube')
})
})
describe('Socket', function () {
-
it('Should sendNotification without any exceptions', async () => {
const user = await servers[0].users.create({ username: 'notis_redding', password: 'secret1234?' })
await makePostBodyRequest({
@@ -123,7 +118,6 @@ describe('Test plugin helpers', function () {
})
describe('Plugin', function () {
-
it('Should get the base static route', async function () {
const res = await makeGetRequest({
url: servers[0].url,
@@ -325,13 +319,17 @@ describe('Test plugin helpers', function () {
{
expect(body.thumbnails).to.be.an('array')
- const miniature = body.thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
+ const miniature = body.thumbnails.find(t => t.type === 1)
expect(miniature).to.exist
+ expect(miniature.width).to.equal(280)
+ expect(miniature.height).to.equal(157)
expect(await pathExists(miniature.path)).to.be.true
await makeRawRequest({ url: miniature.url, expectedStatus: HttpStatusCode.OK_200 })
- const preview = body.thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
+ const preview = body.thumbnails.find(t => t.type === 2)
expect(preview).to.exist
+ expect(preview.width).to.equal(850)
+ expect(preview.height).to.equal(480)
expect(await pathExists(preview.path)).to.be.true
await makeRawRequest({ url: preview.url, expectedStatus: HttpStatusCode.OK_200 })
}
diff --git a/packages/tests/src/server-helpers/image.ts b/packages/tests/src/server-helpers/image.ts
index f345ca883d..140ecf1af1 100644
--- a/packages/tests/src/server-helpers/image.ts
+++ b/packages/tests/src/server-helpers/image.ts
@@ -36,7 +36,7 @@ describe('Image helpers', function () {
const thumbnailSize = { width: 280, height: 157 }
it('Should skip processing if the source image is okay', async function () {
- const input = buildAbsoluteFixturePath('custom-thumbnail.jpg')
+ const input = buildAbsoluteFixturePath('custom-thumbnail-280x157.jpg')
await processImage({ path: input, destination: imageDestJPG, newSize: thumbnailSize, keepOriginal: true })
await checkBuffers(input, imageDestJPG, true)
@@ -49,13 +49,6 @@ describe('Image helpers', function () {
await checkBuffers(input, imageDestJPG, false)
})
- it('Should not skip processing if the source image does not have the appropriate size', async function () {
- const input = buildAbsoluteFixturePath('custom-preview.jpg')
- await processImage({ path: input, destination: imageDestJPG, newSize: thumbnailSize, keepOriginal: true })
-
- await checkBuffers(input, imageDestJPG, false)
- })
-
it('Should not skip processing if the source image does not have the appropriate size', async function () {
const input = buildAbsoluteFixturePath('custom-thumbnail-big.jpg')
await processImage({ path: input, destination: imageDestJPG, newSize: thumbnailSize, keepOriginal: true })
diff --git a/packages/tests/src/shared/checks.ts b/packages/tests/src/shared/checks.ts
index 59e28bdc33..62ee0acaed 100644
--- a/packages/tests/src/shared/checks.ts
+++ b/packages/tests/src/shared/checks.ts
@@ -5,7 +5,7 @@ import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import { makeGetRequest, makeRawRequest, PeerTubeServer } from '@peertube/peertube-server-commands'
import { expect } from 'chai'
import { pathExists } from 'fs-extra/esm'
-import { readFile } from 'fs/promises'
+import { readFile, writeFile } from 'fs/promises'
import { join, parse } from 'path'
// Default interval -> 5 minutes
@@ -67,11 +67,22 @@ async function testAvatarSize (options: {
const minLength = data.length - ((40 * data.length) / 100)
const maxLength = data.length + ((40 * data.length) / 100)
- expect(body.length).to.be.above(minLength, 'the generated image is way smaller than the recorded fixture ' + fixturePath)
- expect(body.length).to.be.below(maxLength, 'the generated image is way larger than the recorded fixture ' + fixturePath)
+ try {
+ expect(body.length).to.be.above(minLength, `the generated image ${avatar.path} is way smaller than the recorded fixture ${fixturePath}`)
+ expect(body.length).to.be.below(maxLength, `the generated image ${avatar.path} is way larger than the recorded fixture ${fixturePath}`)
+ } catch (err) {
+ if (process.env.AUTO_UPDATE_IMAGES === 'true') {
+ await writeFile(fixturePath, body)
+ }
+
+ throw err
+ }
}
-async function testImageGeneratedByFFmpeg (url: string, imageName: string, imageHTTPPath: string, extension = '.jpg') {
+async function testImageGeneratedByFFmpeg (options: {
+ url: string
+ name: string
+}) {
if (process.env.ENABLE_FFMPEG_THUMBNAIL_PIXEL_COMPARISON_TESTS !== 'true') {
console.log(
'Pixel comparison of image generated by ffmpeg is disabled. ' +
@@ -80,7 +91,7 @@ async function testImageGeneratedByFFmpeg (url: string, imageName: string, image
return
}
- return testImage({ url: url + imageHTTPPath, name: `${imageName}${extension}` })
+ return testImage(options)
}
async function testImage (options: {
@@ -90,27 +101,35 @@ async function testImage (options: {
const { name, url } = options
const { body } = await makeRawRequest({ url, expectedStatus: HttpStatusCode.OK_200 })
- const data = await readFile(buildAbsoluteFixturePath(name))
+ const fixturePath = buildAbsoluteFixturePath(name)
+ const data = await readFile(fixturePath)
- const { PNG } = await import('pngjs')
- const JPEG = await import('jpeg-js')
+ const sharp = (await import('sharp')).default
const pixelmatch = (await import('pixelmatch')).default
- const img1 = url.endsWith('.png')
- ? PNG.sync.read(body)
- : JPEG.decode(body)
+ const img1 = sharp(body)
+ const img1Metadata = await img1.metadata()
- const img2 = name.endsWith('.png')
- ? PNG.sync.read(data)
- : JPEG.decode(data)
+ const img2 = sharp(data)
const errorMsg = `${url} image is not the same as ${name}`
try {
- const result = pixelmatch(img1.data, img2.data, null, img1.width, img1.height, { threshold: 0.1 })
+ const result = pixelmatch(
+ await img1.ensureAlpha().raw().toBuffer(),
+ await img2.ensureAlpha().raw().toBuffer(),
+ null,
+ img1Metadata.width,
+ img1Metadata.height,
+ { threshold: 0.1 }
+ )
- expect(result).to.equal(0, errorMsg)
+ expect(result).to.be.below(100, errorMsg)
} catch (err) {
+ if (process.env.AUTO_UPDATE_IMAGES === 'true') {
+ await writeFile(fixturePath, body)
+ }
+
// eslint-disable-next-line preserve-caught-error
throw new Error(`${errorMsg}: ${err.message}`)
}
diff --git a/packages/tests/src/shared/import-export.ts b/packages/tests/src/shared/import-export.ts
index 1511277455..8305b68376 100644
--- a/packages/tests/src/shared/import-export.ts
+++ b/packages/tests/src/shared/import-export.ts
@@ -241,8 +241,7 @@ export async function prepareImportExportTests (options: {
waitTranscoding: true,
channelId: noahSecondChannelId,
privacy: VideoPrivacy.PUBLIC,
- thumbnailfile: 'custom-thumbnail.jpg',
- previewfile: 'custom-preview.jpg'
+ thumbnailfile: 'custom-thumbnail-850x480.jpg'
}
})
diff --git a/packages/tests/src/shared/videos.ts b/packages/tests/src/shared/videos.ts
index feed1a77b6..020c27f7d9 100644
--- a/packages/tests/src/shared/videos.ts
+++ b/packages/tests/src/shared/videos.ts
@@ -1,14 +1,16 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
-import { uuidRegex } from '@peertube/peertube-core-utils'
+import { maxBy, minBy, uuidRegex } from '@peertube/peertube-core-utils'
import { ffprobePromise } from '@peertube/peertube-ffmpeg'
import {
FileStorage,
HttpStatusCode,
HttpStatusCodeType,
+ Video,
VideoCaption,
VideoCommentPolicyType,
VideoDetails,
+ VideoPlaylist,
VideoPrivacy,
VideoResolution
} from '@peertube/peertube-models'
@@ -192,9 +194,6 @@ export async function completeVideoCheck (options: {
}
fixture: string
- thumbnailfile?: string
- previewfile?: string
-
files?: {
resolution: number
size: number
@@ -206,6 +205,8 @@ export async function completeVideoCheck (options: {
hlsOnly: boolean
resolutions: number[]
}
+
+ thumbnails?: string[]
}
}) {
const { attributes, originServer, server, videoUUID, objectStorageBaseUrl } = options
@@ -269,12 +270,10 @@ export async function completeVideoCheck (options: {
expect(video.channel.createdAt).to.exist
expect(dateIsValid(video.channel.updatedAt.toString())).to.be.true
- expect(video.thumbnailPath).to.exist
- await testImageGeneratedByFFmpeg(server.url, attributes.thumbnailfile || attributes.fixture, video.thumbnailPath)
-
- if (attributes.previewfile) {
- expect(video.previewPath).to.exist
- await testImageGeneratedByFFmpeg(server.url, attributes.previewfile, video.previewPath)
+ if (attributes.thumbnails) {
+ await checkThumbnails({ video, thumbnails: attributes.thumbnails, server })
+ } else {
+ await checkThumbnails({ video, thumbnails: [ attributes.fixture + '.jpg' ], strict: false, server })
}
if (attributes.files) {
@@ -311,8 +310,7 @@ export async function checkVideoFilesWereRemoved (options: {
const webVideoFiles = video.files || []
const hlsFiles = video.streamingPlaylists[0]?.files || []
- const thumbnailName = basename(video.thumbnailPath)
- const previewName = basename(video.previewPath)
+ const thumbnailNames = video.thumbnails.map(t => basename(t.fileUrl))
const torrentNames = webVideoFiles.concat(hlsFiles).map(f => basename(f.torrentUrl))
@@ -332,8 +330,7 @@ export async function checkVideoFilesWereRemoved (options: {
directories = {
...directories,
- thumbnails: [ thumbnailName ],
- previews: [ previewName ],
+ thumbnails: thumbnailNames,
torrents: torrentNames,
captions: captionNames
}
@@ -446,3 +443,50 @@ export async function probeResBody (body: Buffer) {
return probe
}
+
+export async function checkThumbnails (options: {
+ server: PeerTubeServer
+ video?: Video
+ playlist?: VideoPlaylist
+ thumbnails: string[]
+ strict?: boolean // default true
+}) {
+ const { server, video, playlist, strict = true } = options
+
+ const thumbnails = options.thumbnails.map(t => {
+ const matched = t.match(/-(\d+)x(\d+)/)
+
+ const width = matched
+ ? +matched[1]
+ : 280
+
+ const height = matched
+ ? +matched[2]
+ : 157
+
+ return { filename: t, width, height }
+ })
+
+ const entity = video || playlist
+
+ if (strict) {
+ expect(entity.thumbnails).to.have.lengthOf(thumbnails.length)
+ }
+
+ for (const thumbnail of thumbnails) {
+ const videoThumbnail = entity.thumbnails.find(t => t.width === thumbnail.width && t.height === thumbnail.height)
+ expect(videoThumbnail).to.exist
+
+ expectStartWith(videoThumbnail.fileUrl, server.url)
+
+ await testImageGeneratedByFFmpeg({ name: thumbnail.filename, url: videoThumbnail.fileUrl })
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ await testImageGeneratedByFFmpeg({ name: minBy(thumbnails, 'width').filename, url: server.url + entity.thumbnailPath })
+
+ if (video && thumbnails.length > 1) {
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
+ await testImageGeneratedByFFmpeg({ name: maxBy(thumbnails, 'width').filename, url: server.url + video.previewPath })
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4d47b1874a..9ef12c65c0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -35,9 +35,6 @@ importers:
'@commander-js/extra-typings':
specifier: ^14.0.0
version: 14.0.0([email protected])
- '@jimp/plugin-color':
- specifier: ^1.6.0
- version: 1.6.0
'@misskey-dev/node-http-message-signatures':
specifier: ^0.0.10
version: 0.0.10
@@ -233,9 +230,6 @@ importers:
iso-639-3:
specifier: 3.0.1
version: 3.0.1
- jimp:
- specifier: ^0.22.12
- version: 0.22.12([email protected])
js-yaml:
specifier: ^4.1.1
version: 4.1.1
@@ -326,6 +320,9 @@ importers:
sequelize-typescript:
specifier: ^2.1.6
+ sharp:
+ specifier: ^0.34.5
+ version: 0.34.5
short-uuid:
specifier: ^5.2.0
version: 5.2.0
@@ -501,9 +498,6 @@ importers:
i18next-parser:
specifier: ^9.3.0
version: 9.3.0
- jpeg-js:
- specifier: ^0.4.4
- version: 0.4.4
jszip:
specifier: ^3.10.1
version: 3.10.1
@@ -516,9 +510,6 @@ importers:
pixelmatch:
specifier: ^7.1.0
version: 7.1.0
- pngjs:
- specifier: ^7.0.0
- version: 7.0.0
proxy:
specifier: ^2.2.0
version: 2.2.0
@@ -1592,6 +1583,9 @@ packages:
'@dual-bundle/[email protected]':
resolution: {integrity: sha512-id+7YRUgoUX6CgV0DtuhirQWodeeA7Lf4i2x71JS/vtA5pRb/hIGWlw+G6MeXvsM+MXrz0VAydTGElX1rAfgPg==}
+ '@emnapi/[email protected]':
+ resolution: {integrity: sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==}
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}
engines: {node: '>=18'}
@@ -1996,6 +1990,143 @@ packages:
resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==}
+ resolution: {integrity: sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}
+ cpu: [arm]
+ os: [linux]
+
+ resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}
+ cpu: [ppc64]
+ os: [linux]
+
+ resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}
+ cpu: [riscv64]
+ os: [linux]
+
+ resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}
+ cpu: [s390x]
+ os: [linux]
+
+ resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm]
+ os: [linux]
+
+ resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [ppc64]
+ os: [linux]
+
+ resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [riscv64]
+ os: [linux]
+
+ resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [s390x]
+ os: [linux]
+
+ resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [wasm32]
+
+ resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [ia32]
+ os: [win32]
+
+ resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [win32]
+
'@inquirer/[email protected]':
resolution: {integrity: sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==}
engines: {node: '>=18'}
@@ -2195,191 +2326,6 @@ packages:
resolution: {integrity: sha512-H9xg1/sfVvyfU7o3zMfBEjQ1gcsdeTMgqHoYdN79tuLqfTtuu7WckRA1R5whDwOzxaZAeMKTYWqP+WCAi0CHsg==}
engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}
- resolution: {integrity: sha512-aeI64HD0npropd+AR76MCcvvRaa+Qck6loCOS03CkkxGHN5/r336qTM5HPUdHKMDOGzqknuVPA8+kK1t03z12g==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-l0RR0dOPyzMKfjUW1uebzueFEDtCOj9fN6pyTYWWOM/VS4BciXQ1VVrJs8pO3kycGYZxncRKhCoygbNr8eEZQA==}
-
- resolution: {integrity: sha512-EQQlKU3s9QfdJqiSrZWNTxBs3rKXgO2W+GxNXDtwchF3a4IqxDheFX1ti+Env9hdJXDiYLp2jTRjlxhPthsk8w==}
- engines: {node: '>=18'}
-
- resolution: {integrity: sha512-xcmww1O/JFP2MrlGUMd3Q78S3Qu6W3mYTXYuIqFq33EorgYHV/HqymHfXy9GjiCJ7OI+7lWx6nYFOzU7M4rd1Q==}
-
- resolution: {integrity: sha512-Dx/bVDmgnRe1AlniRpCKrGRm5YvGmUwbDzt+MAkgmLGf+jvBT75hmMEZ003n9HQI/aPnm/YKnXjg/hOpzNCpHQ==}
- engines: {node: '>=18'}
-
- resolution: {integrity: sha512-y6BFTJgch9mbor2H234VSjd9iwAhaNf/t3US5qpYIs0TSbAvM02Fbc28IaDETj9+4YB4676sz4RcN/zwhfu1pg==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-Rq26XC/uQWaQKyb/5lksCTCxXhtY01NJeBN+dQv5yNYedN0i7iYu+fXEoRsfaJ8xZzjoANH8sns7rVP4GE7d/Q==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-xslz2ZoFZOPLY8EZ4dC29m168BtDx95D6K80TzgUi8gqT7LY6CsajWO0FAxDwHz6h0eomHMfyGX0stspBrTKnQ==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-S0vJADTuh1Q9F+cXAwFPlrKWzDj2F9t/9JAbUvaaDuivpyWuImEKXVz5PUZw2NbpuSHjwssbTpOZ8F13iJX4uw==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-SWVXx1yiuj5jZtMijqUfvVOJBwOifFn0918ou4ftoHgegc5aHWW5dZbYPjvC9fLpvz7oSlptNl2Sxr1zwofjTg==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-xImhTE5BpS8xa+mAN6j4sMRWaUgUDLoaGHhJhpC+r7SKKErYDR0WQV4yCE4gP+N0gozD0F3Ka1LUSaMXrn7ZIA==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-J5q8IVCpkBsxIXM+45XOXTrsyfblyMZg3a9eAo0P7VPH4+CrvyNQwaYatbAIamSIN1YzxmO3DkIZXzRjFSz1SA==}
- engines: {node: '>=18'}
-
- resolution: {integrity: sha512-Eo3DmfixJw3N79lWk8q/0SDYbqmKt1xSTJ69yy8XLYQj9svoBbyRpSnHR+n9hOw5pKXytHwUW6nU4u1wegHNoQ==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-blit': '>=0.3.5'
- '@jimp/plugin-resize': '>=0.3.5'
- '@jimp/plugin-scale': '>=0.3.5'
-
- resolution: {integrity: sha512-z0w/1xH/v/knZkpTNx+E8a7fnasQ2wHG5ze6y5oL2dhH1UufNua8gLQXlv8/W56+4nJ1brhSd233HBJCo01BXA==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-crop': '>=0.3.5'
- '@jimp/plugin-resize': '>=0.3.5'
- '@jimp/plugin-scale': '>=0.3.5'
-
- resolution: {integrity: sha512-FNuUN0OVzRCozx8XSgP9MyLGMxNHHJMFt+LJuFjn1mu3k0VQxrzqbN06yIl46TVejhyAhcq5gLzqmSCHvlcBVw==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-qpRM8JRicxfK6aPPqKZA6+GzBwUIitiHaZw0QrJ64Ygd3+AsTc7BXr+37k2x7QcyCvmKXY4haUrSIsBug4S3CA==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-jYgGdSdSKl1UUEanX8A85v4+QUm+PE8vHFwlamaKk89s+PXQe7eVE3eNeSZX4inCq63EHL7cX580dMqkoC3ZLw==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-LGuUTsFg+fOp6KBKrmLkX4LfyCy8IIsROwoUvsUPKzutSqMJnsm3JGDW2eOmWIS/jJpPaeaishjlxvczjgII+Q==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-m251Rop7GN8W0Yo/rF9LWk6kNclngyjIJs/VXHToGQ6EGveOSTSQaX2Isi9f9lCDLxt+inBIb7nlaLLxnvHX8Q==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-rotate': '>=0.3.5'
-
- resolution: {integrity: sha512-sBfbzoOmJ6FczfG2PquiK84NtVGeScw97JsCC3rpQv1PHVWyW+uqWFF53+n3c8Y0P2HWlUjflEla2h/vWShvhg==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-N+6rwxdB+7OCR6PYijaA/iizXXodpxOGvT/smd/lxeXsZ/empHmFFFJ/FaXcYh19Tm04dGDaXcNF/dN5nm6+xQ==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-4AWZg+DomtpUA099jRV8IEZUfn1wLv6+nem4NRJC7L/82vxzLCgXKTxvNvBcNmJjT9yS1LAAmiJGdWKXG63/NA==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-0So0rexQivnWgnhacX4cfkM2223YdExnJTTy6d06WbkfZk5alHUx8MM3yEzwoCN0ErO7oyqEWRnEkGC+As1FtA==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-c7TnhHlxm87DJeSnwr/XOLjJU/whoiKYY7r21SbuJ5nuH+7a78EW1teOaj5gEr2wYEd7QtkFqGlmyGXY/YclyQ==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-blit': '>=0.3.5'
-
- resolution: {integrity: sha512-3NyTPlPbTnGKDIbaBgQ3HbE6wXbAlFfxHVERmrbqAi8R3r6fQPxpCauA8UVDnieg5eo04D0T8nnnNIX//i/sXg==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-9YNEt7BPAFfTls2FGfKBVgwwLUuKqy+E8bDGGEsOqHtbuhbshVGxN2WMZaD4gh5IDWvR+emmmPPWGgaYNYt1gA==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-blit': '>=0.3.5'
- '@jimp/plugin-crop': '>=0.3.5'
- '@jimp/plugin-resize': '>=0.3.5'
-
- resolution: {integrity: sha512-dghs92qM6MhHj0HrV2qAwKPMklQtjNpoYgAB94ysYpsXslhRTiPisueSIELRwZGEr0J0VUxpUY7HgJwlSIgGZw==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-resize': '>=0.3.5'
-
- resolution: {integrity: sha512-FX8mTJuCt7/3zXVoeD/qHlm4YH2bVqBuWQHXSuBK054e7wFRnRnbSLPUqAwSeYP3lWqpuQzJtgiiBxV3+WWwTg==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-blur': '>=0.3.5'
- '@jimp/plugin-resize': '>=0.3.5'
-
- resolution: {integrity: sha512-4x5GrQr1a/9L0paBC/MZZJjjgjxLYrqSmWd+e+QfAEPvmRxdRoQ5uKEuNgXnm9/weHQBTnQBQsOY2iFja+XGAw==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
- '@jimp/plugin-color': '>=0.8.0'
- '@jimp/plugin-resize': '>=0.8.0'
-
- resolution: {integrity: sha512-yBJ8vQrDkBbTgQZLty9k4+KtUQdRjsIDJSPjuI21YdVeqZxYywifHl4/XWILoTZsjTUASQcGoH0TuC0N7xm3ww==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-Mrp6dr3UTn+aLK8ty/dSKELz+Otdz1v4aAXzV5q53UDD2rbB5joKVJ/ChY310B+eRzNxIovbUF1KVrUsYdE8Hg==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-E1LtMh4RyJsoCAfAkBRVSYyZDTtLq9p9LUiiYP0vPtXyxX4BiYBUYihTLSBlCQg5nF2e4OpQg7SPrLdJ66u7jg==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-wwKYzRdElE1MBXFREvCto5s699izFHNVvALUv79GXNbsOVqlwlOxlWJ8DuyOGIXoLP4JW/m30YyuTtfUJgMRMA==}
- peerDependencies:
- '@jimp/custom': '>=0.3.5'
-
- resolution: {integrity: sha512-7UfRsiKo5GZTAATxm2qQ7jqmUXP0DxTArztllTcYdyw6Xi5oT4RaoXynVtCD4UyLK5gJgkZJcwonoijrhYFKfg==}
- engines: {node: '>=18'}
-
- resolution: {integrity: sha512-yJ5cWUknGnilBq97ZXOyOS0HhsHOyAyjHwYfHxGbSyMTohgQI6sVyE8KPgDwH8HHW/nMKXk8TrSwAE71zt716Q==}
-
- resolution: {integrity: sha512-gqFTGEosKbOkYF/WFj26jMHOI5OH2jeP1MmC/zbK6BF6VJBf8rIC5898dPfSzZEbSA0wbbV5slbntWVc5PKLFA==}
- engines: {node: '>=18'}
-
'@jridgewell/[email protected]':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -3147,6 +3093,7 @@ packages:
'@primeng/[email protected]':
resolution: {integrity: sha512-Hze5bBTjsLzZXb20qsm9apsFuzpZzXiU+Ulj/7R+2fwMmcQk0XpkQS7V88fsFw6xsTD7+R+hgqr7Rzy0Gf+4dw==}
+ deprecated: 'Deprecated. This package is no longer maintained. Please migrate to @primeuix/themes: https://www.npmjs.com/package/@primeuix/themes'
'@primeuix/[email protected]':
resolution: {integrity: sha512-ColZes0+/WKqH4ob2x8DyNYf1NENpe5ZguOvx5yCLxaP8EIMVhLjWLO/3umJiDnQU4XXMLkn2mMHHw+fhTX/mw==}
@@ -3699,9 +3646,6 @@ packages:
resolution: {integrity: sha512-Q53KyCXweV1CS62EfqtPDqfpksn5keQ59PGqzzkK+g8Vif1jB4inoBCcs/BUSdsqddhE3G+2Fn+4RX3S6RqT0A==}
engines: {node: '>=0.2.6'}
- '@tokenizer/[email protected]':
- resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==}
-
'@tootallnate/[email protected]':
resolution: {integrity: sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==}
@@ -3896,9 +3840,6 @@ packages:
resolution: {integrity: sha512-C3Z9v9Evij2yST3RSBktxP9STm6OdMc5uR1xF1SGr98uv8dUlAL2hqwrZ3GVB3uyMyiegnscEK6PGtYvNrjTjw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-QpLcX9ZSsq3YYUUnD3nFDY8H7wctAhQj/TFKL8Ya8v5fMm3CFXxo8zStsLAl780ltoYoo1WvKUVGBQK+1ifr7g==}
-
resolution: {integrity: sha512-ZsJzA5thDQMSQO788d7IocwwQbI8B5OPzmqNvpf3NY/+MHDAS759Wo0gd2WQeXYt5AAAQjzcrTVC6SKCuYgoCQ==}
@@ -4497,10 +4438,6 @@ packages:
resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-zJAaP9zxTcvTHRlejau3ZOY4V7SRpiByf3/dxx2uyKxxor19tpmpV2QRsTKikckwhaPmr2dVpxxMr7jOCYVp5g==}
- engines: {node: '>=6.0.0'}
-
resolution: {integrity: sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==}
@@ -4675,9 +4612,6 @@ packages:
resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}
- resolution: {integrity: sha512-vHdS19CnY3hwiNdkaqk93DvjVLfbEcI8mys4UjuWrlX1haDmroo8o4xCzh4wD6DGV6HxRCyauwhHRqMTfERtjw==}
-
resolution: {integrity: sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==}
@@ -4782,10 +4716,6 @@ packages:
resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}
- resolution: {integrity: sha512-RgSV6InVQ9ODPdLWJ5UAqBqJBOg370Nz6ZQtRzpt6nUjc8v0St97uJ4PYC6NztqIScrAXafKM3mZPMygSe1ggA==}
- engines: {node: '>=0.4.0'}
-
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
@@ -4885,9 +4815,6 @@ packages:
resolution: {integrity: sha512-0CNTVCLZggSh7bc5VkX5WWPWO+cyZbNd07IHIsSXLia/eAq+r836hgk+8BKoEh7949Mda87VUOitx5OddVj64A==}
- resolution: {integrity: sha512-PbFMgMSrmgx6uxCdm57RUos9Tc3fclMvhLSATYN39XsDV29B89zZ3KA89jmY0vwSGazyU+uerqwa6t+KaodPcg==}
-
resolution: {integrity: sha512-TR/xPDxRhqwFFCWg1HgL8nNWbpNfUwaib6pBN++QKpnd0t+o3+MBvAn5CM1mpdUMaM76oJAtUjGKdjGad01lIA==}
engines: {node: '>= 6'}
@@ -6007,9 +5934,6 @@ packages:
resolution: {integrity: sha512-jpWzZ1ZhwUmeWRhS7Qv3mhpOhLfwI+uAX4e5fOcXqwMR7EcJ0pj2kV1CVzHVMX/LphnKWD3LObjZCoJ71lKpHw==}
engines: {node: ^18.19.0 || >=20.5.0}
- resolution: {integrity: sha512-c2bQfLNbMzLPmzQuOr8fy0csy84WmwnER81W88DzTp9CYNPJ6yzOj2EZAh9pywYpqHnshVLHQJ8WzldAyfY+Iw==}
-
resolution: {integrity: sha512-Fqs7ChZm72y40wKjOFXBKg7nJZvQJmewP5/7LtePDdnah/+FH9Hp5sgMujSCMPXlxOAW2//1jrW9pnsY7o20vQ==}
engines: {node: '>=18'}
@@ -6170,10 +6094,6 @@ packages:
resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==}
engines: {node: '>=16.0.0'}
- resolution: {integrity: sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==}
@@ -6424,9 +6344,6 @@ packages:
resolution: {integrity: sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==}
engines: {node: '>= 14'}
- resolution: {integrity: sha512-2760b1vpJHNmLzZ/ubTtNnEx5WApN/PYWJvXvgS+tL1egTTthayFYIQQNi136FLEDcN/IyEY2EcGpIITD6eYUw==}
-
resolution: {integrity: sha512-8aCohiDo4jwjOwma4FmYFd3i97urZulL8XL24nIPxuE+GZnfsAyy/g2Shqx6OjUiFKUXZM+Yy+KHnOmmA3FVcg==}
engines: {node: '>= 4.0'}
@@ -6801,9 +6718,6 @@ packages:
resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==}
engines: {node: '>= 4'}
- resolution: {integrity: sha512-PfJGVgIfKQJuq3s0tTDOKtztksibuUEbJQIYT3by6wctQo+Rdlh7ef4evJ5NCdxY4CfMbvFkocEwbl4BF8RlJw==}
-
resolution: {integrity: sha512-1bHBna0hCa6arRXicu91IiL9RvvkbNYLVq+mzWdaLGZC3hXvX4doh8e1dLhMKez5siu63CYgO5NrGJbRX5lbPA==}
@@ -7145,9 +7059,6 @@ packages:
resolution: {integrity: sha512-SdljCYXOexv/JmbQ0tvigHN43yECoscVpe2y2hlEqy/CStXQlroPhZLj7zKLRiGqLJfw8k7B973UAMDoQczVgQ==}
- resolution: {integrity: sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==}
-
resolution: {integrity: sha512-u4sej9B1LPSxTGKB/HiuzvEQnXH0ECYkSVQU39koSwmFAxhlEAFl9RdTvLv4TOTQUgBS5O3O5fwUxk6byBZ+IQ==}
engines: {node: '>=10'}
@@ -7199,9 +7110,6 @@ packages:
resolution: {integrity: sha512-QKNsM0o3Xe6ISQU869e+DhG+4CK/48aHYdJZGlFQVTjnbvgpcKyxpzk29fGiO7i/J8VENZ+d2iGnSsvmuHywlA==}
engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}
- resolution: {integrity: sha512-R5jZaYDnfkxKJy1dwLpj/7cvyjxiclxU3F4TrI/J4j2rS0niq6YDUMoPn5hs8GDpO+OZGo7Ky057CRtWesyhfg==}
-
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true
@@ -7216,9 +7124,6 @@ packages:
resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==}
-
resolution: {integrity: sha512-rtS5ATOo2Q5k1G+DADISilDA6lv79zIiwFd6CcjuIxGKLFm5C+RLImRscVap9k55i+MOZwgliw+NejvkLuGD5g==}
@@ -7439,9 +7344,6 @@ packages:
resolution: {integrity: sha512-nwVGUfTBUwJKXd6lRV8pFNfnrCC1+l49ESJRM19t/tFb/97QfJEixe5DYRvug5JO7DSFKoKaVy7oGMt5rVqZvg==}
hasBin: true
- resolution: {integrity: sha512-qElWkmjW9Oq1F9EI5Gt7aD9zcdHb9spJCW1L/dmPf7KzCCEJxq8nhHz5eCgI9aMf7vrG/wyaCqdsI+Iy9ZTlog==}
-
resolution: {integrity: sha512-ZFZt1g4Exq01SFtKjffqau+L4Qibt+51utymHHiWo8Iu/W7LYSqE7fiZ/iAZ6dIqbmeU6ICSIK02IizSScBkLQ==}
engines: {node: '>=12.20.0'}
@@ -8188,9 +8090,6 @@ packages:
resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==}
-
resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==}
engines: {node: '>=14.0.0'}
@@ -8355,18 +8254,6 @@ packages:
resolution: {integrity: sha512-fIYNuZ/HastSb80baGOuPRo1O9cf4baWw5WsAp7dBuUzeTD/BoaG8sVTdlPFksBE2lF21dN+A1AnrpIjSWqHHg==}
engines: {node: '>= 0.10'}
- resolution: {integrity: sha512-U4RrVsUFCleIOBsIGYOMKjn9PavsGOXxbvYGtMOEfnId0SVNsgehXh1DxUdVPLoxd5mvcEtvmKs2Mmf0Mpa1ZA==}
-
- resolution: {integrity: sha512-GxmsRea0wdGdYthjuUeWTMWPqm2+FAd4GI8vCvhgJsFnoGhTrLhXDDupwTo7rXVAgaLIGoVHDZS9p/5XbSqeWA==}
-
- resolution: {integrity: sha512-0cEliVMZEhrFDwMh4SxIyVJpqYoOWDJ9P895tFuS+XuNzI5UBmBk5U5O4KuJdTnZpSBI4LFA2+ZiJaiwfSwlMA==}
-
- resolution: {integrity: sha512-Tz11t3uKztEW5FEVZnj1ox8GKblWn+PvHY9TmJV5Mll2uHEwRdR/5Li1OlXoECjLYkApdhWy44ocONwXLiKO5A==}
-
resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}
engines: {node: '>=8'}
@@ -8487,10 +8374,6 @@ packages:
resolution: {integrity: sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==}
- resolution: {integrity: sha512-ZI3LnwUv5nOGbQzD9c2iDG6toheuXSZP5esSHBjopsXH4dg19soufvpUGA3uohi5anFtGb2lhAVdHzH6R/Evvg==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-FhJ+YbOSBb9/rIl2ZeE/QHEsWn7PqNYt8ARAY3kIgNGOk13g9FGyIY6JIl/xB/3TFRVoTv5as0l11weORrTekA==}
@@ -8531,11 +8414,6 @@ packages:
resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==}
- resolution: {integrity: sha512-GEazpTWwTZaEQ9RhL7Nyz0WwqilbqgLahDM3D0hxWwmVDI52nXEybHqiN6/elwpkJBhcuj+WbBu+QfT0uhPGfQ==}
- engines: {node: '>= 8'}
- deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
-
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -8576,10 +8454,6 @@ packages:
resolution: {integrity: sha512-7uU4ZnKeQq22t9AsmHGD2w4OYQGonwFnTypDypaWi7Qr2EvQIFVtG8J5D/3bE7W123Wdc9+v4CZDu5hJXVCtBg==}
engines: {node: '>=20.x'}
- resolution: {integrity: sha512-J8B6xqiO37sU/gkcMglv6h5Jbd9xNER7aHzpfRdNmV4IbQBzBpe4l9XmbG+xPF/znacgu2jfEw+wHffaq/YkXA==}
- hasBin: true
-
resolution: {integrity: sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng==}
hasBin: true
@@ -8599,18 +8473,10 @@ packages:
resolution: {integrity: sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==}
- resolution: {integrity: sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==}
- engines: {node: '>=4.0.0'}
-
resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==}
engines: {node: '>=10.13.0'}
- resolution: {integrity: sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg==}
- engines: {node: '>=12.13.0'}
-
resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==}
engines: {node: '>=14.19.0'}
@@ -8966,10 +8832,6 @@ packages:
resolution: {integrity: sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
- resolution: {integrity: sha512-9nX56alTf5bwXQ3ZDipHJhusu9NTQJ/CVPtb/XHAJCXihZeitfJvIRS4GqQ/mfIoOE3IelHMrpayVrosdHBuLw==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-/8n0Mr10S+HGKFygQ42Z40JIXwafPH3A72pwmlNClThgsImV5LJJiCue5Je1asxwY082sYxq/+kTxH6nTn0w3g==}
@@ -9010,9 +8872,6 @@ packages:
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==}
-
resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==}
engines: {node: '>= 0.4'}
@@ -9493,6 +9352,10 @@ packages:
engines: {node: '>= 0.10'}
hasBin: true
+ resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+
resolution: {integrity: sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==}
engines: {node: '>=0.10.0'}
@@ -9827,10 +9690,6 @@ packages:
resolution: {integrity: sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==}
- resolution: {integrity: sha512-fZtbhtvI9I48xDSywd/somNqgUHl2L2cstmXCCif0itOf96jeW18MBSyrLuNicYQVkvpOxkZtkzujiTJ9LW5Jw==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-QYBxdBtA4Tl5rFPuqmbmdrS9kbtren74RTJTcs0VSQNVV5iRhJD4QlYTLD0+81SBwUQctjEQzjTRI3WG4DzICA==}
engines: {node: '>= 14', npm: '>=6'}
@@ -9996,9 +9855,6 @@ packages:
resolution: {integrity: sha512-wMctrWD2HZZLuIlchlkE2dfXJh7J2KDI9Dwl+2abPYg0mswQHfOAyQW3jJg1pY5VfttSINZuKcXoB3FGypVklA==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-IjZc9KIotudix8bMaBW6QvMuq64BrJWFs1+4V0lXwWGQZwH+LnX87doAYhem4caOEusRP9/g6jVDQmZ8XOk1nw==}
-
resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}
@@ -10006,9 +9862,6 @@ packages:
resolution: {integrity: sha512-hkcz3FjNJfKXjV4mjQ1OrXSLAehg8Hw+cEZclOVT+5c/cWQWImQ9wolzTjth+dmmDe++p3bme3fTxz6Q4Etsqw==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==}
-
resolution: {integrity: sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==}
engines: {node: '>=12.0.0'}
@@ -10063,10 +9916,6 @@ packages:
resolution: {integrity: sha512-VSsyNPPW74RpHwR8Fc21uubwHY7wMDeJLys2IX5zJNih+OnAnaifKHo+1LHT7DAdloQ7apeaaWg8l7qnf/TnEg==}
- resolution: {integrity: sha512-6udB24Q737UD/SDsKAHI9FCRP7Bqc9D/MQUV02ORQg5iskjtLJlZJNdN4kKtcdtwCeWIwIHDGaUsTsCCAa8sFQ==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-rdiCrKjuAurxeK3H3/KXu+3Wktp+H7dgI7XhYvFRr2kE0LdIor+0VTNlcdgyqhYlRq+iWK/A6tagUIims8BHIA==}
@@ -10355,9 +10204,6 @@ packages:
resolution: {integrity: sha512-EYZR+OpIXp9Y1eG1iueg8KRsY8TuT8VNgnanZ0uA3STqhHQTLwbl+WX76/9X5OY12yQubymBpaBSmMPkSTQcKA==}
engines: {node: '>=6.14.2'}
- resolution: {integrity: sha512-+oknB9FHrJ7oW7A2WZYajOcv4FcDR4CfoGB0dPNfxbi4GO05RRnFmt5oa23+9w32EanrYcSJWspUiJkLMs+37w==}
-
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@@ -10657,9 +10503,6 @@ packages:
resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg==}
-
resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}
engines: {node: '>=18'}
@@ -10801,9 +10644,6 @@ packages:
utf-8-validate:
optional: true
- resolution: {integrity: sha512-/eCGLb5rxjx5e3mF1A7s+pLlR6CGyqWN91fv1JgER5mVWg1MZmlhBvy9kjcsOdRk8RrIujotWyJamfyrp+WIcA==}
-
resolution: {integrity: sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==}
hasBin: true
@@ -10812,9 +10652,6 @@ packages:
resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-ErcKwJTF54uRzzNMXq2X5sMIy88zJvfN2DmdoQvy7PAFJ+tPRU6ydWuOKNMyfmOjdyBQTFREi60s0Y0SyI0G0g==}
-
resolution: {integrity: sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==}
engines: {node: '>=4.0.0'}
@@ -10934,9 +10771,6 @@ packages:
peerDependencies:
zod: ^3.25 || ^4
- resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
-
resolution: {integrity: sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==}
@@ -12128,6 +11962,11 @@ snapshots:
'@dual-bundle/[email protected]': {}
+ '@emnapi/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
'@esbuild/[email protected]':
optional: true
@@ -12385,6 +12224,102 @@ snapshots:
'@iarna/[email protected]': {}
+ '@img/[email protected]': {}
+
+ optionalDependencies:
+ '@img/sharp-libvips-darwin-arm64': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-darwin-x64': 1.2.4
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linux-arm64': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linux-arm': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linux-ppc64': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linux-riscv64': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linux-s390x': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linux-x64': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linuxmusl-arm64': 1.2.4
+ optional: true
+
+ optionalDependencies:
+ '@img/sharp-libvips-linuxmusl-x64': 1.2.4
+ optional: true
+
+ dependencies:
+ '@emnapi/runtime': 1.8.1
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
'@inquirer/[email protected]': {}
@@ -12582,251 +12517,6 @@ snapshots:
'@types/yargs': 17.0.34
chalk: 4.1.2
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
- bmp-js: 0.1.0
-
- dependencies:
- '@jimp/utils': 0.22.12
- any-base: 1.1.0
- buffer: 5.7.1
- exif-parser: 0.1.12
- file-type: 16.5.4
- isomorphic-fetch: 3.0.0([email protected])
- pixelmatch: 4.0.2
- tinycolor2: 1.6.0
- transitivePeerDependencies:
- - encoding
-
- dependencies:
- '@jimp/file-ops': 1.6.0
- '@jimp/types': 1.6.0
- '@jimp/utils': 1.6.0
- await-to-js: 3.0.0
- exif-parser: 0.1.12
- file-type: 16.5.4
- mime: 3.0.0
-
- dependencies:
- '@jimp/core': 0.22.12([email protected])
- transitivePeerDependencies:
- - encoding
-
- '@jimp/[email protected]': {}
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
- gifwrap: 0.10.1
- omggif: 1.0.10
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
- jpeg-js: 0.4.4
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
- tinycolor2: 1.6.0
-
- dependencies:
- '@jimp/core': 1.6.0
- '@jimp/types': 1.6.0
- '@jimp/utils': 1.6.0
- tinycolor2: 1.6.0
- zod: 3.25.76
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-blit': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-resize': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-crop': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-resize': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-blit': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/utils': 0.22.12
- load-bmfont: 1.4.2
- transitivePeerDependencies:
- - debug
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-blit': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-crop': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-resize': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-resize': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-blur': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-resize': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-color': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-resize': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/utils': 0.22.12
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugin-blit': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-blur': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-circle': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-color': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-crop': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-displace': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-dither': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-fisheye': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-gaussian': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-invert': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-mask': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-normalize': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/plugin-resize': 0.22.12(@jimp/[email protected]([email protected]))
- timm: 1.7.1
- transitivePeerDependencies:
- - debug
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/utils': 0.22.12
- pngjs: 6.0.0
-
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- utif2: 4.1.0
-
- dependencies:
- '@jimp/bmp': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/gif': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/jpeg': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/png': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/tiff': 0.22.12(@jimp/[email protected]([email protected]))
- timm: 1.7.1
-
- dependencies:
- zod: 3.25.76
-
- dependencies:
- regenerator-runtime: 0.13.11
-
- dependencies:
- '@jimp/types': 1.6.0
- tinycolor2: 1.6.0
-
'@jridgewell/[email protected]':
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -14109,8 +13799,6 @@ snapshots:
dependencies:
uint8-util: 2.2.5
- '@tokenizer/[email protected]': {}
-
'@tootallnate/[email protected]': {}
'@tsconfig/[email protected]': {}
@@ -14323,8 +14011,6 @@ snapshots:
dependencies:
'@types/express': 4.17.9
- '@types/[email protected]': {}
-
dependencies:
undici-types: 6.21.0
@@ -15220,8 +14906,6 @@ snapshots:
dependencies:
possible-typed-array-names: 1.1.0
-
dependencies:
follow-redirects: 1.15.11([email protected])
@@ -15437,8 +15121,6 @@ snapshots:
-
@@ -15599,8 +15281,6 @@ snapshots:
-
@@ -15728,12 +15408,6 @@ snapshots:
- dependencies:
- follow-redirects: 1.15.11([email protected])
- transitivePeerDependencies:
- - debug
-
dependencies:
chai: 6.2.1
@@ -17176,8 +16850,6 @@ snapshots:
strip-final-newline: 4.0.0
yoctocolors: 2.1.2
-
@@ -17392,12 +17064,6 @@ snapshots:
dependencies:
flat-cache: 4.0.1
- dependencies:
- readable-web-to-node-stream: 3.0.4
- strtok3: 6.3.0
- token-types: 4.2.1
-
dependencies:
minimatch: 5.1.6
@@ -17716,11 +17382,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- image-q: 4.0.0
- omggif: 1.0.10
-
@@ -18184,10 +17845,6 @@ snapshots:
- dependencies:
- '@types/node': 16.9.1
-
dependencies:
queue-microtask: 1.2.3
@@ -18499,13 +18156,6 @@ snapshots:
- dependencies:
- node-fetch: 2.7.0([email protected])
- whatwg-fetch: 3.6.20
- transitivePeerDependencies:
- - encoding
-
@@ -18585,16 +18235,6 @@ snapshots:
graceful-fs: 4.2.11
picomatch: 4.0.3
- dependencies:
- '@jimp/custom': 0.22.12([email protected])
- '@jimp/plugins': 0.22.12(@jimp/[email protected]([email protected]))
- '@jimp/types': 0.22.12(@jimp/[email protected]([email protected]))
- regenerator-runtime: 0.13.11
- transitivePeerDependencies:
- - debug
- - encoding
-
@@ -18603,8 +18243,6 @@ snapshots:
-
@@ -18872,19 +18510,6 @@ snapshots:
'@lmdb/lmdb-win32-x64': 3.4.2
optional: true
- dependencies:
- buffer-equal: 0.0.1
- mime: 1.6.0
- parse-bmfont-ascii: 1.0.6
- parse-bmfont-binary: 1.0.6
- parse-bmfont-xml: 1.1.6
- phin: 3.7.1
- xhr: 2.6.0
- xtend: 4.0.2
- transitivePeerDependencies:
- - debug
-
dependencies:
cross-fetch-ponyfill: 1.0.3
@@ -19216,7 +18841,8 @@ snapshots:
+ optional: true
optional: true
@@ -19741,8 +19367,6 @@ snapshots:
define-properties: 1.2.1
es-object-atoms: 1.1.1
-
@@ -19958,17 +19582,6 @@ snapshots:
pbkdf2: 3.1.5
safe-buffer: 5.2.1
-
-
- dependencies:
- xml-parse-from-string: 1.0.1
- xml2js: 0.5.0
-
-
dependencies:
'@babel/code-frame': 7.27.1
@@ -20088,8 +19701,6 @@ snapshots:
-
dependencies:
buffer-from: 1.1.2
@@ -20133,12 +19744,6 @@ snapshots:
dependencies:
split2: 4.2.0
- dependencies:
- centra: 2.7.0
- transitivePeerDependencies:
- - debug
-
@@ -20193,10 +19798,6 @@ snapshots:
optionalDependencies:
'@napi-rs/nice': 1.1.1
- dependencies:
- pngjs: 3.4.0
-
dependencies:
pngjs: 7.0.0
@@ -20215,12 +19816,8 @@ snapshots:
dependencies:
semver-compare: 1.0.0
-
-
@@ -20669,10 +20266,6 @@ snapshots:
process: 0.11.10
string_decoder: 1.3.0
- dependencies:
- readable-stream: 4.7.0
-
dependencies:
readable-stream: 1.1.14
@@ -20719,8 +20312,6 @@ snapshots:
get-proto: 1.0.1
which-builtin-type: 1.2.1
-
dependencies:
call-bind: 1.0.8
@@ -21249,6 +20840,37 @@ snapshots:
safe-buffer: 5.2.1
to-buffer: 1.2.2
+ dependencies:
+ '@img/colour': 1.0.0
+ detect-libc: 2.1.2
+ semver: 7.7.3
+ optionalDependencies:
+ '@img/sharp-darwin-arm64': 0.34.5
+ '@img/sharp-darwin-x64': 0.34.5
+ '@img/sharp-libvips-darwin-arm64': 1.2.4
+ '@img/sharp-libvips-darwin-x64': 1.2.4
+ '@img/sharp-libvips-linux-arm': 1.2.4
+ '@img/sharp-libvips-linux-arm64': 1.2.4
+ '@img/sharp-libvips-linux-ppc64': 1.2.4
+ '@img/sharp-libvips-linux-riscv64': 1.2.4
+ '@img/sharp-libvips-linux-s390x': 1.2.4
+ '@img/sharp-libvips-linux-x64': 1.2.4
+ '@img/sharp-libvips-linuxmusl-arm64': 1.2.4
+ '@img/sharp-libvips-linuxmusl-x64': 1.2.4
+ '@img/sharp-linux-arm': 0.34.5
+ '@img/sharp-linux-arm64': 0.34.5
+ '@img/sharp-linux-ppc64': 0.34.5
+ '@img/sharp-linux-riscv64': 0.34.5
+ '@img/sharp-linux-s390x': 0.34.5
+ '@img/sharp-linux-x64': 0.34.5
+ '@img/sharp-linuxmusl-arm64': 0.34.5
+ '@img/sharp-linuxmusl-x64': 0.34.5
+ '@img/sharp-wasm32': 0.34.5
+ '@img/sharp-win32-arm64': 0.34.5
+ '@img/sharp-win32-ia32': 0.34.5
+ '@img/sharp-win32-x64': 0.34.5
+
dependencies:
shebang-regex: 1.0.0
@@ -21657,11 +21279,6 @@ snapshots:
- dependencies:
- '@tokenizer/token': 0.3.0
- peek-readable: 4.1.0
-
@@ -21916,14 +21533,10 @@ snapshots:
-
-
dependencies:
fdir: 6.5.0([email protected])
@@ -21975,11 +21588,6 @@ snapshots:
- dependencies:
- '@tokenizer/token': 0.3.0
- ieee754: 1.2.1
-
@@ -22291,10 +21899,6 @@ snapshots:
node-gyp-build: 4.8.4
optional: true
- dependencies:
- pako: 1.0.11
-
@@ -22659,8 +22263,6 @@ snapshots:
dependencies:
iconv-lite: 0.6.3
-
@@ -22840,21 +22442,12 @@ snapshots:
bufferutil: 4.0.9
utf-8-validate: 6.0.5
- dependencies:
- global: 4.4.0
- is-function: 1.0.2
- parse-headers: 2.0.6
- xtend: 4.0.2
-
dependencies:
sax: 1.4.3
-
dependencies:
sax: 1.4.3
@@ -22979,8 +22572,6 @@ snapshots:
dependencies:
zod: 4.1.13
-
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index eda731eb93..54a353f91b 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -20,6 +20,7 @@ onlyBuiltDependencies:
- node-datachannel
- utf-8-validate
- utp-native
+ - sharp
patchedDependencies:
'@types/markdown-it': pnpm-patches/@types__markdown-it.patch
diff --git a/server/core/controllers/api/config.ts b/server/core/controllers/api/config.ts
index 91bf9466d9..8faf45591a 100644
--- a/server/core/controllers/api/config.ts
+++ b/server/core/controllers/api/config.ts
@@ -378,20 +378,6 @@ function customConfig (): CustomConfig {
}
}
},
- cache: {
- previews: {
- size: CONFIG.CACHE.PREVIEWS.SIZE
- },
- captions: {
- size: CONFIG.CACHE.VIDEO_CAPTIONS.SIZE
- },
- torrents: {
- size: CONFIG.CACHE.TORRENTS.SIZE
- },
- storyboards: {
- size: CONFIG.CACHE.STORYBOARDS.SIZE
- }
- },
signup: {
enabled: CONFIG.SIGNUP.ENABLED,
limit: CONFIG.SIGNUP.LIMIT,
diff --git a/server/core/controllers/api/runners/jobs-files.ts b/server/core/controllers/api/runners/jobs-files.ts
index e54deb5d79..c59a5ebfa7 100644
--- a/server/core/controllers/api/runners/jobs-files.ts
+++ b/server/core/controllers/api/runners/jobs-files.ts
@@ -33,11 +33,11 @@ runnerJobFilesRouter.post(
)
runnerJobFilesRouter.post(
- '/jobs/:jobUUID/files/videos/:videoId/previews/max-quality',
+ [ '/jobs/:jobUUID/files/videos/:videoId/thumbnails/max-quality', '/jobs/:jobUUID/files/videos/:videoId/previews/max-quality' ],
apiRateLimiter,
asyncMiddleware(jobOfRunnerGetValidatorFactory([ RunnerJobState.PROCESSING ])),
asyncMiddleware(runnerJobGetVideoTranscodingFileValidator),
- getMaxQualityVideoPreview
+ getMaxQualityVideoThumbnail
)
runnerJobFilesRouter.post(
@@ -107,7 +107,6 @@ async function serveVideoFile (options: {
req,
res,
filename: file.filename,
- playlist: video.getHLSPlaylist(),
reinjectVideoFileToken: false,
video
})
@@ -128,7 +127,7 @@ async function serveVideoFile (options: {
// ---------------------------------------------------------------------------
-function getMaxQualityVideoPreview (req: express.Request, res: express.Response) {
+function getMaxQualityVideoThumbnail (req: express.Request, res: express.Response) {
const runnerJob = res.locals.runnerJob
const runner = runnerJob.Runner
const video = res.locals.videoAll
@@ -141,9 +140,9 @@ function getMaxQualityVideoPreview (req: express.Request, res: express.Response)
lTags(runner.name, runnerJob.id, runnerJob.type)
)
- const file = video.getPreview()
+ const file = video.getBestThumbnail()
- return res.sendFile(file.getPath())
+ return res.sendFile(file.getFSPath())
}
function getVideoStudioTaskFile (req: express.Request, res: express.Response) {
diff --git a/server/core/controllers/api/video-playlist.ts b/server/core/controllers/api/video-playlist.ts
index def43299d4..5f6a9bba15 100644
--- a/server/core/controllers/api/video-playlist.ts
+++ b/server/core/controllers/api/video-playlist.ts
@@ -32,7 +32,7 @@ import { MIMETYPES, VIDEO_PLAYLIST_PRIVACIES } from '../../initializers/constant
import { sequelizeTypescript } from '../../initializers/database.js'
import { sendCreateVideoPlaylist, sendDeleteVideoPlaylist, sendUpdateVideoPlaylist } from '../../lib/activitypub/send/index.js'
import { getLocalVideoPlaylistActivityPubUrl, getLocalVideoPlaylistElementActivityPubUrl } from '../../lib/activitypub/url.js'
-import { updateLocalPlaylistMiniatureFromExisting } from '../../lib/thumbnail.js'
+import { createLocalPlaylistThumbnailFromImage } from '../../lib/thumbnail.js'
import {
apiRateLimiter,
asyncMiddleware,
@@ -197,7 +197,7 @@ async function createVideoPlaylist (req: express.Request, res: express.Response)
const thumbnailField = req.files?.['thumbnailfile']
const thumbnailModel = thumbnailField
- ? await updateLocalPlaylistMiniatureFromExisting({
+ ? await createLocalPlaylistThumbnailFromImage({
inputPath: thumbnailField[0].path,
playlist: videoPlaylist,
automaticallyGenerated: false
@@ -259,7 +259,7 @@ async function updateVideoPlaylist (req: express.Request, res: express.Response)
const thumbnailField = req.files?.['thumbnailfile']
const thumbnailModel = thumbnailField
- ? await updateLocalPlaylistMiniatureFromExisting({
+ ? await createLocalPlaylistThumbnailFromImage({
inputPath: thumbnailField[0].path,
playlist,
automaticallyGenerated: false
@@ -567,8 +567,6 @@ async function reorderVideosOfPlaylist (req: express.Request, res: express.Respo
videoPlaylist.changed('updatedAt', true)
await videoPlaylist.save({ transaction: t })
-
- await sendUpdateVideoPlaylist(videoPlaylist, t)
})
// The first element changed
@@ -576,6 +574,8 @@ async function reorderVideosOfPlaylist (req: express.Request, res: express.Respo
await regeneratePlaylistThumbnail(videoPlaylist)
}
+ await sendUpdateVideoPlaylist(videoPlaylist, undefined)
+
logger.info(
'Reordered playlist %s (inserted after position %d elements %d - %d).',
videoPlaylist.uuid,
diff --git a/server/core/controllers/api/videos/import.ts b/server/core/controllers/api/videos/import.ts
index 315e241d0f..152c5c070f 100644
--- a/server/core/controllers/api/videos/import.ts
+++ b/server/core/controllers/api/videos/import.ts
@@ -2,15 +2,16 @@ import {
HttpStatusCode,
HttpStatusCodeType,
ServerErrorCode,
- ThumbnailType,
VideoImportCreate,
VideoImportPayload,
VideoImportState
} from '@peertube/peertube-models'
+import { getVideoThumbnailFile } from '@server/helpers/video.js'
import { YoutubeDlImportError, YoutubeDlImportErrorCode } from '@server/helpers/youtube-dl/youtube-dl-wrapper.js'
+import { createLocalVideoThumbnailsFromImage } from '@server/lib/thumbnail.js'
import { buildRetryImportJob } from '@server/lib/video-post-import.js'
import { buildVideoFromImport, buildYoutubeDLImport, insertFromImportIntoDB } from '@server/lib/video-pre-import.js'
-import { MThumbnail, MVideoThumbnail } from '@server/types/models/index.js'
+import { MVideoThumbnail } from '@server/types/models/index.js'
import express from 'express'
import { move } from 'fs-extra/esm'
import { readFile } from 'fs/promises'
@@ -25,7 +26,6 @@ import { getSecureTorrentName } from '../../../helpers/utils.js'
import { CONFIG } from '../../../initializers/config.js'
import { MIMETYPES } from '../../../initializers/constants.js'
import { JobQueue } from '../../../lib/job-queue/job-queue.js'
-import { updateLocalVideoMiniatureFromExisting } from '../../../lib/thumbnail.js'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
@@ -140,13 +140,11 @@ async function handleTorrentImport (req: express.Request, res: express.Response,
importType: 'torrent'
})
- const thumbnailModel = await processThumbnail(req, video)
- const previewModel = await processPreview(req, video)
+ const thumbnails = await processThumbnails(req, video)
const videoImport = await insertFromImportIntoDB({
video,
- thumbnailModel,
- previewModel,
+ thumbnails,
videoChannel: res.locals.videoChannel,
tags: body.tags || undefined,
user,
@@ -198,12 +196,13 @@ async function handleYoutubeDlImport (req: express.Request, res: express.Respons
const user = res.locals.oauth.token.User
try {
+ const thumbnailfile = getVideoThumbnailFile(req.files)
+
const { job, videoImport } = await buildYoutubeDLImport({
targetUrl,
channel: res.locals.videoChannel,
importDataOverride: body,
- thumbnailFilePath: req.files?.['thumbnailfile']?.[0].path,
- previewFilePath: req.files?.['previewfile']?.[0].path,
+ thumbnailFilePath: thumbnailfile?.path,
user
})
await JobQueue.Instance.createJob(job)
@@ -224,36 +223,15 @@ async function handleYoutubeDlImport (req: express.Request, res: express.Respons
}
}
-async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
- const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
- if (thumbnailField) {
- const thumbnailPhysicalFile = thumbnailField[0]
-
- return updateLocalVideoMiniatureFromExisting({
- inputPath: thumbnailPhysicalFile.path,
- video,
- type: ThumbnailType.MINIATURE,
- automaticallyGenerated: false
- })
- }
-
- return undefined
-}
-
-async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
- const previewField = req.files ? req.files['previewfile'] : undefined
- if (previewField) {
- const previewPhysicalFile = previewField[0]
-
- return updateLocalVideoMiniatureFromExisting({
- inputPath: previewPhysicalFile.path,
- video,
- type: ThumbnailType.PREVIEW,
- automaticallyGenerated: false
- })
- }
+function processThumbnails (req: express.Request, video: MVideoThumbnail) {
+ const file = getVideoThumbnailFile(req.files)
+ if (!file) return []
- return undefined
+ return createLocalVideoThumbnailsFromImage({
+ inputPath: file.path,
+ video,
+ automaticallyGenerated: false
+ })
}
async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
diff --git a/server/core/controllers/api/videos/live.ts b/server/core/controllers/api/videos/live.ts
index 7bc65d7493..8e95d8f783 100644
--- a/server/core/controllers/api/videos/live.ts
+++ b/server/core/controllers/api/videos/live.ts
@@ -3,7 +3,6 @@ import {
HttpStatusCode,
LiveVideoCreate,
LiveVideoUpdate,
- ThumbnailType,
UserRight,
VideoChannelActivityAction,
VideoState
@@ -13,6 +12,7 @@ import { exists, isArray } from '@server/helpers/custom-validators/misc.js'
import { retryTransactionWrapper } from '@server/helpers/database-utils.js'
import { createReqFiles } from '@server/helpers/express-utils.js'
import { getFormattedObjects } from '@server/helpers/utils.js'
+import { getVideoThumbnailFile } from '@server/helpers/video.js'
import { ASSETS_PATH, MIMETYPES } from '@server/initializers/constants.js'
import { sequelizeTypescript } from '@server/initializers/database.js'
import { federateVideoIfNeeded } from '@server/lib/activitypub/videos/index.js'
@@ -198,24 +198,7 @@ async function updateReplaySettings (videoLive: MVideoLive, body: LiveVideoUpdat
async function addLiveVideo (req: express.Request, res: express.Response) {
const videoInfo: LiveVideoCreate = req.body
- const thumbnails = [ { type: ThumbnailType.MINIATURE, field: 'thumbnailfile' }, { type: ThumbnailType.PREVIEW, field: 'previewfile' } ]
- .map(({ type, field }) => {
- if (req.files?.[field]?.[0]) {
- return {
- path: req.files[field][0].path,
- type,
- automaticallyGenerated: false,
- keepOriginal: false
- }
- }
-
- return {
- path: ASSETS_PATH.DEFAULT_LIVE_BACKGROUND,
- type,
- automaticallyGenerated: true,
- keepOriginal: true
- }
- })
+ const thumbnailfile = getVideoThumbnailFile(req.files)
const localVideoCreator = new LocalVideoCreator({
channel: res.locals.videoChannel,
@@ -237,7 +220,18 @@ async function addLiveVideo (req: express.Request, res: express.Response) {
},
videoFile: undefined,
user: res.locals.oauth.token.User,
- thumbnails
+
+ thumbnail: thumbnailfile
+ ? {
+ path: thumbnailfile.path,
+ automaticallyGenerated: false,
+ keepOriginal: false
+ }
+ : {
+ path: ASSETS_PATH.DEFAULT_LIVE_BACKGROUND,
+ automaticallyGenerated: true,
+ keepOriginal: true
+ }
})
const { video } = await localVideoCreator.create()
diff --git a/server/core/controllers/api/videos/source.ts b/server/core/controllers/api/videos/source.ts
index 5cba7efb2b..02f4cfd210 100644
--- a/server/core/controllers/api/videos/source.ts
+++ b/server/core/controllers/api/videos/source.ts
@@ -3,7 +3,7 @@ import { HttpStatusCode, VideoChannelActivityAction, VideoState } from '@peertub
import { sequelizeTypescript } from '@server/initializers/database.js'
import { CreateJobArgument, CreateJobOptions, JobQueue } from '@server/lib/job-queue/index.js'
import { Hooks } from '@server/lib/plugins/hooks.js'
-import { regenerateMiniaturesIfNeeded } from '@server/lib/thumbnail.js'
+import { regenerateLocalVideoThumbnailsFromVideoIfNeeded } from '@server/lib/thumbnail.js'
import { setupUploadResumableRoutes } from '@server/lib/uploadx.js'
import { autoBlacklistVideoIfNeeded } from '@server/lib/video-blacklist.js'
import { regenerateTranscriptionTaskIfNeeded } from '@server/lib/video-captions.js'
@@ -162,7 +162,7 @@ async function replaceVideoSourceResumable (req: express.Request, res: express.R
createdAt: inputFileUpdatedAt
})
- await regenerateMiniaturesIfNeeded(video, res.locals.ffprobe)
+ await regenerateLocalVideoThumbnailsFromVideoIfNeeded(video, res.locals.ffprobe)
await video.VideoChannel.setAsUpdated()
await addVideoJobsAfterUpload(video, videoFile.withVideoOrPlaylist(video))
diff --git a/server/core/controllers/api/videos/update.ts b/server/core/controllers/api/videos/update.ts
index 51db0cd1cc..914edbf31b 100644
--- a/server/core/controllers/api/videos/update.ts
+++ b/server/core/controllers/api/videos/update.ts
@@ -2,19 +2,19 @@ import { forceNumber } from '@peertube/peertube-core-utils'
import {
HttpStatusCode,
NSFWFlag,
- ThumbnailType,
VideoChannelActivityAction,
VideoPrivacy,
VideoPrivacyType,
VideoUpdate
} from '@peertube/peertube-models'
import { exists } from '@server/helpers/custom-validators/misc.js'
+import { getVideoThumbnailFile } from '@server/helpers/video.js'
import { sendDeleteVideo } from '@server/lib/activitypub/send/send-delete.js'
import { changeVideoChannelShare } from '@server/lib/activitypub/share.js'
import { isNewVideoPrivacyForFederation, isPrivacyForFederation } from '@server/lib/activitypub/videos/federate.js'
import { AutomaticTagger } from '@server/lib/automatic-tags/automatic-tagger.js'
import { setAndSaveVideoAutomaticTags } from '@server/lib/automatic-tags/automatic-tags.js'
-import { updateLocalVideoMiniatureFromExisting } from '@server/lib/thumbnail.js'
+import { createLocalVideoThumbnailsFromImage } from '@server/lib/thumbnail.js'
import { replaceChaptersFromDescriptionIfNeeded } from '@server/lib/video-chapters.js'
import { addVideoJobsAfterUpdate } from '@server/lib/video-jobs.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
@@ -25,7 +25,7 @@ import { VideoChannelActivityModel } from '@server/models/video/video-channel-ac
import { VideoPasswordModel } from '@server/models/video/video-password.js'
import { FilteredModelAttributes } from '@server/types/index.js'
import { MVideoFullLight, MVideoThumbnail } from '@server/types/models/index.js'
-import express, { UploadFiles } from 'express'
+import express from 'express'
import { Transaction } from 'sequelize'
import { VideoAuditView, auditLoggerFactory, getAuditIdFromRes } from '../../../helpers/audit-logger.js'
import { resetSequelizeInstance } from '../../../helpers/database-utils.js'
@@ -71,7 +71,7 @@ async function updateVideo (req: express.Request, res: express.Response) {
const hadPrivacyForFederation = isPrivacyForFederation(videoFromReq.privacy)
const oldPrivacy = videoFromReq.privacy
- const thumbnails = await buildVideoThumbnailsFromReq(videoFromReq, req.files)
+ const thumbnails = await buildVideoThumbnailsFromReq(videoFromReq, req)
const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoFromReq.uuid)
try {
@@ -135,9 +135,8 @@ async function updateVideo (req: express.Request, res: express.Response) {
const videoInstanceUpdated = await video.save({ transaction: t }) as MVideoFullLight
- // Thumbnail & preview updates?
- for (const thumbnail of thumbnails) {
- await videoInstanceUpdated.addAndSaveThumbnail(thumbnail, t)
+ if (thumbnails.length !== 0) {
+ await videoInstanceUpdated.replaceAndSaveThumbnails(thumbnails, t)
}
// Video tags update?
@@ -298,29 +297,13 @@ async function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate
}
}
-async function buildVideoThumbnailsFromReq (video: MVideoThumbnail, files: UploadFiles) {
- const promises = [
- {
- type: ThumbnailType.MINIATURE,
- fieldName: 'thumbnailfile'
- },
- {
- type: ThumbnailType.PREVIEW,
- fieldName: 'previewfile'
- }
- ].map(p => {
- const fields = files?.[p.fieldName]
- if (!fields) return undefined
-
- return updateLocalVideoMiniatureFromExisting({
- inputPath: fields[0].path,
- video,
- type: p.type,
- automaticallyGenerated: false
- })
- })
+async function buildVideoThumbnailsFromReq (video: MVideoThumbnail, req: express.Request) {
+ const file = getVideoThumbnailFile(req.files)
+ if (!file) return []
- const thumbnailsOrUndefined = await Promise.all(promises)
-
- return thumbnailsOrUndefined.filter(t => !!t)
+ return createLocalVideoThumbnailsFromImage({
+ inputPath: file.path,
+ video,
+ automaticallyGenerated: false
+ })
}
diff --git a/server/core/controllers/api/videos/upload.ts b/server/core/controllers/api/videos/upload.ts
index 2dfd14ff65..8e434c1077 100644
--- a/server/core/controllers/api/videos/upload.ts
+++ b/server/core/controllers/api/videos/upload.ts
@@ -1,7 +1,8 @@
import { ffprobePromise, getChaptersFromContainer } from '@peertube/peertube-ffmpeg'
-import { isPeerTubeError, ThumbnailType, VideoCreate } from '@peertube/peertube-models'
+import { isPeerTubeError, VideoCreate } from '@peertube/peertube-models'
import { uuidToShort } from '@peertube/peertube-node-utils'
import { getResumableUploadPath } from '@server/helpers/upload.js'
+import { getVideoThumbnailFile } from '@server/helpers/video.js'
import { LocalVideoCreator } from '@server/lib/local-video-creator.js'
import { Redis } from '@server/lib/redis.js'
import { setupUploadResumableRoutes, uploadx } from '@server/lib/uploadx.js'
@@ -117,14 +118,7 @@ async function addVideo (options: {
})
logger.debug(`Got ${containerChapters.length} chapters from video "${videoInfo.name}" container`, { containerChapters, ...lTags() })
- const thumbnails = [ { type: ThumbnailType.MINIATURE, field: 'thumbnailfile' }, { type: ThumbnailType.PREVIEW, field: 'previewfile' } ]
- .filter(({ field }) => !!files?.[field]?.[0])
- .map(({ type, field }) => ({
- path: files[field][0].path,
- type,
- automaticallyGenerated: false,
- keepOriginal: false
- }))
+ const thumbnailfile = getVideoThumbnailFile(files)
const localVideoCreator = new LocalVideoCreator({
lTags,
@@ -156,7 +150,13 @@ async function addVideo (options: {
videoAttributeResultHook: 'filter:api.video.upload.video-attribute.result',
- thumbnails
+ thumbnail: thumbnailfile
+ ? {
+ path: thumbnailfile.path,
+ automaticallyGenerated: false,
+ keepOriginal: false
+ }
+ : undefined
})
try {
diff --git a/server/core/controllers/download.ts b/server/core/controllers/download.ts
index a9b4274e08..25b2498b40 100644
--- a/server/core/controllers/download.ts
+++ b/server/core/controllers/download.ts
@@ -2,8 +2,8 @@ import { forceNumber, maxBy } from '@peertube/peertube-core-utils'
import { FileStorage, HttpStatusCode, VideoResolution, VideoStreamingPlaylistType } from '@peertube/peertube-models'
import { exists } from '@server/helpers/custom-validators/misc.js'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
+import { generateRequestStream } from '@server/helpers/requests.js'
import { CONFIG } from '@server/initializers/config.js'
-import { VideoTorrentsSimpleFileCache } from '@server/lib/files-cache/index.js'
import {
generateHLSFilePresignedUrl,
generateOriginalFilePresignedUrl,
@@ -14,6 +14,7 @@ import { getFSUserExportFilePath } from '@server/lib/paths.js'
import { Hooks } from '@server/lib/plugins/hooks.js'
import { VideoDownload } from '@server/lib/video-download.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
+import { VideoFileModel } from '@server/models/video/video-file.js'
import {
MStreamingPlaylist,
MStreamingPlaylistVideo,
@@ -26,6 +27,8 @@ import { MVideoSource } from '@server/types/models/video/video-source.js'
import contentDisposition from 'content-disposition'
import cors from 'cors'
import express from 'express'
+import { join } from 'path'
+import { pipeline } from 'stream/promises'
import { DOWNLOAD_PATHS, WEBSERVER } from '../initializers/constants.js'
import {
asyncMiddleware,
@@ -103,19 +106,23 @@ export {
// ---------------------------------------------------------------------------
async function downloadTorrent (req: express.Request, res: express.Response) {
- const result = await VideoTorrentsSimpleFileCache.Instance.getFilePath(req.params.filename)
- if (!result) {
- return res.fail({
- status: HttpStatusCode.NOT_FOUND_404,
- message: 'Torrent file not found'
- })
- }
+ const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(req.params.filename)
+ if (!file) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
+
+ const video = file.getVideo()
+
+ const path = video.isLocal()
+ ? join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename)
+ : undefined
+
+ const downloadFilename = `${video.name}-${file.resolution}p.torrent`
const allowParameters = {
req,
res,
- torrentPath: result.path,
- downloadName: result.downloadName
+ torrentFilename: req.params.filename,
+ torrentPath: path,
+ downloadName: downloadFilename
}
const allowedResult = await Hooks.wrapFun(
@@ -126,7 +133,17 @@ async function downloadTorrent (req: express.Request, res: express.Response) {
if (!checkAllowResult(res, allowParameters, allowedResult)) return
- return res.download(result.path, result.downloadName)
+ if (video.isLocal()) {
+ return res.download(path, downloadFilename)
+ }
+
+ // Proxify remote request without cache
+ res.type('application/x-bittorrent')
+ res.setHeader('Content-disposition', contentDisposition(encodeURI(downloadFilename)))
+
+ const remoteUrl = file.getRemoteTorrentUrl(video)
+
+ await pipeline(generateRequestStream(remoteUrl), res)
}
// ---------------------------------------------------------------------------
diff --git a/server/core/controllers/feeds/shared/video-feed-utils.ts b/server/core/controllers/feeds/shared/video-feed-utils.ts
index 768586f9d9..392091c2f3 100644
--- a/server/core/controllers/feeds/shared/video-feed-utils.ts
+++ b/server/core/controllers/feeds/shared/video-feed-utils.ts
@@ -8,7 +8,7 @@ import { getServerActor } from '@server/models/application/application.js'
import { getCategoryLabel } from '@server/models/video/formatter/index.js'
import { DisplayOnlyForFollowerOptions } from '@server/models/video/sql/video/index.js'
import { VideoModel } from '@server/models/video/video.js'
-import { MChannelHostOnly, MThumbnail, MUserDefault } from '@server/types/models/index.js'
+import { MChannelHostOnly, MUserDefault } from '@server/types/models/index.js'
export async function getVideosForFeeds (options: {
sort: string
@@ -26,17 +26,17 @@ export async function getVideosForFeeds (options: {
const { data } = await Hooks.wrapPromiseFun(
VideoModel.listForApi.bind(VideoModel),
{
- start: 0,
- count: CONFIG.FEEDS.VIDEOS.COUNT,
- displayOnlyForFollower: {
- actorId: server.id,
- orLocalVideos: true
- },
- hasFiles: true,
- countVideos: false,
+ start: 0,
+ count: CONFIG.FEEDS.VIDEOS.COUNT,
+ displayOnlyForFollower: {
+ actorId: server.id,
+ orLocalVideos: true
+ },
+ hasFiles: true,
+ countVideos: false,
- ...options
- },
+ ...options
+ },
'filter:feed.videos.list.result'
)
@@ -46,10 +46,6 @@ export async function getVideosForFeeds (options: {
export function getCommonVideoFeedAttributes (video: VideoModel) {
const localLink = WEBSERVER.URL + video.getWatchStaticPath()
- const thumbnailModels: MThumbnail[] = []
- if (video.hasPreview()) thumbnailModels.push(video.getPreview())
- if (video.hasMiniature()) thumbnailModels.push(video.getMiniature())
-
return {
title: video.name,
link: localLink,
@@ -63,8 +59,8 @@ export function getCommonVideoFeedAttributes (video: VideoModel) {
? [ { name: getCategoryLabel(video.category) } ]
: undefined,
- thumbnails: thumbnailModels.map(t => ({
- url: WEBSERVER.URL + t.getLocalStaticPath(),
+ thumbnails: video.Thumbnails.map(t => ({
+ url: WEBSERVER.URL + t.getFileStaticPath(),
width: t.width,
height: t.height
}))
diff --git a/server/core/controllers/feeds/video-podcast-feeds.ts b/server/core/controllers/feeds/video-podcast-feeds.ts
index 90b31ad71d..20ae0bb3d3 100644
--- a/server/core/controllers/feeds/video-podcast-feeds.ts
+++ b/server/core/controllers/feeds/video-podcast-feeds.ts
@@ -223,7 +223,7 @@ async function addVODPodcastItem (options: {
// So web videos are default if enabled
const media = [ ...webVideos, ...streamingPlaylistFiles ]
- const videoCaptions = buildVODCaptions(video, captionsGroup[video.id])
+ const videoCaptions = buildVODCaptions(captionsGroup[video.id])
const item = await generatePodcastItem({ video, liveItem: false, media })
feed.addPodcastItem({ ...item, subTitle: videoCaptions })
@@ -335,13 +335,13 @@ function buildLiveStreamingPlaylists (video: MVideoFullLight) {
]
}
-function buildVODCaptions (video: MVideo, videoCaptions: MVideoCaptionVideo[]) {
+function buildVODCaptions (videoCaptions: MVideoCaptionVideo[]) {
return videoCaptions.map(caption => {
const type = MIMETYPES.VIDEO_CAPTIONS.EXT_MIMETYPE[extname(caption.filename)]
if (!type) return null
return {
- url: caption.getFileUrl(video),
+ url: caption.getLocalFileUrl(),
language: caption.language,
type,
rel: 'captions'
diff --git a/server/core/controllers/lazy-static.ts b/server/core/controllers/lazy-static.ts
index 95a7dd38a6..8ce6c6423f 100644
--- a/server/core/controllers/lazy-static.ts
+++ b/server/core/controllers/lazy-static.ts
@@ -1,27 +1,19 @@
-import cors from 'cors'
-import express from 'express'
import { HttpStatusCode } from '@peertube/peertube-models'
+import { generateRequestStream } from '@server/helpers/requests.js'
import { CONFIG } from '@server/initializers/config.js'
-import { FILES_CACHE, LAZY_STATIC_PATHS, STATIC_MAX_AGE } from '../initializers/constants.js'
-import {
- AvatarPermanentFileCache,
- VideoCaptionsSimpleFileCache,
- VideoMiniaturePermanentFileCache,
- VideoPreviewsSimpleFileCache,
- VideoStoryboardsSimpleFileCache,
- VideoTorrentsSimpleFileCache
-} from '../lib/files-cache/index.js'
+import { VideoFileModel } from '@server/models/video/video-file.js'
+import cors from 'cors'
+import express from 'express'
+import { join } from 'node:path'
+import { pipeline } from 'node:stream/promises'
+import { LAZY_STATIC_PATHS, STATIC_MAX_AGE } from '../initializers/constants.js'
+
+import { AvatarImageFileCache } from '@server/lib/files-cache/avatar-image-file-cache.js'
+import { VideoCaptionsFileCache } from '@server/lib/files-cache/video-captions-file-cache.js'
+import { VideoStoryboardsImageFileCache } from '@server/lib/files-cache/video-storyboards-image-file-cache.js'
+import { VideoThumbnailsImageFileCache } from '@server/lib/files-cache/video-thumbnails-image-file-cache.js'
import { asyncMiddleware, handleStaticError } from '../middlewares/index.js'
-// ---------------------------------------------------------------------------
-// Cache initializations
-// ---------------------------------------------------------------------------
-
-VideoPreviewsSimpleFileCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
-VideoCaptionsSimpleFileCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
-VideoTorrentsSimpleFileCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
-VideoStoryboardsSimpleFileCache.Instance.init(CONFIG.CACHE.STORYBOARDS.SIZE, FILES_CACHE.STORYBOARDS.MAX_AGE)
-
// ---------------------------------------------------------------------------
const lazyStaticRouter = express.Router()
@@ -46,9 +38,10 @@ lazyStaticRouter.use(
handleStaticError
)
+// TODO: deprecated, remove in v9
lazyStaticRouter.use(
- LAZY_STATIC_PATHS.PREVIEWS + ':filename',
- asyncMiddleware(getPreview),
+ '/lazy-static/previews/:filename',
+ asyncMiddleware(getThumbnail),
handleStaticError
)
@@ -77,49 +70,56 @@ export {
}
// ---------------------------------------------------------------------------
-const avatarPermanentFileCache = new AvatarPermanentFileCache()
+const avatarImageFileCache = new AvatarImageFileCache()
function getActorImage (req: express.Request, res: express.Response, next: express.NextFunction) {
const filename = req.params.filename
- return avatarPermanentFileCache.lazyServe({ filename, res, next })
+ return avatarImageFileCache.lazyServe({ filename, res, next })
}
// ---------------------------------------------------------------------------
-const videoMiniaturePermanentFileCache = new VideoMiniaturePermanentFileCache()
-function getThumbnail (req: express.Request, res: express.Response, next: express.NextFunction) {
+const videoThumbnailImageFileCache = new VideoThumbnailsImageFileCache()
+
+async function getThumbnail (req: express.Request, res: express.Response, next: express.NextFunction) {
const filename = req.params.filename
- return videoMiniaturePermanentFileCache.lazyServe({ filename, res, next })
+ return videoThumbnailImageFileCache.lazyServe({ filename, res, next })
}
// ---------------------------------------------------------------------------
-async function getPreview (req: express.Request, res: express.Response) {
- const result = await VideoPreviewsSimpleFileCache.Instance.getFilePath(req.params.filename)
- if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()
+const videoStoryboardsImageFileCache = new VideoStoryboardsImageFileCache()
- return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER })
+async function getStoryboard (req: express.Request, res: express.Response, next: express.NextFunction) {
+ const filename = req.params.filename
+
+ return videoStoryboardsImageFileCache.lazyServe({ filename, res, next })
}
-async function getStoryboard (req: express.Request, res: express.Response) {
- const result = await VideoStoryboardsSimpleFileCache.Instance.getFilePath(req.params.filename)
- if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()
+// ---------------------------------------------------------------------------
- return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER })
-}
+const videoCaptionFileCache = new VideoCaptionsFileCache()
-async function getVideoCaption (req: express.Request, res: express.Response) {
- const result = await VideoCaptionsSimpleFileCache.Instance.getFilePath(req.params.filename)
- if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()
+async function getVideoCaption (req: express.Request, res: express.Response, next: express.NextFunction) {
+ const filename = req.params.filename
- return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER })
+ return videoCaptionFileCache.lazyServe({ filename, res, next })
}
+// ---------------------------------------------------------------------------
+
async function getTorrent (req: express.Request, res: express.Response) {
- const result = await VideoTorrentsSimpleFileCache.Instance.getFilePath(req.params.filename)
- if (!result) return res.status(HttpStatusCode.NOT_FOUND_404).end()
+ const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(req.params.filename)
+ if (!file) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
+
+ if (file.getVideo().isLocal()) {
+ return res.sendFile(join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), { maxAge: STATIC_MAX_AGE.SERVER })
+ }
+
+ // Proxify remote request without cache
+ const remoteUrl = file.getRemoteTorrentUrl(file.getVideo())
- return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.SERVER })
+ await pipeline(generateRequestStream(remoteUrl), res)
}
diff --git a/server/core/controllers/object-storage-proxy.ts b/server/core/controllers/object-storage-proxy.ts
index 957f46198d..ec879adeb3 100644
--- a/server/core/controllers/object-storage-proxy.ts
+++ b/server/core/controllers/object-storage-proxy.ts
@@ -1,5 +1,3 @@
-import cors from 'cors'
-import express from 'express'
import { OBJECT_STORAGE_PROXY_PATHS } from '@server/initializers/constants.js'
import { proxifyHLS, proxifyWebVideoFile } from '@server/lib/object-storage/index.js'
import {
@@ -9,6 +7,8 @@ import {
ensurePrivateObjectStorageProxyIsEnabled,
optionalAuthenticate
} from '@server/middlewares/index.js'
+import cors from 'cors'
+import express from 'express'
import { doReinjectVideoFileToken } from './shared/m3u8-playlist.js'
const objectStorageProxyRouter = express.Router()
@@ -23,7 +23,8 @@ objectStorageProxyRouter.get(
asyncMiddleware(proxifyWebVideoController)
)
-objectStorageProxyRouter.get(OBJECT_STORAGE_PROXY_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS + ':videoUUID/:filename',
+objectStorageProxyRouter.get(
+ OBJECT_STORAGE_PROXY_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS + ':videoUUID/:filename',
ensurePrivateObjectStorageProxyIsEnabled,
optionalAuthenticate,
asyncMiddleware(ensureCanAccessPrivateVideoHLSFiles),
@@ -43,7 +44,6 @@ function proxifyWebVideoController (req: express.Request, res: express.Response)
}
function proxifyHLSController (req: express.Request, res: express.Response) {
- const playlist = res.locals.videoStreamingPlaylist
const video = res.locals.onlyVideo
const filename = req.params.filename
@@ -52,7 +52,6 @@ function proxifyHLSController (req: express.Request, res: express.Response) {
return proxifyHLS({
req,
res,
- playlist,
video,
filename,
reinjectVideoFileToken
diff --git a/server/core/controllers/services.ts b/server/core/controllers/services.ts
index 28985467fa..22f213ef75 100644
--- a/server/core/controllers/services.ts
+++ b/server/core/controllers/services.ts
@@ -1,16 +1,16 @@
import { escapeHTML, forceNumber } from '@peertube/peertube-core-utils'
import { HttpStatusCode } from '@peertube/peertube-models'
+import { logger } from '@server/helpers/logger.js'
import { getOrCreateAPActor } from '@server/lib/activitypub/actors/get.js'
import { loadActorUrlOrGetFromWebfinger } from '@server/lib/activitypub/actors/webfinger.js'
import { AccountModel } from '@server/models/account/account.js'
import { VideoChannelModel } from '@server/models/video/video-channel.js'
-import { MChannelSummary } from '@server/types/models/index.js'
+import { MChannelSummary, MThumbnail } from '@server/types/models/index.js'
import cors from 'cors'
import express from 'express'
-import { EMBED_SIZE, PREVIEWS_SIZE, THUMBNAILS_SIZE, WEBSERVER } from '../initializers/constants.js'
+import { EMBED_SIZE, WEBSERVER } from '../initializers/constants.js'
import { apiRateLimiter, asyncMiddleware, oembedValidator } from '../middlewares/index.js'
import { accountHandleGetValidatorFactory } from '../middlewares/validators/index.js'
-import { logger } from '@server/helpers/logger.js'
const servicesRouter = express.Router()
@@ -51,8 +51,7 @@ function generatePlaylistOEmbed (req: express.Request, res: express.Response) {
channel: playlist.VideoChannel,
title: playlist.name,
embedPath: playlist.getEmbedStaticPath() + buildPlayerURLQuery(req.query.url),
- previewPath: playlist.getThumbnailStaticPath(),
- previewSize: THUMBNAILS_SIZE,
+ thumbnail: playlist.Thumbnail,
req
})
@@ -66,8 +65,7 @@ function generateVideoOEmbed (req: express.Request, res: express.Response) {
channel: video.VideoChannel,
title: video.name,
embedPath: video.getEmbedStaticPath() + buildPlayerURLQuery(req.query.url),
- previewPath: video.getPreviewStaticPath(),
- previewSize: PREVIEWS_SIZE,
+ thumbnail: video.getBestThumbnail(),
req
})
@@ -116,14 +114,11 @@ function buildOEmbed (options: {
req: express.Request
title: string
channel: MChannelSummary
- previewPath: string | null
embedPath: string
- previewSize: {
- height: number
- width: number
- }
+
+ thumbnail: MThumbnail
}) {
- const { req, previewSize, previewPath, title, channel, embedPath } = options
+ const { req, thumbnail, title, channel, embedPath } = options
const webserverUrl = WEBSERVER.URL
const maxHeight = forceNumber(req.query.maxheight)
@@ -132,24 +127,12 @@ function buildOEmbed (options: {
const embedUrl = webserverUrl + embedPath
const embedTitle = escapeHTML(title)
- let thumbnailUrl = previewPath
- ? webserverUrl + previewPath
- : undefined
-
let embedWidth = EMBED_SIZE.width
if (maxWidth < embedWidth) embedWidth = maxWidth
let embedHeight = EMBED_SIZE.height
if (maxHeight < embedHeight) embedHeight = maxHeight
- // Our thumbnail is too big for the consumer
- if (
- (maxHeight !== undefined && maxHeight < previewSize.height) ||
- (maxWidth !== undefined && maxWidth < previewSize.width)
- ) {
- thumbnailUrl = undefined
- }
-
const html = `<iframe width="${embedWidth}" height="${embedHeight}" sandbox="allow-same-origin allow-scripts allow-popups allow-forms" ` +
`title="${embedTitle}" src="${embedUrl}" style="border: none" allow="fullscreen"></iframe>`
@@ -166,10 +149,10 @@ function buildOEmbed (options: {
provider_url: webserverUrl
}
- if (thumbnailUrl !== undefined) {
- json.thumbnail_url = thumbnailUrl
- json.thumbnail_width = previewSize.width
- json.thumbnail_height = previewSize.height
+ if (thumbnail && (!maxHeight || thumbnail.height < maxHeight) && (!maxWidth || thumbnail.width < maxWidth)) {
+ json.thumbnail_url = webserverUrl + thumbnail.getFileStaticPath()
+ json.thumbnail_width = thumbnail.width
+ json.thumbnail_height = thumbnail.height
}
return json
diff --git a/server/core/controllers/sitemap.ts b/server/core/controllers/sitemap.ts
index ead4d2f39a..77d811acb9 100644
--- a/server/core/controllers/sitemap.ts
+++ b/server/core/controllers/sitemap.ts
@@ -112,7 +112,7 @@ async function getSitemapLocalVideoUrls () {
// Sitemap description should be < 2000 characters
'description': truncate(v.description || v.name, { length: 2000, omission: '...' }),
'player_loc': WEBSERVER.URL + v.getEmbedStaticPath(),
- 'thumbnail_loc': WEBSERVER.URL + v.getMiniatureStaticPath(),
+ 'thumbnail_loc': WEBSERVER.URL + v.getSmallestThumbnailStaticPath(),
'content_loc': contentLoc,
'duration': v.duration,
'view_count': v.views,
diff --git a/server/core/helpers/audit-logger.ts b/server/core/helpers/audit-logger.ts
index c4b95faae9..88fbbfa9ac 100644
--- a/server/core/helpers/audit-logger.ts
+++ b/server/core/helpers/audit-logger.ts
@@ -66,12 +66,15 @@ function auditLoggerWrapper (domain: string, user: string, action: AUDIT_TYPE, e
entityInfos = { ...entity.toLogKeys() }
}
- auditLogger.log('audit', JSON.stringify({
- user,
- domain,
- action,
- ...entityInfos
- }))
+ auditLogger.log(
+ 'audit',
+ JSON.stringify({
+ user,
+ domain,
+ action,
+ ...entityInfos
+ })
+ )
}
function auditLoggerFactory (domain: string) {
@@ -89,7 +92,7 @@ function auditLoggerFactory (domain: string) {
}
abstract class EntityAuditView {
- constructor (private readonly keysToKeep: Set<string>, private readonly prefix: string, private readonly entityInfos: object) { }
+ constructor (private readonly keysToKeep: Set<string>, private readonly prefix: string, private readonly entityInfos: object) {}
toLogKeys (): object {
const obj = flatten<object, any>(this.entityInfos, { delimiter: '-', safe: true })
@@ -116,8 +119,6 @@ const videoKeysToKeep = new Set([
'duration',
'isLocal',
'name',
- 'thumbnailPath',
- 'previewPath',
'nsfw',
'waitTranscoding',
'account-id',
@@ -243,7 +244,6 @@ const customConfigKeysToKeep = new Set([
'instance-customizations-javascript',
'instance-customizations-css',
'services-twitter-username',
- 'cache-previews-size',
'cache-captions-size',
'signup-enabled',
'signup-limit',
@@ -261,9 +261,9 @@ class CustomConfigAuditView extends EntityAuditView {
const resolutionsArray = []
Object.entries(resolutionsDict)
- .forEach(([ resolution, isEnabled ]) => {
- if (isEnabled) resolutionsArray.push(resolution)
- })
+ .forEach(([ resolution, isEnabled ]) => {
+ if (isEnabled) resolutionsArray.push(resolution)
+ })
Object.assign({}, infos, { transcoding: { resolutions: resolutionsArray } })
super(customConfigKeysToKeep, 'config', infos)
@@ -284,7 +284,6 @@ class VideoChannelSyncAuditView extends EntityAuditView {
export {
getAuditIdFromRes,
-
auditLoggerFactory,
VideoImportAuditView,
VideoChannelAuditView,
diff --git a/server/core/helpers/ffmpeg/ffmpeg-image.ts b/server/core/helpers/ffmpeg/ffmpeg-image.ts
index 25cac50d79..7630adb092 100644
--- a/server/core/helpers/ffmpeg/ffmpeg-image.ts
+++ b/server/core/helpers/ffmpeg/ffmpeg-image.ts
@@ -1,10 +1,6 @@
import { FFmpegImage } from '@peertube/peertube-ffmpeg'
import { getFFmpegCommandWrapperOptions } from './ffmpeg-options.js'
-export function processImage (options: Parameters<FFmpegImage['processImage']>[0]) {
- return new FFmpegImage(getFFmpegCommandWrapperOptions('thumbnail')).processImage(options)
-}
-
export function generateThumbnailFromVideo (options: Parameters<FFmpegImage['generateThumbnailFromVideo']>[0]) {
return new FFmpegImage(getFFmpegCommandWrapperOptions('thumbnail')).generateThumbnailFromVideo(options)
}
diff --git a/server/core/helpers/image-utils.ts b/server/core/helpers/image-utils.ts
index eaa69cd75b..f84ed0be59 100644
--- a/server/core/helpers/image-utils.ts
+++ b/server/core/helpers/image-utils.ts
@@ -1,12 +1,9 @@
-import { ColorActionName } from '@jimp/plugin-color'
import { buildUUID, getLowercaseExtension } from '@peertube/peertube-node-utils'
import { copy, remove } from 'fs-extra/esm'
import { readFile } from 'fs/promises'
-import { processImage as processImageByFFmpeg } from './ffmpeg/index.js'
+import sharp from 'sharp'
import { logger } from './logger.js'
-import type Jimp from 'jimp'
-
export function generateImageFilename (extension = '.jpg') {
return buildUUID() + extension
}
@@ -22,17 +19,12 @@ export async function processImage (options: {
const extension = getLowercaseExtension(path)
if (path === destination) {
- throw new Error('Jimp/FFmpeg needs an input path different that the output path.')
+ throw new Error('Input path must be different from output path.')
}
logger.debug('Processing image %s to %s.', path, destination)
- // Use FFmpeg to process GIF
- if (extension === '.gif' || extension === '.webp') {
- await processImageByFFmpeg({ path, destination, newSize })
- } else {
- await jimpProcessor({ path, destination, newSize, inputExt: extension })
- }
+ await sharpProcessor({ path, destination, newSize, inputExt: extension, animated: extension.toLowerCase() === '.gif' })
if (keepOriginal !== true) await remove(path)
@@ -40,15 +32,11 @@ export async function processImage (options: {
}
export async function getImageSize (path: string) {
- const inputBuffer = await readFile(path)
-
- const Jimp = await import('jimp')
-
- const image = await Jimp.default.read(inputBuffer)
+ const metadata = await sharp(path).metadata()
return {
- width: image.getWidth(),
- height: image.getHeight()
+ width: metadata.width,
+ height: metadata.height
}
}
@@ -71,7 +59,7 @@ export async function buildImageSize (imagePath: string, sizeArg: { width?: numb
// Private
// ---------------------------------------------------------------------------
-async function jimpProcessor (options: {
+async function sharpProcessor (options: {
path: string
destination: string
newSize?: {
@@ -79,13 +67,24 @@ async function jimpProcessor (options: {
height: number
}
inputExt: string
+ animated: boolean
}) {
- const { path, newSize, inputExt, destination } = options
+ const { path, newSize, inputExt, destination, animated } = options
const inputBuffer = await readFile(path)
- const Jimp = await import('jimp')
- const sourceImage = await Jimp.default.read(inputBuffer)
+ const sharpInstance = buildSharp({
+ inputBuffer,
+ animated
+ })
+
+ const metadata = await sharpInstance.metadata()
+
+ if (metadata.pages > 200) {
+ logger.info('Too much frames in animated image ' + path + ', skipping animation')
+
+ return sharpProcessor({ ...options, animated: false })
+ }
await remove(destination)
@@ -93,7 +92,7 @@ async function jimpProcessor (options: {
if (
skipProcessing({
- sourceImage,
+ metadata,
newSize,
imageBytes: inputBuffer.byteLength,
inputExt,
@@ -104,52 +103,57 @@ async function jimpProcessor (options: {
}
if (newSize) {
- await autoResize({ sourceImage, newSize, destination })
+ await autoResize({ sharpInstance, metadata, newSize, destination })
} else {
- await write(sourceImage, destination)
+ await writeSharp({ sharpInstance, destination })
}
}
-function autoResize (options: {
- sourceImage: Jimp
+async function autoResize (options: {
+ sharpInstance: sharp.Sharp
+ metadata: sharp.Metadata
newSize: { width: number, height: number }
destination: string
}) {
- const { sourceImage, newSize, destination } = options
+ const { sharpInstance, metadata, newSize, destination } = options
// Portrait mode targeting a landscape, apply some effect on the image
- const sourceIsPortrait = sourceImage.getWidth() <= sourceImage.getHeight()
+ const sourceIsPortrait = metadata.width <= metadata.height
const destIsPortraitOrSquare = newSize.width <= newSize.height
- removeExif(sourceImage)
-
if (sourceIsPortrait && !destIsPortraitOrSquare) {
- const baseImage = sourceImage.cloneQuiet().cover(newSize.width, newSize.height)
- .color([ { apply: ColorActionName.SHADE, params: [ 50 ] } ])
+ const foregroundImage = sharpInstance.clone()
+ .resize(newSize.width, newSize.height, { fit: 'inside' })
- const topImage = sourceImage.cloneQuiet().contain(newSize.width, newSize.height)
+ return writeSharp({
+ sharpInstance: sharpInstance
+ .resize(newSize.width, newSize.height, { fit: 'cover' })
+ .modulate({ brightness: 0.5 })
+ .composite([ { input: await foregroundImage.toBuffer(), gravity: 'center' } ]),
- return write(baseImage.blit(topImage, 0, 0), destination)
+ destination
+ })
}
- return write(sourceImage.cover(newSize.width, newSize.height), destination)
-}
+ return writeSharp({
+ sharpInstance: sharpInstance
+ .resize(newSize.width, newSize.height, { fit: 'cover' }),
-function write (image: Jimp, destination: string) {
- return image.quality(80).writeAsync(destination)
+ destination
+ })
}
function skipProcessing (options: {
- sourceImage: Jimp
+ metadata: sharp.Metadata
newSize?: { width: number, height: number }
imageBytes: number
inputExt: string
outputExt: string
}) {
- const { sourceImage, newSize, imageBytes, inputExt, outputExt } = options
+ const { metadata, newSize, imageBytes, inputExt, outputExt } = options
- if (hasExif(sourceImage)) return false
- if (newSize && (sourceImage.getWidth() !== newSize.width || sourceImage.getHeight() !== newSize.height)) return false
+ if (metadata.exif) return false
+ if (newSize && (metadata.width !== newSize.width || metadata.height !== newSize.height)) return false
if (inputExt !== outputExt) return false
const kB = 1000
@@ -162,10 +166,32 @@ function skipProcessing (options: {
return imageBytes <= 15 * kB
}
-function hasExif (image: Jimp) {
- return !!(image.bitmap as any).exifBuffer
+function buildSharp (options: {
+ inputBuffer: Buffer
+ animated: boolean
+}) {
+ const { inputBuffer, animated } = options
+
+ return sharp(inputBuffer, { animated })
}
-function removeExif (image: Jimp) {
- ;(image.bitmap as any).exifBuffer = null
+function writeSharp (options: {
+ sharpInstance: sharp.Sharp
+ destination: string
+}) {
+ const { sharpInstance, destination } = options
+
+ if (destination.endsWith('.jpg')) {
+ return sharpInstance
+ .jpeg({ quality: 85 }) // mozjpeg option seems to cause some issues to ffmpeg (probe difficulties), so prefer to not enable it
+ .toFile(destination)
+ }
+
+ if (destination.endsWith('.png')) {
+ return sharpInstance
+ .png({ palette: true })
+ .toFile(destination)
+ }
+
+ return sharpInstance.toFile(destination)
}
diff --git a/server/core/helpers/video.ts b/server/core/helpers/video.ts
index ff7539bc28..99af095ab7 100644
--- a/server/core/helpers/video.ts
+++ b/server/core/helpers/video.ts
@@ -1,9 +1,16 @@
import { VideoPrivacy } from '@peertube/peertube-models'
import { CONFIG } from '@server/initializers/config.js'
import { isStreamingPlaylist, MStreamingPlaylistVideo, MVideo } from '@server/types/models/index.js'
-import { Response } from 'express'
+import express from 'express'
-export function getVideoWithAttributes (res: Response) {
+export function getVideoThumbnailFile (files: express.UploadFiles): Express.Multer.File {
+ const file = files?.['previewfile'] || files?.['thumbnailfile']
+ if (!file) return undefined
+
+ return file[0]
+}
+
+export function getVideoWithAttributes (res: express.Response) {
return res.locals.videoAPI || res.locals.videoAll || res.locals.onlyVideo
}
diff --git a/server/core/initializers/checker-before-init.ts b/server/core/initializers/checker-before-init.ts
index a87ef74783..b556303967 100644
--- a/server/core/initializers/checker-before-init.ts
+++ b/server/core/initializers/checker-before-init.ts
@@ -70,10 +70,6 @@ export function checkMissedConfig () {
'csp.report_uri',
'security.frameguard.enabled',
'security.powered_by_header.enabled',
- 'cache.previews.size',
- 'cache.captions.size',
- 'cache.torrents.size',
- 'cache.storyboards.size',
'admin.email',
'contact_form.enabled',
'signup.enabled',
diff --git a/server/core/initializers/config.ts b/server/core/initializers/config.ts
index eb12ce5662..5fdd298521 100644
--- a/server/core/initializers/config.ts
+++ b/server/core/initializers/config.ts
@@ -15,6 +15,7 @@ import { IConfig } from 'config'
import { createRequire } from 'module'
import { dirname, join } from 'path'
import { parseBytes, parseDurationToMs } from '../helpers/core-utils.js'
+import { sortBy } from '@peertube/peertube-core-utils'
const require = createRequire(import.meta.url)
let config: IConfig = require('config')
@@ -474,7 +475,7 @@ const CONFIG = {
GENERATION_FROM_VIDEO: {
FRAMES_TO_ANALYZE: config.get<number>('thumbnails.generation_from_video.frames_to_analyze')
},
- SIZES: config.get<{ width: number, height: number }[]>('thumbnails.sizes')
+ SIZES: sortBy(config.get<{ width: number, height: number }[]>('thumbnails.sizes'), 'width')
},
STATS: {
REGISTRATION_REQUESTS: {
@@ -891,28 +892,6 @@ const CONFIG = {
}
}
},
- CACHE: {
- PREVIEWS: {
- get SIZE () {
- return config.get<number>('cache.previews.size')
- }
- },
- VIDEO_CAPTIONS: {
- get SIZE () {
- return config.get<number>('cache.captions.size')
- }
- },
- TORRENTS: {
- get SIZE () {
- return config.get<number>('cache.torrents.size')
- }
- },
- STORYBOARDS: {
- get SIZE () {
- return config.get<number>('cache.storyboards.size')
- }
- }
- },
INSTANCE: {
get NAME () {
return config.get<string>('instance.name')
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.ts
index cb040de5f2..78290190c4 100644
--- a/server/core/initializers/constants.ts
+++ b/server/core/initializers/constants.ts
@@ -1,4 +1,4 @@
-import { maxBy, minBy, randomInt } from '@peertube/peertube-core-utils'
+import { randomInt } from '@peertube/peertube-core-utils'
import {
AbuseState,
AbuseStateType,
@@ -58,7 +58,7 @@ import { CONFIG, registerConfigChangedHandler } from './config.js'
// ---------------------------------------------------------------------------
-export const LAST_MIGRATION_VERSION = 980
+export const LAST_MIGRATION_VERSION = 990
// ---------------------------------------------------------------------------
@@ -950,7 +950,6 @@ export const LAZY_STATIC_PATHS = {
THUMBNAILS: '/lazy-static/thumbnails/',
BANNERS: '/lazy-static/banners/',
AVATARS: '/lazy-static/avatars/',
- PREVIEWS: '/lazy-static/previews/',
VIDEO_CAPTIONS: '/lazy-static/video-captions/',
TORRENTS: '/lazy-static/torrents/',
STORYBOARDS: '/lazy-static/storyboards/'
@@ -972,17 +971,6 @@ export const STATIC_MAX_AGE = {
CLIENT: '30d'
}
-// Videos thumbnail size
-export const THUMBNAILS_SIZE = {
- width: minBy(CONFIG.THUMBNAILS.SIZES, 'width').width,
- height: minBy(CONFIG.THUMBNAILS.SIZES, 'width').height,
- minRemoteWidth: 150
-}
-export const PREVIEWS_SIZE = {
- width: maxBy(CONFIG.THUMBNAILS.SIZES, 'width').width,
- height: maxBy(CONFIG.THUMBNAILS.SIZES, 'width').height,
- minRemoteWidth: 400
-}
export const ACTOR_IMAGES_SIZE: { [key in ActorImageType_Type]: { width: number, height: number }[] } = {
[ActorImageType.AVATAR]: [ // 1/1 ratio
{
@@ -1052,8 +1040,12 @@ export const EMBED_SIZE = {
// Sub folders of cache directory
export const FILES_CACHE = {
- PREVIEWS: {
- DIRECTORY: join(CONFIG.STORAGE.CACHE_DIR, 'previews'),
+ AVATARS: {
+ DIRECTORY: join(CONFIG.STORAGE.CACHE_DIR, 'avatars'),
+ MAX_AGE: 1000 * 3600 * 24 * 7 // 7 days
+ },
+ THUMBNAILS: {
+ DIRECTORY: join(CONFIG.STORAGE.CACHE_DIR, 'thumbnails'),
MAX_AGE: 1000 * 3600 * 3 // 3 hours
},
STORYBOARDS: {
@@ -1063,10 +1055,6 @@ export const FILES_CACHE = {
VIDEO_CAPTIONS: {
DIRECTORY: join(CONFIG.STORAGE.CACHE_DIR, 'video-captions'),
MAX_AGE: 1000 * 3600 * 3 // 3 hours
- },
- TORRENTS: {
- DIRECTORY: join(CONFIG.STORAGE.CACHE_DIR, 'torrents'),
- MAX_AGE: 1000 * 3600 * 3 // 3 hours
}
}
@@ -1075,7 +1063,7 @@ export const LRU_CACHE = {
MAX_SIZE: 1000
},
FILENAME_TO_PATH_PERMANENT_FILE_CACHE: {
- MAX_SIZE: 1000
+ MAX_SIZE: 5000
},
STATIC_VIDEO_FILES_RIGHTS_CHECK: {
MAX_SIZE: 5000,
diff --git a/server/core/initializers/installer.ts b/server/core/initializers/installer.ts
index 36a630d384..de0c43eff2 100644
--- a/server/core/initializers/installer.ts
+++ b/server/core/initializers/installer.ts
@@ -1,12 +1,13 @@
-import { ensureDir, remove } from 'fs-extra/esm'
-import { readdir } from 'fs/promises'
-import passwordGenerator from 'password-generator'
-import { join } from 'path'
import { UserRole } from '@peertube/peertube-models'
import { isTestOrDevInstance } from '@peertube/peertube-node-utils'
import { generateRunnerRegistrationToken } from '@server/helpers/token-generator.js'
import { getNodeABIVersion } from '@server/helpers/version.js'
+import { initPNPM } from '@server/lib/plugins/package-manager.js'
import { RunnerRegistrationTokenModel } from '@server/models/runner/runner-registration-token.js'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { readdir } from 'fs/promises'
+import passwordGenerator from 'password-generator'
+import { join } from 'path'
import { logger } from '../helpers/logger.js'
import { buildUser, createApplicationActor, createUserAccountAndChannelAndPlaylist } from '../lib/user.js'
import { ApplicationModel } from '../models/application/application.js'
@@ -15,7 +16,6 @@ import { applicationExist, clientsExist, usersExist } from './checker-after-init
import { CONFIG } from './config.js'
import { DIRECTORIES, FILES_CACHE, LAST_MIGRATION_VERSION } from './constants.js'
import { sequelizeTypescript } from './database.js'
-import { initPNPM } from '@server/lib/plugins/package-manager.js'
async function installApplication () {
try {
@@ -33,7 +33,7 @@ async function installApplication () {
}),
// Directories
- removeCacheAndTmpDirectories()
+ removeTmpDirectory()
.then(() => createDirectoriesIfNotExist())
])
} catch (err) {
@@ -50,20 +50,8 @@ export {
// ---------------------------------------------------------------------------
-function removeCacheAndTmpDirectories () {
- const cacheDirectories = Object.keys(FILES_CACHE)
- .map(k => FILES_CACHE[k].DIRECTORY)
-
- const tasks: Promise<any>[] = []
-
- // Cache directories
- for (const dir of cacheDirectories) {
- tasks.push(removeDirectoryOrContent(dir))
- }
-
- tasks.push(removeDirectoryOrContent(CONFIG.STORAGE.TMP_DIR))
-
- return Promise.all(tasks)
+function removeTmpDirectory () {
+ return removeDirectoryOrContent(CONFIG.STORAGE.TMP_DIR)
}
async function removeDirectoryOrContent (dir: string) {
@@ -100,9 +88,9 @@ function createDirectoriesIfNotExist () {
tasks.push(ensureDir(DIRECTORIES.HLS_STREAMING_PLAYLIST.PUBLIC))
tasks.push(ensureDir(DIRECTORIES.WEB_VIDEOS.PUBLIC))
tasks.push(ensureDir(DIRECTORIES.WEB_VIDEOS.PRIVATE))
-
- // Resumable upload directory
+ tasks.push(ensureDir(DIRECTORIES.UPLOAD_IMAGES))
tasks.push(ensureDir(DIRECTORIES.RESUMABLE_UPLOAD))
+ tasks.push(ensureDir(DIRECTORIES.HLS_REDUNDANCY))
return Promise.all(tasks)
}
diff --git a/server/core/initializers/migrations/0985-thumbnail-refactor.ts b/server/core/initializers/migrations/0985-thumbnail-refactor.ts
new file mode 100644
index 0000000000..b45ba6ebd9
--- /dev/null
+++ b/server/core/initializers/migrations/0985-thumbnail-refactor.ts
@@ -0,0 +1,31 @@
+import * as Sequelize from 'sequelize'
+
+async function up (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ {
+ await utils.queryInterface.removeColumn('thumbnail', 'type', { transaction: utils.transaction })
+ }
+
+ {
+ const query = 'DELETE FROM "thumbnail" s1 ' +
+ 'USING (SELECT MIN(id) as id, "filename" FROM "thumbnail" GROUP BY "filename" HAVING COUNT(*) > 1) s2 ' +
+ 'WHERE s1."filename" = s2."filename" AND s1.id <> s2.id'
+ await utils.sequelize.query(query, { transaction: utils.transaction })
+ }
+
+ {
+ await utils.sequelize.query('DROP INDEX IF EXISTS thumbnail_filename_type', { transaction: utils.transaction })
+ }
+}
+
+function down (options) {
+ throw new Error('Not implemented.')
+}
+
+export {
+ down,
+ up
+}
diff --git a/server/core/initializers/migrations/0990-media-cache-refactor.ts b/server/core/initializers/migrations/0990-media-cache-refactor.ts
new file mode 100644
index 0000000000..0e785fa4cd
--- /dev/null
+++ b/server/core/initializers/migrations/0990-media-cache-refactor.ts
@@ -0,0 +1,44 @@
+import * as Sequelize from 'sequelize'
+
+async function up (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ const { transaction } = utils
+
+ {
+ await utils.queryInterface.removeColumn('userExport', 'fileUrl', { transaction })
+ await utils.queryInterface.removeColumn('videoSource', 'fileUrl', { transaction })
+ }
+
+ const tablesToUpdate = [ 'actorImage', 'thumbnail', 'videoCaption', 'storyboard' ]
+
+ for (const table of tablesToUpdate) {
+ await utils.queryInterface.addColumn(table, 'cached', {
+ type: Sequelize.BOOLEAN,
+ defaultValue: false,
+ allowNull: false
+ }, { transaction })
+
+ await utils.queryInterface.changeColumn(table, 'cached', {
+ type: Sequelize.BOOLEAN,
+ defaultValue: null,
+ allowNull: false
+ }, { transaction })
+ }
+
+ {
+ await utils.queryInterface.removeColumn('actorImage', 'onDisk', { transaction: utils.transaction })
+ await utils.queryInterface.removeColumn('thumbnail', 'onDisk', { transaction: utils.transaction })
+ }
+}
+
+function down (options) {
+ throw new Error('Not implemented.')
+}
+
+export {
+ down,
+ up
+}
diff --git a/server/core/lib/activitypub/actors/image.ts b/server/core/lib/activitypub/actors/image.ts
index 290f967b7a..a4e6c22552 100644
--- a/server/core/lib/activitypub/actors/image.ts
+++ b/server/core/lib/activitypub/actors/image.ts
@@ -9,7 +9,7 @@ type ImageInfo = {
fileUrl: string
height: number
width: number
- onDisk?: boolean
+ cached?: boolean
}
async function updateActorImages (actor: MActorImages, type: ActorImageType_Type, imagesInfo: ImageInfo[], t: Transaction) {
@@ -46,7 +46,7 @@ async function updateActorImages (actor: MActorImages, type: ActorImageType_Type
const imageModel = await ActorImageModel.create({
filename: imageInfo.name,
- onDisk: imageInfo.onDisk ?? false,
+ cached: imageInfo.cached ?? false,
fileUrl: imageInfo.fileUrl,
height: imageInfo.height,
width: imageInfo.width,
@@ -91,7 +91,6 @@ async function safeDeleteActorImage (actor: MActorImages, toDelete: MActorImage,
export {
type ImageInfo,
-
updateActorImages,
deleteActorImages
}
diff --git a/server/core/lib/activitypub/playlists/create-update.ts b/server/core/lib/activitypub/playlists/create-update.ts
index 980b75fc20..91acbc8591 100644
--- a/server/core/lib/activitypub/playlists/create-update.ts
+++ b/server/core/lib/activitypub/playlists/create-update.ts
@@ -5,7 +5,7 @@ import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import { PeerTubeRequestError } from '@server/helpers/requests.js'
import { CRAWL_REQUEST_CONCURRENCY } from '@server/initializers/constants.js'
import { sequelizeTypescript } from '@server/initializers/database.js'
-import { updateRemotePlaylistMiniatureFromUrl } from '@server/lib/thumbnail.js'
+import { updateRemotePlaylistThumbnailFromUrl } from '@server/lib/thumbnail.js'
import { VideoPlaylistElementModel } from '@server/models/video/video-playlist-element.js'
import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'
import { FilteredModelAttributes } from '@server/types/index.js'
@@ -130,12 +130,12 @@ async function updatePlaylistThumbnail (playlistObject: PlaylistObject, playlist
let thumbnailModel: MThumbnail
try {
- thumbnailModel = await updateRemotePlaylistMiniatureFromUrl({ downloadUrl: playlistObject.icon.url, playlist })
+ thumbnailModel = updateRemotePlaylistThumbnailFromUrl({ fileUrl: playlistObject.icon.url, playlist })
await playlist.setAndSaveThumbnail(thumbnailModel, undefined)
} catch (err) {
logger.warn('Cannot set thumbnail of %s.', playlistObject.id, { err, ...lTags(playlistObject.id, playlist.uuid, playlist.url) })
- if (thumbnailModel) await thumbnailModel.removeThumbnail()
+ if (thumbnailModel) await thumbnailModel.removeFile()
}
return
diff --git a/server/core/lib/activitypub/videos/shared/abstract-builder.ts b/server/core/lib/activitypub/videos/shared/abstract-builder.ts
index d8ecf879e1..bcffe470db 100644
--- a/server/core/lib/activitypub/videos/shared/abstract-builder.ts
+++ b/server/core/lib/activitypub/videos/shared/abstract-builder.ts
@@ -1,10 +1,4 @@
-import {
- ActivityTagObject,
- ThumbnailType,
- VideoChaptersObject,
- VideoObject,
- VideoStreamingPlaylistType_Type
-} from '@peertube/peertube-models'
+import { ActivityTagObject, VideoChaptersObject, VideoObject, VideoStreamingPlaylistType_Type } from '@peertube/peertube-models'
import { isVideoChaptersObjectValid } from '@server/helpers/custom-validators/activitypub/video-chapters.js'
import { deleteAllModels, filterNonExistingModels, retryTransactionWrapper } from '@server/helpers/database-utils.js'
import { LoggerTagsFn, logger } from '@server/helpers/logger.js'
@@ -38,11 +32,9 @@ import {
getFileAttributesFromUrl,
getLiveAttributesFromObject,
getLiveSchedulesAttributesFromObject,
- getPreviewFromIcons,
getStoryboardAttributeFromObject,
getStreamingPlaylistAttributesFromObject,
- getTagsFromObject,
- getThumbnailFromIcons
+ getTagsFromObject
} from './object-to-model-attributes.js'
import { getTrackerUrls, setVideoTrackers } from './trackers.js'
@@ -57,37 +49,16 @@ export abstract class APVideoAbstractBuilder {
return getOrCreateAPActor(channel.id, 'all')
}
- protected async setThumbnail (video: MVideoThumbnail, t?: Transaction) {
- const miniatureIcon = getThumbnailFromIcons(this.videoObject)
- if (!miniatureIcon) {
- logger.warn('Cannot find thumbnail in video object', { object: this.videoObject, ...this.lTags() })
+ protected async setThumbnails (video: MVideoThumbnail, t?: Transaction) {
+ const icons = this.videoObject.icon
+ if (icons.length === 0) {
+ logger.warn('Cannot find thumbnails in video object', { object: this.videoObject, ...this.lTags() })
return undefined
}
- const miniatureModel = updateRemoteVideoThumbnail({
- fileUrl: miniatureIcon.url,
- video,
- type: ThumbnailType.MINIATURE,
- size: miniatureIcon,
- onDisk: false // Lazy download remote thumbnails
- })
-
- await video.addAndSaveThumbnail(miniatureModel, t)
- }
-
- protected async setPreview (video: MVideoFullLight, t?: Transaction) {
- const previewIcon = getPreviewFromIcons(this.videoObject)
- if (!previewIcon) return
-
- const previewModel = updateRemoteVideoThumbnail({
- fileUrl: previewIcon.url,
- video,
- type: ThumbnailType.PREVIEW,
- size: previewIcon,
- onDisk: false // Lazy download remote previews
- })
+ const thumbnails = icons.map(icon => updateRemoteVideoThumbnail({ fileUrl: icon.url, video, size: icon }))
- await video.addAndSaveThumbnail(previewModel, t)
+ await video.replaceAndSaveThumbnails(thumbnails, t)
}
protected async setTags (video: MVideoFullLight, t: Transaction) {
diff --git a/server/core/lib/activitypub/videos/shared/creator.ts b/server/core/lib/activitypub/videos/shared/creator.ts
index c73ed96c78..b31c281514 100644
--- a/server/core/lib/activitypub/videos/shared/creator.ts
+++ b/server/core/lib/activitypub/videos/shared/creator.ts
@@ -31,8 +31,7 @@ export class APVideoCreator extends APVideoAbstractBuilder {
const videoCreated = await video.save({ transaction: t }) as MVideoFullLight
videoCreated.VideoChannel = channel
- await this.setThumbnail(videoCreated, t)
- await this.setPreview(videoCreated, t)
+ await this.setThumbnails(videoCreated, t)
await this.setWebVideoFiles(videoCreated, t)
await this.setStreamingPlaylists(videoCreated, t)
await this.setTags(videoCreated, t)
diff --git a/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts b/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts
index b0405b1b0c..15eedd7e7a 100644
--- a/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts
+++ b/server/core/lib/activitypub/videos/shared/object-to-model-attributes.ts
@@ -1,4 +1,4 @@
-import { arrayify, maxBy, minBy } from '@peertube/peertube-core-utils'
+import { arrayify } from '@peertube/peertube-core-utils'
import {
ActivityHashTagObject,
ActivityMagnetUrlObject,
@@ -24,7 +24,7 @@ import { exists, isArray } from '@server/helpers/custom-validators/misc.js'
import { isVideoFileInfoHashValid } from '@server/helpers/custom-validators/videos.js'
import { generateImageFilename } from '@server/helpers/image-utils.js'
import { getExtFromMimetype } from '@server/helpers/video.js'
-import { MIMETYPES, P2P_MEDIA_LOADER_PEER_VERSION, PREVIEWS_SIZE, THUMBNAILS_SIZE } from '@server/initializers/constants.js'
+import { MIMETYPES, P2P_MEDIA_LOADER_PEER_VERSION } from '@server/initializers/constants.js'
import { generateTorrentFileName } from '@server/lib/paths.js'
import { VideoCaptionModel } from '@server/models/video/video-caption.js'
import { VideoFileModel } from '@server/models/video/video-file.js'
@@ -43,20 +43,6 @@ import { decode as magnetUriDecode } from 'magnet-uri'
import { basename, extname } from 'path'
import { getDurationFromActivityStream } from '../../activity.js'
-export function getThumbnailFromIcons (videoObject: VideoObject) {
- let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minRemoteWidth)
- // Fallback if there are not valid icons
- if (validIcons.length === 0) validIcons = videoObject.icon
-
- return minBy(validIcons, 'width')
-}
-
-export function getPreviewFromIcons (videoObject: VideoObject) {
- const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minRemoteWidth)
-
- return maxBy(validIcons, 'width')
-}
-
export function getTagsFromObject (videoObject: VideoObject) {
return videoObject.tag
.filter(isAPHashTagObject)
@@ -186,7 +172,7 @@ export function getStreamingPlaylistAttributesFromObject (video: MVideoId, video
playlistFilename: basename(playlistUrlObject.href),
playlistUrl: playlistUrlObject.href,
- segmentsSha256Filename: segmentsSha256UrlObject
+ segmentsSha256Filename: segmentsSha256UrlObject?.href
? basename(segmentsSha256UrlObject.href)
: null,
@@ -234,9 +220,10 @@ export function getCaptionAttributesFromObject (video: MVideoId, videoObject: Vi
filename,
language: c.identifier,
automaticallyGenerated: c.automaticallyGenerated === true,
- fileUrl: url.find(u => u.mediaType === 'text/vtt')?.href,
+ fileUrl: url.find(u => u.mediaType === 'text/vtt').href,
m3u8Filename: VideoCaptionModel.generateM3U8Filename(filename),
- m3u8Url: url.find(u => u.mediaType === 'application/x-mpegURL')?.href
+ m3u8Url: url.find(u => u.mediaType === 'application/x-mpegURL')?.href,
+ cached: false
} as Partial<AttributesOnly<VideoCaptionModel>>
})
}
@@ -257,7 +244,8 @@ export function getStoryboardAttributeFromObject (video: MVideoId, videoObject:
spriteWidth: url.tileWidth,
spriteDuration: getDurationFromActivityStream(url.tileDuration),
fileUrl: url.href,
- videoId: video.id
+ videoId: video.id,
+ cached: false
}
}
diff --git a/server/core/lib/activitypub/videos/updater.ts b/server/core/lib/activitypub/videos/updater.ts
index 8f22114cc2..9852002062 100644
--- a/server/core/lib/activitypub/videos/updater.ts
+++ b/server/core/lib/activitypub/videos/updater.ts
@@ -68,12 +68,7 @@ export class APVideoUpdater extends APVideoAbstractBuilder {
runInReadCommittedTransaction(t => this.setTrackers(videoUpdated, t)),
runInReadCommittedTransaction(t => this.setStoryboard(videoUpdated, t)),
runInReadCommittedTransaction(t => this.setAutomaticTags({ video: videoUpdated, transaction: t, oldVideo })),
- runInReadCommittedTransaction(t => {
- return Promise.all([
- this.setPreview(videoUpdated, t),
- this.setThumbnail(videoUpdated, t)
- ])
- }),
+ runInReadCommittedTransaction(t => this.setThumbnails(videoUpdated, t)),
this.setOrDeleteLive(videoUpdated)
])
diff --git a/server/core/lib/files-cache/avatar-image-file-cache.ts b/server/core/lib/files-cache/avatar-image-file-cache.ts
new file mode 100644
index 0000000000..b0163c6c9c
--- /dev/null
+++ b/server/core/lib/files-cache/avatar-image-file-cache.ts
@@ -0,0 +1,17 @@
+import { ActorImageModel } from '@server/models/actor/actor-image.js'
+import { MActorImage } from '@server/types/models/index.js'
+import { AbstractImageFileCache } from './shared/abstract-image-file-cache.js'
+
+export class AvatarImageFileCache extends AbstractImageFileCache<MActorImage> {
+ protected loadModel (filename: string) {
+ return ActorImageModel.loadByFilename(filename)
+ }
+
+ protected getFSFilePath (model: MActorImage) {
+ return model.getFSPath()
+ }
+
+ protected getFSFileCachedPath (model: MActorImage) {
+ return model.getFSCachedPath()
+ }
+}
diff --git a/server/core/lib/files-cache/avatar-permanent-file-cache.ts b/server/core/lib/files-cache/avatar-permanent-file-cache.ts
deleted file mode 100644
index d8a63765ec..0000000000
--- a/server/core/lib/files-cache/avatar-permanent-file-cache.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { CONFIG } from '@server/initializers/config.js'
-import { ActorImageModel } from '@server/models/actor/actor-image.js'
-import { MActorImage } from '@server/types/models/index.js'
-import { AbstractPermanentFileCache } from './shared/index.js'
-
-export class AvatarPermanentFileCache extends AbstractPermanentFileCache<MActorImage> {
-
- constructor () {
- super(CONFIG.STORAGE.ACTOR_IMAGES_DIR)
- }
-
- protected loadModel (filename: string) {
- return ActorImageModel.loadByFilename(filename)
- }
-
- protected getImageSize (image: MActorImage): { width: number, height: number } {
- if (image.width && image.height) {
- return {
- height: image.height,
- width: image.width
- }
- }
-
- return undefined
- }
-}
diff --git a/server/core/lib/files-cache/index.ts b/server/core/lib/files-cache/index.ts
index 219baed52d..706b13b37f 100644
--- a/server/core/lib/files-cache/index.ts
+++ b/server/core/lib/files-cache/index.ts
@@ -1,6 +1,4 @@
-export * from './avatar-permanent-file-cache.js'
-export * from './video-miniature-permanent-file-cache.js'
-export * from './video-captions-simple-file-cache.js'
-export * from './video-previews-simple-file-cache.js'
-export * from './video-storyboards-simple-file-cache.js'
-export * from './video-torrents-simple-file-cache.js'
+export * from './avatar-image-file-cache.js'
+export * from './video-captions-file-cache.js'
+export * from './video-storyboards-image-file-cache.js'
+export * from './video-thumbnails-image-file-cache.js'
diff --git a/server/core/lib/files-cache/shared/abstract-file-cache.ts b/server/core/lib/files-cache/shared/abstract-file-cache.ts
new file mode 100644
index 0000000000..0a9eef819a
--- /dev/null
+++ b/server/core/lib/files-cache/shared/abstract-file-cache.ts
@@ -0,0 +1,119 @@
+import { HttpStatusCode } from '@peertube/peertube-models'
+import { logger } from '@server/helpers/logger.js'
+import { CachePromise } from '@server/helpers/promise-cache.js'
+import { doRequestAndSaveToFile } from '@server/helpers/requests.js'
+import { LRU_CACHE, STATIC_MAX_AGE } from '@server/initializers/constants.js'
+import express from 'express'
+import { LRUCache } from 'lru-cache'
+import { Model } from 'sequelize'
+
+export type FileModel = {
+ fileUrl: string
+ filename: string
+ cached: boolean
+
+ isLocal(): boolean
+
+ save(): Promise<Model>
+}
+
+export abstract class AbstractFileCache<M extends FileModel> {
+ private readonly filenameToPathCache = new LRUCache<string, string>({
+ max: LRU_CACHE.FILENAME_TO_PATH_PERMANENT_FILE_CACHE.MAX_SIZE
+ })
+
+ protected abstract loadModel (filename: string): Promise<M>
+ protected abstract getFSFilePath (model: M): string
+ protected abstract getFSFileCachedPath (model: M): string
+
+ async lazyServe (options: {
+ filename: string
+ res: express.Response
+ next: express.NextFunction
+ }) {
+ const { filename, res, next } = options
+
+ if (this.filenameToPathCache.has(filename)) {
+ return res.sendFile(this.filenameToPathCache.get(filename), { maxAge: STATIC_MAX_AGE.SERVER })
+ }
+
+ const file = await this.lazyLoadIfNeeded(filename)
+ if (!file) return res.status(HttpStatusCode.NOT_FOUND_404).end()
+
+ const path = file.isLocal()
+ ? this.getFSFilePath(file)
+ : this.getFSFileCachedPath(file)
+
+ this.filenameToPathCache.set(filename, path)
+
+ return res.sendFile(path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER }, (err: any) => {
+ if (!err) return
+
+ this.onServeError({ err, file, next, filename })
+ })
+ }
+
+ @CachePromise({
+ keyBuilder: filename => filename
+ })
+ private async lazyLoadIfNeeded (filename: string) {
+ const file = await this.loadModel(filename)
+ if (!file) return undefined
+
+ if (!file.isLocal() && file.cached === false) {
+ if (!file.fileUrl) return undefined
+
+ try {
+ await this.downloadRemoteFile(file)
+ } catch (err) {
+ logger.warn('Cannot process remote image %s.', file.fileUrl, { err })
+
+ return undefined
+ }
+ }
+
+ return file
+ }
+
+ async downloadRemoteFile (file: M) {
+ logger.info('Download remote file %s lazily.', file.fileUrl)
+
+ const destination = await this.downloadImpl(file)
+
+ file.cached = true
+ file.save()
+ .catch(err => logger.error('Cannot save new image disk state.', { err }))
+
+ return destination
+ }
+
+ protected async downloadImpl (file: M) {
+ const destPath = this.getFSFileCachedPath(file)
+
+ await doRequestAndSaveToFile(file.fileUrl, destPath)
+
+ return destPath
+ }
+
+ private onServeError (options: {
+ err: any
+ file: M
+ filename: string
+ next: express.NextFunction
+ }) {
+ const { err, file, filename, next } = options
+
+ // It seems this actor image is not on the disk anymore
+ if (err.status === HttpStatusCode.NOT_FOUND_404 && !file.isLocal()) {
+ logger.error('Cannot lazy serve image %s.', filename, { err })
+
+ this.filenameToPathCache.delete(filename)
+
+ file.cached = false
+ file.save()
+ .catch(err => logger.error('Cannot save new file disk state.', { err }))
+ }
+
+ return next(err)
+ }
+}
diff --git a/server/core/lib/files-cache/shared/abstract-image-file-cache.ts b/server/core/lib/files-cache/shared/abstract-image-file-cache.ts
new file mode 100644
index 0000000000..8d47800ce2
--- /dev/null
+++ b/server/core/lib/files-cache/shared/abstract-image-file-cache.ts
@@ -0,0 +1,34 @@
+import { downloadImageFromWorker } from '@server/lib/worker/parent-process.js'
+import { basename, dirname } from 'path'
+import { AbstractFileCache, FileModel } from './abstract-file-cache.js'
+
+export interface ImageFileModel extends FileModel {
+ width?: number
+ height?: number
+}
+
+export abstract class AbstractImageFileCache<M extends ImageFileModel> extends AbstractFileCache<M> {
+ protected async downloadImpl (image: M) {
+ const destPath = this.getFSFileCachedPath(image)
+
+ const downloaderOptions = {
+ url: image.fileUrl,
+ destDir: dirname(destPath),
+ destName: basename(destPath),
+ size: this.getImageSize(image)
+ }
+
+ return downloadImageFromWorker(downloaderOptions)
+ }
+
+ private getImageSize (image: M): { width: number, height: number } {
+ if (image.width && image.height) {
+ return {
+ height: image.height,
+ width: image.width
+ }
+ }
+
+ return undefined
+ }
+}
diff --git a/server/core/lib/files-cache/shared/abstract-permanent-file-cache.ts b/server/core/lib/files-cache/shared/abstract-permanent-file-cache.ts
deleted file mode 100644
index 0aa4f6d0f6..0000000000
--- a/server/core/lib/files-cache/shared/abstract-permanent-file-cache.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import express from 'express'
-import { LRUCache } from 'lru-cache'
-import { Model } from 'sequelize'
-import { logger } from '@server/helpers/logger.js'
-import { CachePromise } from '@server/helpers/promise-cache.js'
-import { LRU_CACHE, STATIC_MAX_AGE } from '@server/initializers/constants.js'
-import { downloadImageFromWorker } from '@server/lib/worker/parent-process.js'
-import { HttpStatusCode } from '@peertube/peertube-models'
-
-type ImageModel = {
- fileUrl: string
- filename: string
- onDisk: boolean
-
- isLocal(): boolean
- getPath(): string
-
- save(): Promise<Model>
-}
-
-export abstract class AbstractPermanentFileCache<M extends ImageModel> {
- // Unsafe because it can return paths that do not exist anymore
- private readonly filenameToPathUnsafeCache = new LRUCache<string, string>({
- max: LRU_CACHE.FILENAME_TO_PATH_PERMANENT_FILE_CACHE.MAX_SIZE
- })
-
- protected abstract getImageSize (image: M): { width: number, height: number }
- protected abstract loadModel (filename: string): Promise<M>
-
- constructor (private readonly directory: string) {
- }
-
- async lazyServe (options: {
- filename: string
- res: express.Response
- next: express.NextFunction
- }) {
- const { filename, res, next } = options
-
- if (this.filenameToPathUnsafeCache.has(filename)) {
- return res.sendFile(this.filenameToPathUnsafeCache.get(filename), { maxAge: STATIC_MAX_AGE.SERVER })
- }
-
- const image = await this.lazyLoadIfNeeded(filename)
- if (!image) return res.status(HttpStatusCode.NOT_FOUND_404).end()
-
- const path = image.getPath()
- this.filenameToPathUnsafeCache.set(filename, path)
-
- return res.sendFile(path, { maxAge: STATIC_MAX_AGE.LAZY_SERVER }, (err: any) => {
- if (!err) return
-
- this.onServeError({ err, image, next, filename })
- })
- }
-
- @CachePromise({
- keyBuilder: filename => filename
- })
- private async lazyLoadIfNeeded (filename: string) {
- const image = await this.loadModel(filename)
- if (!image) return undefined
-
- if (image.onDisk === false) {
- if (!image.fileUrl) return undefined
-
- try {
- await this.downloadRemoteFile(image)
- } catch (err) {
- logger.warn('Cannot process remote image %s.', image.fileUrl, { err })
-
- return undefined
- }
- }
-
- return image
- }
-
- async downloadRemoteFile (image: M) {
- logger.info('Download remote image %s lazily.', image.fileUrl)
-
- const destination = await this.downloadImage({
- filename: image.filename,
- fileUrl: image.fileUrl,
- size: this.getImageSize(image)
- })
-
- image.onDisk = true
- image.save()
- .catch(err => logger.error('Cannot save new image disk state.', { err }))
-
- return destination
- }
-
- private onServeError (options: {
- err: any
- image: M
- filename: string
- next: express.NextFunction
- }) {
- const { err, image, filename, next } = options
-
- // It seems this actor image is not on the disk anymore
- if (err.status === HttpStatusCode.NOT_FOUND_404 && !image.isLocal()) {
- logger.error('Cannot lazy serve image %s.', filename, { err })
-
- this.filenameToPathUnsafeCache.delete(filename)
-
- image.onDisk = false
- image.save()
- .catch(err => logger.error('Cannot save new image disk state.', { err }))
- }
-
- return next(err)
- }
-
- private downloadImage (options: {
- fileUrl: string
- filename: string
- size?: { width: number, height: number }
- }) {
- const downloaderOptions = {
- url: options.fileUrl,
- destDir: this.directory,
- destName: options.filename,
- size: options.size
- }
-
- return downloadImageFromWorker(downloaderOptions)
- }
-}
diff --git a/server/core/lib/files-cache/shared/abstract-simple-file-cache.ts b/server/core/lib/files-cache/shared/abstract-simple-file-cache.ts
deleted file mode 100644
index 2febaa80a2..0000000000
--- a/server/core/lib/files-cache/shared/abstract-simple-file-cache.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { remove } from 'fs-extra/esm'
-import { logger } from '../../../helpers/logger.js'
-import memoizee from 'memoizee'
-
-type GetFilePathResult = { isLocal: boolean, path: string, downloadName?: string } | undefined
-
-export abstract class AbstractSimpleFileCache<T> {
- getFilePath: (params: T) => Promise<GetFilePathResult>
-
- abstract getFilePathImpl (params: T): Promise<GetFilePathResult>
-
- // Load and save the remote file, then return the local path from filesystem
- protected abstract loadRemoteFile (key: string): Promise<GetFilePathResult>
-
- init (max: number, maxAge: number) {
- this.getFilePath = memoizee(this.getFilePathImpl.bind(this), {
- maxAge,
- max,
- promise: true,
- dispose: (result?: GetFilePathResult) => {
- if (result && result.isLocal !== true) {
- remove(result.path)
- .then(() => logger.debug('%s removed from %s', result.path, this.constructor.name))
- .catch(err => logger.error('Cannot remove %s from cache %s.', result.path, this.constructor.name, { err }))
- }
- }
- })
- }
-}
diff --git a/server/core/lib/files-cache/shared/index.ts b/server/core/lib/files-cache/shared/index.ts
deleted file mode 100644
index 4dc4d8c4db..0000000000
--- a/server/core/lib/files-cache/shared/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from './abstract-permanent-file-cache.js'
-export * from './abstract-simple-file-cache.js'
diff --git a/server/core/lib/files-cache/video-captions-file-cache.ts b/server/core/lib/files-cache/video-captions-file-cache.ts
new file mode 100644
index 0000000000..b3a51ec16d
--- /dev/null
+++ b/server/core/lib/files-cache/video-captions-file-cache.ts
@@ -0,0 +1,17 @@
+import { VideoCaptionModel } from '@server/models/video/video-caption.js'
+import { MVideoCaption } from '@server/types/models/index.js'
+import { AbstractFileCache } from './shared/abstract-file-cache.js'
+
+export class VideoCaptionsFileCache extends AbstractFileCache<MVideoCaption> {
+ protected loadModel (filename: string) {
+ return VideoCaptionModel.loadByFilename(filename)
+ }
+
+ protected getFSFilePath (model: MVideoCaption) {
+ return model.getFSFilePath()
+ }
+
+ protected getFSFileCachedPath (model: MVideoCaption) {
+ return model.getFSFileCachedPath()
+ }
+}
diff --git a/server/core/lib/files-cache/video-captions-simple-file-cache.ts b/server/core/lib/files-cache/video-captions-simple-file-cache.ts
deleted file mode 100644
index 6e0e7038f9..0000000000
--- a/server/core/lib/files-cache/video-captions-simple-file-cache.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { join } from 'path'
-import { logger } from '@server/helpers/logger.js'
-import { doRequestAndSaveToFile } from '@server/helpers/requests.js'
-import { FILES_CACHE } from '../../initializers/constants.js'
-import { VideoModel } from '../../models/video/video.js'
-import { VideoCaptionModel } from '../../models/video/video-caption.js'
-import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'
-
-class VideoCaptionsSimpleFileCache extends AbstractSimpleFileCache<string> {
- private static instance: VideoCaptionsSimpleFileCache
-
- private constructor () {
- super()
- }
-
- static get Instance () {
- return this.instance || (this.instance = new this())
- }
-
- async getFilePathImpl (filename: string) {
- const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(filename)
- if (!videoCaption) return undefined
-
- if (videoCaption.isLocal()) {
- return { isLocal: true, path: videoCaption.getFSFilePath() }
- }
-
- return this.loadRemoteFile(filename)
- }
-
- // Key is the caption filename
- protected async loadRemoteFile (key: string) {
- const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(key)
- if (!videoCaption) return undefined
-
- if (videoCaption.isLocal()) throw new Error('Cannot load remote caption of owned video.')
-
- // Used to fetch the path
- const video = await VideoModel.loadFull(videoCaption.videoId)
- if (!video) return undefined
-
- const remoteUrl = videoCaption.getOriginFileUrl(video)
- const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.filename)
-
- try {
- await doRequestAndSaveToFile(remoteUrl, destPath)
-
- return { isLocal: false, path: destPath }
- } catch (err) {
- logger.info('Cannot fetch remote caption file %s.', remoteUrl, { err })
-
- return undefined
- }
- }
-}
-
-export {
- VideoCaptionsSimpleFileCache
-}
diff --git a/server/core/lib/files-cache/video-miniature-permanent-file-cache.ts b/server/core/lib/files-cache/video-miniature-permanent-file-cache.ts
deleted file mode 100644
index d3366ba437..0000000000
--- a/server/core/lib/files-cache/video-miniature-permanent-file-cache.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { CONFIG } from '@server/initializers/config.js'
-import { THUMBNAILS_SIZE } from '@server/initializers/constants.js'
-import { ThumbnailModel } from '@server/models/video/thumbnail.js'
-import { MThumbnail } from '@server/types/models/index.js'
-import { ThumbnailType } from '@peertube/peertube-models'
-import { AbstractPermanentFileCache } from './shared/index.js'
-
-export class VideoMiniaturePermanentFileCache extends AbstractPermanentFileCache<MThumbnail> {
-
- constructor () {
- super(CONFIG.STORAGE.THUMBNAILS_DIR)
- }
-
- protected loadModel (filename: string) {
- return ThumbnailModel.loadByFilename(filename, ThumbnailType.MINIATURE)
- }
-
- protected getImageSize (image: MThumbnail): { width: number, height: number } {
- if (image.width && image.height) {
- return {
- height: image.height,
- width: image.width
- }
- }
-
- return THUMBNAILS_SIZE
- }
-}
diff --git a/server/core/lib/files-cache/video-previews-simple-file-cache.ts b/server/core/lib/files-cache/video-previews-simple-file-cache.ts
deleted file mode 100644
index 262882f319..0000000000
--- a/server/core/lib/files-cache/video-previews-simple-file-cache.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { ThumbnailType } from '@peertube/peertube-models'
-import { logger } from '@server/helpers/logger.js'
-import { doRequestAndSaveToFile } from '@server/helpers/requests.js'
-import { ThumbnailModel } from '@server/models/video/thumbnail.js'
-import { join } from 'path'
-import { FILES_CACHE } from '../../initializers/constants.js'
-import { VideoModel } from '../../models/video/video.js'
-import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'
-
-class VideoPreviewsSimpleFileCache extends AbstractSimpleFileCache<string> {
- private static instance: VideoPreviewsSimpleFileCache
-
- private constructor () {
- super()
- }
-
- static get Instance () {
- return this.instance || (this.instance = new this())
- }
-
- async getFilePathImpl (filename: string) {
- const thumbnail = await ThumbnailModel.loadWithVideoByFilename(filename, ThumbnailType.PREVIEW)
- if (!thumbnail) return undefined
-
- if (thumbnail.Video.isLocal()) return { isLocal: true, path: thumbnail.getPath() }
-
- return this.loadRemoteFile(thumbnail.Video.uuid)
- }
-
- // Key is the video UUID
- protected async loadRemoteFile (key: string) {
- const video = await VideoModel.loadFull(key)
- if (!video) return undefined
-
- if (video.isLocal()) throw new Error('Cannot load remote preview of owned video.')
-
- const preview = video.getPreview()
- const destPath = join(FILES_CACHE.PREVIEWS.DIRECTORY, preview.filename)
- const remoteUrl = preview.getOriginFileUrl(video)
-
- try {
- await doRequestAndSaveToFile(remoteUrl, destPath)
-
- logger.debug('Fetched remote preview %s to %s.', remoteUrl, destPath)
-
- return { isLocal: false, path: destPath }
- } catch (err) {
- logger.info('Cannot fetch remote preview file %s.', remoteUrl, { err })
-
- return undefined
- }
- }
-}
-
-export {
- VideoPreviewsSimpleFileCache
-}
diff --git a/server/core/lib/files-cache/video-storyboards-image-file-cache.ts b/server/core/lib/files-cache/video-storyboards-image-file-cache.ts
new file mode 100644
index 0000000000..a7a73fcd44
--- /dev/null
+++ b/server/core/lib/files-cache/video-storyboards-image-file-cache.ts
@@ -0,0 +1,17 @@
+import { StoryboardModel } from '@server/models/video/storyboard.js'
+import { MStoryboard } from '@server/types/models/index.js'
+import { AbstractImageFileCache } from './shared/abstract-image-file-cache.js'
+
+export class VideoStoryboardsImageFileCache extends AbstractImageFileCache<MStoryboard> {
+ protected loadModel (filename: string) {
+ return StoryboardModel.loadByFilename(filename)
+ }
+
+ protected getFSFilePath (model: MStoryboard) {
+ return model.getFSPath()
+ }
+
+ protected getFSFileCachedPath (model: MStoryboard) {
+ return model.getFSCachedPath()
+ }
+}
diff --git a/server/core/lib/files-cache/video-storyboards-simple-file-cache.ts b/server/core/lib/files-cache/video-storyboards-simple-file-cache.ts
deleted file mode 100644
index b0389ce631..0000000000
--- a/server/core/lib/files-cache/video-storyboards-simple-file-cache.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { logger } from '@server/helpers/logger.js'
-import { doRequestAndSaveToFile } from '@server/helpers/requests.js'
-import { StoryboardModel } from '@server/models/video/storyboard.js'
-import { join } from 'path'
-import { FILES_CACHE } from '../../initializers/constants.js'
-import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'
-
-class VideoStoryboardsSimpleFileCache extends AbstractSimpleFileCache<string> {
- private static instance: VideoStoryboardsSimpleFileCache
-
- private constructor () {
- super()
- }
-
- static get Instance () {
- return this.instance || (this.instance = new this())
- }
-
- async getFilePathImpl (filename: string) {
- const storyboard = await StoryboardModel.loadWithVideoByFilename(filename)
- if (!storyboard) return undefined
-
- if (storyboard.Video.isLocal()) return { isLocal: true, path: storyboard.getPath() }
-
- return this.loadRemoteFile(storyboard.filename)
- }
-
- // Key is the storyboard filename
- protected async loadRemoteFile (key: string) {
- const storyboard = await StoryboardModel.loadWithVideoByFilename(key)
- if (!storyboard) return undefined
-
- const destPath = join(FILES_CACHE.STORYBOARDS.DIRECTORY, storyboard.filename)
- const remoteUrl = storyboard.getOriginFileUrl(storyboard.Video)
-
- try {
- await doRequestAndSaveToFile(remoteUrl, destPath)
-
- logger.debug('Fetched remote storyboard %s to %s.', remoteUrl, destPath)
-
- return { isLocal: false, path: destPath }
- } catch (err) {
- logger.info('Cannot fetch remote storyboard file %s.', remoteUrl, { err })
-
- return undefined
- }
- }
-}
-
-export {
- VideoStoryboardsSimpleFileCache
-}
diff --git a/server/core/lib/files-cache/video-thumbnails-image-file-cache.ts b/server/core/lib/files-cache/video-thumbnails-image-file-cache.ts
new file mode 100644
index 0000000000..5e2d9102d6
--- /dev/null
+++ b/server/core/lib/files-cache/video-thumbnails-image-file-cache.ts
@@ -0,0 +1,17 @@
+import { ThumbnailModel } from '@server/models/video/thumbnail.js'
+import { MThumbnail } from '@server/types/models/index.js'
+import { AbstractImageFileCache } from './shared/abstract-image-file-cache.js'
+
+export class VideoThumbnailsImageFileCache extends AbstractImageFileCache<MThumbnail> {
+ protected loadModel (filename: string) {
+ return ThumbnailModel.loadByFilename(filename)
+ }
+
+ protected getFSFilePath (model: MThumbnail) {
+ return model.getFSPath()
+ }
+
+ protected getFSFileCachedPath (model: MThumbnail) {
+ return model.getFSCachedPath()
+ }
+}
diff --git a/server/core/lib/files-cache/video-torrents-simple-file-cache.ts b/server/core/lib/files-cache/video-torrents-simple-file-cache.ts
deleted file mode 100644
index 3e09e1764e..0000000000
--- a/server/core/lib/files-cache/video-torrents-simple-file-cache.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { join } from 'path'
-import { logger } from '@server/helpers/logger.js'
-import { doRequestAndSaveToFile } from '@server/helpers/requests.js'
-import { VideoFileModel } from '@server/models/video/video-file.js'
-import { MVideo, MVideoFile } from '@server/types/models/index.js'
-import { CONFIG } from '../../initializers/config.js'
-import { FILES_CACHE } from '../../initializers/constants.js'
-import { VideoModel } from '../../models/video/video.js'
-import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'
-
-class VideoTorrentsSimpleFileCache extends AbstractSimpleFileCache<string> {
- private static instance: VideoTorrentsSimpleFileCache
-
- private constructor () {
- super()
- }
-
- static get Instance () {
- return this.instance || (this.instance = new this())
- }
-
- async getFilePathImpl (filename: string) {
- const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(filename)
- if (!file) return undefined
-
- if (file.getVideo().isLocal()) {
- const downloadName = this.buildDownloadName(file.getVideo(), file)
-
- return { isLocal: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }
- }
-
- return this.loadRemoteFile(filename)
- }
-
- // Key is the torrent filename
- protected async loadRemoteFile (key: string) {
- const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(key)
- if (!file) return undefined
-
- if (file.getVideo().isLocal()) throw new Error('Cannot load remote file of owned video.')
-
- // Used to fetch the path
- const video = await VideoModel.loadFull(file.getVideo().id)
- if (!video) return undefined
-
- const remoteUrl = file.getRemoteTorrentUrl(video)
- const destPath = join(FILES_CACHE.TORRENTS.DIRECTORY, file.torrentFilename)
-
- try {
- await doRequestAndSaveToFile(remoteUrl, destPath)
-
- const downloadName = this.buildDownloadName(video, file)
-
- return { isLocal: false, path: destPath, downloadName }
- } catch (err) {
- logger.info('Cannot fetch remote torrent file %s.', remoteUrl, { err })
-
- return undefined
- }
- }
-
- private buildDownloadName (video: MVideo, file: MVideoFile) {
- return `${video.name}-${file.resolution}p.torrent`
- }
-}
-
-export {
- VideoTorrentsSimpleFileCache
-}
diff --git a/server/core/lib/hls.ts b/server/core/lib/hls.ts
index 3ab01f4c22..3870150374 100644
--- a/server/core/lib/hls.ts
+++ b/server/core/lib/hls.ts
@@ -158,8 +158,8 @@ function updateMasterHLSPlaylist (video: MVideo, playlistArg: MStreamingPlaylist
const masterPlaylistContent = masterPlaylists.join('\n') + '\n'
if (playlist.storage === FileStorage.OBJECT_STORAGE) {
- playlist.playlistUrl = await storeHLSFileFromContent({
- playlist,
+ await storeHLSFileFromContent({
+ video,
pathOrFilename: playlist.playlistFilename,
content: masterPlaylistContent
})
@@ -215,8 +215,8 @@ function updateSha256VODSegments (video: MVideo, playlistArg: MStreamingPlaylist
playlist.segmentsSha256Filename = generateHlsSha256SegmentsFilename(video.isLive)
if (playlist.storage === FileStorage.OBJECT_STORAGE) {
- playlist.segmentsSha256Url = await storeHLSFileFromContent({
- playlist,
+ await storeHLSFileFromContent({
+ video,
pathOrFilename: playlist.segmentsSha256Filename,
content: JSON.stringify(json)
})
@@ -332,7 +332,7 @@ export function buildCaptionM3U8Content (options: {
const { video, caption } = options
return `#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:${video.duration}\n#EXT-X-MEDIA-SEQUENCE:0\n` +
- `#EXTINF:${video.duration},\n${caption.getFileUrl(video)}\n#EXT-X-ENDLIST\n`
+ `#EXTINF:${video.duration},\n${caption.getLocalFileUrl()}\n#EXT-X-ENDLIST\n`
}
// ---------------------------------------------------------------------------
diff --git a/server/core/lib/html/shared/actor-html.ts b/server/core/lib/html/shared/actor-html.ts
index 06db06c36f..0713223e63 100644
--- a/server/core/lib/html/shared/actor-html.ts
+++ b/server/core/lib/html/shared/actor-html.ts
@@ -2,7 +2,6 @@ import { escapeHTML, maxBy } from '@peertube/peertube-core-utils'
import { HttpStatusCode } from '@peertube/peertube-models'
import { getChannelRSSFeeds, getDefaultRSSFeeds } from '@server/lib/rss.js'
import { AccountModel } from '@server/models/account/account.js'
-import { ActorImageModel } from '@server/models/actor/actor-image.js'
import { VideoChannelModel } from '@server/models/video/video-channel.js'
import { MAccountDefault, MChannelDefault } from '@server/types/models/index.js'
import express from 'express'
@@ -83,12 +82,13 @@ export class ActorHtml {
const title = entity.getDisplayName()
const avatar = maxBy(entity.Actor.Avatars, 'width')
- const image = {
- url: ActorImageModel.getImageUrl(avatar),
- width: avatar?.width,
- height: avatar?.height
- }
-
+ const image = avatar
+ ? {
+ url: avatar.getLocalFileUrl(),
+ width: avatar.width,
+ height: avatar.height
+ }
+ : undefined
const ogType = 'website'
const twitterCard = 'summary'
const schemaType = 'ProfilePage'
diff --git a/server/core/lib/html/shared/video-html.ts b/server/core/lib/html/shared/video-html.ts
index b30cfd4cc7..4dc817d4df 100644
--- a/server/core/lib/html/shared/video-html.ts
+++ b/server/core/lib/html/shared/video-html.ts
@@ -98,7 +98,7 @@ export class VideoHtml {
let customHTML = TagsHtml.addTitleTag(html, video.name)
customHTML = TagsHtml.addDescriptionTag(customHTML, escapedTruncatedDescription)
- const preview = video.getPreview()
+ const thumbnail = video.getBestThumbnail()
return TagsHtml.addTags(customHTML, {
url: WEBSERVER.URL + video.getWatchStaticPath(),
@@ -113,8 +113,8 @@ export class VideoHtml {
embedIndexation: isEmbed,
- image: preview
- ? { url: WEBSERVER.URL + video.getPreviewStaticPath(), width: preview.width, height: preview.height }
+ image: thumbnail
+ ? { url: WEBSERVER.URL + thumbnail.getFileStaticPath(), width: thumbnail.width, height: thumbnail.height }
: undefined,
videoOrPlaylist: {
@@ -143,7 +143,7 @@ export class VideoHtml {
label: VideoCaptionModel.getLanguageLabel(c.language),
mediaType: 'text/vtt',
language: c.language,
- url: c.getFileUrl(video)
+ url: c.getLocalFileUrl()
}))
},
diff --git a/server/core/lib/job-queue/handlers/federate-video.ts b/server/core/lib/job-queue/handlers/federate-video.ts
index 8972d92d44..3e4a1e4970 100644
--- a/server/core/lib/job-queue/handlers/federate-video.ts
+++ b/server/core/lib/job-queue/handlers/federate-video.ts
@@ -1,12 +1,12 @@
-import { Job } from 'bullmq'
+import { FederateVideoPayload } from '@peertube/peertube-models'
import { retryTransactionWrapper } from '@server/helpers/database-utils.js'
import { sequelizeTypescript } from '@server/initializers/database.js'
import { federateVideoIfNeeded } from '@server/lib/activitypub/videos/index.js'
import { VideoModel } from '@server/models/video/video.js'
-import { FederateVideoPayload } from '@peertube/peertube-models'
+import { Job } from 'bullmq'
import { logger } from '../../../helpers/logger.js'
-function processFederateVideo (job: Job) {
+export function processFederateVideo (job: Job) {
const payload = job.data as FederateVideoPayload
logger.info('Processing video federation in job %s.', job.id)
@@ -20,9 +20,3 @@ function processFederateVideo (job: Job) {
})
})
}
-
-// ---------------------------------------------------------------------------
-
-export {
- processFederateVideo
-}
diff --git a/server/core/lib/job-queue/handlers/video-import.ts b/server/core/lib/job-queue/handlers/video-import.ts
index c2572d4725..90b3a4e786 100644
--- a/server/core/lib/job-queue/handlers/video-import.ts
+++ b/server/core/lib/job-queue/handlers/video-import.ts
@@ -1,8 +1,6 @@
import { buildAspectRatio } from '@peertube/peertube-core-utils'
import { ffprobePromise, getChaptersFromContainer, getVideoStreamDuration } from '@peertube/peertube-ffmpeg'
import {
- ThumbnailType,
- ThumbnailType_Type,
VideoImportPayload,
VideoImportPreventExceptionResult,
VideoImportState,
@@ -45,7 +43,7 @@ import { VideoImportModel } from '../../../models/video/video-import.js'
import { VideoModel } from '../../../models/video/video.js'
import { federateVideoIfNeeded } from '../../activitypub/videos/index.js'
import { Notifier } from '../../notifier/index.js'
-import { generateLocalVideoMiniature } from '../../thumbnail.js'
+import { createLocalVideoThumbnailsFromVideo } from '../../thumbnail.js'
import { JobQueue } from '../job-queue.js'
async function processVideoImport (job: Job): Promise<VideoImportPreventExceptionResult> {
@@ -206,7 +204,7 @@ async function processFile (downloader: () => Promise<string>, videoImport: MVid
tmpVideoPath = null // This path is not used anymore
- const thumbnails = await generateMiniature({ videoImportWithFiles, videoFile, ffprobe })
+ const thumbnails = await generateThumbnails({ videoImportWithFiles, videoFile, ffprobe })
// Create torrent
await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
@@ -225,8 +223,8 @@ async function processFile (downloader: () => Promise<string>, videoImport: MVid
video.aspectRatio = buildAspectRatio({ width: videoFile.width, height: videoFile.height })
await video.save({ transaction: t })
- for (const thumbnail of thumbnails) {
- await video.addAndSaveThumbnail(thumbnail, t)
+ if (thumbnails.length !== 0) {
+ await video.replaceAndSaveThumbnails(thumbnails, t)
}
await replaceChaptersIfNotExist({ video, chapters: containerChapters, transaction: t })
@@ -273,29 +271,16 @@ async function refreshVideoImportFromDB (videoImport: MVideoImportDefault, video
return Object.assign(videoImport, { Video: videoWithFiles })
}
-async function generateMiniature (options: {
+async function generateThumbnails (options: {
videoImportWithFiles: MVideoImportDefaultFiles
videoFile: MVideoFile
ffprobe: FfprobeData
}) {
const { ffprobe, videoFile, videoImportWithFiles } = options
- const thumbnailsToGenerate: ThumbnailType_Type[] = []
+ if (videoImportWithFiles.Video.Thumbnails.length !== 0) return []
- if (!videoImportWithFiles.Video.getMiniature()) {
- thumbnailsToGenerate.push(ThumbnailType.MINIATURE)
- }
-
- if (!videoImportWithFiles.Video.getPreview()) {
- thumbnailsToGenerate.push(ThumbnailType.PREVIEW)
- }
-
- return generateLocalVideoMiniature({
- video: videoImportWithFiles.Video,
- videoFile,
- types: thumbnailsToGenerate,
- ffprobe
- })
+ return createLocalVideoThumbnailsFromVideo({ video: videoImportWithFiles.Video, videoFile, ffprobe })
}
async function afterImportSuccess (options: {
diff --git a/server/core/lib/job-queue/handlers/video-live-ending.ts b/server/core/lib/job-queue/handlers/video-live-ending.ts
index 678884b928..992d86ae87 100644
--- a/server/core/lib/job-queue/handlers/video-live-ending.ts
+++ b/server/core/lib/job-queue/handlers/video-live-ending.ts
@@ -1,5 +1,5 @@
import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamFPS } from '@peertube/peertube-ffmpeg'
-import { ThumbnailType, VideoFileStream, VideoLiveEndingPayload, VideoState } from '@peertube/peertube-models'
+import { VideoFileStream, VideoLiveEndingPayload, VideoState } from '@peertube/peertube-models'
import { peertubeTruncate } from '@server/helpers/core-utils.js'
import { CONSTRAINTS_FIELDS } from '@server/initializers/constants.js'
import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url.js'
@@ -11,7 +11,11 @@ import {
getHLSDirectory,
getLiveReplayBaseDirectory
} from '@server/lib/paths.js'
-import { generateLocalVideoMiniature, regenerateMiniaturesIfNeeded, updateLocalVideoMiniatureFromExisting } from '@server/lib/thumbnail.js'
+import {
+ createLocalVideoThumbnailsFromVideo,
+ regenerateLocalVideoThumbnailsFromVideoIfNeeded,
+ createLocalVideoThumbnailsFromImage
+} from '@server/lib/thumbnail.js'
import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/hls-transcoding.js'
import { createTranscriptionTaskIfNeeded } from '@server/lib/video-captions.js'
import { addLocalOrRemoteStoryboardJobIfNeeded } from '@server/lib/video-jobs.js'
@@ -202,32 +206,25 @@ async function copyOrRegenerateThumbnails (options: {
const { liveVideo, replayVideo } = options
let thumbnails: MThumbnail[] = []
- const preview = liveVideo.getPreview()
-
- if (preview?.automaticallyGenerated === false) {
- thumbnails = await Promise.all(
- [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ].map(type => {
- return updateLocalVideoMiniatureFromExisting({
- inputPath: preview.getPath(),
- video: replayVideo,
- type,
- automaticallyGenerated: false,
- keepOriginal: true
- })
- })
- )
+
+ const bestThumbnail = liveVideo.getBestThumbnail()
+
+ if (bestThumbnail.automaticallyGenerated === false) {
+ thumbnails = await createLocalVideoThumbnailsFromImage({
+ inputPath: bestThumbnail.getFSPath(),
+ video: replayVideo,
+ automaticallyGenerated: false,
+ keepOriginal: true
+ })
} else {
- thumbnails = await generateLocalVideoMiniature({
+ thumbnails = await createLocalVideoThumbnailsFromVideo({
video: replayVideo,
videoFile: replayVideo.getMaxQualityFile(VideoFileStream.VIDEO) || replayVideo.getMaxQualityFile(VideoFileStream.AUDIO),
- types: [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ],
ffprobe: undefined
})
}
- for (const thumbnail of thumbnails) {
- await replayVideo.addAndSaveThumbnail(thumbnail)
- }
+ await replayVideo.replaceAndSaveThumbnails(thumbnails)
}
async function replaceLiveByReplay (options: {
@@ -285,7 +282,7 @@ async function replaceLiveByReplay (options: {
// Regenerate the thumbnail & preview?
try {
- await regenerateMiniaturesIfNeeded(videoWithFiles, undefined)
+ await regenerateLocalVideoThumbnailsFromVideoIfNeeded(videoWithFiles, undefined)
} catch (err) {
logger.error(`Cannot regenerate thumbnails of ended live ${videoWithFiles.uuid}`, lTags(liveVideo.uuid))
}
diff --git a/server/core/lib/live/live-segment-sha-store.ts b/server/core/lib/live/live-segment-sha-store.ts
index 91c5f856cd..24aae9f163 100644
--- a/server/core/lib/live/live-segment-sha-store.ts
+++ b/server/core/lib/live/live-segment-sha-store.ts
@@ -82,12 +82,7 @@ class LiveSegmentShaStore {
await rename(this.sha256PathTMP, this.sha256Path)
if (this.sendToObjectStorage) {
- const url = await storeHLSFileFromPath(this.streamingPlaylist, this.sha256Path)
-
- if (this.streamingPlaylist.segmentsSha256Url !== url) {
- this.streamingPlaylist.segmentsSha256Url = url
- await this.streamingPlaylist.save()
- }
+ await storeHLSFileFromPath(this.streamingPlaylist.Video, this.sha256Path)
}
})
}
diff --git a/server/core/lib/live/live-utils.ts b/server/core/lib/live/live-utils.ts
index fe32e4b527..4abde18204 100644
--- a/server/core/lib/live/live-utils.ts
+++ b/server/core/lib/live/live-utils.ts
@@ -38,7 +38,7 @@ export async function cleanupUnsavedNormalLive (video: MVideo, streamingPlaylist
// We uploaded files to object storage too, remove them
if (streamingPlaylist.storage === FileStorage.OBJECT_STORAGE) {
- await removeHLSObjectStorage(streamingPlaylist.withVideo(video))
+ await removeHLSObjectStorage(video)
}
await remove(hlsDirectory)
@@ -97,7 +97,7 @@ async function cleanupTMPLiveFilesFromObjectStorage (streamingPlaylist: MStreami
logger.info('Cleanup TMP live files from object storage for %s.', streamingPlaylist.Video.uuid)
- const keys = await listHLSFileKeysOf(streamingPlaylist)
+ const keys = await listHLSFileKeysOf(streamingPlaylist.Video)
for (const key of keys) {
if (isTMPLiveFile(key)) {
diff --git a/server/core/lib/live/shared/muxing-session.ts b/server/core/lib/live/shared/muxing-session.ts
index 4513cf5729..8afb420923 100644
--- a/server/core/lib/live/shared/muxing-session.ts
+++ b/server/core/lib/live/shared/muxing-session.ts
@@ -225,15 +225,13 @@ class MuxingSession extends EventEmitter implements MuxingSession {
logger.debug('Uploading live master playlist on object storage for %s', this.videoUUID, { masterContent, ...this.lTags() })
- const url = await storeHLSFileFromContent(
+ await storeHLSFileFromContent(
{
- playlist: this.streamingPlaylist,
+ video: this.streamingPlaylist.Video,
pathOrFilename: this.streamingPlaylist.playlistFilename,
content: masterContent
}
)
-
- this.streamingPlaylist.playlistUrl = url
}
this.streamingPlaylist.assignP2PMediaLoaderInfoHashes(this.videoLive.Video, this.allResolutions.map(r => ({ height: r })))
@@ -294,7 +292,7 @@ class MuxingSession extends EventEmitter implements MuxingSession {
if (this.streamingPlaylist.storage === FileStorage.OBJECT_STORAGE) {
try {
- await removeHLSFileObjectStorageByPath(this.streamingPlaylist, segmentPath)
+ await removeHLSFileObjectStorageByPath(this.streamingPlaylist.Video, segmentPath)
} catch (err) {
logger.error('Cannot remove segment %s from object storage', segmentPath, { err, ...this.lTags() })
}
@@ -381,7 +379,7 @@ class MuxingSession extends EventEmitter implements MuxingSession {
if (this.streamingPlaylist.storage === FileStorage.OBJECT_STORAGE) {
try {
- await storeHLSFileFromPath(this.streamingPlaylist, segmentPath)
+ await storeHLSFileFromPath(this.streamingPlaylist.Video, segmentPath)
await this.processM3U8ToObjectStorage(segmentPath)
} catch (err) {
@@ -416,7 +414,7 @@ class MuxingSession extends EventEmitter implements MuxingSession {
const queue = this.objectStorageSendQueues.get(m3u8Path)
await queue.add(() =>
storeHLSFileFromContent({
- playlist: this.streamingPlaylist,
+ video: this.streamingPlaylist.Video,
pathOrFilename: m3u8Path,
content: filteredPlaylistContent
})
diff --git a/server/core/lib/local-actor.ts b/server/core/lib/local-actor.ts
index 9cad140399..f4ce471768 100644
--- a/server/core/lib/local-actor.ts
+++ b/server/core/lib/local-actor.ts
@@ -1,5 +1,6 @@
import { ActivityPubActorType, ActorImageType, ActorImageType_Type } from '@peertube/peertube-models'
import { buildUUID, getLowercaseExtension } from '@peertube/peertube-node-utils'
+import { processImage } from '@server/helpers/image-utils.js'
import { ActorReservedModel } from '@server/models/actor/actor-reserved.js'
import { ActorModel } from '@server/models/actor/actor.js'
import { remove } from 'fs-extra/esm'
@@ -12,7 +13,6 @@ import { sequelizeTypescript } from '../initializers/database.js'
import { MAccountDefault, MActor, MChannelDefault } from '../types/models/index.js'
import { deleteActorImages, updateActorImages } from './activitypub/actors/index.js'
import { sendUpdateActor } from './activitypub/send/index.js'
-import { processImageFromWorker } from './worker/parent-process.js'
export function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string) {
return new ActorModel({
@@ -44,7 +44,7 @@ export async function updateLocalActorImageFiles (options: {
const imageName = buildUUID() + extension
const destination = join(CONFIG.STORAGE.ACTOR_IMAGES_DIR, imageName)
- await processImageFromWorker({ path: imagePhysicalFile.path, destination, newSize: imageSize, keepOriginal: true })
+ await processImage({ path: imagePhysicalFile.path, destination, newSize: imageSize, keepOriginal: true })
return {
imageName,
@@ -62,7 +62,7 @@ export async function updateLocalActorImageFiles (options: {
fileUrl: null,
height: imageSize.height,
width: imageSize.width,
- onDisk: true
+ cached: false
}))
const updatedActor = await updateActorImages(accountOrChannel.Actor, type, actorImagesInfo, t)
diff --git a/server/core/lib/local-video-creator.ts b/server/core/lib/local-video-creator.ts
index df39fe8d24..72fe40ae35 100644
--- a/server/core/lib/local-video-creator.ts
+++ b/server/core/lib/local-video-creator.ts
@@ -4,8 +4,6 @@ import {
LiveVideoLatencyMode,
NSFWFlag,
PeerTubeError,
- ThumbnailType,
- ThumbnailType_Type,
VideoChannelActivityAction,
VideoCreate,
VideoPrivacy,
@@ -23,7 +21,7 @@ import { VideoLiveScheduleModel } from '@server/models/video/video-live-schedule
import { VideoLiveModel } from '@server/models/video/video-live.js'
import { VideoPasswordModel } from '@server/models/video/video-password.js'
import { VideoModel } from '@server/models/video/video.js'
-import { MChannel, MChannelAccountLight, MThumbnail, MUserAccountId, MVideoFile, MVideoFullLight } from '@server/types/models/index.js'
+import { MChannel, MChannelAccountLight, MUserAccountId, MVideoFile, MVideoFullLight } from '@server/types/models/index.js'
import { FilteredModelAttributes } from '@server/types/sequelize.js'
import { FfprobeData } from 'fluent-ffmpeg'
import { move } from 'fs-extra/esm'
@@ -32,7 +30,7 @@ import { federateVideoIfNeeded } from './activitypub/videos/federate.js'
import { AutomaticTagger } from './automatic-tags/automatic-tagger.js'
import { setAndSaveVideoAutomaticTags } from './automatic-tags/automatic-tags.js'
import { Hooks } from './plugins/hooks.js'
-import { generateLocalVideoMiniature, updateLocalVideoMiniatureFromExisting } from './thumbnail.js'
+import { createLocalVideoThumbnailsFromVideo, createLocalVideoThumbnailsFromImage } from './thumbnail.js'
import { autoBlacklistVideoIfNeeded } from './video-blacklist.js'
import { replaceChapters, replaceChaptersFromDescriptionIfNeeded } from './video-chapters.js'
import { buildNewFile, createVideoSource } from './video-file.js'
@@ -51,12 +49,11 @@ type LiveAttributes = Pick<LiveVideoCreate, 'permanentLive' | 'latencyMode' | 's
streamKey?: string
}
-export type ThumbnailOptions = {
+export type ThumbnailOption = {
path: string
- type: ThumbnailType_Type
automaticallyGenerated: boolean
keepOriginal: boolean
-}[]
+}
type ChaptersOption = { timecode: number, title: string }[]
@@ -96,7 +93,7 @@ export class LocalVideoCreator {
channel: MChannelAccountLight
user: MUserAccountId
videoAttributeResultHook: VideoAttributeHookFilter
- thumbnails: ThumbnailOptions
+ thumbnail: ThumbnailOption
chapters: ChaptersOption | undefined
fallbackChapters: {
@@ -149,9 +146,7 @@ export class LocalVideoCreator {
transaction
})
- for (const thumbnail of thumbnails) {
- await this.video.addAndSaveThumbnail(thumbnail, transaction)
- }
+ await this.video.replaceAndSaveThumbnails(thumbnails, transaction)
if (this.videoFile) {
this.videoFile.videoId = this.video.id
@@ -264,39 +259,23 @@ export class LocalVideoCreator {
}
private async createThumbnails () {
- const promises: Promise<MThumbnail>[] = []
- let toGenerate = [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]
-
- for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) {
- const thumbnail = this.options.thumbnails.find(t => t.type === type)
- if (!thumbnail) continue
-
- promises.push(
- updateLocalVideoMiniatureFromExisting({
- inputPath: thumbnail.path,
- video: this.video,
- type,
- automaticallyGenerated: thumbnail.automaticallyGenerated || false,
- keepOriginal: thumbnail.keepOriginal
- }).catch(err => {
- // eslint-disable-next-line @typescript-eslint/only-throw-error
- throw PeerTubeError.fromError(err, 'INVALID_IMAGE_FILE')
- })
- )
-
- toGenerate = toGenerate.filter(t => t !== thumbnail.type)
+ if (this.options.thumbnail) {
+ return createLocalVideoThumbnailsFromImage({
+ automaticallyGenerated: this.options.thumbnail.automaticallyGenerated,
+ keepOriginal: this.options.thumbnail.keepOriginal,
+ inputPath: this.options.thumbnail.path,
+ video: this.video
+ }).catch(err => {
+ // eslint-disable-next-line @typescript-eslint/only-throw-error
+ throw PeerTubeError.fromError(err, 'INVALID_IMAGE_FILE')
+ })
}
- return [
- ...await Promise.all(promises),
-
- ...await generateLocalVideoMiniature({
- video: this.video,
- videoFile: this.videoFile,
- types: toGenerate,
- ffprobe: this.videoFileProbe
- })
- ]
+ return createLocalVideoThumbnailsFromVideo({
+ video: this.video,
+ videoFile: this.videoFile,
+ ffprobe: this.videoFileProbe
+ })
}
private buildVideo (videoInfo: VideoAttributes, channel: MChannel): FilteredModelAttributes<VideoModel> {
diff --git a/server/core/lib/move-storage/move-to-file-system.ts b/server/core/lib/move-storage/move-to-file-system.ts
index 9a69a0e79b..ce8f160244 100644
--- a/server/core/lib/move-storage/move-to-file-system.ts
+++ b/server/core/lib/move-storage/move-to-file-system.ts
@@ -1,7 +1,13 @@
import { FileStorage, VideoStateType } from '@peertube/peertube-models'
import { logger, LoggerTags, loggerTagsFactory } from '@server/helpers/logger.js'
+import { CONFIG } from '@server/initializers/config.js'
import { P2P_MEDIA_LOADER_PEER_VERSION } from '@server/initializers/constants.js'
import {
+ buildObjectStoragePublicFileUrl,
+ generateCaptionObjectStorageKey,
+ generateHLSObjectStorageKey,
+ generateOriginalVideoObjectStorageKey,
+ generateWebVideoObjectStorageKey,
makeCaptionFileAvailable,
makeHLSFileAvailable,
makeOriginalFileAvailable,
@@ -96,9 +102,11 @@ async function moveVideoSourceFile (source: MVideoSource) {
VideoPathManager.Instance.getFSOriginalVideoFilePath(source.keptOriginalFilename)
)
- const oldFileUrl = source.fileUrl
+ const oldFileUrl = buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.ORIGINAL_VIDEO_FILES,
+ key: generateOriginalVideoObjectStorageKey(source.keptOriginalFilename)
+ })
- source.fileUrl = null
source.storage = FileStorage.FILE_SYSTEM
await source.save()
@@ -122,8 +130,6 @@ async function moveWebVideoFiles (video: MVideoWithAllFiles) {
async function moveHLSFiles (video: MVideoWithAllFiles) {
for (const playlist of video.VideoStreamingPlaylists) {
- const playlistWithVideo = playlist.withVideo(video)
-
let updatedFile = false
for (const file of playlist.VideoFiles) {
@@ -133,36 +139,34 @@ async function moveHLSFiles (video: MVideoWithAllFiles) {
// Resolution playlist
const playlistFilename = getHLSResolutionPlaylistFilename(file.filename)
- await makeHLSFileAvailable(playlistWithVideo, playlistFilename, join(getHLSDirectory(video), playlistFilename))
- await makeHLSFileAvailable(playlistWithVideo, file.filename, join(getHLSDirectory(video), file.filename))
+ await makeHLSFileAvailable(video, playlistFilename, join(getHLSDirectory(video), playlistFilename))
+ await makeHLSFileAvailable(video, file.filename, join(getHLSDirectory(video), file.filename))
await onVideoFileMoved({
- videoOrPlaylist: playlistWithVideo,
+ videoOrPlaylist: playlist.withVideo(video),
file,
objetStorageRemover: async () => {
- await removeHLSFileObjectStorageByFilename(playlistWithVideo, playlistFilename)
- await removeHLSFileObjectStorageByFilename(playlistWithVideo, file.filename)
+ await removeHLSFileObjectStorageByFilename(video, playlistFilename)
+ await removeHLSFileObjectStorageByFilename(video, file.filename)
}
})
}
- if (playlistWithVideo.storage !== FileStorage.FILE_SYSTEM) {
- await makeHLSFileAvailable(playlistWithVideo, playlist.playlistFilename, join(getHLSDirectory(video), playlist.playlistFilename))
+ if (playlist.storage !== FileStorage.FILE_SYSTEM) {
+ await makeHLSFileAvailable(video, playlist.playlistFilename, join(getHLSDirectory(video), playlist.playlistFilename))
await makeHLSFileAvailable(
- playlistWithVideo,
+ video,
playlist.segmentsSha256Filename,
join(getHLSDirectory(video), playlist.segmentsSha256Filename)
)
- playlist.playlistUrl = null
- playlist.segmentsSha256Url = null
playlist.storage = FileStorage.FILE_SYSTEM
await playlist.save()
- await removeHLSFileObjectStorageByFilename(playlistWithVideo, playlist.playlistFilename)
- await removeHLSFileObjectStorageByFilename(playlistWithVideo, playlist.segmentsSha256Filename)
+ await removeHLSFileObjectStorageByFilename(video, playlist.playlistFilename)
+ await removeHLSFileObjectStorageByFilename(video, playlist.segmentsSha256Filename)
}
if (updatedFile === true) {
@@ -181,9 +185,11 @@ async function onVideoFileMoved (options: {
}) {
const { videoOrPlaylist, file, objetStorageRemover } = options
- const oldFileUrl = file.fileUrl
+ const oldFileUrl = buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.WEB_VIDEOS,
+ key: generateWebVideoObjectStorageKey(file.filename)
+ })
- file.fileUrl = null
file.storage = FileStorage.FILE_SYSTEM
await updateTorrentMetadata(videoOrPlaylist, file)
@@ -200,12 +206,14 @@ async function moveCaptionFiles (captions: MVideoCaption[], hls: MStreamingPlayl
for (const caption of captions) {
if (caption.storage === FileStorage.OBJECT_STORAGE) {
- const oldFileUrl = caption.fileUrl
+ const oldFileUrl = buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.CAPTIONS,
+ key: generateCaptionObjectStorageKey(caption.filename)
+ })
await makeCaptionFileAvailable(caption.filename, caption.getFSFilePath())
// Assign new values before building the m3u8 file
- caption.fileUrl = null
caption.storage = FileStorage.FILE_SYSTEM
await caption.save()
@@ -214,22 +222,25 @@ async function moveCaptionFiles (captions: MVideoCaption[], hls: MStreamingPlayl
await removeCaptionObjectStorage(caption)
}
- if (hls && (!caption.m3u8Filename || caption.m3u8Url)) {
+ if (hls) {
hlsUpdated = true
- const oldM3U8Url = caption.m3u8Url
+ const oldM3U8Url = buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
+ key: generateHLSObjectStorageKey(hls.Video, caption.m3u8Filename)
+ })
+
const oldM3U8Filename = caption.m3u8Filename
// Caption link has been updated, so we must also update the HLS caption playlist
caption.m3u8Filename = await upsertCaptionPlaylistOnFS(caption, hls.Video)
- caption.m3u8Url = null
await caption.save()
- if (oldM3U8Url) {
+ if (oldM3U8Filename) {
logger.debug(`Removing video caption playlist file ${oldM3U8Url} because it's now on file system`, lTagsBase())
- await removeHLSFileObjectStorageByFilename(hls, oldM3U8Filename)
+ await removeHLSFileObjectStorageByFilename(hls.Video, oldM3U8Filename)
}
}
}
diff --git a/server/core/lib/move-storage/move-to-object-storage.ts b/server/core/lib/move-storage/move-to-object-storage.ts
index 9ad2ed7e93..43779108a6 100644
--- a/server/core/lib/move-storage/move-to-object-storage.ts
+++ b/server/core/lib/move-storage/move-to-object-storage.ts
@@ -93,10 +93,9 @@ async function moveVideoSourceFile (source: MVideoSource) {
if (source.storage !== FileStorage.FILE_SYSTEM) return
const sourcePath = VideoPathManager.Instance.getFSOriginalVideoFilePath(source.keptOriginalFilename)
- const fileUrl = await storeOriginalVideoFile(sourcePath, source.keptOriginalFilename)
+ await storeOriginalVideoFile(sourcePath, source.keptOriginalFilename)
source.storage = FileStorage.OBJECT_STORAGE
- source.fileUrl = fileUrl
await source.save()
logger.debug('Removing original video file ' + sourcePath + ' because it\'s now on object storage', lTagsBase())
@@ -113,8 +112,8 @@ async function moveCaptionFiles (captions: MVideoCaption[], hls: MStreamingPlayl
if (caption.storage === FileStorage.FILE_SYSTEM) {
const captionPath = caption.getFSFilePath()
+ await storeVideoCaption(captionPath, caption.filename)
// Assign new values before building the m3u8 file
- caption.fileUrl = await storeVideoCaption(captionPath, caption.filename)
caption.storage = FileStorage.OBJECT_STORAGE
await caption.save()
@@ -123,7 +122,7 @@ async function moveCaptionFiles (captions: MVideoCaption[], hls: MStreamingPlayl
await remove(captionPath)
}
- if (hls && (!caption.m3u8Filename || !caption.m3u8Url)) {
+ if (hls) {
hlsUpdated = true
const m3u8PathToRemove = caption.getFSM3U8Path(hls.Video)
@@ -132,8 +131,9 @@ async function moveCaptionFiles (captions: MVideoCaption[], hls: MStreamingPlayl
const content = buildCaptionM3U8Content({ video: hls.Video, caption })
caption.m3u8Filename = VideoCaptionModel.generateM3U8Filename(caption.filename)
- caption.m3u8Url = await storeHLSFileFromContent({
- playlist: hls,
+
+ await storeHLSFileFromContent({
+ video: hls.Video,
pathOrFilename: caption.m3u8Filename,
content
})
@@ -158,17 +158,15 @@ async function moveWebVideoFiles (video: MVideoWithAllFiles) {
for (const file of video.VideoFiles) {
if (file.storage !== FileStorage.FILE_SYSTEM) continue
- const fileUrl = await storeWebVideoFile(video, file)
+ await storeWebVideoFile(video, file)
const oldPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, file)
- await onVideoFileMoved({ videoOrPlaylist: video, file, fileUrl, oldPath })
+ await onVideoFileMoved({ videoOrPlaylist: video, file, oldPath })
}
}
async function moveHLSFiles (video: MVideoWithAllFiles) {
for (const playlist of video.VideoStreamingPlaylists) {
- const playlistWithVideo = playlist.withVideo(video)
-
let updatedFile = false
for (const file of playlist.VideoFiles) {
@@ -178,21 +176,21 @@ async function moveHLSFiles (video: MVideoWithAllFiles) {
// Resolution playlist
const playlistFilename = getHLSResolutionPlaylistFilename(file.filename)
- await storeHLSFileFromFilename(playlistWithVideo, playlistFilename)
+ await storeHLSFileFromFilename(video, playlistFilename)
// Resolution fragmented file
- const fileUrl = await storeHLSFileFromFilename(playlistWithVideo, file.filename)
+ await storeHLSFileFromFilename(video, file.filename)
const oldPath = join(getHLSDirectory(video), file.filename)
- await onVideoFileMoved({ videoOrPlaylist: Object.assign(playlist, { Video: video }), file, fileUrl, oldPath })
+ await onVideoFileMoved({ videoOrPlaylist: Object.assign(playlist, { Video: video }), file, oldPath })
await remove(join(getHLSDirectory(video), playlistFilename))
}
- if (playlistWithVideo.storage === FileStorage.FILE_SYSTEM) {
- playlist.playlistUrl = await storeHLSFileFromFilename(playlistWithVideo, playlist.playlistFilename)
- playlist.segmentsSha256Url = await storeHLSFileFromFilename(playlistWithVideo, playlist.segmentsSha256Filename)
+ if (playlist.storage === FileStorage.FILE_SYSTEM) {
+ await storeHLSFileFromFilename(video, playlist.playlistFilename)
+ await storeHLSFileFromFilename(video, playlist.segmentsSha256Filename)
playlist.storage = FileStorage.OBJECT_STORAGE
await playlist.save()
@@ -219,12 +217,10 @@ async function moveHLSFiles (video: MVideoWithAllFiles) {
async function onVideoFileMoved (options: {
videoOrPlaylist: MVideo | MStreamingPlaylistVideo
file: MVideoFile
- fileUrl: string
oldPath: string
}) {
- const { videoOrPlaylist, file, fileUrl, oldPath } = options
+ const { videoOrPlaylist, file, oldPath } = options
- file.fileUrl = fileUrl
file.storage = FileStorage.OBJECT_STORAGE
await updateTorrentMetadata(videoOrPlaylist, file)
diff --git a/server/core/lib/object-storage/keys.ts b/server/core/lib/object-storage/keys.ts
index 343bc5e41b..4faca32583 100644
--- a/server/core/lib/object-storage/keys.ts
+++ b/server/core/lib/object-storage/keys.ts
@@ -1,12 +1,13 @@
-import { MStreamingPlaylistVideoUUID } from '@server/types/models/index.js'
+import { VideoStreamingPlaylistTypeString } from '@peertube/peertube-models'
+import { MVideoUUID } from '@server/types/models/index.js'
import { join } from 'path'
-export function generateHLSObjectStorageKey (playlist: MStreamingPlaylistVideoUUID, filename: string) {
- return join(generateHLSObjectBaseStorageKey(playlist), filename)
+export function generateHLSObjectStorageKey (video: MVideoUUID, filename: string) {
+ return join(generateHLSObjectBaseStorageKey(video), filename)
}
-export function generateHLSObjectBaseStorageKey (playlist: MStreamingPlaylistVideoUUID) {
- return join(playlist.getStringType(), playlist.Video.uuid)
+export function generateHLSObjectBaseStorageKey (video: MVideoUUID) {
+ return join('hls' satisfies VideoStreamingPlaylistTypeString, video.uuid)
}
export function generateWebVideoObjectStorageKey (filename: string) {
diff --git a/server/core/lib/object-storage/object-storage-helpers.ts b/server/core/lib/object-storage/object-storage-helpers.ts
index c15dbf786b..ef77240806 100644
--- a/server/core/lib/object-storage/object-storage-helpers.ts
+++ b/server/core/lib/object-storage/object-storage-helpers.ts
@@ -9,12 +9,12 @@ import { dirname } from 'path'
import { Readable } from 'stream'
import { getClient } from './shared/client.js'
import { lTags } from './shared/logger.js'
-import { getInternalUrl } from './urls.js'
import type { _Object, ObjectCannedACL, PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'
type BucketInfo = {
BUCKET_NAME: string
+ BASE_URL: string
PREFIX?: string
}
@@ -54,7 +54,7 @@ async function storeObject (options: {
bucketInfo: BucketInfo
isPrivate: boolean
contentType: string
-}): Promise<string> {
+}): Promise<void> {
const { inputPath, objectStorageKey, bucketInfo, isPrivate, contentType } = options
logger.debug('Uploading file %s to %s%s in bucket %s', inputPath, bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags())
@@ -70,7 +70,7 @@ async function storeContent (options: {
bucketInfo: BucketInfo
isPrivate: boolean
contentType: string
-}): Promise<string> {
+}): Promise<void> {
const { content, objectStorageKey, bucketInfo, isPrivate, contentType } = options
logger.debug('Uploading %s content to %s%s in bucket %s', content, bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags())
@@ -84,7 +84,7 @@ async function storeStream (options: {
bucketInfo: BucketInfo
isPrivate: boolean
contentType: string
-}): Promise<string> {
+}): Promise<void> {
const { stream, objectStorageKey, bucketInfo, isPrivate, contentType } = options
logger.debug('Streaming file to %s%s in bucket %s', bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags())
@@ -357,8 +357,6 @@ async function uploadToStorage (options: {
bucketInfo.BUCKET_NAME,
{ ...lTags(), responseMetadata: response.$metadata }
)
-
- return getInternalUrl(bucketInfo, objectStorageKey)
} catch (err) {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw parseS3Error(err)
diff --git a/server/core/lib/object-storage/pre-signed-urls.ts b/server/core/lib/object-storage/pre-signed-urls.ts
index 3abf556121..436f7eb6ef 100644
--- a/server/core/lib/object-storage/pre-signed-urls.ts
+++ b/server/core/lib/object-storage/pre-signed-urls.ts
@@ -8,7 +8,6 @@ import {
generateWebVideoObjectStorageKey
} from './keys.js'
import { buildKey, getClient } from './shared/index.js'
-import { getObjectStoragePublicFileUrl } from './urls.js'
export async function generateWebVideoPresignedUrl (options: {
file: MVideoFile
@@ -22,7 +21,7 @@ export async function generateWebVideoPresignedUrl (options: {
downloadFilename
})
- return getObjectStoragePublicFileUrl(url, CONFIG.OBJECT_STORAGE.WEB_VIDEOS)
+ return replaceByBaseUrl(url, CONFIG.OBJECT_STORAGE.WEB_VIDEOS)
}
export async function generateHLSFilePresignedUrl (options: {
@@ -34,11 +33,11 @@ export async function generateHLSFilePresignedUrl (options: {
const url = await generatePresignedUrl({
bucket: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET_NAME,
- key: buildKey(generateHLSObjectStorageKey(streamingPlaylist, file.filename), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS),
+ key: buildKey(generateHLSObjectStorageKey(streamingPlaylist.Video, file.filename), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS),
downloadFilename
})
- return getObjectStoragePublicFileUrl(url, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+ return replaceByBaseUrl(url, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
}
export async function generateUserExportPresignedUrl (options: {
@@ -53,7 +52,7 @@ export async function generateUserExportPresignedUrl (options: {
downloadFilename
})
- return getObjectStoragePublicFileUrl(url, CONFIG.OBJECT_STORAGE.USER_EXPORTS)
+ return replaceByBaseUrl(url, CONFIG.OBJECT_STORAGE.USER_EXPORTS)
}
export async function generateOriginalFilePresignedUrl (options: {
@@ -68,7 +67,7 @@ export async function generateOriginalFilePresignedUrl (options: {
downloadFilename
})
- return getObjectStoragePublicFileUrl(url, CONFIG.OBJECT_STORAGE.ORIGINAL_VIDEO_FILES)
+ return replaceByBaseUrl(url, CONFIG.OBJECT_STORAGE.ORIGINAL_VIDEO_FILES)
}
// ---------------------------------------------------------------------------
@@ -93,3 +92,10 @@ async function generatePresignedUrl (options: {
return getSignedUrl(await getClient(), command, { expiresIn: 3600 * 24 })
}
+
+const regex = new RegExp('https?://[^/]+')
+function replaceByBaseUrl (fileUrl: string, bucket: { BASE_URL: string }) {
+ if (!bucket.BASE_URL) return fileUrl
+
+ return fileUrl.replace(regex, bucket.BASE_URL)
+}
diff --git a/server/core/lib/object-storage/proxy.ts b/server/core/lib/object-storage/proxy.ts
index e13fd74757..fc7e3b8ffc 100644
--- a/server/core/lib/object-storage/proxy.ts
+++ b/server/core/lib/object-storage/proxy.ts
@@ -1,10 +1,10 @@
-import express from 'express'
-import { PassThrough, pipeline } from 'stream'
import { HttpStatusCode } from '@peertube/peertube-models'
import { buildReinjectVideoFileTokenQuery } from '@server/controllers/shared/m3u8-playlist.js'
import { logger } from '@server/helpers/logger.js'
import { StreamReplacer } from '@server/helpers/stream-replacer.js'
-import { MStreamingPlaylist, MVideo } from '@server/types/models/index.js'
+import { MVideo } from '@server/types/models/index.js'
+import express from 'express'
+import { PassThrough, pipeline } from 'stream'
import { injectQueryToPlaylistUrls } from '../hls.js'
import { getHLSFileReadStream, getWebVideoFileReadStream } from './videos.js'
@@ -36,18 +36,17 @@ export async function proxifyWebVideoFile (options: {
export async function proxifyHLS (options: {
req: express.Request
res: express.Response
- playlist: MStreamingPlaylist
video: MVideo
filename: string
reinjectVideoFileToken: boolean
}) {
- const { req, res, playlist, video, filename, reinjectVideoFileToken } = options
+ const { req, res, video, filename, reinjectVideoFileToken } = options
logger.debug('Proxifying HLS file %s from object storage.', filename)
try {
const { response: s3Response, stream } = await getHLSFileReadStream({
- playlist: playlist.withVideo(video),
+ video,
filename,
rangeHeader: req.header('range')
})
diff --git a/server/core/lib/object-storage/urls.ts b/server/core/lib/object-storage/urls.ts
index a6df19213f..d967a8e284 100644
--- a/server/core/lib/object-storage/urls.ts
+++ b/server/core/lib/object-storage/urls.ts
@@ -3,26 +3,22 @@ import { OBJECT_STORAGE_PROXY_PATHS, WEBSERVER } from '@server/initializers/cons
import { MVideoUUID } from '@server/types/models/index.js'
import { BucketInfo, buildKey, getEndpointParsed } from './shared/index.js'
-export function getInternalUrl (config: BucketInfo, keyWithoutPrefix: string) {
- return getBaseUrl(config) + buildKey(keyWithoutPrefix, config)
-}
-
// ---------------------------------------------------------------------------
-export function getObjectStoragePublicFileUrl (fileUrl: string, objectStorageConfig: { BASE_URL: string }) {
- const baseUrl = objectStorageConfig.BASE_URL
- if (!baseUrl) return fileUrl
-
- return replaceByBaseUrl(fileUrl, baseUrl)
+export function buildObjectStoragePublicFileUrl (options: {
+ bucket: BucketInfo
+ key: string
+}) {
+ return buildBaseUrl(options.bucket) + buildKey(options.key, options.bucket)
}
// ---------------------------------------------------------------------------
-export function getHLSPrivateFileUrl (video: MVideoUUID, filename: string) {
+export function buildObjectStorageHLSPrivateFileUrl (video: MVideoUUID, filename: string) {
return WEBSERVER.URL + OBJECT_STORAGE_PROXY_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS + video.uuid + `/${filename}`
}
-export function getWebVideoPrivateFileUrl (filename: string) {
+export function buildObjectStorageWebVideoPrivateFileUrl (filename: string) {
return WEBSERVER.URL + OBJECT_STORAGE_PROXY_PATHS.PRIVATE_WEB_VIDEOS + filename
}
@@ -30,19 +26,17 @@ export function getWebVideoPrivateFileUrl (filename: string) {
// Private
// ---------------------------------------------------------------------------
-function getBaseUrl (bucketInfo: BucketInfo, baseUrl?: string) {
- if (baseUrl) return baseUrl
+function buildBaseUrl (bucketInfo: BucketInfo) {
+ let baseUrlConfig = bucketInfo.BASE_URL
+ if (baseUrlConfig && !baseUrlConfig.endsWith('/')) baseUrlConfig += '/'
if (CONFIG.OBJECT_STORAGE.FORCE_PATH_STYLE) {
- return `${getEndpointParsed().protocol}//${getEndpointParsed().host}/${bucketInfo.BUCKET_NAME}/`
- }
+ const baseUrl = baseUrlConfig || `${getEndpointParsed().protocol}//${getEndpointParsed().host}/`
- return `${getEndpointParsed().protocol}//${bucketInfo.BUCKET_NAME}.${getEndpointParsed().host}/`
-}
+ return baseUrl + `${bucketInfo.BUCKET_NAME}/`
+ }
-const regex = new RegExp('https?://[^/]+')
-function replaceByBaseUrl (fileUrl: string, baseUrl: string) {
- if (!fileUrl) return fileUrl
+ if (baseUrlConfig) return baseUrlConfig
- return fileUrl.replace(regex, baseUrl)
+ return `${getEndpointParsed().protocol}//${bucketInfo.BUCKET_NAME}.${getEndpointParsed().host}/`
}
diff --git a/server/core/lib/object-storage/videos.ts b/server/core/lib/object-storage/videos.ts
index 95a6748b75..48f1fb18ad 100644
--- a/server/core/lib/object-storage/videos.ts
+++ b/server/core/lib/object-storage/videos.ts
@@ -1,6 +1,7 @@
import { logger } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
-import { MStreamingPlaylistVideo, MStreamingPlaylistVideoUUID, MVideo, MVideoCaption, MVideoFile } from '@server/types/models/index.js'
+import { MIMETYPES } from '@server/initializers/constants.js'
+import { MVideo, MVideoCaption, MVideoFile, MVideoPrivacy, MVideoUUID } from '@server/types/models/index.js'
import { MVideoSource } from '@server/types/models/video/video-source.js'
import { basename, extname, join } from 'path'
import { getHLSDirectory } from '../paths.js'
@@ -25,50 +26,49 @@ import {
updateObjectACL,
updatePrefixACL
} from './shared/index.js'
-import { MIMETYPES } from '@server/initializers/constants.js'
-export function listHLSFileKeysOf (playlist: MStreamingPlaylistVideo) {
- return listKeysOfPrefix(generateHLSObjectBaseStorageKey(playlist), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+export function listHLSFileKeysOf (video: MVideoUUID) {
+ return listKeysOfPrefix(generateHLSObjectBaseStorageKey(video), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
}
// ---------------------------------------------------------------------------
-export function storeHLSFileFromFilename (playlist: MStreamingPlaylistVideo, filename: string) {
+export function storeHLSFileFromFilename (video: MVideoPrivacy, filename: string) {
return storeObject({
- inputPath: join(getHLSDirectory(playlist.Video), filename),
- objectStorageKey: generateHLSObjectStorageKey(playlist, filename),
+ inputPath: join(getHLSDirectory(video), filename),
+ objectStorageKey: generateHLSObjectStorageKey(video, filename),
bucketInfo: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
- isPrivate: playlist.Video.hasPrivateStaticPath(),
+ isPrivate: video.hasPrivateStaticPath(),
contentType: getObjectStorageContentType(filename)
})
}
-export function storeHLSFileFromPath (playlist: MStreamingPlaylistVideo, path: string) {
+export function storeHLSFileFromPath (video: MVideoPrivacy, path: string) {
const filename = basename(path)
return storeObject({
inputPath: path,
- objectStorageKey: generateHLSObjectStorageKey(playlist, filename),
+ objectStorageKey: generateHLSObjectStorageKey(video, filename),
bucketInfo: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
- isPrivate: playlist.Video.hasPrivateStaticPath(),
+ isPrivate: video.hasPrivateStaticPath(),
contentType: getObjectStorageContentType(filename)
})
}
export function storeHLSFileFromContent (options: {
- playlist: MStreamingPlaylistVideo
+ video: MVideoPrivacy
pathOrFilename: string
content: string
}) {
- const { playlist, pathOrFilename, content } = options
+ const { video, pathOrFilename, content } = options
const filename = basename(pathOrFilename)
return storeContent({
content,
- objectStorageKey: generateHLSObjectStorageKey(playlist, filename),
+ objectStorageKey: generateHLSObjectStorageKey(video, filename),
bucketInfo: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
- isPrivate: playlist.Video.hasPrivateStaticPath(),
+ isPrivate: video.hasPrivateStaticPath(),
contentType: getObjectStorageContentType(filename)
})
}
@@ -119,26 +119,26 @@ export async function updateWebVideoFileACL (video: MVideo, file: MVideoFile) {
})
}
-export async function updateHLSFilesACL (playlist: MStreamingPlaylistVideo) {
+export async function updateHLSFilesACL (video: MVideoPrivacy) {
await updatePrefixACL({
- prefix: generateHLSObjectBaseStorageKey(playlist),
+ prefix: generateHLSObjectBaseStorageKey(video),
bucketInfo: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
- isPrivate: playlist.Video.hasPrivateStaticPath()
+ isPrivate: video.hasPrivateStaticPath()
})
}
// ---------------------------------------------------------------------------
-export function removeHLSObjectStorage (playlist: MStreamingPlaylistVideoUUID) {
- return removePrefix(generateHLSObjectBaseStorageKey(playlist), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+export function removeHLSObjectStorage (video: MVideoPrivacy) {
+ return removePrefix(generateHLSObjectBaseStorageKey(video), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
}
-export function removeHLSFileObjectStorageByFilename (playlist: MStreamingPlaylistVideoUUID, filename: string) {
- return removeObject(generateHLSObjectStorageKey(playlist, filename), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+export function removeHLSFileObjectStorageByFilename (video: MVideoPrivacy, filename: string) {
+ return removeObject(generateHLSObjectStorageKey(video, filename), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
}
-export function removeHLSFileObjectStorageByPath (playlist: MStreamingPlaylistVideoUUID, path: string) {
- return removeObject(generateHLSObjectStorageKey(playlist, basename(path)), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+export function removeHLSFileObjectStorageByPath (video: MVideoPrivacy, path: string) {
+ return removeObject(generateHLSObjectStorageKey(video, basename(path)), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
}
export function removeHLSFileObjectStorageByFullKey (key: string) {
@@ -165,8 +165,8 @@ export function removeCaptionObjectStorage (videoCaption: MVideoCaption) {
// ---------------------------------------------------------------------------
-export async function makeHLSFileAvailable (playlist: MStreamingPlaylistVideoUUID, filename: string, destination: string) {
- const key = generateHLSObjectStorageKey(playlist, filename)
+export async function makeHLSFileAvailable (video: MVideoUUID, filename: string, destination: string) {
+ const key = generateHLSObjectStorageKey(video, filename)
logger.info('Fetching HLS file %s from object storage to %s.', key, destination, lTags())
@@ -241,13 +241,13 @@ export function getWebVideoFileReadStream (options: {
}
export function getHLSFileReadStream (options: {
- playlist: MStreamingPlaylistVideo
+ video: MVideoUUID
filename: string
rangeHeader: string
}) {
- const { playlist, filename, rangeHeader } = options
+ const { video, filename, rangeHeader } = options
- const key = generateHLSObjectStorageKey(playlist, filename)
+ const key = generateHLSObjectStorageKey(video, filename)
return createObjectReadStream({
key,
diff --git a/server/core/lib/plugins/plugin-helpers-builder.ts b/server/core/lib/plugins/plugin-helpers-builder.ts
index 4a17dcded9..05d2c925df 100644
--- a/server/core/lib/plugins/plugin-helpers-builder.ts
+++ b/server/core/lib/plugins/plugin-helpers-builder.ts
@@ -1,22 +1,22 @@
-import express from 'express'
-import { Server } from 'http'
-import { join } from 'path'
+import { ffprobePromise } from '@peertube/peertube-ffmpeg'
+import { FileStorage, VideoBlacklistCreate } from '@peertube/peertube-models'
import { buildLogger } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
import { WEBSERVER } from '@server/initializers/constants.js'
import { sequelizeTypescript } from '@server/initializers/database.js'
-import { AccountModel } from '@server/models/account/account.js'
import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'
+import { AccountModel } from '@server/models/account/account.js'
import { getServerActor } from '@server/models/application/application.js'
-import { ServerModel } from '@server/models/server/server.js'
import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'
+import { ServerModel } from '@server/models/server/server.js'
import { UserModel } from '@server/models/user/user.js'
-import { VideoModel } from '@server/models/video/video.js'
import { VideoBlacklistModel } from '@server/models/video/video-blacklist.js'
+import { VideoModel } from '@server/models/video/video.js'
import { MPlugin, MVideo, UserNotificationModelForApi } from '@server/types/models/index.js'
import { PeerTubeHelpers } from '@server/types/plugins/index.js'
-import { ffprobePromise } from '@peertube/peertube-ffmpeg'
-import { VideoBlacklistCreate, FileStorage } from '@peertube/peertube-models'
+import express from 'express'
+import { Server } from 'http'
+import { join } from 'path'
import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist, removeServerFromBlocklist } from '../blocklist.js'
import { PeerTubeSocket } from '../peertube-socket.js'
import { ServerConfigManager } from '../server-config-manager.js'
@@ -136,9 +136,16 @@ function buildVideosHelpers () {
: []
const thumbnails = video.Thumbnails.map(t => ({
- type: t.type,
- url: t.getOriginFileUrl(video),
- path: t.getPath()
+ type: t.width > 300
+ ? 2 as const // Preview
+ : 1 as const, // Thumbnail
+
+ width: t.width,
+ height: t.height,
+ url: t.getLocalFileUrl(),
+ path: t.isLocal()
+ ? t.getFSPath()
+ : null
}))
return {
diff --git a/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts
index de5035aeb8..095d9e72db 100644
--- a/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts
+++ b/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts
@@ -10,7 +10,7 @@ import { logger } from '@server/helpers/logger.js'
import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
import { MVideo } from '@server/types/models/index.js'
import { MRunnerJob } from '@server/types/models/runners/index.js'
-import { generateRunnerTranscodingVideoInputFileUrl, generateRunnerTranscodingVideoPreviewFileUrl } from '../runner-urls.js'
+import { generateRunnerTranscodingVideoInputFileUrl, generateRunnerTranscodingVideoThumbnailFileUrl } from '../runner-urls.js'
import { AbstractVODTranscodingJobHandler } from './abstract-vod-transcoding-job-handler.js'
import { loadRunnerVideo, onVODWebVideoOrAudioMergeTranscodingJob } from './shared/utils.js'
@@ -36,7 +36,7 @@ export class VODAudioMergeTranscodingJobHandler
const payload: RunnerJobVODAudioMergeTranscodingPayload = {
input: {
audioFileUrl: generateRunnerTranscodingVideoInputFileUrl(jobUUID, video.uuid),
- previewFileUrl: generateRunnerTranscodingVideoPreviewFileUrl(jobUUID, video.uuid)
+ previewFileUrl: generateRunnerTranscodingVideoThumbnailFileUrl(jobUUID, video.uuid)
},
output: {
resolution,
diff --git a/server/core/lib/runners/runner-urls.ts b/server/core/lib/runners/runner-urls.ts
index 0819e7ebef..695488277a 100644
--- a/server/core/lib/runners/runner-urls.ts
+++ b/server/core/lib/runners/runner-urls.ts
@@ -8,8 +8,8 @@ export function generateRunnerTranscodingAudioInputFileUrl (jobUUID: string, vid
return WEBSERVER.URL + '/api/v1/runners/jobs/' + jobUUID + '/files/videos/' + videoUUID + '/max-quality/audio'
}
-export function generateRunnerTranscodingVideoPreviewFileUrl (jobUUID: string, videoUUID: string) {
- return WEBSERVER.URL + '/api/v1/runners/jobs/' + jobUUID + '/files/videos/' + videoUUID + '/previews/max-quality'
+export function generateRunnerTranscodingVideoThumbnailFileUrl (jobUUID: string, videoUUID: string) {
+ return WEBSERVER.URL + '/api/v1/runners/jobs/' + jobUUID + '/files/videos/' + videoUUID + '/thumbnails/max-quality'
}
export function generateRunnerEditionTranscodingVideoInputFileUrl (jobUUID: string, videoUUID: string, filename: string) {
diff --git a/server/core/lib/server-config-manager.ts b/server/core/lib/server-config-manager.ts
index 0cf7ce0690..b31a514206 100644
--- a/server/core/lib/server-config-manager.ts
+++ b/server/core/lib/server-config-manager.ts
@@ -13,9 +13,7 @@ import { CONFIG, isEmailEnabled } from '@server/initializers/config.js'
import { CONSTRAINTS_FIELDS, DEFAULT_THEME_NAME, PEERTUBE_VERSION, WEBSERVER } from '@server/initializers/constants.js'
import { isSignupAllowed, isSignupAllowedForCurrentIP } from '@server/lib/signup.js'
import { ActorCustomPageModel } from '@server/models/account/actor-custom-page.js'
-import { ActorImageModel } from '@server/models/actor/actor-image.js'
import { getServerActor } from '@server/models/application/application.js'
-import { UploadImageModel } from '@server/models/application/upload-image.js'
import { PluginModel } from '@server/models/server/plugin.js'
import { MActorImage, MActorUploadImages, MUploadImage } from '@server/types/models/index.js'
import { Hooks } from './plugins/hooks.js'
@@ -653,7 +651,7 @@ class ServerConfigManager {
height: logo.height,
width: logo.width,
type,
- fileUrl: UploadImageModel.getImageUrl(logo),
+ fileUrl: logo.getLocalFileUrl(),
isFallback
}
}
@@ -663,7 +661,7 @@ class ServerConfigManager {
height: logo.height,
width: logo.width,
type,
- fileUrl: ActorImageModel.getImageUrl(logo),
+ fileUrl: logo.getLocalFileUrl(),
isFallback
}
}
diff --git a/server/core/lib/storyboard.ts b/server/core/lib/storyboard.ts
index 15276a8b4f..99e2d733a5 100644
--- a/server/core/lib/storyboard.ts
+++ b/server/core/lib/storyboard.ts
@@ -87,7 +87,8 @@ export async function insertStoryboardInDatabase (options: {
spriteHeight,
spriteWidth,
spriteDuration,
- videoId: video.id
+ videoId: video.id,
+ cached: false
}, { transaction })
if (federate) {
diff --git a/server/core/lib/thumbnail.ts b/server/core/lib/thumbnail.ts
index ad400649c2..523da2a8b8 100644
--- a/server/core/lib/thumbnail.ts
+++ b/server/core/lib/thumbnail.ts
@@ -1,136 +1,161 @@
-import { ThumbnailType, ThumbnailType_Type, VideoFileStream } from '@peertube/peertube-models'
+import { sortBy } from '@peertube/peertube-core-utils'
+import { VideoFileStream } from '@peertube/peertube-models'
import { generateThumbnailFromVideo } from '@server/helpers/ffmpeg/ffmpeg-image.js'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import Bluebird from 'bluebird'
import { FfprobeData } from 'fluent-ffmpeg'
import { remove } from 'fs-extra/esm'
import { extname, join } from 'path'
-import { generateImageFilename } from '../helpers/image-utils.js'
+import { generateImageFilename, processImage } from '../helpers/image-utils.js'
import { CONFIG } from '../initializers/config.js'
-import { ASSETS_PATH, MIMETYPES, PREVIEWS_SIZE, THUMBNAILS_SIZE } from '../initializers/constants.js'
+import { ASSETS_PATH, MIMETYPES } from '../initializers/constants.js'
import { ThumbnailModel } from '../models/video/thumbnail.js'
import { MVideoFile, MVideoThumbnail, MVideoUUID, MVideoWithAllFiles } from '../types/models/index.js'
import { MThumbnail } from '../types/models/video/thumbnail.js'
import { MVideoPlaylistThumbnail } from '../types/models/video/video-playlist.js'
import { VideoPathManager } from './video-path-manager.js'
-import { downloadImageFromWorker, processImageFromWorker } from './worker/parent-process.js'
+import { downloadImageFromWorker } from './worker/parent-process.js'
const lTags = loggerTagsFactory('thumbnail')
-type ImageSize = { height?: number, width?: number }
+type ImageSize = { height: number, width: number }
-export function updateLocalPlaylistMiniatureFromExisting (options: {
+export function createLocalPlaylistThumbnailFromImage (options: {
inputPath: string
playlist: MVideoPlaylistThumbnail
automaticallyGenerated: boolean
keepOriginal?: boolean // default to false
- size?: ImageSize
}) {
- const { inputPath, playlist, automaticallyGenerated, keepOriginal = false, size } = options
- const { filename, outputPath, height, width, existingThumbnail } = buildMetadataFromPlaylist(playlist, size)
- const type = ThumbnailType.MINIATURE
+ const { inputPath, playlist, automaticallyGenerated, keepOriginal = false } = options
+ const size = CONFIG.THUMBNAILS.SIZES[0] // Minimum size
+
+ const { filename, outputPath, height, width } = buildMetadataFromPlaylist({
+ playlist,
+ size,
+ extension: getImageExtension(inputPath)
+ })
const thumbnailCreator = () => {
- return processImageFromWorker({ path: inputPath, destination: outputPath, newSize: { width, height }, keepOriginal })
+ return processImage({ path: inputPath, destination: outputPath, newSize: { width, height }, keepOriginal })
}
- return updateThumbnailFromFunction({
+ return createThumbnailFromFunction({
thumbnailCreator,
filename,
height,
width,
- type,
automaticallyGenerated,
- onDisk: true,
- existingThumbnail
+ cached: false
})
}
-export function updateRemotePlaylistMiniatureFromUrl (options: {
- downloadUrl: string
+export function updateRemotePlaylistThumbnailFromUrl (options: {
+ fileUrl: string
playlist: MVideoPlaylistThumbnail
- size?: ImageSize
}) {
- const { downloadUrl, playlist, size } = options
- const { filename, basePath, height, width, existingThumbnail } = buildMetadataFromPlaylist(playlist, size)
- const type = ThumbnailType.MINIATURE
+ const { fileUrl, playlist } = options
+ const size = CONFIG.THUMBNAILS.SIZES[0] // Minimum size
+ const extension = getImageExtension(fileUrl)
- // Only save the file URL if it is a remote playlist
- const fileUrl = playlist.isLocal()
- ? null
- : downloadUrl
+ const { filename: generatedFilename, height, width, existingThumbnail } = buildMetadataFromPlaylist({ playlist, size, extension })
- const thumbnailCreator = () => {
- return downloadImageFromWorker({ url: downloadUrl, destDir: basePath, destName: filename, size: { width, height } })
+ // Only change thumbnail filename if the file changed
+ if (hasThumbnailUrlChanged({ existingThumbnail, fileUrl, extension })) {
+ if (existingThumbnail) {
+ logger.debug(
+ `Remote thumbnail changed for playlist ${playlist.url}, ` +
+ `updating filename from ${existingThumbnail.filename} to ${generatedFilename}`,
+ lTags(playlist.uuid)
+ )
+ }
+
+ const thumbnail = new ThumbnailModel()
+
+ thumbnail.filename = generatedFilename
+ thumbnail.height = height
+ thumbnail.width = width
+ thumbnail.fileUrl = fileUrl
+ thumbnail.cached = false
+
+ return thumbnail
}
- return updateThumbnailFromFunction({ thumbnailCreator, filename, height, width, type, existingThumbnail, fileUrl, onDisk: true })
+ existingThumbnail.height = height
+ existingThumbnail.width = width
+
+ return existingThumbnail
}
// ---------------------------------------------------------------------------
-export function updateLocalVideoMiniatureFromExisting (options: {
+export function createLocalVideoThumbnailsFromImage (options: {
inputPath: string
video: MVideoThumbnail
- type: ThumbnailType_Type
automaticallyGenerated: boolean
- size?: ImageSize
keepOriginal?: boolean // default to false
}) {
- const { inputPath, video, type, automaticallyGenerated, size, keepOriginal = false } = options
+ const { inputPath, automaticallyGenerated, video, keepOriginal = false } = options
+
+ return Promise.all(
+ CONFIG.THUMBNAILS.SIZES.map(size =>
+ _createLocalVideoThumbnailFromImage({ inputPath, video, automaticallyGenerated, size, keepOriginal })
+ )
+ )
+}
- const { filename, outputPath, height, width, existingThumbnail } = buildMetadataFromVideo({
+function _createLocalVideoThumbnailFromImage (options: {
+ inputPath: string
+ video: MVideoThumbnail
+ automaticallyGenerated: boolean
+ size: ImageSize
+ keepOriginal?: boolean // default to false
+}) {
+ const { inputPath, video, automaticallyGenerated, size, keepOriginal = false } = options
+
+ const { filename, outputPath, height, width } = buildMetadataFromVideo({
video,
- type,
size,
extension: getImageExtension(inputPath)
})
const thumbnailCreator = () => {
- return processImageFromWorker({ path: inputPath, destination: outputPath, newSize: { width, height }, keepOriginal })
+ return processImage({ path: inputPath, destination: outputPath, newSize: { width, height }, keepOriginal })
}
- return updateThumbnailFromFunction({
+ return createThumbnailFromFunction({
thumbnailCreator,
filename,
height,
width,
- type,
automaticallyGenerated,
- existingThumbnail,
- onDisk: true
+ cached: false
})
}
+// ---------------------------------------------------------------------------
+
// Returns thumbnail models sorted by their size (height) in descendent order (biggest first)
-export function generateLocalVideoMiniature (options: {
+export function createLocalVideoThumbnailsFromVideo (options: {
video: MVideoThumbnail
videoFile: MVideoFile
- types: ThumbnailType_Type[]
ffprobe: FfprobeData
}): Promise<MThumbnail[]> {
- const { video, videoFile, types, ffprobe } = options
-
- if (types.length === 0) return Promise.resolve([])
+ const { video, videoFile, ffprobe } = options
return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(video), input => {
- // Get bigger images to generate first
- const metadatas = types.map(type => buildMetadataFromVideo({ video, type }))
- .sort((a, b) => {
- if (a.height < b.height) return 1
- if (a.height === b.height) return 0
- return -1
- })
+ const metadata = CONFIG.THUMBNAILS.SIZES.map(size => buildMetadataFromVideo({ video, size, extension: '.jpg' }))
let biggestImagePath: string
- return Bluebird.mapSeries(metadatas, metadata => {
- const { filename, basePath, height, width, existingThumbnail, outputPath, type } = metadata
+
+ // Get bigger images to generate first
+ return Bluebird.mapSeries(sortBy(metadata, 'height').reverse(), metadata => {
+ const { filename, basePath, height, width, outputPath } = metadata
let thumbnailCreator: () => Promise<any>
if (videoFile.isAudio()) {
thumbnailCreator = () =>
- processImageFromWorker({
+ processImage({
path: ASSETS_PATH.DEFAULT_AUDIO_BACKGROUND,
destination: outputPath,
newSize: { width, height },
@@ -138,7 +163,7 @@ export function generateLocalVideoMiniature (options: {
})
} else if (biggestImagePath) {
thumbnailCreator = () =>
- processImageFromWorker({
+ processImage({
path: biggestImagePath,
destination: outputPath,
newSize: { width, height },
@@ -157,15 +182,13 @@ export function generateLocalVideoMiniature (options: {
if (!biggestImagePath) biggestImagePath = outputPath
- return updateThumbnailFromFunction({
+ return createThumbnailFromFunction({
thumbnailCreator,
filename,
height,
width,
- type,
automaticallyGenerated: true,
- onDisk: true,
- existingThumbnail
+ cached: false
})
})
})
@@ -173,102 +196,86 @@ export function generateLocalVideoMiniature (options: {
// ---------------------------------------------------------------------------
-export function updateLocalVideoMiniatureFromUrl (options: {
+export function createLocalVideoThumbnailsFromUrl (options: {
downloadUrl: string
video: MVideoThumbnail
- type: ThumbnailType_Type
- size?: ImageSize
}) {
- const { downloadUrl, video, type, size } = options
- const extension = getImageExtension(downloadUrl)
+ const { downloadUrl, video } = options
- const { filename: updatedFilename, basePath, height, width, existingThumbnail } = buildMetadataFromVideo({
- video,
- type,
- size,
- extension
- })
+ return Promise.all(
+ CONFIG.THUMBNAILS.SIZES.map(size => _createLocalVideoThumbnailFromUrl({ downloadUrl, video, size }))
+ )
+}
- const thumbnailUrlChanged = hasThumbnailUrlChanged({ existingThumbnail, fileUrl: downloadUrl, video, extension })
+function _createLocalVideoThumbnailFromUrl (options: {
+ downloadUrl: string
+ video: MVideoThumbnail
+ size: ImageSize
+}) {
+ const { downloadUrl, video, size } = options
- // Do not change the thumbnail filename if the file did not change
- const filename = thumbnailUrlChanged
- ? updatedFilename
- : existingThumbnail.filename
+ const extension = getImageExtension(downloadUrl)
+ const { filename, basePath, height, width } = buildMetadataFromVideo({ video, size, extension })
const thumbnailCreator = () => {
- if (thumbnailUrlChanged) {
- return downloadImageFromWorker({ url: downloadUrl, destDir: basePath, destName: filename, size: { width, height } })
- }
-
- return Promise.resolve()
+ return downloadImageFromWorker({ url: downloadUrl, destDir: basePath, destName: filename, size: { width, height } })
}
- // Only save the file URL if it is a remote video
- const fileUrl = video.isLocal()
- ? null
- : downloadUrl
-
- return updateThumbnailFromFunction({ thumbnailCreator, filename, height, width, type, existingThumbnail, fileUrl, onDisk: true })
+ return createThumbnailFromFunction({ thumbnailCreator, filename, height, width, cached: false })
}
+// ---------------------------------------------------------------------------
+
export function updateRemoteVideoThumbnail (options: {
fileUrl: string
video: MVideoThumbnail
- type: ThumbnailType_Type
size: ImageSize
- onDisk: boolean
}) {
- const { fileUrl, video, type, size, onDisk } = options
+ const { fileUrl, video, size } = options
+
const extension = getImageExtension(fileUrl)
+ const { filename: generatedFilename, height, width, existingThumbnail } = buildMetadataFromVideo({ video, size, extension })
- const { filename: generatedFilename, height, width, existingThumbnail } = buildMetadataFromVideo({
- video,
- type,
- size,
- extension
- })
+ if (hasThumbnailUrlChanged({ existingThumbnail, fileUrl, video, extension })) {
+ if (existingThumbnail) {
+ logger.debug(
+ `Remote thumbnail changed for video ${video.url}, updating filename from ${existingThumbnail.filename} to ${generatedFilename}`,
+ lTags(video.uuid)
+ )
+ }
- const thumbnail = existingThumbnail || new ThumbnailModel()
+ const thumbnail = new ThumbnailModel()
- // Do not change the thumbnail filename if the file did not change
- if (hasThumbnailUrlChanged({ existingThumbnail, fileUrl, video, extension })) {
- thumbnail.previousThumbnailFilename = thumbnail.filename
thumbnail.filename = generatedFilename
+ thumbnail.height = height
+ thumbnail.width = width
+ thumbnail.fileUrl = fileUrl
+ thumbnail.cached = false
+
+ return thumbnail
}
- thumbnail.height = height
- thumbnail.width = width
- thumbnail.type = type
- thumbnail.fileUrl = fileUrl
- thumbnail.onDisk = onDisk
+ // Update sizes, that PeerTube did not federate in previous versions
+ existingThumbnail.height = height
+ existingThumbnail.width = width
- return thumbnail
+ return existingThumbnail
}
// ---------------------------------------------------------------------------
-export async function regenerateMiniaturesIfNeeded (video: MVideoWithAllFiles, ffprobe: FfprobeData) {
- const thumbnailsToGenerate: ThumbnailType_Type[] = []
+export async function regenerateLocalVideoThumbnailsFromVideoIfNeeded (video: MVideoWithAllFiles, ffprobe: FfprobeData) {
+ if (video.Thumbnails.some(t => t.automaticallyGenerated === false)) return
- if (video.getMiniature().automaticallyGenerated === true) {
- thumbnailsToGenerate.push(ThumbnailType.MINIATURE)
- }
+ logger.info('Re-generate thumbnails for video ' + video.url, lTags(video.uuid))
- if (video.getPreview().automaticallyGenerated === true) {
- thumbnailsToGenerate.push(ThumbnailType.PREVIEW)
- }
-
- const models = await generateLocalVideoMiniature({
+ const thumbnails = await createLocalVideoThumbnailsFromVideo({
video,
videoFile: video.getMaxQualityFile(VideoFileStream.VIDEO) || video.getMaxQualityFile(VideoFileStream.AUDIO),
- ffprobe,
- types: thumbnailsToGenerate
+ ffprobe
})
- for (const model of models) {
- await video.addAndSaveThumbnail(model)
- }
+ await video.replaceAndSaveThumbnails(thumbnails)
}
// ---------------------------------------------------------------------------
@@ -278,10 +285,10 @@ export async function regenerateMiniaturesIfNeeded (video: MVideoWithAllFiles, f
function hasThumbnailUrlChanged (options: {
existingThumbnail: MThumbnail
fileUrl: string
- video: MVideoUUID
extension: string
+ video?: MVideoUUID
}) {
- const { existingThumbnail, fileUrl, video, extension } = options
+ const { existingThumbnail, fileUrl, extension, video } = options
if (!existingThumbnail) return true
@@ -289,8 +296,8 @@ function hasThumbnailUrlChanged (options: {
const existingUrl = existingThumbnail.fileUrl
if (!existingUrl || existingUrl !== fileUrl) return true
- // Or has a unique filename (introduced in 3.1)
- if (fileUrl.endsWith(`${video.uuid}.jpg`)) return true
+ // Or has a unique filename (PeerTube <= 3.1)
+ if (video && fileUrl.endsWith(`${video.uuid}.jpg`)) return true
// Or the extension changed
if (extname(existingThumbnail.filename).toLowerCase() !== extension) return true
@@ -298,103 +305,75 @@ function hasThumbnailUrlChanged (options: {
return false
}
-function buildMetadataFromPlaylist (playlist: MVideoPlaylistThumbnail, size: ImageSize) {
- const filename = playlist.generateThumbnailName()
- const basePath = CONFIG.STORAGE.THUMBNAILS_DIR
+function buildMetadataFromPlaylist (options: {
+ playlist: MVideoPlaylistThumbnail
+ extension: string
+ size: ImageSize
+}) {
+ const { playlist, extension, size } = options
+
+ const filename = playlist.generateThumbnailName(extension)
return {
filename,
- basePath,
+ basePath: CONFIG.STORAGE.THUMBNAILS_DIR,
existingThumbnail: playlist.Thumbnail,
- outputPath: join(basePath, filename),
- height: size ? size.height : THUMBNAILS_SIZE.height,
- width: size ? size.width : THUMBNAILS_SIZE.width
+ outputPath: join(CONFIG.STORAGE.THUMBNAILS_DIR, filename),
+ height: size.height,
+ width: size.width
}
}
function buildMetadataFromVideo (options: {
video: MVideoThumbnail
- type: ThumbnailType_Type
- extension?: string
- size?: ImageSize
+ size: ImageSize
+ extension: string
}) {
- const { video, type, extension, size } = options
+ const { video, extension, size } = options
const existingThumbnail = Array.isArray(video.Thumbnails)
- ? video.Thumbnails.find(t => t.type === type)
+ ? video.Thumbnails.find(t => t.height === size.height && t.width === size.width)
: undefined
- if (type === ThumbnailType.MINIATURE) {
- const filename = generateImageFilename(extension)
- const basePath = CONFIG.STORAGE.THUMBNAILS_DIR
-
- return {
- type,
- filename,
- basePath,
- existingThumbnail,
- outputPath: join(basePath, filename),
- height: size ? size.height : THUMBNAILS_SIZE.height,
- width: size ? size.width : THUMBNAILS_SIZE.width
- }
- }
+ const filename = generateImageFilename(extension)
- if (type === ThumbnailType.PREVIEW) {
- const filename = generateImageFilename(extension)
- const basePath = CONFIG.STORAGE.PREVIEWS_DIR
-
- return {
- type,
- filename,
- basePath,
- existingThumbnail,
- outputPath: join(basePath, filename),
- height: size ? size.height : PREVIEWS_SIZE.height,
- width: size ? size.width : PREVIEWS_SIZE.width
- }
+ return {
+ filename,
+ basePath: CONFIG.STORAGE.THUMBNAILS_DIR,
+ existingThumbnail,
+ outputPath: join(CONFIG.STORAGE.THUMBNAILS_DIR, filename),
+ height: size.height,
+ width: size.width
}
-
- return undefined
}
-async function updateThumbnailFromFunction (parameters: {
+async function createThumbnailFromFunction (parameters: {
thumbnailCreator: () => Promise<any>
filename: string
height: number
width: number
- type: ThumbnailType_Type
- onDisk: boolean
+ cached: boolean
automaticallyGenerated?: boolean
fileUrl?: string
- existingThumbnail?: MThumbnail
}) {
const {
thumbnailCreator,
filename,
width,
height,
- type,
- existingThumbnail,
- onDisk,
+ cached,
automaticallyGenerated = null,
fileUrl = null
} = parameters
- const oldFilename = existingThumbnail && existingThumbnail.filename !== filename
- ? existingThumbnail.filename
- : undefined
-
- const thumbnail: MThumbnail = existingThumbnail || new ThumbnailModel()
+ const thumbnail: MThumbnail = new ThumbnailModel()
thumbnail.filename = filename
thumbnail.height = height
thumbnail.width = width
- thumbnail.type = type
thumbnail.fileUrl = fileUrl
thumbnail.automaticallyGenerated = automaticallyGenerated
- thumbnail.onDisk = onDisk
-
- if (oldFilename) thumbnail.previousThumbnailFilename = oldFilename
+ thumbnail.cached = cached
await thumbnailCreator()
@@ -418,7 +397,7 @@ async function generateImageFromVideoFile (options: {
await generateThumbnailFromVideo({ fromPath, output: pendingImagePath, framesToAnalyze, ffprobe, scale: size })
const destination = join(folder, imageName)
- await processImageFromWorker({ path: pendingImagePath, destination, newSize: size })
+ await processImage({ path: pendingImagePath, destination, newSize: size })
return destination
} catch (err) {
diff --git a/server/core/lib/transcoding/web-transcoding.ts b/server/core/lib/transcoding/web-transcoding.ts
index b8cb295846..044df27bef 100644
--- a/server/core/lib/transcoding/web-transcoding.ts
+++ b/server/core/lib/transcoding/web-transcoding.ts
@@ -21,8 +21,8 @@ import { buildNewFile, saveNewOriginalFileIfNeeded } from '../video-file.js'
import { addLocalOrRemoteStoryboardJobIfNeeded } from '../video-jobs.js'
import { VideoPathManager } from '../video-path-manager.js'
import { buildFFmpegVOD } from './shared/index.js'
-import { buildOriginalFileResolution } from './transcoding-resolutions.js'
import { canDoQuickTranscode } from './transcoding-quick-transcode.js'
+import { buildOriginalFileResolution } from './transcoding-resolutions.js'
// Optimize the original video file and replace it. The resolution is not changed.
export async function optimizeOriginalVideofile (options: {
@@ -142,15 +142,15 @@ export async function mergeAudioVideofile (options: {
const result = await VideoPathManager.Instance.makeAvailableVideoFile(inputVideoFile, async audioInputPath => {
const videoOutputPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname)
- // If the user updates the video preview during transcoding
- const previewPath = video.getPreview().getPath()
- const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath))
- await copyFile(previewPath, tmpPreviewPath)
+ // If the user updates the video thumbnails during transcoding
+ const thumbnailPath = video.getBestThumbnail().getFSPath()
+ const tmpThumbnailPath = join(CONFIG.STORAGE.TMP_DIR, basename(thumbnailPath))
+ await copyFile(thumbnailPath, tmpThumbnailPath)
const transcodeOptions: MergeAudioTranscodeOptions = {
type: 'merge-audio',
- videoInputPath: tmpPreviewPath,
+ videoInputPath: tmpThumbnailPath,
audioPath: audioInputPath,
outputPath: videoOutputPath,
@@ -164,9 +164,9 @@ export async function mergeAudioVideofile (options: {
try {
await buildFFmpegVOD(job).transcode(transcodeOptions)
- await remove(tmpPreviewPath)
+ await remove(tmpThumbnailPath)
} catch (err) {
- await remove(tmpPreviewPath)
+ await remove(tmpThumbnailPath)
throw err
}
diff --git a/server/core/lib/upload-image.ts b/server/core/lib/upload-image.ts
index 2ac5d5214a..df014e19ac 100644
--- a/server/core/lib/upload-image.ts
+++ b/server/core/lib/upload-image.ts
@@ -1,13 +1,12 @@
import { LogoType, UploadImageType, UploadImageType_Type } from '@peertube/peertube-models'
import { buildUUID, getLowercaseExtension } from '@peertube/peertube-node-utils'
-import { buildImageSize } from '@server/helpers/image-utils.js'
+import { buildImageSize, processImage } from '@server/helpers/image-utils.js'
import { UploadImageModel } from '@server/models/application/upload-image.js'
import { copy, remove } from 'fs-extra/esm'
import { retryTransactionWrapper } from '../helpers/database-utils.js'
import { UPLOAD_IMAGES_SIZE } from '../initializers/constants.js'
import { sequelizeTypescript } from '../initializers/database.js'
import { MActorUploadImages } from '../types/models/index.js'
-import { processImageFromWorker } from './worker/parent-process.js'
export async function replaceUploadImage (options: {
actor: MActorUploadImages
@@ -49,7 +48,7 @@ async function generateImageSizes (imagePath: string, type: UploadImageType_Type
if (imagePath.endsWith('.svg')) {
const extension = getLowercaseExtension(imagePath)
const imageName = buildUUID() + extension
- const destination = UploadImageModel.getPathOf(imageName)
+ const destination = UploadImageModel.getFSPathOf(imageName)
await copy(imagePath, destination)
@@ -70,9 +69,9 @@ async function generateImageSize (options: {
const extension = getLowercaseExtension(imagePath)
const imageName = buildUUID() + extension
- const destination = UploadImageModel.getPathOf(imageName)
+ const destination = UploadImageModel.getFSPathOf(imageName)
- await processImageFromWorker({ path: imagePath, destination, newSize: imageSize, keepOriginal: true })
+ await processImage({ path: imagePath, destination, newSize: imageSize, keepOriginal: true })
return { imageName, imageSize }
}
diff --git a/server/core/lib/uploadx.ts b/server/core/lib/uploadx.ts
index 067459dd5a..f47461622d 100644
--- a/server/core/lib/uploadx.ts
+++ b/server/core/lib/uploadx.ts
@@ -14,7 +14,7 @@ export const uploadx = new Uploadx({
expiration: { maxAge: undefined, rolling: true },
- // Could be big with thumbnails/previews
+ // Could be big with a big thumbnail
maxMetadataSize: '10MB',
logger: {
diff --git a/server/core/lib/user-import-export/exporters/actor-exporter.ts b/server/core/lib/user-import-export/exporters/actor-exporter.ts
index 7b9eb3d7fb..30d09fcf44 100644
--- a/server/core/lib/user-import-export/exporters/actor-exporter.ts
+++ b/server/core/lib/user-import-export/exporters/actor-exporter.ts
@@ -1,12 +1,10 @@
-import { ActorImageModel } from '@server/models/actor/actor-image.js'
-import { ExportResult, AbstractUserExporter } from './abstract-user-exporter.js'
import { ActorImageType } from '@peertube/peertube-models'
import { MActor, MActorDefaultBanner, MActorImage } from '@server/types/models/index.js'
-import { extname, join } from 'path'
import { createReadStream } from 'fs'
+import { extname, join } from 'path'
+import { AbstractUserExporter, ExportResult } from './abstract-user-exporter.js'
-export abstract class ActorExporter <T> extends AbstractUserExporter<T> {
-
+export abstract class ActorExporter<T> extends AbstractUserExporter<T> {
protected exportActorJSON (actor: MActorDefaultBanner) {
return {
url: actor.url,
@@ -26,7 +24,8 @@ export abstract class ActorExporter <T> extends AbstractUserExporter<T> {
protected exportActorImageJSON (images: MActorImage[]) {
return images.map(i => ({
width: i.width,
- url: ActorImageModel.getImageUrl(i),
+ height: i.height,
+ url: i.getLocalFileUrl(),
createdAt: i.createdAt.toISOString(),
updatedAt: i.updatedAt.toISOString()
}))
@@ -59,7 +58,7 @@ export abstract class ActorExporter <T> extends AbstractUserExporter<T> {
staticFiles.push({
archivePath: archivePathBuilder(image.filename),
- readStreamFactory: () => Promise.resolve(createReadStream(image.getPath()))
+ readStreamFactory: () => Promise.resolve(createReadStream(image.getFSPath()))
})
const relativePath = join(this.relativeStaticDirPath, archivePathBuilder(image.filename))
diff --git a/server/core/lib/user-import-export/exporters/video-playlists-exporter.ts b/server/core/lib/user-import-export/exporters/video-playlists-exporter.ts
index 9d45208dd5..d273ca559a 100644
--- a/server/core/lib/user-import-export/exporters/video-playlists-exporter.ts
+++ b/server/core/lib/user-import-export/exporters/video-playlists-exporter.ts
@@ -1,13 +1,12 @@
-import { ExportResult, AbstractUserExporter } from './abstract-user-exporter.js'
import { VideoPlaylistsExportJSON } from '@peertube/peertube-models'
-import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'
import { VideoPlaylistElementModel } from '@server/models/video/video-playlist-element.js'
-import { extname, join } from 'path'
-import { createReadStream } from 'fs'
+import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'
import { MThumbnail, MVideoPlaylist } from '@server/types/models/index.js'
+import { createReadStream } from 'fs'
+import { extname, join } from 'path'
+import { AbstractUserExporter, ExportResult } from './abstract-user-exporter.js'
-export class VideoPlaylistsExporter extends AbstractUserExporter <VideoPlaylistsExportJSON> {
-
+export class VideoPlaylistsExporter extends AbstractUserExporter<VideoPlaylistsExportJSON> {
async export () {
const playlistsJSON: VideoPlaylistsExportJSON['videoPlaylists'] = []
const staticFiles: ExportResult<VideoPlaylistsExportJSON>['staticFiles'] = []
@@ -26,7 +25,7 @@ export class VideoPlaylistsExporter extends AbstractUserExporter <VideoPlaylists
staticFiles.push({
archivePath: this.getArchiveThumbnailPath(playlist, thumbnail),
- readStreamFactory: () => Promise.resolve(createReadStream(thumbnail.getPath()))
+ readStreamFactory: () => Promise.resolve(createReadStream(thumbnail.getFSPath()))
})
archiveFiles.thumbnail = join(this.relativeStaticDirPath, this.getArchiveThumbnailPath(playlist, thumbnail))
@@ -48,7 +47,7 @@ export class VideoPlaylistsExporter extends AbstractUserExporter <VideoPlaylists
createdAt: playlist.createdAt.toISOString(),
updatedAt: playlist.updatedAt.toISOString(),
- thumbnailUrl: playlist.Thumbnail?.getOriginFileUrl(playlist),
+ thumbnailUrl: playlist.Thumbnail?.getLocalFileUrl(),
elements: elements.map(e => ({
videoUrl: e.Video.url,
diff --git a/server/core/lib/user-import-export/exporters/videos-exporter.ts b/server/core/lib/user-import-export/exporters/videos-exporter.ts
index 0c66ffbc0a..9e9a496b05 100644
--- a/server/core/lib/user-import-export/exporters/videos-exporter.ts
+++ b/server/core/lib/user-import-export/exporters/videos-exporter.ts
@@ -164,8 +164,15 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {
url: video.url,
- thumbnailUrl: video.getMiniature()?.getOriginFileUrl(video) || null,
- previewUrl: video.getPreview()?.getOriginFileUrl(video) || null,
+ thumbnailUrl: video.getBestThumbnail()?.getLocalFileUrl() || null,
+ previewUrl: video.getBestThumbnail()?.getLocalFileUrl() || null,
+ thumbnails: video.Thumbnails.map(t => ({
+ width: t.width,
+ height: t.height,
+ url: t.getLocalFileUrl(),
+ createdAt: t.createdAt.toISOString(),
+ updatedAt: t.updatedAt.toISOString()
+ })),
views: video.views,
@@ -226,7 +233,7 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {
language: c.language,
filename: c.filename,
automaticallyGenerated: c.automaticallyGenerated,
- fileUrl: c.getFileUrl(video)
+ fileUrl: c.getLocalFileUrl()
}))
}
@@ -290,7 +297,7 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {
chapters: MVideoChapter[],
exportedVideoFileOrSource: MVideoFile | MVideoSource
): Promise<ActivityCreate<VideoObject>> {
- const icon = video.getPreview()
+ const icon = video.getBestThumbnail()
const audience = getVideoAudience({
account: video.VideoChannel.Account,
@@ -302,13 +309,15 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {
const videoObject: VideoObject = {
...audiencify(await video.toActivityPubObject(), audience),
- icon: [
- {
- ...icon.toActivityPubObject(video),
+ icon: icon
+ ? [
+ {
+ ...icon.toActivityPubObject(),
- url: join(this.options.relativeStaticDirPath, this.getArchiveThumbnailFilePath(video, icon))
- }
- ],
+ url: join(this.options.relativeStaticDirPath, this.getArchiveThumbnailFilePath(video, icon))
+ }
+ ]
+ : [],
subtitleLanguage: video.VideoCaptions.map(c => ({
...c.toActivityPubObject(video),
@@ -396,11 +405,11 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {
relativePathsFromJSON.captions[caption.language] = join(this.relativeStaticDirPath, this.getArchiveCaptionFilePath(video, caption))
}
- const thumbnail = video.getPreview() || video.getMiniature()
+ const thumbnail = video.getBestThumbnail()
if (thumbnail) {
staticFiles.push({
archivePath: this.getArchiveThumbnailFilePath(video, thumbnail),
- readStreamFactory: () => Promise.resolve(createReadStream(thumbnail.getPath()))
+ readStreamFactory: () => Promise.resolve(createReadStream(thumbnail.getFSPath()))
})
relativePathsFromJSON.thumbnail = join(this.relativeStaticDirPath, this.getArchiveThumbnailFilePath(video, thumbnail))
@@ -441,7 +450,7 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {
}
const { stream } = videoFile.isHLS()
- ? await getHLSFileReadStream({ playlist: video.getHLSPlaylist(), filename: videoFile.filename, rangeHeader: undefined })
+ ? await getHLSFileReadStream({ video, filename: videoFile.filename, rangeHeader: undefined })
: await getWebVideoFileReadStream({ filename: videoFile.filename, rangeHeader: undefined })
return stream
diff --git a/server/core/lib/user-import-export/importers/video-playlists-importer.ts b/server/core/lib/user-import-export/importers/video-playlists-importer.ts
index 2434ba4015..d573e9c42c 100644
--- a/server/core/lib/user-import-export/importers/video-playlists-importer.ts
+++ b/server/core/lib/user-import-export/importers/video-playlists-importer.ts
@@ -8,7 +8,7 @@ import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'
import { AbstractUserImporter } from './abstract-user-importer.js'
import { sendCreateVideoPlaylist } from '@server/lib/activitypub/send/send-create.js'
import { sequelizeTypescript } from '@server/initializers/database.js'
-import { updateLocalPlaylistMiniatureFromExisting } from '@server/lib/thumbnail.js'
+import { createLocalPlaylistThumbnailFromImage } from '@server/lib/thumbnail.js'
import { CONSTRAINTS_FIELDS, USER_IMPORT } from '@server/initializers/constants.js'
import { VideoPlaylistElementModel } from '@server/models/video/video-playlist-element.js'
import { loadOrCreateVideoIfAllowedForUser } from '@server/lib/model-loaders/video.js'
@@ -122,7 +122,7 @@ export class VideoPlaylistsImporter extends AbstractUserImporter<VideoPlaylistsE
if (!await this.isFileValidOrLog(thumbnailPath, CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.FILE_SIZE.max)) return undefined
- const thumbnail = await updateLocalPlaylistMiniatureFromExisting({
+ const thumbnail = await createLocalPlaylistThumbnailFromImage({
inputPath: thumbnailPath,
playlist,
automaticallyGenerated: false
diff --git a/server/core/lib/user-import-export/importers/videos-importer.ts b/server/core/lib/user-import-export/importers/videos-importer.ts
index 8fd854c8a1..126a6a173c 100644
--- a/server/core/lib/user-import-export/importers/videos-importer.ts
+++ b/server/core/lib/user-import-export/importers/videos-importer.ts
@@ -1,6 +1,6 @@
import { pick } from '@peertube/peertube-core-utils'
import { ffprobePromise, getVideoStreamDuration } from '@peertube/peertube-ffmpeg'
-import { LiveVideoLatencyMode, ThumbnailType, VideoExportJSON, VideoPrivacy, VideoState } from '@peertube/peertube-models'
+import { LiveVideoLatencyMode, VideoExportJSON, VideoPrivacy, VideoState } from '@peertube/peertube-models'
import { buildUUID, getFileSize } from '@peertube/peertube-node-utils'
import { isArray, isBooleanValid, isUUIDValid } from '@server/helpers/custom-validators/misc.js'
import { isPlayerVideoThemeSettingValid } from '@server/helpers/custom-validators/player-settings.js'
@@ -27,7 +27,7 @@ import {
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
import { CONSTRAINTS_FIELDS } from '@server/initializers/constants.js'
-import { LocalVideoCreator, ThumbnailOptions } from '@server/lib/local-video-creator.js'
+import { LocalVideoCreator } from '@server/lib/local-video-creator.js'
import { isLocalVideoFileAccepted } from '@server/lib/moderation.js'
import { Hooks } from '@server/lib/plugins/hooks.js'
import { isUserQuotaValid } from '@server/lib/user.js'
@@ -202,18 +202,6 @@ export class VideosImporter extends AbstractUserImporter<VideoExportJSON, Import
const thumbnailPath = this.getSafeArchivePathOrThrow(videoImportData.archiveFiles.thumbnail)
- const thumbnails: ThumbnailOptions = []
- for (const type of [ ThumbnailType.MINIATURE, ThumbnailType.PREVIEW ]) {
- if (!await this.isFileValidOrLog(thumbnailPath, CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max)) continue
-
- thumbnails.push({
- path: thumbnailPath,
- automaticallyGenerated: false,
- keepOriginal: true,
- type
- })
- }
-
const localVideoCreator = new LocalVideoCreator({
lTags,
@@ -262,7 +250,13 @@ export class VideosImporter extends AbstractUserImporter<VideoExportJSON, Import
videoAttributeResultHook: 'filter:api.video.user-import.video-attribute.result',
- thumbnails
+ thumbnail: await this.isFileValidOrLog(thumbnailPath, CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max)
+ ? {
+ path: thumbnailPath,
+ automaticallyGenerated: false,
+ keepOriginal: true
+ }
+ : undefined
})
const { video } = await localVideoCreator.create()
diff --git a/server/core/lib/user-import-export/user-exporter.ts b/server/core/lib/user-import-export/user-exporter.ts
index 2a8fc2eced..07264ba384 100644
--- a/server/core/lib/user-import-export/user-exporter.ts
+++ b/server/core/lib/user-import-export/user-exporter.ts
@@ -36,7 +36,6 @@ import {
const lTags = loggerTagsFactory('user-export')
export class UserExporter {
-
private archive: Archiver
async export (exportModel: MUserExport) {
@@ -51,7 +50,7 @@ export class UserExporter {
if (exportModel.storage === FileStorage.FILE_SYSTEM) {
output = createWriteStream(getFSUserExportFilePath(exportModel))
- endPromise = new Promise<string>(res => output.on('close', () => res('')))
+ endPromise = new Promise<void>(res => output.on('close', () => res()))
} else {
output = new PassThrough()
endPromise = storeUserExportFile(output as PassThrough, exportModel)
@@ -59,10 +58,9 @@ export class UserExporter {
await this.createZip({ exportModel, user, output })
- const fileUrl = await endPromise
+ await endPromise
if (exportModel.storage === FileStorage.OBJECT_STORAGE) {
- exportModel.fileUrl = fileUrl
exportModel.size = await getUserExportFileObjectStorageSize(exportModel)
} else if (exportModel.storage === FileStorage.FILE_SYSTEM) {
exportModel.size = await getFileSize(getFSUserExportFilePath(exportModel))
diff --git a/server/core/lib/video-captions.ts b/server/core/lib/video-captions.ts
index 4c1e3539d5..d3b6391d8e 100644
--- a/server/core/lib/video-captions.ts
+++ b/server/core/lib/video-captions.ts
@@ -39,7 +39,8 @@ export async function createLocalCaption (options: {
filename: VideoCaptionModel.generateCaptionName(language),
storage: FileStorage.FILE_SYSTEM,
language,
- automaticallyGenerated
+ automaticallyGenerated,
+ cached: false
}) as MVideoCaption
await moveAndProcessCaptionFile({ path }, videoCaption)
diff --git a/server/core/lib/video-download.ts b/server/core/lib/video-download.ts
index 622fc0839f..fab717a9ad 100644
--- a/server/core/lib/video-download.ts
+++ b/server/core/lib/video-download.ts
@@ -187,7 +187,7 @@ export class VideoDownload {
const destination = VideoPathManager.Instance.buildTMPDestination(videoFile.filename)
if (videoFile.isHLS()) {
- await makeHLSFileAvailable(this.video.getHLSPlaylist(), videoFile.filename, destination)
+ await makeHLSFileAvailable(this.video, videoFile.filename, destination)
} else {
await makeWebVideoFileAvailable(videoFile.filename, destination)
}
@@ -197,7 +197,7 @@ export class VideoDownload {
if (videoFile.isHLS()) {
const { stream } = await getHLSFileReadStream({
- playlist: this.video.getHLSPlaylist().withVideo(this.video),
+ video: this.video,
filename: videoFile.filename,
rangeHeader: undefined
})
@@ -217,14 +217,14 @@ export class VideoDownload {
// ---------------------------------------------------------------------------
private async buildCoverInput () {
- const preview = this.video.getPreview()
+ const thumbnail = this.video.getBestThumbnail()
- if (this.video.isLocal()) return { coverPath: preview?.getPath() }
+ if (this.video.isLocal()) return { coverPath: thumbnail?.getFSPath() }
- if (preview.fileUrl) {
- const destination = VideoPathManager.Instance.buildTMPDestination(preview.filename)
+ if (thumbnail.fileUrl) {
+ const destination = VideoPathManager.Instance.buildTMPDestination(thumbnail.filename)
- await doRequestAndSaveToFile(preview.fileUrl, destination)
+ await doRequestAndSaveToFile(thumbnail.fileUrl, destination)
return { coverPath: destination, isTmpDestination: true }
}
diff --git a/server/core/lib/video-file.ts b/server/core/lib/video-file.ts
index 1f8cd75d29..f00a6e1acc 100644
--- a/server/core/lib/video-file.ts
+++ b/server/core/lib/video-file.ts
@@ -222,11 +222,10 @@ export async function saveNewOriginalFileIfNeeded (video: MVideo, videoFile: MVi
const sourcePath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
if (CONFIG.OBJECT_STORAGE.ENABLED) {
- const fileUrl = await storeOriginalVideoFile(sourcePath, videoSource.keptOriginalFilename)
+ await storeOriginalVideoFile(sourcePath, videoSource.keptOriginalFilename)
await remove(sourcePath)
videoSource.storage = FileStorage.OBJECT_STORAGE
- videoSource.fileUrl = fileUrl
} else {
const destinationPath = VideoPathManager.Instance.getFSOriginalVideoFilePath(videoSource.keptOriginalFilename)
await move(sourcePath, destinationPath)
diff --git a/server/core/lib/video-path-manager.ts b/server/core/lib/video-path-manager.ts
index c26b2569a3..f77ab8d489 100644
--- a/server/core/lib/video-path-manager.ts
+++ b/server/core/lib/video-path-manager.ts
@@ -81,7 +81,7 @@ class VideoPathManager {
const playlist = (videoFile as MVideoFileStreamingPlaylistVideo).VideoStreamingPlaylist
createMethods.push({
- method: () => makeHLSFileAvailable(playlist, videoFile.filename, destination),
+ method: () => makeHLSFileAvailable(playlist.Video, videoFile.filename, destination),
clean: true
})
} else {
@@ -130,11 +130,10 @@ class VideoPathManager {
})
}
- const playlist = videoFile.VideoStreamingPlaylist
return this.makeAvailableFactory({
createMethods: [
{
- method: () => makeHLSFileAvailable(playlist, filename, this.buildTMPDestination(filename)),
+ method: () => makeHLSFileAvailable(videoFile.VideoStreamingPlaylist.Video, filename, this.buildTMPDestination(filename)),
clean: true
}
],
@@ -158,7 +157,7 @@ class VideoPathManager {
return this.makeAvailableFactory({
createMethods: [
{
- method: () => makeHLSFileAvailable(playlist, filename, this.buildTMPDestination(filename)),
+ method: () => makeHLSFileAvailable(playlist.Video, filename, this.buildTMPDestination(filename)),
clean: true
}
],
diff --git a/server/core/lib/video-playlist.ts b/server/core/lib/video-playlist.ts
index 8ced4eab19..d7268ede03 100644
--- a/server/core/lib/video-playlist.ts
+++ b/server/core/lib/video-playlist.ts
@@ -1,15 +1,19 @@
import { VideoPlaylistPrivacy, VideoPlaylistType } from '@peertube/peertube-models'
+import { generateImageFilename } from '@server/helpers/image-utils.js'
import { logger } from '@server/helpers/logger.js'
+import { CONFIG } from '@server/initializers/config.js'
import { SequelizeModel } from '@server/models/shared/sequelize-type.js'
import { VideoPlaylistElementModel } from '@server/models/video/video-playlist-element.js'
+import { copy } from 'fs-extra/esm'
+import { extname, join } from 'path'
import { Transaction } from 'sequelize'
import { VideoPlaylistModel } from '../models/video/video-playlist.js'
import { MAccount, MVideoThumbnail } from '../types/models/index.js'
import { MVideoPlaylistOwner, MVideoPlaylistThumbnail } from '../types/models/video/video-playlist.js'
import { sendUpdateVideoPlaylist } from './activitypub/send/send-update.js'
import { getLocalVideoPlaylistActivityPubUrl } from './activitypub/url.js'
-import { VideoMiniaturePermanentFileCache } from './files-cache/video-miniature-permanent-file-cache.js'
-import { updateLocalPlaylistMiniatureFromExisting } from './thumbnail.js'
+import { createLocalPlaylistThumbnailFromImage } from './thumbnail.js'
+import { downloadImageFromWorker } from './worker/parent-process.js'
export async function createWatchLaterPlaylist (account: MAccount, t: Transaction) {
const videoPlaylist: MVideoPlaylistOwner = new VideoPlaylistModel({
@@ -31,23 +35,33 @@ export async function createWatchLaterPlaylist (account: MAccount, t: Transactio
export async function generateThumbnailForPlaylist (videoPlaylist: MVideoPlaylistThumbnail, video: MVideoThumbnail) {
logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
- const videoMiniature = video.getMiniature()
- if (!videoMiniature) {
+ const videoThumbnail = video.getBestThumbnail()
+ if (!videoThumbnail) {
logger.info('Cannot generate thumbnail for playlist %s because video %s does not have any.', videoPlaylist.url, video.url)
return
}
- // Ensure the file is on disk
- const videoMiniaturePermanentFileCache = new VideoMiniaturePermanentFileCache()
- const inputPath = videoMiniature.isLocal()
- ? videoMiniature.getPath()
- : await videoMiniaturePermanentFileCache.downloadRemoteFile(videoMiniature)
+ const tmpImageName = generateImageFilename(extname(videoThumbnail.filename))
+
+ if (video.isLocal() === true) {
+ await copy(videoThumbnail.getFSPath(), join(CONFIG.STORAGE.TMP_DIR, tmpImageName))
+ } else {
+ await downloadImageFromWorker({
+ url: videoThumbnail.fileUrl,
+ destDir: CONFIG.STORAGE.TMP_DIR,
+ destName: tmpImageName,
+ size: {
+ height: videoThumbnail.height || 280,
+ width: videoThumbnail.width || 157
+ }
+ })
+ }
- const thumbnailModel = await updateLocalPlaylistMiniatureFromExisting({
- inputPath,
+ const thumbnailModel = await createLocalPlaylistThumbnailFromImage({
+ inputPath: join(CONFIG.STORAGE.TMP_DIR, tmpImageName),
playlist: videoPlaylist,
automaticallyGenerated: true,
- keepOriginal: true
+ keepOriginal: false
})
thumbnailModel.videoPlaylistId = videoPlaylist.id
diff --git a/server/core/lib/video-pre-import.ts b/server/core/lib/video-pre-import.ts
index 63392383a6..25f7fd9311 100644
--- a/server/core/lib/video-pre-import.ts
+++ b/server/core/lib/video-pre-import.ts
@@ -1,7 +1,5 @@
import {
NSFWFlag,
- ThumbnailType,
- ThumbnailType_Type,
VideoChannelActivityAction,
VideoImportCreate,
VideoImportPayload,
@@ -41,7 +39,7 @@ import {
import express from 'express'
import { remove } from 'fs-extra/esm'
import { getLocalVideoActivityPubUrl } from './activitypub/url.js'
-import { updateLocalVideoMiniatureFromExisting, updateLocalVideoMiniatureFromUrl } from './thumbnail.js'
+import { createLocalVideoThumbnailsFromUrl, createLocalVideoThumbnailsFromImage } from './thumbnail.js'
import { createLocalCaption } from './video-captions.js'
import { replaceChapters, replaceChaptersFromDescriptionIfNeeded } from './video-chapters.js'
@@ -49,15 +47,14 @@ import { replaceChapters, replaceChaptersFromDescriptionIfNeeded } from './video
export async function insertFromImportIntoDB (parameters: {
video: MVideoThumbnail
- thumbnailModel: MThumbnail
- previewModel: MThumbnail
+ thumbnails: MThumbnail[]
videoChannel: MChannelAccountDefault
tags: string[]
videoImportAttributes: FilteredModelAttributes<VideoImportModel>
user: MUserAccountId
videoPasswords?: string[]
}): Promise<MVideoImportFormattable> {
- const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user, videoPasswords } = parameters
+ const { video, thumbnails, videoChannel, tags, videoImportAttributes, user, videoPasswords } = parameters
const videoImport = await sequelizeTypescript.transaction(async t => {
const sequelizeOptions = { transaction: t }
@@ -67,8 +64,9 @@ export async function insertFromImportIntoDB (parameters: {
) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag & MVideoThumbnail)
videoCreated.VideoChannel = videoChannel
- if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
- if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
+ if (thumbnails.length !== 0) {
+ await videoCreated.replaceAndSaveThumbnails(thumbnails, t)
+ }
if (videoCreated.privacy === VideoPrivacy.PASSWORD_PROTECTED) {
await VideoPasswordModel.addPasswords(videoPasswords, video.id, t)
@@ -158,7 +156,6 @@ export async function buildYoutubeDLImport (options: {
channelSync?: MChannelSync
importDataOverride?: Partial<VideoImportCreate>
thumbnailFilePath?: string
- previewFilePath?: string
skipPublishedBeforeOrEq?: Date
@@ -171,7 +168,6 @@ export async function buildYoutubeDLImport (options: {
channelSync,
importDataOverride,
thumbnailFilePath,
- previewFilePath,
user,
skipPublishedBeforeOrEq,
req,
@@ -220,24 +216,15 @@ export async function buildYoutubeDLImport (options: {
importType: 'url'
})
- const thumbnailModel = await forgeThumbnail({
+ const thumbnails = await processThumbnails({
inputPath: thumbnailFilePath,
downloadUrl: youtubeDLInfo.thumbnailUrl,
- video,
- type: ThumbnailType.MINIATURE
- })
-
- const previewModel = await forgeThumbnail({
- inputPath: previewFilePath,
- downloadUrl: youtubeDLInfo.thumbnailUrl,
- video,
- type: ThumbnailType.PREVIEW
+ video
})
const videoImport = await insertFromImportIntoDB({
video,
- thumbnailModel,
- previewModel,
+ thumbnails,
videoChannel: channel,
tags: importDataOverride?.tags || youtubeDLInfo.tags,
user,
@@ -301,30 +288,30 @@ export async function buildYoutubeDLImport (options: {
// Private
// ---------------------------------------------------------------------------
-async function forgeThumbnail ({ inputPath, video, downloadUrl, type }: {
+async function processThumbnails (options: {
inputPath?: string
downloadUrl?: string
video: MVideoThumbnail
- type: ThumbnailType_Type
-}): Promise<MThumbnail> {
+}): Promise<MThumbnail[]> {
+ const { inputPath, downloadUrl, video } = options
+
if (inputPath) {
- return updateLocalVideoMiniatureFromExisting({
+ return createLocalVideoThumbnailsFromImage({
inputPath,
video,
- type,
automaticallyGenerated: false
})
}
if (downloadUrl) {
try {
- return await updateLocalVideoMiniatureFromUrl({ downloadUrl, video, type })
+ return await createLocalVideoThumbnailsFromUrl({ downloadUrl, video })
} catch (err) {
logger.warn('Cannot process thumbnail %s from youtube-dl.', downloadUrl, { err })
}
}
- return null
+ return []
}
async function processYoutubeSubtitles (youtubeDL: YoutubeDLWrapper, targetUrl: string, video: MVideo) {
diff --git a/server/core/lib/video-privacy.ts b/server/core/lib/video-privacy.ts
index f414182723..60a4ac5fa0 100644
--- a/server/core/lib/video-privacy.ts
+++ b/server/core/lib/video-privacy.ts
@@ -84,7 +84,7 @@ async function moveFiles (options: {
await moveHLSFilesOnFS(type, video)
} else {
try {
- await updateHLSFilesACL(hls)
+ await updateHLSFilesACL(video)
} catch (err) {
logger.error(objectStorageErrorMsg, { err, ...lTags('object-storage', video.uuid) })
}
diff --git a/server/core/lib/worker/parent-process.ts b/server/core/lib/worker/parent-process.ts
index ffe3acc174..9341aa2127 100644
--- a/server/core/lib/worker/parent-process.ts
+++ b/server/core/lib/worker/parent-process.ts
@@ -8,7 +8,6 @@ import type getImageSize from './workers/get-image-size.js'
import type httpBroadcast from './workers/http-broadcast.js'
import type httpUnicast from './workers/http-unicast.js'
import type downloadImage from './workers/image-downloader.js'
-import type processImage from './workers/image-processor.js'
import type signJsonLDObject from './workers/sign-json-ld-object.js'
let downloadImageWorker: Piscina
@@ -31,26 +30,6 @@ export function downloadImageFromWorker (options: Parameters<typeof downloadImag
// ---------------------------------------------------------------------------
-let processImageWorker: Piscina
-
-export function processImageFromWorker (options: Parameters<typeof processImage>[0]): Promise<ReturnType<typeof processImage>> {
- if (!processImageWorker) {
- processImageWorker = new Piscina({
- filename: new URL(join('workers', 'image-processor.js'), import.meta.url).href,
- concurrentTasksPerWorker: WORKER_THREADS.PROCESS_IMAGE.CONCURRENCY,
- maxThreads: WORKER_THREADS.PROCESS_IMAGE.MAX_THREADS,
- minThreads: 1,
- idleTimeout: WORKER_THREADS.IDLE_TIMEOUT
- })
-
- processImageWorker.on('error', err => logger.error('Error in process image worker', { err }))
- }
-
- return processImageWorker.run(options)
-}
-
-// ---------------------------------------------------------------------------
-
let getImageSizeWorker: Piscina
export function getImageSizeFromWorker (options: Parameters<typeof getImageSize>[0]): Promise<ReturnType<typeof getImageSize>> {
@@ -210,11 +189,6 @@ export function getWorkersStats () {
queueSize: downloadImageWorker?.queueSize || 0,
completed: downloadImageWorker?.completed || 0
},
- {
- label: 'processImageWorker',
- queueSize: processImageWorker?.queueSize || 0,
- completed: processImageWorker?.completed || 0
- },
{
label: 'getImageSizeWorker',
queueSize: getImageSizeWorker?.queueSize || 0,
diff --git a/server/core/lib/worker/workers/image-processor.ts b/server/core/lib/worker/workers/image-processor.ts
deleted file mode 100644
index 6aa8dcc295..0000000000
--- a/server/core/lib/worker/workers/image-processor.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { processImage } from '@server/helpers/image-utils.js'
-
-export default processImage
diff --git a/server/core/middlewares/validators/config.ts b/server/core/middlewares/validators/config.ts
index 23df71f6fd..66afc75725 100644
--- a/server/core/middlewares/validators/config.ts
+++ b/server/core/middlewares/validators/config.ts
@@ -47,11 +47,6 @@ export const customConfigUpdateValidator = [
body('services.twitter.username').exists(),
- body('cache.previews.size').isInt(),
- body('cache.captions.size').isInt(),
- body('cache.torrents.size').isInt(),
- body('cache.storyboards.size').isInt(),
-
body('signup.enabled').isBoolean(),
body('signup.limit').isInt(),
body('signup.requiresEmailVerification').isBoolean(),
diff --git a/server/core/middlewares/validators/static.ts b/server/core/middlewares/validators/static.ts
index 39a4f7e4d6..5d919cd898 100644
--- a/server/core/middlewares/validators/static.ts
+++ b/server/core/middlewares/validators/static.ts
@@ -10,7 +10,7 @@ import { logger } from '@server/helpers/logger.js'
import { LRU_CACHE } from '@server/initializers/constants.js'
import { VideoFileModel } from '@server/models/video/video-file.js'
import { VideoModel } from '@server/models/video/video.js'
-import { MStreamingPlaylist, MVideoFile, MVideoThumbnailBlacklist } from '@server/types/models/index.js'
+import { MVideoFile, MVideoThumbnailBlacklist } from '@server/types/models/index.js'
import express from 'express'
import { param, query } from 'express-validator'
import { LRUCache } from 'lru-cache'
@@ -21,7 +21,6 @@ type LRUValue = {
allowed: boolean
video?: MVideoThumbnailBlacklist
file?: MVideoFile
- playlist?: MStreamingPlaylist
}
const staticFileTokenBypass = new LRUCache<string, LRUValue>({
@@ -119,12 +118,11 @@ export const ensureCanAccessPrivateVideoHLSFiles = [
const cacheKey = token + '-' + videoUUID
if (staticFileTokenBypass.has(cacheKey)) {
- const { allowed, file, playlist, video } = staticFileTokenBypass.get(cacheKey)
+ const { allowed, file, video } = staticFileTokenBypass.get(cacheKey)
if (allowed === true) {
res.locals.onlyVideo = video
res.locals.videoFile = file
- res.locals.videoStreamingPlaylist = playlist
return next()
}
@@ -140,7 +138,6 @@ export const ensureCanAccessPrivateVideoHLSFiles = [
res.locals.onlyVideo = result.video
res.locals.videoFile = result.file
- res.locals.videoStreamingPlaylist = result.playlist
return next()
}
@@ -185,7 +182,6 @@ async function isHLSAllowed (req: express.Request, res: express.Response, videoU
return {
file,
video,
- playlist: video.getHLSPlaylist(),
allowed: await checkCanAccessVideoStaticFiles({ req, res, video, paramId: video.uuid })
}
}
diff --git a/server/core/middlewares/validators/videos/videos.ts b/server/core/middlewares/validators/videos/videos.ts
index 31ee417ff8..4491a65c70 100644
--- a/server/core/middlewares/validators/videos/videos.ts
+++ b/server/core/middlewares/validators/videos/videos.ts
@@ -176,8 +176,8 @@ export const videosAddResumableInitValidator = [
const user = res.locals.oauth.token.User
const cleanup = () => cleanUpReqFiles(req)
- logger.debug('Checking videosAddResumableInitValidator parameters and headers', {
- parameters: req.body,
+ logger.debug('Checking videosAddResumableInitValidator body and headers', {
+ body: req.body,
headers: req.headers,
files: req.files
})
diff --git a/server/core/models/abuse/abuse.ts b/server/core/models/abuse/abuse.ts
index 5a3802ee86..354b563b20 100644
--- a/server/core/models/abuse/abuse.ts
+++ b/server/core/models/abuse/abuse.ts
@@ -159,7 +159,7 @@ export enum ScopeNames {
model: VideoModel.unscoped(),
include: [
{
- attributes: [ 'filename', 'fileUrl', 'type' ],
+ attributes: [ 'filename', 'fileUrl', 'width', 'height' ],
model: ThumbnailModel
},
{
@@ -502,6 +502,8 @@ export class AbuseModel extends SequelizeModel<AbuseModel> {
const abuseModel = this.VideoAbuse
const entity = abuseModel.Video || abuseModel.deletedVideo
+ const video = abuseModel.Video
+
return {
id: entity.id,
uuid: entity.uuid,
@@ -512,11 +514,13 @@ export class AbuseModel extends SequelizeModel<AbuseModel> {
startAt: abuseModel.startAt,
endAt: abuseModel.endAt,
- deleted: !abuseModel.Video,
- blacklisted: abuseModel.Video?.isBlacklisted() || false,
- thumbnailPath: abuseModel.Video?.getMiniatureStaticPath(),
+ deleted: !video,
+ blacklisted: video?.isBlacklisted() || false,
+
+ thumbnailPath: video?.getSmallestThumbnailStaticPath(),
+ thumbnails: video?.Thumbnails.map(t => t.toFormattedJSON()) || [],
- channel: abuseModel.Video?.VideoChannel.toFormattedJSON() || abuseModel.deletedVideo?.channel
+ channel: video?.VideoChannel.toFormattedJSON() || abuseModel.deletedVideo?.channel
}
}
diff --git a/server/core/models/actor/actor-image.ts b/server/core/models/actor/actor-image.ts
index e1c0cb70a6..4176bd0fbe 100644
--- a/server/core/models/actor/actor-image.ts
+++ b/server/core/models/actor/actor-image.ts
@@ -7,7 +7,7 @@ import { Op, Transaction } from 'sequelize'
import { AfterDestroy, AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
import { logger } from '../../helpers/logger.js'
import { CONFIG } from '../../initializers/config.js'
-import { LAZY_STATIC_PATHS, MIMETYPES, WEBSERVER } from '../../initializers/constants.js'
+import { FILES_CACHE, LAZY_STATIC_PATHS, MIMETYPES, WEBSERVER } from '../../initializers/constants.js'
import { SequelizeModel, buildSQLAttributes } from '../shared/index.js'
import { ActorModel } from './actor.js'
@@ -45,7 +45,7 @@ export class ActorImageModel extends SequelizeModel<ActorImageModel> {
@AllowNull(false)
@Column
- declare onDisk: boolean
+ declare cached: boolean
@AllowNull(false)
@Column
@@ -74,7 +74,7 @@ export class ActorImageModel extends SequelizeModel<ActorImageModel> {
logger.info('Removing actor image file %s.', instance.filename)
// Don't block the transaction
- instance.removeImage()
+ instance.removeFile()
.catch(err => logger.error('Cannot remove actor image file %s.', instance.filename, { err }))
}
@@ -120,32 +120,17 @@ export class ActorImageModel extends SequelizeModel<ActorImageModel> {
return { avatars, banners }
}
- static listRemoteOnDisk () {
+ static listRemoteCached () {
return this.findAll<MActorImage>({
where: {
- onDisk: true
- },
- include: [
- {
- attributes: [ 'id' ],
- model: ActorModel.unscoped(),
- required: true,
- where: {
- serverId: {
- [Op.ne]: null
- }
- }
+ cached: true,
+ fileUrl: {
+ [Op.ne]: null
}
- ]
+ }
})
}
- static getImageUrl (image: MActorImagePath) {
- if (!image) return undefined
-
- return WEBSERVER.URL + image.getStaticPath()
- }
-
// ---------------------------------------------------------------------------
toFormattedJSON (this: MActorImageFormattable): ActorImage {
@@ -153,7 +138,7 @@ export class ActorImageModel extends SequelizeModel<ActorImageModel> {
height: this.height,
width: this.width,
path: this.getStaticPath(),
- fileUrl: ActorImageModel.getImageUrl(this),
+ fileUrl: this.getLocalFileUrl(),
createdAt: this.createdAt,
updatedAt: this.updatedAt
}
@@ -165,10 +150,17 @@ export class ActorImageModel extends SequelizeModel<ActorImageModel> {
mediaType: this.getMimeType(),
height: this.height,
width: this.width,
- url: ActorImageModel.getImageUrl(this)
+ url: this.getLocalFileUrl()
}
}
+ // ---------------------------------------------------------------------------
+
+ getLocalFileUrl (this: MActorImagePath) {
+ // Remote files are cached by our instance
+ return WEBSERVER.URL + this.getStaticPath()
+ }
+
getStaticPath (this: MActorImagePath) {
switch (this.type) {
case ActorImageType.AVATAR:
@@ -182,13 +174,22 @@ export class ActorImageModel extends SequelizeModel<ActorImageModel> {
}
}
- getPath () {
+ getFSPath () {
return join(CONFIG.STORAGE.ACTOR_IMAGES_DIR, this.filename)
}
- removeImage () {
- const imagePath = join(CONFIG.STORAGE.ACTOR_IMAGES_DIR, this.filename)
- return remove(imagePath)
+ getFSCachedPath () {
+ return join(FILES_CACHE.AVATARS.DIRECTORY, this.filename)
+ }
+
+ removeFile () {
+ const path = this.cached
+ ? this.getFSCachedPath()
+ : this.getFSPath()
+
+ logger.info('Removing actor image file ' + path)
+
+ return remove(path)
}
isLocal () {
diff --git a/server/core/models/application/upload-image.ts b/server/core/models/application/upload-image.ts
index 78897ebd69..8ee4e89a2b 100644
--- a/server/core/models/application/upload-image.ts
+++ b/server/core/models/application/upload-image.ts
@@ -98,28 +98,29 @@ export class UploadImageModel extends SequelizeModel<UploadImageModel> {
return UploadImageModel.findAll(query)
}
- static getImageUrl (image: MUploadImage) {
- if (!image) return undefined
-
- return WEBSERVER.URL + image.getStaticPath()
- }
+ // ---------------------------------------------------------------------------
- static getPathOf (filename: string) {
+ static getFSPathOf (filename: string) {
return join(DIRECTORIES.UPLOAD_IMAGES, filename)
}
// ---------------------------------------------------------------------------
+ getLocalFileUrl (this: MUploadImage) {
+ // Remote files are cached by our instance
+ return WEBSERVER.URL + this.getStaticPath()
+ }
+
getStaticPath (this: MUploadImage) {
return join(STATIC_PATHS.UPLOAD_IMAGES, this.filename)
}
- getPath () {
- return UploadImageModel.getPathOf(this.filename)
+ getFSPath () {
+ return UploadImageModel.getFSPathOf(this.filename)
}
removeImage () {
- return remove(this.getPath())
+ return remove(this.getFSPath())
}
isLocal () {
diff --git a/server/core/models/user/user-export.ts b/server/core/models/user/user-export.ts
index 3999ff0937..1e1820bd73 100644
--- a/server/core/models/user/user-export.ts
+++ b/server/core/models/user/user-export.ts
@@ -2,8 +2,8 @@ import { FileStorage, UserExportState, type FileStorageType, type UserExport, ty
import { logger } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
import {
- JWT_TOKEN_USER_EXPORT_FILE_LIFETIME,
DOWNLOAD_PATHS,
+ JWT_TOKEN_USER_EXPORT_FILE_LIFETIME,
USER_EXPORT_FILE_PREFIX,
USER_EXPORT_STATES,
WEBSERVER
@@ -64,10 +64,6 @@ export class UserExportModel extends SequelizeModel<UserExportModel> {
@Column
declare storage: FileStorageType
- @AllowNull(true)
- @Column
- declare fileUrl: string
-
@ForeignKey(() => UserModel)
@Column
declare userId: number
@@ -200,7 +196,7 @@ export class UserExportModel extends SequelizeModel<UserExportModel> {
}
}
- getFileDownloadUrl () {
+ getLocalDownloadFileUrl () {
if (this.state !== UserExportState.COMPLETED) return null
return WEBSERVER.URL + join(DOWNLOAD_PATHS.USER_EXPORTS, this.filename) + '?jwt=' + this.generateJWT()
@@ -219,8 +215,7 @@ export class UserExportModel extends SequelizeModel<UserExportModel> {
size: this.size,
- fileUrl: this.fileUrl,
- privateDownloadUrl: this.getFileDownloadUrl(),
+ privateDownloadUrl: this.getLocalDownloadFileUrl(),
createdAt: this.createdAt.toISOString(),
expiresOn: new Date(this.createdAt.getTime() + CONFIG.EXPORT.USERS.EXPORT_EXPIRATION).toISOString()
}
diff --git a/server/core/models/user/user-notification.ts b/server/core/models/user/user-notification.ts
index 1ae00f8b51..5c294a24dc 100644
--- a/server/core/models/user/user-notification.ts
+++ b/server/core/models/user/user-notification.ts
@@ -9,7 +9,6 @@ import { isUserNotificationTypeValid } from '../../helpers/custom-validators/use
import { AbuseModel } from '../abuse/abuse.js'
import { AccountModel } from '../account/account.js'
import { ActorFollowModel } from '../actor/actor-follow.js'
-import { ActorImageModel } from '../actor/actor-image.js'
import { ApplicationModel } from '../application/application.js'
import { PluginModel } from '../server/plugin.js'
import { SequelizeModel, throwIfNotValid } from '../shared/index.js'
@@ -618,7 +617,7 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>
formatAvatar (a: UserNotificationIncludes.ActorImageInclude) {
return {
- fileUrl: ActorImageModel.getImageUrl(a),
+ fileUrl: a.getLocalFileUrl(),
path: a.getStaticPath(),
width: a.width
}
diff --git a/server/core/models/video/formatter/video-activity-pub-format.ts b/server/core/models/video/formatter/video-activity-pub-format.ts
index 65367e6053..e99874a21c 100644
--- a/server/core/models/video/formatter/video-activity-pub-format.ts
+++ b/server/core/models/video/formatter/video-activity-pub-format.ts
@@ -13,9 +13,9 @@ import {
} from '@peertube/peertube-models'
import { getAPPublicValue } from '@server/helpers/activity-pub-utils.js'
import { isArray } from '@server/helpers/custom-validators/misc.js'
-import { generateMagnetUri } from '@server/lib/webtorrent.js'
import { getActivityStreamDuration } from '@server/lib/activitypub/activity.js'
import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls.js'
+import { generateMagnetUri } from '@server/lib/webtorrent.js'
import { WEBSERVER } from '../../../initializers/constants.js'
import {
getLocalVideoChaptersActivityPubUrl,
@@ -169,7 +169,7 @@ function buildPreviewAPAttribute (video: MVideoAP): ActivityPubStoryboard[] {
{
mediaType: 'image/jpeg',
- href: storyboard.getOriginFileUrl(video),
+ href: storyboard.getLocalFileUrl(),
width: storyboard.totalWidth,
height: storyboard.totalHeight,
@@ -309,9 +309,9 @@ function buildTags (video: MVideoAP): (ActivitySensitiveTagObject | ActivityHash
}
function buildIcon (video: MVideoAP): ActivityIconObject[] {
- return [ video.getMiniature(), video.getPreview() ]
+ return video.Thumbnails
.filter(i => !!i)
- .map(i => i.toActivityPubObject(video))
+ .map(i => i.toActivityPubObject())
}
function buildSubtitleLanguage (video: MVideoAP) {
diff --git a/server/core/models/video/formatter/video-api-format.ts b/server/core/models/video/formatter/video-api-format.ts
index 8b67e44309..e92b445ea7 100644
--- a/server/core/models/video/formatter/video-api-format.ts
+++ b/server/core/models/video/formatter/video-api-format.ts
@@ -9,11 +9,11 @@ import {
VideoStreamingPlaylist
} from '@peertube/peertube-models'
import { uuidToShort } from '@peertube/peertube-node-utils'
-import { generateMagnetUri } from '@server/lib/webtorrent.js'
import { tracer } from '@server/lib/opentelemetry/tracing.js'
import { getHLSResolutionPlaylistFilename } from '@server/lib/paths.js'
import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls.js'
import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
+import { generateMagnetUri } from '@server/lib/webtorrent.js'
import { isArray } from '../../../helpers/custom-validators/misc.js'
import {
VIDEO_CATEGORIES,
@@ -114,8 +114,12 @@ export function videoModelToFormattedJSON (video: MVideoFormattable, options: Vi
likes: video.likes,
dislikes: video.dislikes,
- thumbnailPath: video.getMiniatureStaticPath(),
- previewPath: video.getPreviewStaticPath(),
+
+ thumbnailPath: video.getSmallestThumbnailStaticPath(),
+ previewPath: video.getBestThumbnailStaticPath(),
+
+ thumbnails: (video.Thumbnails || []).map(t => t.toFormattedJSON()),
+
embedPath: video.getEmbedStaticPath(),
createdAt: video.createdAt,
updatedAt: video.updatedAt,
diff --git a/server/core/models/video/sql/video/shared/video-table-attributes.ts b/server/core/models/video/sql/video/shared/video-table-attributes.ts
index cc3c156a08..806e677686 100644
--- a/server/core/models/video/sql/video/shared/video-table-attributes.ts
+++ b/server/core/models/video/sql/video/shared/video-table-attributes.ts
@@ -48,14 +48,14 @@ export class VideoTableAttributes {
}
getThumbnailAttributes () {
- let attributeKeys = [ 'id', 'type', 'filename' ]
+ let attributeKeys = [ 'id', 'filename', 'height', 'width', 'fileUrl' ]
if (this.mode === 'get') {
attributeKeys = attributeKeys.concat([
'height',
'width',
'fileUrl',
- 'onDisk',
+ 'cached',
'automaticallyGenerated',
'videoId',
'videoPlaylistId',
@@ -255,7 +255,7 @@ export class VideoTableAttributes {
'filename',
'type',
'fileUrl',
- 'onDisk',
+ 'cached',
'createdAt',
'updatedAt'
]
diff --git a/server/core/models/video/storyboard.ts b/server/core/models/video/storyboard.ts
index c2685dde5b..513b0dcdc6 100644
--- a/server/core/models/video/storyboard.ts
+++ b/server/core/models/video/storyboard.ts
@@ -1,14 +1,14 @@
+import { Storyboard } from '@peertube/peertube-models'
+import { CONFIG } from '@server/initializers/config.js'
+import { MStoryboard, MStoryboardVideo, MVideo } from '@server/types/models/index.js'
import { remove } from 'fs-extra/esm'
import { join } from 'path'
+import { Op, Transaction } from 'sequelize'
import { AfterDestroy, AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
-import { CONFIG } from '@server/initializers/config.js'
-import { MStoryboard, MStoryboardVideo, MVideo } from '@server/types/models/index.js'
-import { Storyboard } from '@peertube/peertube-models'
import { logger } from '../../helpers/logger.js'
-import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, WEBSERVER } from '../../initializers/constants.js'
-import { VideoModel } from './video.js'
-import { Transaction } from 'sequelize'
+import { CONSTRAINTS_FIELDS, FILES_CACHE, LAZY_STATIC_PATHS, WEBSERVER } from '../../initializers/constants.js'
import { SequelizeModel } from '../shared/index.js'
+import { VideoModel } from './video.js'
@Table({
tableName: 'storyboard',
@@ -52,6 +52,10 @@ export class StoryboardModel extends SequelizeModel<StoryboardModel> {
@Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
declare fileUrl: string
+ @AllowNull(false)
+ @Column
+ declare cached: boolean
+
@ForeignKey(() => VideoModel)
@Column
declare videoId: number
@@ -72,8 +76,6 @@ export class StoryboardModel extends SequelizeModel<StoryboardModel> {
@AfterDestroy
static removeInstanceFile (instance: StoryboardModel) {
- logger.info('Removing storyboard file %s.', instance.filename)
-
// Don't block the transaction
instance.removeFile()
.catch(err => logger.error('Cannot remove storyboard file %s.', instance.filename, { err }))
@@ -100,22 +102,6 @@ export class StoryboardModel extends SequelizeModel<StoryboardModel> {
return StoryboardModel.findOne(query)
}
- static loadWithVideoByFilename (filename: string): Promise<MStoryboardVideo> {
- const query = {
- where: {
- filename
- },
- include: [
- {
- model: VideoModel.unscoped(),
- required: true
- }
- ]
- }
-
- return StoryboardModel.findOne(query)
- }
-
// ---------------------------------------------------------------------------
static async listStoryboardsOf (video: MVideo): Promise<MStoryboardVideo[]> {
@@ -130,36 +116,54 @@ export class StoryboardModel extends SequelizeModel<StoryboardModel> {
return storyboards.map(s => Object.assign(s, { Video: video }))
}
+ static listRemoteCached () {
+ return this.findAll<MStoryboard>({
+ where: {
+ cached: true,
+ fileUrl: {
+ [Op.ne]: null
+ }
+ }
+ })
+ }
+
// ---------------------------------------------------------------------------
- getOriginFileUrl (video: MVideo) {
- if (video.isLocal()) {
- return WEBSERVER.URL + this.getLocalStaticPath()
- }
+ getLocalFileUrl () {
+ // Remote files are cached by our instance
+ return WEBSERVER.URL + this.getFileStaticPath()
+ }
- return this.fileUrl
+ getFileStaticPath () {
+ return LAZY_STATIC_PATHS.STORYBOARDS + this.filename
}
- getFileUrl () {
- return WEBSERVER.URL + this.getLocalStaticPath()
+ getFSPath () {
+ return join(CONFIG.STORAGE.STORYBOARDS_DIR, this.filename)
}
- getLocalStaticPath () {
- return LAZY_STATIC_PATHS.STORYBOARDS + this.filename
+ getFSCachedPath () {
+ return join(FILES_CACHE.STORYBOARDS.DIRECTORY, this.filename)
}
- getPath () {
- return join(CONFIG.STORAGE.STORYBOARDS_DIR, this.filename)
+ isLocal () {
+ return !this.fileUrl
}
removeFile () {
- return remove(this.getPath())
+ const path = this.cached
+ ? this.getFSCachedPath()
+ : this.getFSPath()
+
+ logger.info('Removing storyboard file ' + path)
+
+ return remove(path)
}
toFormattedJSON (this: MStoryboardVideo): Storyboard {
return {
- fileUrl: this.getFileUrl(),
- storyboardPath: this.getLocalStaticPath(),
+ fileUrl: this.getLocalFileUrl(),
+ storyboardPath: this.getFileStaticPath(),
totalHeight: this.totalHeight,
totalWidth: this.totalWidth,
diff --git a/server/core/models/video/thumbnail.ts b/server/core/models/video/thumbnail.ts
index 507d6dfa67..eeb5fd3b90 100644
--- a/server/core/models/video/thumbnail.ts
+++ b/server/core/models/video/thumbnail.ts
@@ -1,13 +1,12 @@
-import { ActivityIconObject, ThumbnailType, type ThumbnailType_Type } from '@peertube/peertube-models'
-import { afterCommitIfTransaction } from '@server/helpers/database-utils.js'
-import { MThumbnail, MThumbnailVideo, MVideo, MVideoPlaylist } from '@server/types/models/index.js'
+import { ActivityIconObject } from '@peertube/peertube-models'
+import { CONFIG } from '@server/initializers/config.js'
+import { MThumbnail } from '@server/types/models/index.js'
import { remove } from 'fs-extra/esm'
import { extname, join } from 'path'
+import { Op } from 'sequelize'
import {
AfterDestroy,
AllowNull,
- BeforeCreate,
- BeforeUpdate,
BelongsTo,
Column,
CreatedAt,
@@ -18,8 +17,7 @@ import {
UpdatedAt
} from 'sequelize-typescript'
import { logger } from '../../helpers/logger.js'
-import { CONFIG } from '../../initializers/config.js'
-import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, MIMETYPES, WEBSERVER } from '../../initializers/constants.js'
+import { CONSTRAINTS_FIELDS, FILES_CACHE, LAZY_STATIC_PATHS, MIMETYPES, WEBSERVER } from '../../initializers/constants.js'
import { SequelizeModel } from '../shared/sequelize-type.js'
import { buildSQLAttributes } from '../shared/table.js'
import { VideoPlaylistModel } from './video-playlist.js'
@@ -36,7 +34,7 @@ import { VideoModel } from './video.js'
unique: true
},
{
- fields: [ 'filename', 'type' ],
+ fields: [ 'filename' ],
unique: true
}
]
@@ -56,10 +54,6 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {
@Column
declare width: number
- @AllowNull(false)
- @Column
- declare type: ThumbnailType_Type
-
@AllowNull(true)
@Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
declare fileUrl: string
@@ -70,7 +64,7 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {
@AllowNull(false)
@Column
- declare onDisk: boolean
+ declare cached: boolean
@ForeignKey(() => VideoModel)
@Column
@@ -102,34 +96,10 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {
@UpdatedAt
declare updatedAt: Date
- // If this thumbnail replaced existing one, track the old name
- previousThumbnailFilename: string
-
- private static readonly types: { [id in ThumbnailType_Type]: { label: string, directory: string, staticPath: string } } = {
- [ThumbnailType.MINIATURE]: {
- label: 'miniature',
- directory: CONFIG.STORAGE.THUMBNAILS_DIR,
- staticPath: LAZY_STATIC_PATHS.THUMBNAILS
- },
- [ThumbnailType.PREVIEW]: {
- label: 'preview',
- directory: CONFIG.STORAGE.PREVIEWS_DIR,
- staticPath: LAZY_STATIC_PATHS.PREVIEWS
- }
- }
-
- @BeforeCreate
- @BeforeUpdate
- static removeOldFile (instance: ThumbnailModel, options) {
- return afterCommitIfTransaction(options.transaction, () => instance.removePreviousFilenameIfNeeded())
- }
-
@AfterDestroy
static removeFiles (instance: ThumbnailModel) {
- logger.info('Removing %s file %s.', ThumbnailModel.types[instance.type].label, instance.filename)
-
// Don't block the transaction
- instance.removeThumbnail()
+ instance.removeFile()
.catch(err => logger.error('Cannot remove thumbnail file %s.', instance.filename, { err }))
}
@@ -145,95 +115,52 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {
// ---------------------------------------------------------------------------
- static loadByFilename (filename: string, thumbnailType: ThumbnailType_Type): Promise<MThumbnail> {
- const query = {
- where: {
- filename,
- type: thumbnailType
- }
- }
-
- return ThumbnailModel.findOne(query)
- }
-
- static loadWithVideoByFilename (filename: string, thumbnailType: ThumbnailType_Type): Promise<MThumbnailVideo> {
+ static loadByFilename (filename: string): Promise<MThumbnail> {
const query = {
- where: {
- filename,
- type: thumbnailType
- },
- include: [
- {
- model: VideoModel.unscoped(),
- required: true
- }
- ]
+ where: { filename }
}
return ThumbnailModel.findOne(query)
}
- static listRemoteOnDisk () {
+ static listRemoteCached () {
return this.findAll<MThumbnail>({
where: {
- onDisk: true
- },
- include: [
- {
- attributes: [ 'id' ],
- model: VideoModel.unscoped(),
- required: true,
- where: {
- remote: true
- }
+ cached: true,
+ fileUrl: {
+ [Op.ne]: null
}
- ]
+ }
})
}
// ---------------------------------------------------------------------------
- static buildPath (type: ThumbnailType_Type, filename: string) {
- const directory = ThumbnailModel.types[type].directory
-
- return join(directory, filename)
+ getFSPath () {
+ return join(CONFIG.STORAGE.THUMBNAILS_DIR, this.filename)
}
- // ---------------------------------------------------------------------------
-
- getOriginFileUrl (videoOrPlaylist: MVideo | MVideoPlaylist) {
- const staticPath = ThumbnailModel.types[this.type].staticPath + this.filename
-
- // FIXME: typings
- if ((videoOrPlaylist as MVideo).isLocal()) return WEBSERVER.URL + staticPath
-
- return this.fileUrl
+ getFSCachedPath () {
+ return join(FILES_CACHE.THUMBNAILS.DIRECTORY, this.filename)
}
- getLocalStaticPath () {
- return ThumbnailModel.types[this.type].staticPath + this.filename
- }
+ removeFile () {
+ const path = this.cached
+ ? this.getFSCachedPath()
+ : this.getFSPath()
- getPath () {
- return ThumbnailModel.buildPath(this.type, this.filename)
- }
+ logger.info('Removing thumbnail file ' + path)
- getPreviousPath () {
- return ThumbnailModel.buildPath(this.type, this.previousThumbnailFilename)
+ return remove(path)
}
- removeThumbnail () {
- return remove(this.getPath())
+ getLocalFileUrl () {
+ // Remote files are cached by our instance
+ return WEBSERVER.URL + this.getFileStaticPath()
}
- removePreviousFilenameIfNeeded () {
- if (!this.previousThumbnailFilename) return
-
- const previousPath = this.getPreviousPath()
- remove(previousPath)
- .catch(err => logger.error('Cannot remove previous thumbnail file %s.', previousPath, { err }))
-
- this.previousThumbnailFilename = undefined
+ getFileStaticPath () {
+ return LAZY_STATIC_PATHS.THUMBNAILS + this.filename
}
isLocal () {
@@ -242,10 +169,18 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {
// ---------------------------------------------------------------------------
- toActivityPubObject (this: MThumbnail, video: MVideo): ActivityIconObject {
+ toFormattedJSON () {
+ return {
+ height: this.height,
+ width: this.width,
+ fileUrl: this.getLocalFileUrl()
+ }
+ }
+
+ toActivityPubObject (this: MThumbnail): ActivityIconObject {
return {
type: 'Image',
- url: this.getOriginFileUrl(video),
+ url: this.getLocalFileUrl(),
mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extname(this.filename)],
width: this.width,
height: this.height
diff --git a/server/core/models/video/video-blacklist.ts b/server/core/models/video/video-blacklist.ts
index 382e90b759..01c893cf8f 100644
--- a/server/core/models/video/video-blacklist.ts
+++ b/server/core/models/video/video-blacklist.ts
@@ -84,7 +84,7 @@ export class VideoBlacklistModel extends SequelizeModel<VideoBlacklistModel> {
},
{
model: ThumbnailModel,
- attributes: [ 'type', 'filename' ],
+ attributes: [ 'width', 'height', 'filename' ],
required: false
}
]
diff --git a/server/core/models/video/video-caption.ts b/server/core/models/video/video-caption.ts
index ac00bf8532..5ec1522021 100644
--- a/server/core/models/video/video-caption.ts
+++ b/server/core/models/video/video-caption.ts
@@ -1,7 +1,8 @@
import { removeVTTExt } from '@peertube/peertube-core-utils'
import { FileStorage, type FileStorageType, VideoCaption, VideoCaptionObject } from '@peertube/peertube-models'
import { buildUUID } from '@peertube/peertube-node-utils'
-import { getObjectStoragePublicFileUrl } from '@server/lib/object-storage/urls.js'
+import { generateCaptionObjectStorageKey, generateHLSObjectStorageKey } from '@server/lib/object-storage/keys.js'
+import { buildObjectStoragePublicFileUrl } from '@server/lib/object-storage/urls.js'
import { removeCaptionObjectStorage, removeHLSFileObjectStorageByFilename } from '@server/lib/object-storage/videos.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
import {
@@ -35,7 +36,7 @@ import {
import { isVideoCaptionLanguageValid } from '../../helpers/custom-validators/video-captions.js'
import { logger } from '../../helpers/logger.js'
import { CONFIG } from '../../initializers/config.js'
-import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, VIDEO_LANGUAGES, WEBSERVER } from '../../initializers/constants.js'
+import { CONSTRAINTS_FIELDS, FILES_CACHE, LAZY_STATIC_PATHS, VIDEO_LANGUAGES, WEBSERVER } from '../../initializers/constants.js'
import { SequelizeModel, buildWhereIdOrUUID, doesExist, throwIfNotValid } from '../shared/index.js'
import { VideoStreamingPlaylistModel } from './video-streaming-playlist.js'
import { VideoModel } from './video.js'
@@ -110,6 +111,10 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
@Column
declare automaticallyGenerated: boolean
+ @AllowNull(false)
+ @Column
+ declare cached: boolean
+
@ForeignKey(() => VideoModel)
@Column
declare videoId: number
@@ -128,12 +133,8 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
instance.Video = await instance.$get('Video', { transaction: options.transaction })
}
- if (instance.isLocal()) {
- logger.info('Removing caption %s.', instance.filename)
-
- instance.removeAllCaptionFiles()
- .catch(err => logger.error('Cannot remove caption file ' + instance.filename, { err }))
- }
+ instance.removeAllCaptionFiles()
+ .catch(err => logger.error('Cannot remove caption file ' + instance.filename, { err }))
return undefined
}
@@ -187,17 +188,11 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
return VideoCaptionModel.findOne(query)
}
- static loadWithVideoByFilename (filename: string): Promise<MVideoCaptionVideo> {
+ static loadByFilename (filename: string): Promise<MVideoCaption> {
const query = {
where: {
filename
- },
- include: [
- {
- model: VideoModel.unscoped(),
- attributes: videoAttributes
- }
- ]
+ }
}
return VideoCaptionModel.findOne(query)
@@ -254,6 +249,17 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
return result
}
+ static listRemoteCached () {
+ return this.findAll<MVideoCaption>({
+ where: {
+ cached: true,
+ fileUrl: {
+ [Op.ne]: null
+ }
+ }
+ })
+ }
+
// ---------------------------------------------------------------------------
static getLanguageLabel (language: string) {
@@ -279,11 +285,11 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
automaticallyGenerated: this.automaticallyGenerated,
// TODO: remove, deprecated in 8.0
- captionPath: this.Video.isLocal() && this.fileUrl
+ captionPath: this.isLocal() && this.fileUrl
? null // On object storage
: this.getFileStaticPath(),
- fileUrl: this.getFileUrl(this.Video),
+ fileUrl: this.getLocalFileUrl(),
m3u8Url: this.getM3U8Url(this.Video),
updatedAt: this.updatedAt.toISOString()
@@ -300,12 +306,12 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
{
type: 'Link',
mediaType: 'text/vtt',
- href: this.getOriginFileUrl(video)
+ href: this.getLocalFileUrl()
},
{
type: 'Link',
mediaType: 'application/x-mpegURL',
- href: this.getOriginFileUrl(video)
+ href: this.getM3U8Url(video)
}
]
}
@@ -314,7 +320,7 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
// ---------------------------------------------------------------------------
isLocal () {
- return this.Video.remote === false
+ return !this.fileUrl
}
// ---------------------------------------------------------------------------
@@ -335,6 +341,10 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
return join(CONFIG.STORAGE.CAPTIONS_DIR, this.filename)
}
+ getFSFileCachedPath () {
+ return join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, this.filename)
+ }
+
getFSM3U8Path (video: MVideoPrivacy) {
if (!this.m3u8Filename) return null
@@ -342,21 +352,20 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
}
async removeAllCaptionFiles (this: MVideoCaptionVideo) {
+ logger.info('Removing caption files of video ' + this.Video.uuid)
+
await this.removeCaptionFile()
await this.removeCaptionPlaylist()
}
- async removeCaptionFile (this: MVideoCaptionVideo) {
- if (this.storage === FileStorage.OBJECT_STORAGE) {
- if (this.fileUrl) {
- await removeCaptionObjectStorage(this)
- }
+ async removeCaptionFile (this: MVideoCaption) {
+ if (this.cached) {
+ await remove(this.getFSFileCachedPath())
+ } else if (this.storage === FileStorage.OBJECT_STORAGE) {
+ await removeCaptionObjectStorage(this)
} else {
await remove(this.getFSFilePath())
}
-
- this.filename = null
- this.fileUrl = null
}
async removeCaptionPlaylist (this: MVideoCaptionVideo) {
@@ -365,48 +374,45 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
const hls = await VideoStreamingPlaylistModel.loadHLSByVideoWithVideo(this.videoId)
if (!hls) return
+ // M3U8 is proxified by our our instance, not cached
+
if (this.storage === FileStorage.OBJECT_STORAGE) {
- if (this.m3u8Url) {
- await removeHLSFileObjectStorageByFilename(hls, this.m3u8Filename)
- }
+ await removeHLSFileObjectStorageByFilename(hls.Video, this.m3u8Filename)
} else {
await remove(this.getFSM3U8Path(this.Video))
}
this.m3u8Filename = null
- this.m3u8Url = null
}
// ---------------------------------------------------------------------------
- getFileUrl (this: MVideoCaptionUrl, video: MVideoOwned) {
- if (video.isLocal() && this.storage === FileStorage.OBJECT_STORAGE) {
- return getObjectStoragePublicFileUrl(this.fileUrl, CONFIG.OBJECT_STORAGE.CAPTIONS)
+ getLocalFileUrl (this: MVideoCaptionUrl) {
+ if (this.isLocal() && this.storage === FileStorage.OBJECT_STORAGE) {
+ return buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.CAPTIONS,
+ key: generateCaptionObjectStorageKey(this.filename)
+ })
}
+ // Captions are cached by our instance
return WEBSERVER.URL + this.getFileStaticPath()
}
- getOriginFileUrl (this: MVideoCaptionUrl, video: MVideoOwned) {
- if (video.isLocal()) return this.getFileUrl(video)
-
- return this.fileUrl
- }
-
// ---------------------------------------------------------------------------
getM3U8Url (this: MVideoCaptionUrl, video: MVideoOwned & MVideoPrivacy) {
if (!this.m3u8Filename) return null
+ if (!this.isLocal()) return this.m3u8Url
- if (video.isLocal()) {
- if (this.storage === FileStorage.OBJECT_STORAGE) {
- return getObjectStoragePublicFileUrl(this.m3u8Url, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
- }
-
- return WEBSERVER.URL + this.getM3U8StaticPath(video)
+ if (this.storage === FileStorage.OBJECT_STORAGE) {
+ return buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS, // M3U8 caption file is in the streaming playlists bucket
+ key: generateHLSObjectStorageKey(video, this.m3u8Filename)
+ })
}
- return this.m3u8Url
+ return WEBSERVER.URL + this.getM3U8StaticPath(video)
}
// ---------------------------------------------------------------------------
diff --git a/server/core/models/video/video-file.ts b/server/core/models/video/video-file.ts
index d6650155b8..5810616a58 100644
--- a/server/core/models/video/video-file.ts
+++ b/server/core/models/video/video-file.ts
@@ -12,7 +12,13 @@ import { logger } from '@server/helpers/logger.js'
import { extractVideo } from '@server/helpers/video.js'
import { CONFIG } from '@server/initializers/config.js'
import { buildRemoteUrl } from '@server/lib/activitypub/url.js'
-import { getHLSPrivateFileUrl, getObjectStoragePublicFileUrl, getWebVideoPrivateFileUrl } from '@server/lib/object-storage/index.js'
+import {
+ buildObjectStorageHLSPrivateFileUrl,
+ buildObjectStoragePublicFileUrl,
+ buildObjectStorageWebVideoPrivateFileUrl,
+ generateHLSObjectStorageKey,
+ generateWebVideoObjectStorageKey
+} from '@server/lib/object-storage/index.js'
import { getFSTorrentFilePath } from '@server/lib/paths.js'
import { getVideoFileMimeType } from '@server/lib/video-file.js'
import { isVideoInPrivateDirectory } from '@server/lib/video-privacy.js'
@@ -191,22 +197,20 @@ export class VideoFileModel extends SequelizeModel<VideoFileModel> {
@Column
declare metadataUrl: string
- // Could be null for remote files
@AllowNull(true)
@Column
declare fileUrl: string
- // Could be null for live files
+ // Can be null for live files
@AllowNull(true)
@Column
declare filename: string
- // Could be null for remote files
@AllowNull(true)
@Column
declare torrentUrl: string
- // Could be null for live files
+ // Can be null for live files
@AllowNull(true)
@Column
declare torrentFilename: string
@@ -502,26 +506,32 @@ export class VideoFileModel extends SequelizeModel<VideoFileModel> {
getObjectStorageUrl (video: MVideo) {
if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
- return this.getPrivateObjectStorageUrl(video)
+ return this.buildPrivateObjectStorageUrl(video)
}
- return this.getPublicObjectStorageUrl()
+ return this.buildPublicObjectStorageUrl(video)
}
- private getPrivateObjectStorageUrl (video: MVideo) {
+ private buildPrivateObjectStorageUrl (video: MVideo) {
if (this.isHLS()) {
- return getHLSPrivateFileUrl(video, this.filename)
+ return buildObjectStorageHLSPrivateFileUrl(video, this.filename)
}
- return getWebVideoPrivateFileUrl(this.filename)
+ return buildObjectStorageWebVideoPrivateFileUrl(this.filename)
}
- private getPublicObjectStorageUrl () {
+ private buildPublicObjectStorageUrl (video: MVideo) {
if (this.isHLS()) {
- return getObjectStoragePublicFileUrl(this.fileUrl, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+ return buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
+ key: generateHLSObjectStorageKey(video, this.filename)
+ })
}
- return getObjectStoragePublicFileUrl(this.fileUrl, CONFIG.OBJECT_STORAGE.WEB_VIDEOS)
+ return buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.WEB_VIDEOS,
+ key: generateWebVideoObjectStorageKey(this.filename)
+ })
}
// ---------------------------------------------------------------------------
@@ -585,13 +595,7 @@ export class VideoFileModel extends SequelizeModel<VideoFileModel> {
getTorrentUrl () {
if (!this.torrentFilename) return null
- return WEBSERVER.URL + this.getTorrentStaticPath()
- }
-
- getTorrentStaticPath () {
- if (!this.torrentFilename) return null
-
- return join(LAZY_STATIC_PATHS.TORRENTS, this.torrentFilename)
+ return WEBSERVER.URL + join(LAZY_STATIC_PATHS.TORRENTS, this.torrentFilename)
}
getTorrentDownloadUrl () {
diff --git a/server/core/models/video/video-playlist.ts b/server/core/models/video/video-playlist.ts
index 28bf82ad99..7c32a7d645 100644
--- a/server/core/models/video/video-playlist.ts
+++ b/server/core/models/video/video-playlist.ts
@@ -8,7 +8,8 @@ import {
type VideoPlaylistPrivacyType,
type VideoPlaylistType_Type
} from '@peertube/peertube-models'
-import { buildUUID, uuidToShort } from '@peertube/peertube-node-utils'
+import { uuidToShort } from '@peertube/peertube-node-utils'
+import { generateImageFilename } from '@server/helpers/image-utils.js'
import { activityPubCollectionPagination } from '@server/lib/activitypub/collection.js'
import { MAccountId, MChannelId, MVideoPlaylistElement } from '@server/types/models/index.js'
import { join } from 'path'
@@ -39,7 +40,6 @@ import {
ACTIVITY_PUB,
CONSTRAINTS_FIELDS,
LAZY_STATIC_PATHS,
- THUMBNAILS_SIZE,
USER_EXPORT_MAX_ITEMS,
VIDEO_PLAYLIST_PRIVACIES,
VIDEO_PLAYLIST_TYPES,
@@ -532,6 +532,10 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {
async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
thumbnail.videoPlaylistId = this.id
+ if (this.Thumbnail && thumbnail.id !== this.Thumbnail?.id) {
+ await this.Thumbnail.destroy({ transaction: t })
+ }
+
this.Thumbnail = await thumbnail.save({ transaction: t })
}
@@ -550,12 +554,12 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {
return false
}
- generateThumbnailName () {
- const extension = '.jpg'
-
- return 'playlist-' + buildUUID() + extension
+ generateThumbnailName (extension: string) {
+ return 'playlist-' + generateImageFilename(extension)
}
+ // ---------------------------------------------------------------------------
+
getThumbnailUrl () {
if (!this.hasThumbnail()) return null
@@ -568,6 +572,8 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {
return join(LAZY_STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
}
+ // ---------------------------------------------------------------------------
+
getWatchStaticPath () {
return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
}
@@ -639,6 +645,10 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {
},
thumbnailPath: this.getThumbnailStaticPath(),
+ thumbnails: this.Thumbnail
+ ? [ this.Thumbnail.toFormattedJSON() ]
+ : [],
+
embedPath: this.getEmbedStaticPath(),
type: {
@@ -671,8 +681,8 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {
type: 'Image' as 'Image',
url: this.getThumbnailUrl(),
mediaType: 'image/jpeg' as 'image/jpeg',
- width: THUMBNAILS_SIZE.width,
- height: THUMBNAILS_SIZE.height
+ width: this.Thumbnail.width,
+ height: this.Thumbnail.height
}
}
diff --git a/server/core/models/video/video-source.ts b/server/core/models/video/video-source.ts
index 11572071c8..156c0e2cd1 100644
--- a/server/core/models/video/video-source.ts
+++ b/server/core/models/video/video-source.ts
@@ -70,10 +70,6 @@ export class VideoSourceModel extends SequelizeModel<VideoSourceModel> {
@Column
declare storage: FileStorageType
- @AllowNull(true)
- @Column
- declare fileUrl: string
-
@ForeignKey(() => VideoModel)
@Column
declare videoId: number
@@ -144,7 +140,6 @@ export class VideoSourceModel extends SequelizeModel<VideoSourceModel> {
return {
inputFilename: this.inputFilename,
- fileUrl: this.fileUrl,
fileDownloadUrl: this.getFileDownloadUrl(),
resolution: {
diff --git a/server/core/models/video/video-streaming-playlist.ts b/server/core/models/video/video-streaming-playlist.ts
index 6fb11533b3..f673c73029 100644
--- a/server/core/models/video/video-streaming-playlist.ts
+++ b/server/core/models/video/video-streaming-playlist.ts
@@ -2,13 +2,18 @@ import {
FileStorage,
VideoResolution,
VideoStreamingPlaylistType,
+ VideoStreamingPlaylistTypeString,
type FileStorageType,
type VideoStreamingPlaylistType_Type
} from '@peertube/peertube-models'
import { generateP2PMediaLoaderHash } from '@peertube/peertube-node-utils'
import { logger } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
-import { getHLSPrivateFileUrl, getObjectStoragePublicFileUrl } from '@server/lib/object-storage/index.js'
+import {
+ buildObjectStorageHLSPrivateFileUrl,
+ buildObjectStoragePublicFileUrl,
+ generateHLSObjectStorageKey
+} from '@server/lib/object-storage/index.js'
import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '@server/lib/paths.js'
import { isVideoInPrivateDirectory } from '@server/lib/video-privacy.js'
import { VideoFileModel } from '@server/models/video/video-file.js'
@@ -305,10 +310,13 @@ export class VideoStreamingPlaylistModel extends SequelizeModel<VideoStreamingPl
private getMasterPlaylistObjectStorageUrl (video: MVideo) {
if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
- return getHLSPrivateFileUrl(video, this.playlistFilename)
+ return buildObjectStorageHLSPrivateFileUrl(video, this.playlistFilename)
}
- return getObjectStoragePublicFileUrl(this.playlistUrl, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+ return buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
+ key: generateHLSObjectStorageKey(video, this.playlistFilename)
+ })
}
// ---------------------------------------------------------------------------
@@ -329,10 +337,13 @@ export class VideoStreamingPlaylistModel extends SequelizeModel<VideoStreamingPl
private getSha256SegmentsObjectStorageUrl (video: MVideo) {
if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
- return getHLSPrivateFileUrl(video, this.segmentsSha256Filename)
+ return buildObjectStorageHLSPrivateFileUrl(video, this.segmentsSha256Filename)
}
- return getObjectStoragePublicFileUrl(this.segmentsSha256Url, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
+ return buildObjectStoragePublicFileUrl({
+ bucket: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS,
+ key: generateHLSObjectStorageKey(video, this.segmentsSha256Filename)
+ })
}
// ---------------------------------------------------------------------------
@@ -357,7 +368,7 @@ export class VideoStreamingPlaylistModel extends SequelizeModel<VideoStreamingPl
return false
}
- getStringType () {
+ getStringType (): VideoStreamingPlaylistTypeString {
if (this.type === VideoStreamingPlaylistType.HLS) return 'hls'
return 'unknown'
diff --git a/server/core/models/video/video.ts b/server/core/models/video/video.ts
index 2cc4460b0b..fb4fa479f9 100644
--- a/server/core/models/video/video.ts
+++ b/server/core/models/video/video.ts
@@ -1,8 +1,7 @@
-import { buildVideoEmbedPath, buildVideoWatchPath, maxBy, pick, wait } from '@peertube/peertube-core-utils'
+import { buildVideoEmbedPath, buildVideoWatchPath, maxBy, minBy, pick, wait } from '@peertube/peertube-core-utils'
import {
FileStorage,
ResultList,
- ThumbnailType,
UserRight,
Video,
VideoDetails,
@@ -211,7 +210,7 @@ export type ForAPIOptions = {
required: true
},
{
- attributes: [ 'type', 'filename' ],
+ attributes: [ 'width', 'height', 'fileUrl', 'filename' ],
model: ThumbnailModel,
required: false
}
@@ -1894,37 +1893,57 @@ export class VideoModel extends SequelizeModel<VideoModel> {
// ---------------------------------------------------------------------------
- async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
- thumbnail.videoId = this.id
-
- const savedThumbnail = await thumbnail.save({ transaction })
+ async replaceAndSaveThumbnails (thumbnails: MThumbnail[], transaction?: Transaction) {
+ if (thumbnails.length === 0) {
+ throw new Error('Cannot replace thumbnails with an empty array, at least one thumbnail is required')
+ }
if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
- this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
- this.Thumbnails.push(savedThumbnail)
+ let oldThumbnails = [ ...this.Thumbnails ]
+
+ for (const thumbnail of thumbnails) {
+ thumbnail.videoId = this.id
+
+ const savedThumbnail = await thumbnail.save({ transaction })
+
+ this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
+ oldThumbnails = oldThumbnails.filter(t => t.id !== savedThumbnail.id)
+
+ this.Thumbnails.push(savedThumbnail)
+ }
+
+ for (const oldThumbnail of oldThumbnails) {
+ await oldThumbnail.destroy({ transaction })
+ }
}
// ---------------------------------------------------------------------------
- hasMiniature (this: Pick<MVideoThumbnail, 'getMiniature' | 'Thumbnails'>) {
- return !!this.getMiniature()
+ getBestThumbnail (this: Pick<MVideoThumbnail, 'Thumbnails'>) {
+ if (!this.Thumbnails || this.Thumbnails.length === 0) return undefined
+
+ return maxBy(this.Thumbnails, 'width')
}
- getMiniature (this: Pick<MVideoThumbnail, 'Thumbnails'>) {
- if (Array.isArray(this.Thumbnails) === false) return undefined
+ getBestThumbnailStaticPath (this: Pick<MVideoThumbnail, 'Thumbnails' | 'getBestThumbnail'>) {
+ const thumbnail = this.getBestThumbnail()
+ if (!thumbnail) return null
- return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
+ return thumbnail.getFileStaticPath()
}
- hasPreview (this: Pick<MVideoThumbnail, 'getPreview' | 'Thumbnails'>) {
- return !!this.getPreview()
+ getSmallestThumbnail (this: Pick<MVideoThumbnail, 'Thumbnails'>) {
+ if (!this.Thumbnails || this.Thumbnails.length === 0) return undefined
+
+ return minBy(this.Thumbnails, 'width')
}
- getPreview (this: Pick<MVideoThumbnail, 'Thumbnails'>) {
- if (Array.isArray(this.Thumbnails) === false) return undefined
+ getSmallestThumbnailStaticPath (this: Pick<MVideoThumbnail, 'Thumbnails' | 'getSmallestThumbnail'>) {
+ const thumbnail = this.getSmallestThumbnail()
+ if (!thumbnail) return null
- return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
+ return thumbnail.getFileStaticPath()
}
// ---------------------------------------------------------------------------
@@ -1941,20 +1960,6 @@ export class VideoModel extends SequelizeModel<VideoModel> {
return buildVideoEmbedPath({ shortUUID: uuidToShort(this.uuid) })
}
- getMiniatureStaticPath (this: Pick<MVideoThumbnail, 'getMiniature' | 'Thumbnails'>) {
- const thumbnail = this.getMiniature()
- if (!thumbnail) return null
-
- return thumbnail.getLocalStaticPath()
- }
-
- getPreviewStaticPath (this: Pick<MVideoThumbnail, 'getPreview' | 'Thumbnails'>) {
- const preview = this.getPreview()
- if (!preview) return null
-
- return preview.getLocalStaticPath()
- }
-
toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
return videoModelToFormattedJSON(this, options)
}
@@ -2158,7 +2163,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {
)
if (playlist.storage === FileStorage.OBJECT_STORAGE) {
- await removeHLSObjectStorage(playlist.withVideo(this))
+ await removeHLSObjectStorage(this)
}
}
@@ -2177,8 +2182,8 @@ export class VideoModel extends SequelizeModel<VideoModel> {
await remove(VideoPathManager.Instance.getFSHLSOutputPath(this, resolutionFilename))
if (videoFile.storage === FileStorage.OBJECT_STORAGE) {
- await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), videoFile.filename)
- await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), resolutionFilename)
+ await removeHLSFileObjectStorageByFilename(this, videoFile.filename)
+ await removeHLSFileObjectStorageByFilename(this, resolutionFilename)
}
logger.debug(
@@ -2192,7 +2197,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {
await remove(filePath)
if (streamingPlaylist.storage === FileStorage.OBJECT_STORAGE) {
- await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), filename)
+ await removeHLSFileObjectStorageByFilename(this, filename)
}
logger.debug(`Removing streaming playlist file ${filename}`, lTags(this.uuid))
diff --git a/server/core/types/models/abuse/abuse.ts b/server/core/types/models/abuse/abuse.ts
index 5d0ab8a702..94100f1e4a 100644
--- a/server/core/types/models/abuse/abuse.ts
+++ b/server/core/types/models/abuse/abuse.ts
@@ -43,7 +43,15 @@ export type MVideoAbuseFormattable =
'Video',
Pick<
MVideoAccountLightBlacklistAllFiles,
- 'id' | 'uuid' | 'name' | 'nsfw' | 'getMiniature' | 'getMiniatureStaticPath' | 'isBlacklisted' | 'VideoChannel' | 'Thumbnails'
+ | 'id'
+ | 'uuid'
+ | 'name'
+ | 'nsfw'
+ | 'isBlacklisted'
+ | 'VideoChannel'
+ | 'Thumbnails'
+ | 'getSmallestThumbnail'
+ | 'getSmallestThumbnailStaticPath'
>
>
diff --git a/server/core/types/models/user/user-notification.ts b/server/core/types/models/user/user-notification.ts
index 191e89b04f..926e543884 100644
--- a/server/core/types/models/user/user-notification.ts
+++ b/server/core/types/models/user/user-notification.ts
@@ -26,7 +26,10 @@ type Use<K extends keyof UserNotificationModel, M> = PickWith<UserNotificationMo
// ############################################################################
export namespace UserNotificationIncludes {
- export type ActorImageInclude = Pick<ActorImageModel, 'createdAt' | 'filename' | 'type' | 'getStaticPath' | 'width' | 'updatedAt'>
+ export type ActorImageInclude = Pick<
+ ActorImageModel,
+ 'createdAt' | 'filename' | 'type' | 'getStaticPath' | 'getLocalFileUrl' | 'width' | 'updatedAt'
+ >
export type VideoInclude = Pick<VideoModel, 'id' | 'uuid' | 'name' | 'state'>
export type VideoIncludeChannel =
diff --git a/server/core/types/models/video/video-caption.ts b/server/core/types/models/video/video-caption.ts
index a47f474816..a060dce891 100644
--- a/server/core/types/models/video/video-caption.ts
+++ b/server/core/types/models/video/video-caption.ts
@@ -15,7 +15,16 @@ export type MVideoCaptionFilename = Pick<MVideoCaption, 'filename' | 'getFileSta
export type MVideoCaptionUrl = Pick<
MVideoCaption,
- 'filename' | 'getFileStaticPath' | 'storage' | 'fileUrl' | 'm3u8Url' | 'getFileUrl' | 'getM3U8Url' | 'm3u8Filename' | 'getM3U8StaticPath'
+ | 'filename'
+ | 'getFileStaticPath'
+ | 'storage'
+ | 'fileUrl'
+ | 'm3u8Url'
+ | 'getLocalFileUrl'
+ | 'getM3U8Url'
+ | 'm3u8Filename'
+ | 'getM3U8StaticPath'
+ | 'isLocal'
>
export type MVideoCaptionLanguageUrl = Pick<
@@ -28,16 +37,22 @@ export type MVideoCaptionLanguageUrl = Pick<
| 'm3u8Filename'
| 'm3u8Url'
| 'toActivityPubObject'
- | 'getFileUrl'
+ | 'getLocalFileUrl'
| 'getFileStaticPath'
- | 'getOriginFileUrl'
| 'getM3U8Url'
| 'getM3U8StaticPath'
+ | 'isLocal'
>
export type MVideoCaptionVideo =
& MVideoCaption
- & Use<'Video', Pick<MVideo, 'id' | 'name' | 'remote' | 'uuid' | 'url' | 'state' | 'getWatchStaticPath' | 'isLocal' | 'privacy'>>
+ & Use<
+ 'Video',
+ Pick<
+ MVideo,
+ 'id' | 'name' | 'remote' | 'uuid' | 'url' | 'state' | 'getWatchStaticPath' | 'isLocal' | 'privacy' | 'hasPrivateStaticPath'
+ >
+ >
// ############################################################################
diff --git a/server/core/types/models/video/video-playlist.ts b/server/core/types/models/video/video-playlist.ts
index e43f55adb2..406b53de7b 100644
--- a/server/core/types/models/video/video-playlist.ts
+++ b/server/core/types/models/video/video-playlist.ts
@@ -95,6 +95,7 @@ export type MVideoPlaylistFullSummary =
export type MVideoPlaylistFormattable =
& MVideoPlaylistVideosLength
+ & Use<'Thumbnail', MThumbnail>
& Use<'OwnerAccount', MAccountSummaryFormattable>
& Use<'VideoChannel', MChannelSummaryFormattable>
diff --git a/server/core/types/models/video/video.ts b/server/core/types/models/video/video.ts
index 41436aad40..2365e16e92 100644
--- a/server/core/types/models/video/video.ts
+++ b/server/core/types/models/video/video.ts
@@ -66,7 +66,7 @@ export type MVideo = Omit<
export type MVideoId = Pick<MVideo, 'id'>
export type MVideoUrl = Pick<MVideo, 'url'>
export type MVideoUUID = Pick<MVideo, 'uuid'>
-export type MVideoPrivacy = Pick<MVideo, 'privacy' | 'uuid'>
+export type MVideoPrivacy = Pick<MVideo, 'privacy' | 'uuid' | 'hasPrivateStaticPath'>
export type MVideoImmutable = Pick<MVideo, 'id' | 'url' | 'uuid' | 'remote' | 'isLocal'>
export type MVideoOwned = Pick<MVideo, 'remote' | 'isLocal'>
diff --git a/server/core/types/plugins/register-server-option.model.ts b/server/core/types/plugins/register-server-option.model.ts
index 536dedddcc..ac4dd4096b 100644
--- a/server/core/types/plugins/register-server-option.model.ts
+++ b/server/core/types/plugins/register-server-option.model.ts
@@ -13,7 +13,6 @@ import {
RegisterServerHookOptions,
RegisterServerSettingOptions,
ServerConfig,
- ThumbnailType_Type,
VideoBlacklistCreate
} from '@peertube/peertube-models'
import { ActorModel } from '@server/models/actor/actor.js'
@@ -63,7 +62,11 @@ export type PeerTubeHelpers = {
}
thumbnails: {
- type: ThumbnailType_Type
+ // 1 = Thumbnail, 2 = Preview (deprecated, use width/height instead)
+ type: 1 | 2
+
+ height: number
+ width: number
path: string
}[]
}>
diff --git a/server/scripts/house-keeping.ts b/server/scripts/house-keeping.ts
index 439d292c09..16d5430ba3 100644
--- a/server/scripts/house-keeping.ts
+++ b/server/scripts/house-keeping.ts
@@ -1,7 +1,9 @@
import { createCommand } from '@commander-js/extra-typings'
import { initDatabaseModels } from '@server/initializers/database.js'
import { ActorImageModel } from '@server/models/actor/actor-image.js'
+import { StoryboardModel } from '@server/models/video/storyboard.js'
import { ThumbnailModel } from '@server/models/video/thumbnail.js'
+import { VideoCaptionModel } from '@server/models/video/video-caption.js'
import Bluebird from 'bluebird'
import { askConfirmation, displayPeerTubeMustBeStoppedWarning } from './shared/common.js'
@@ -37,22 +39,28 @@ async function run () {
async function deleteRemoteFiles () {
console.log('Detecting remote files that can be deleted...')
- const thumbnails = await ThumbnailModel.listRemoteOnDisk()
- const actorImages = await ActorImageModel.listRemoteOnDisk()
+ const thumbnails = await ThumbnailModel.listRemoteCached()
+ const actorImages = await ActorImageModel.listRemoteCached()
+ const captions = await VideoCaptionModel.listRemoteCached()
+ const storyboards = await StoryboardModel.listRemoteCached()
- if (thumbnails.length === 0 && actorImages.length === 0) {
+ if (thumbnails.length === 0 && actorImages.length === 0 && captions.length === 0 && storyboards.length === 0) {
console.log('No remote files to delete detected.')
process.exit(0)
}
const res = await askConfirmation(
- `${thumbnails.length.toLocaleString()} thumbnails and ${actorImages.length.toLocaleString()} avatars/banners can be locally deleted. ` +
- `PeerTube will download them again on-demand. ` +
- `Do you want to delete these remote files?`
+ `${thumbnails.length.toLocaleString()} thumbnails, ` +
+ `${actorImages.length.toLocaleString()} avatars/banners, ` +
+ `${captions.length.toLocaleString()} captions and ` +
+ `${storyboards.length.toLocaleString()} storyboards ` +
+ `can be locally deleted. ` +
+ `PeerTube will download them again on-demand. ` +
+ `Do you want to delete these remote files?`
)
if (res !== true) {
- console.log('Exiting without delete remote files.')
+ console.log('Exiting without deleting remote files.')
process.exit(0)
}
@@ -61,14 +69,9 @@ async function deleteRemoteFiles () {
console.log('Deleting remote thumbnails...')
await Bluebird.map(thumbnails, async thumbnail => {
- if (!thumbnail.fileUrl) {
- console.log(`Skipping thumbnail removal of ${thumbnail.getPath()} as we don't have its remote file URL in the database.`)
- return
- }
+ await thumbnail.removeFile()
- await thumbnail.removeThumbnail()
-
- thumbnail.onDisk = false
+ thumbnail.cached = false
await thumbnail.save()
}, { concurrency: 20 })
@@ -77,16 +80,37 @@ async function deleteRemoteFiles () {
console.log('Deleting remote avatars/banners...')
await Bluebird.map(actorImages, async actorImage => {
- if (!actorImage.fileUrl) {
- console.log(`Skipping avatar/banner removal of ${actorImage.getPath()} as we don't have its remote file URL in the database.`)
- return
- }
-
- await actorImage.removeImage()
+ await actorImage.removeFile()
- actorImage.onDisk = false
+ actorImage.cached = false
await actorImage.save()
}, { concurrency: 20 })
console.log('Remote files deleted!')
+
+ // ---------------------------------------------------------------------------
+
+ console.log('Deleting remote captions...')
+
+ await Bluebird.map(captions, async caption => {
+ await caption.removeCaptionFile()
+
+ caption.cached = false
+ await caption.save()
+ }, { concurrency: 20 })
+
+ console.log('Remote caption files deleted!')
+
+ // ---------------------------------------------------------------------------
+
+ console.log('Deleting remote storyboards...')
+
+ await Bluebird.map(storyboards, async storyboard => {
+ await storyboard.removeFile()
+
+ storyboard.cached = false
+ await storyboard.save()
+ }, { concurrency: 20 })
+
+ console.log('Remote storyboard files deleted!')
}
diff --git a/server/scripts/migrations/peertube-4.2.ts b/server/scripts/migrations/peertube-4.2.ts
index 9fddaa0f4d..163ae3b3ab 100644
--- a/server/scripts/migrations/peertube-4.2.ts
+++ b/server/scripts/migrations/peertube-4.2.ts
@@ -115,7 +115,7 @@ async function generateSmallerAvatar (actor: MActorDefault) {
fileUrl: null,
height: imageSize.height,
width: imageSize.width,
- onDisk: true
+ cached: false
}
await updateActorImages(actor, ActorImageType.AVATAR, [ actorImageInfo ], undefined)
diff --git a/server/scripts/migrations/peertube-8.1.ts b/server/scripts/migrations/peertube-8.1.ts
new file mode 100644
index 0000000000..a682ee647f
--- /dev/null
+++ b/server/scripts/migrations/peertube-8.1.ts
@@ -0,0 +1,164 @@
+import { CONFIG } from '@server/initializers/config.js'
+import { sequelizeTypescript } from '@server/initializers/database.js'
+import Bluebird from 'bluebird'
+import { move } from 'fs-extra'
+import { readdir } from 'fs/promises'
+import { join } from 'path'
+
+run()
+ .then(() => process.exit(0))
+ .catch(err => {
+ console.error(err)
+ process.exit(-1)
+ })
+
+async function run () {
+ try {
+ await movePreviewsToThumbnails()
+ } catch (err) {
+ console.error('An error occurred while moving preview files to thumbnail directory:', err)
+ }
+
+ try {
+ await removeInvalidRemoteCaptions()
+ } catch (err) {
+ console.error('An error occurred while removing invalid remote captions:', err)
+ }
+
+ try {
+ await deleteInvalidRemoteAvatars()
+ } catch (err) {
+ console.error('An error occurred while deleting invalid remote avatars:', err)
+ }
+
+ try {
+ await updateLocalVideoFileUrls()
+ } catch (err) {
+ console.error('An error occurred while updating local video file URLs:', err)
+ }
+
+ try {
+ await updateLocalVideoStreamingPlaylistUrls()
+ } catch (err) {
+ console.error('An error occurred while updating local video streaming playlist URLs:', err)
+ }
+
+ try {
+ await updateLocalVideoCaptionUrls()
+ } catch (err) {
+ console.error('An error occurred while updating local video caption URLs:', err)
+ }
+}
+
+async function movePreviewsToThumbnails () {
+ const thumbnailDir = CONFIG.STORAGE.THUMBNAILS_DIR
+ const previewDir = CONFIG.STORAGE.PREVIEWS_DIR
+
+ const toMove = await readdir(previewDir)
+
+ console.log(`Moving ${toMove.length} files from ${previewDir} directory to ${thumbnailDir} directory...`)
+
+ await Bluebird.map(toMove, async previewFilename => {
+ try {
+ await move(join(previewDir, previewFilename), join(thumbnailDir, previewFilename), { overwrite: true })
+ } catch (err) {
+ console.error(`Failed to move file ${previewFilename} from ${previewDir} to ${thumbnailDir}:`, err)
+ }
+ }, { concurrency: 10 })
+
+ console.log('Done!')
+}
+
+async function removeInvalidRemoteCaptions () {
+ console.log('Removing invalid remote captions...')
+
+ await sequelizeTypescript.query(
+ `DELETE FROM "videoCaption" WHERE id IN (` +
+ `SELECT id FROM "videoCaption" INNER JOIN video ON video.id = "videoCaption"."videoId" ` +
+ `WHERE "videoCaption"."fileUrl" IS NULL AND video.remote IS TRUE` +
+ `)`
+ )
+
+ console.log('Invalid remote captions removed.')
+}
+
+async function deleteInvalidRemoteAvatars () {
+ console.log('Removing invalid remote avatars...')
+
+ await sequelizeTypescript.query(
+ `DELETE FROM "actorImage" WHERE id IN (` +
+ `SELECT "actorImage".id FROM "actorImage" ` +
+ `INNER JOIN actor ON actor.id = "actorImage"."actorId" ` +
+ `WHERE actor."serverId" IS NOT NULL AND "actorImage"."fileUrl" IS NULL` +
+ `)`
+ )
+
+ console.log('Invalid remote avatars removed.')
+}
+
+async function updateLocalVideoFileUrls () {
+ console.log('Updating local video file URLs...')
+
+ await sequelizeTypescript.query(
+ `UPDATE "videoFile" SET "fileUrl" = NULL WHERE "id" IN (` +
+ `SELECT id FROM "videoFile" ` +
+ `INNER JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist".id = "videoFile"."videoStreamingPlaylistId" ` +
+ `INNER JOIN video ON video.id = "videoStreamingPlaylist"."videoId" ` +
+ `WHERE "videoFile"."fileUrl" IS NOT NULL AND video.remote IS FALSE` +
+ `)`
+ )
+
+ await sequelizeTypescript.query(
+ `UPDATE "videoFile" SET "fileUrl" = NULL WHERE "id" IN (` +
+ `SELECT id FROM "videoFile" ` +
+ `INNER JOIN video ON video.id = "videoFile"."videoId" ` +
+ `WHERE "videoFile"."fileUrl" IS NOT NULL AND video.remote IS FALSE` +
+ `)`
+ )
+
+ console.log('Local video file URLs updated.')
+}
+
+async function updateLocalVideoCaptionUrls () {
+ console.log('Updating local video caption URLs...')
+
+ await sequelizeTypescript.query(
+ `UPDATE "videoCaption" SET "fileUrl" = NULL WHERE "id" IN (` +
+ `SELECT id FROM "videoCaption" ` +
+ `INNER JOIN video ON video.id = "videoCaption"."videoId" ` +
+ `WHERE "videoCaption"."fileUrl" IS NOT NULL AND video.remote IS FALSE` +
+ `)`
+ )
+
+ await sequelizeTypescript.query(
+ `UPDATE "videoCaption" SET "m3u8Url" = NULL WHERE "id" IN (` +
+ `SELECT id FROM "videoCaption" ` +
+ `INNER JOIN video ON video.id = "videoCaption"."videoId" ` +
+ `WHERE "videoCaption"."m3u8Url" IS NOT NULL AND video.remote IS FALSE` +
+ `)`
+ )
+
+ console.log('Local video caption URLs updated.')
+}
+
+async function updateLocalVideoStreamingPlaylistUrls () {
+ console.log('Updating local video streaming playlist URLs...')
+
+ await sequelizeTypescript.query(
+ `UPDATE "videoStreamingPlaylist" SET "playlistUrl" = NULL WHERE "id" IN (` +
+ `SELECT id FROM "videoStreamingPlaylist" ` +
+ `INNER JOIN video ON video.id = "videoStreamingPlaylist"."videoId" ` +
+ `WHERE "videoStreamingPlaylist"."playlistUrl" IS NOT NULL AND video.remote IS FALSE` +
+ `)`
+ )
+
+ await sequelizeTypescript.query(
+ `UPDATE "videoStreamingPlaylist" SET "segmentsSha256Url" = NULL WHERE "id" IN (` +
+ `SELECT id FROM "videoStreamingPlaylist" ` +
+ `INNER JOIN video ON video.id = "videoStreamingPlaylist"."videoId" ` +
+ `WHERE "videoStreamingPlaylist"."segmentsSha256Url" IS NOT NULL AND video.remote IS FALSE` +
+ `)`
+ )
+
+ console.log('Local video streaming playlist URLs updated.')
+}
diff --git a/server/scripts/prune-storage.ts b/server/scripts/prune-storage.ts
index 256e9def45..6109f98c18 100755
--- a/server/scripts/prune-storage.ts
+++ b/server/scripts/prune-storage.ts
@@ -1,8 +1,8 @@
import { createCommand } from '@commander-js/extra-typings'
import { uniqify } from '@peertube/peertube-core-utils'
-import { FileStorage, ThumbnailType, ThumbnailType_Type } from '@peertube/peertube-models'
+import { FileStorage } from '@peertube/peertube-models'
import { DIRECTORIES, USER_EXPORT_FILE_PREFIX } from '@server/initializers/constants.js'
-import { listKeysOfPrefix, removeObjectByFullKey } from '@server/lib/object-storage/object-storage-helpers.js'
+import { BucketInfo, listKeysOfPrefix, removeObjectByFullKey } from '@server/lib/object-storage/object-storage-helpers.js'
import { UserExportModel } from '@server/models/user/user-export.js'
import { StoryboardModel } from '@server/models/video/storyboard.js'
import { VideoCaptionModel } from '@server/models/video/video-caption.js'
@@ -90,7 +90,7 @@ class ObjectStoragePruner {
}
private async findFilesToDelete (
- config: { BUCKET_NAME: string, PREFIX?: string },
+ config: BucketInfo,
existFun: (file: string) => Promise<boolean> | boolean
) {
try {
@@ -187,8 +187,7 @@ class FSPruner {
await this.findFilesToDelete(CONFIG.STORAGE.REDUNDANCY_DIR, this.doesRedundancyExistFactory())
- await this.findFilesToDelete(CONFIG.STORAGE.PREVIEWS_DIR, this.doesThumbnailExistFactory(true, ThumbnailType.PREVIEW))
- await this.findFilesToDelete(CONFIG.STORAGE.THUMBNAILS_DIR, this.doesThumbnailExistFactory(false, ThumbnailType.MINIATURE))
+ await this.findFilesToDelete(CONFIG.STORAGE.THUMBNAILS_DIR, this.doesThumbnailExistFactory())
await this.findFilesToDelete(CONFIG.STORAGE.CAPTIONS_DIR, this.doesCaptionExistFactory())
@@ -264,15 +263,11 @@ class FSPruner {
return (filePath: string) => VideoFileModel.doesOwnedTorrentFileExist(basename(filePath))
}
- private doesThumbnailExistFactory (keepOnlyOwned: boolean, type: ThumbnailType_Type) {
+ private doesThumbnailExistFactory () {
return async (filePath: string) => {
- const thumbnail = await ThumbnailModel.loadByFilename(basename(filePath), type)
+ const thumbnail = await ThumbnailModel.loadByFilename(basename(filePath))
if (!thumbnail) return false
-
- if (keepOnlyOwned) {
- const video = await VideoModel.load(thumbnail.videoId)
- if (video.isLocal() === false) return false
- }
+ if (thumbnail.isLocal() === false) return false
return true
}
@@ -281,22 +276,28 @@ class FSPruner {
private doesActorImageExistFactory () {
return async (filePath: string) => {
const image = await ActorImageModel.loadByFilename(basename(filePath))
+ if (!image) return false
+ if (image.isLocal() === false) return false
- return !!image
+ return true
}
}
private doesStoryboardExistFactory () {
return async (filePath: string) => {
const storyboard = await StoryboardModel.loadByFilename(basename(filePath))
+ if (!storyboard) return false
+ if (storyboard.isLocal() === false) return false
- return !!storyboard
+ return true
}
}
private doesCaptionExistFactory () {
return async (filePath: string) => {
- const caption = await VideoCaptionModel.loadWithVideoByFilename(basename(filePath))
+ const caption = await VideoCaptionModel.loadByFilename(basename(filePath))
+ if (!caption) return false
+ if (caption.isLocal() === false) return false
return !!caption
}
@@ -330,7 +331,8 @@ class FSPruner {
return (filePath: string) => {
const filename = basename(filePath)
- // Only detect non-existing user export
+ // Only detect user exports, since we're in the persistent tmp directory
+ // We don't want to delete other files that could be in this directory for other reasons
if (!filename.startsWith(USER_EXPORT_FILE_PREFIX)) return true
return UserExportModel.doesOwnedFileExist(filename, FileStorage.FILE_SYSTEM)
diff --git a/server/scripts/regenerate-thumbnails.ts b/server/scripts/regenerate-thumbnails.ts
index d4346ce400..17ae455f88 100644
--- a/server/scripts/regenerate-thumbnails.ts
+++ b/server/scripts/regenerate-thumbnails.ts
@@ -1,10 +1,11 @@
-import Bluebird from 'bluebird'
-import { program } from 'commander'
-import { pathExists, remove } from 'fs-extra/esm'
import { generateImageFilename, processImage } from '@server/helpers/image-utils.js'
-import { THUMBNAILS_SIZE } from '@server/initializers/constants.js'
+import { CONFIG } from '@server/initializers/config.js'
import { initDatabaseModels } from '@server/initializers/database.js'
+import { ThumbnailModel } from '@server/models/video/thumbnail.js'
import { VideoModel } from '@server/models/video/video.js'
+import Bluebird from 'bluebird'
+import { program } from 'commander'
+import { pathExists } from 'fs-extra/esm'
program
.description('Regenerate local thumbnails using preview files')
@@ -30,35 +31,41 @@ async function processVideo (id: number) {
console.log('Processing video %s.', video.name)
- const thumbnail = video.getMiniature()
- const preview = video.getPreview()
-
- const previewPath = preview.getPath()
+ const bestImage = video.getBestThumbnail()
- if (!await pathExists(previewPath)) {
- throw new Error(`Preview ${previewPath} does not exist on disk`)
+ if (!await pathExists(bestImage.getFSPath())) {
+ throw new Error(`Thumbnail ${bestImage.getFSPath()} does not exist on disk`)
}
- const size = {
- width: THUMBNAILS_SIZE.width,
- height: THUMBNAILS_SIZE.height
+ const oldThumbnails = [ ...video.Thumbnails ]
+
+ const thumbnails = await Bluebird.mapSeries(CONFIG.THUMBNAILS.SIZES, async size => {
+ const thumbnail = new ThumbnailModel({
+ filename: generateImageFilename(),
+ height: size.height,
+ width: size.width,
+ fileUrl: null,
+ automaticallyGenerated: bestImage.automaticallyGenerated,
+ cached: false
+ })
+
+ await processImage({
+ path: bestImage.getFSPath(),
+ destination: thumbnail.getFSPath(),
+ newSize: size,
+ keepOriginal: true
+ })
+
+ return thumbnail
+ })
+
+ await video.replaceAndSaveThumbnails(thumbnails)
+
+ for (const oldThumbnail of oldThumbnails) {
+ // Explicitly remove the file
+ // We have a destroy hook but it's async, so ensure we wait for it to be done before ending the script
+ await oldThumbnail.removeFile()
}
- const oldPath = thumbnail.getPath()
-
- // Update thumbnail
- thumbnail.filename = generateImageFilename()
- thumbnail.width = size.width
- thumbnail.height = size.height
-
- const thumbnailPath = thumbnail.getPath()
- await processImage({ path: previewPath, destination: thumbnailPath, newSize: size, keepOriginal: true })
-
- // Save new attributes
- await thumbnail.save()
-
- // Remove old thumbnail
- await remove(oldPath)
-
// Don't federate, remote instances will refresh the thumbnails after a while
}
diff --git a/server/scripts/update-object-storage-url.ts b/server/scripts/update-object-storage-url.ts
deleted file mode 100644
index b85075d782..0000000000
--- a/server/scripts/update-object-storage-url.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/* eslint-disable max-len */
-import { InvalidArgumentError, createCommand } from '@commander-js/extra-typings'
-import { FileStorage } from '@peertube/peertube-models'
-import { escapeForRegex } from '@server/helpers/regexp.js'
-import { initDatabaseModels, sequelizeTypescript } from '@server/initializers/database.js'
-import { QueryTypes } from 'sequelize'
-import { askConfirmation, displayPeerTubeMustBeStoppedWarning } from './shared/common.js'
-
-const program = createCommand()
- .description('Update PeerTube object file URLs after an object storage migration.')
- .requiredOption('-f, --from <url>', 'Previous object storage base URL', parseUrl)
- .requiredOption('-t, --to <url>', 'New object storage base URL', parseUrl)
- .parse(process.argv)
-
-const options = program.opts()
-
-run()
- .then(() => process.exit(0))
- .catch(err => {
- console.error(err)
- process.exit(-1)
- })
-
-async function run () {
- await initDatabaseModels(true)
-
- displayPeerTubeMustBeStoppedWarning()
-
- const fromRegexp = `^${escapeForRegex(options.from)}`
- const to = options.to
-
- const replacements = { fromRegexp, to, storage: FileStorage.OBJECT_STORAGE }
-
- // Candidates
- {
- const queries = [
- `SELECT COUNT(*) AS "c", 'videoFile->fileUrl: ' || COUNT(*) AS "t" FROM "videoFile" WHERE "fileUrl" ~ :fromRegexp AND "storage" = :storage`,
- `SELECT COUNT(*) AS "c", 'videoStreamingPlaylist->playlistUrl: ' || COUNT(*) AS "t" FROM "videoStreamingPlaylist" WHERE "playlistUrl" ~ :fromRegexp AND "storage" = :storage`,
- `SELECT COUNT(*) AS "c", 'videoStreamingPlaylist->segmentsSha256Url: ' || COUNT(*) AS "t" FROM "videoStreamingPlaylist" WHERE "segmentsSha256Url" ~ :fromRegexp AND "storage" = :storage`,
- `SELECT COUNT(*) AS "c", 'userExport->fileUrl: ' || COUNT(*) AS "t" FROM "userExport" WHERE "fileUrl" ~ :fromRegexp AND "storage" = :storage`,
- `SELECT COUNT(*) AS "c", 'videoSource->fileUrl: ' || COUNT(*) AS "t" FROM "videoSource" WHERE "fileUrl" ~ :fromRegexp AND "storage" = :storage`,
- `SELECT COUNT(*) AS "c", 'videoCaption->fileUrl: ' || COUNT(*) AS "t" FROM "videoCaption" WHERE "fileUrl" ~ :fromRegexp AND "storage" = :storage`
- ]
-
- let hasResults = false
-
- console.log('Candidate URLs to update:')
- for (const query of queries) {
- const [ row ] = await sequelizeTypescript.query(query, { replacements, type: QueryTypes.SELECT as QueryTypes.SELECT })
-
- if (row['c'] !== 0) hasResults = true
-
- console.log(` ${row['t']}`)
- }
-
- console.log('\n')
-
- if (!hasResults) {
- console.log('No candidate URLs found, exiting.')
- process.exit(0)
- }
- }
-
- const res = await askUpdateConfirmation()
- if (res !== true) {
- console.log('Exiting without updating URLs.')
- process.exit(0)
- }
-
- // Execute
- {
- const queries = [
- `UPDATE "videoFile" SET "fileUrl" = regexp_replace("fileUrl", :fromRegexp, :to) WHERE "storage" = :storage`,
- `UPDATE "videoStreamingPlaylist" SET "playlistUrl" = regexp_replace("playlistUrl", :fromRegexp, :to) WHERE "storage" = :storage`,
- `UPDATE "videoStreamingPlaylist" SET "segmentsSha256Url" = regexp_replace("segmentsSha256Url", :fromRegexp, :to) WHERE "storage" = :storage`,
- `UPDATE "userExport" SET "fileUrl" = regexp_replace("fileUrl", :fromRegexp, :to) WHERE "storage" = :storage`,
- `UPDATE "videoSource" SET "fileUrl" = regexp_replace("fileUrl", :fromRegexp, :to) WHERE "storage" = :storage`,
- `UPDATE "videoCaption" SET "fileUrl" = regexp_replace("fileUrl", :fromRegexp, :to) WHERE "storage" = :storage`
- ]
-
- for (const query of queries) {
- await sequelizeTypescript.query(query, { replacements })
- }
-
- console.log('URLs updated.')
- }
-}
-
-function parseUrl (value: string) {
- if (!value || /^https?:\/\//.test(value) !== true) {
- throw new InvalidArgumentError('Must be a valid URL (starting with http:// or https://).')
- }
-
- return value
-}
-
-async function askUpdateConfirmation () {
- return askConfirmation(
- 'These URLs can be updated, but please check your backups first (bugs happen). ' +
- 'Can we update these URLs?'
- )
-}
diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yaml
index d343e58523..3e9278177b 100644
--- a/support/doc/api/openapi.yaml
+++ b/support/doc/api/openapi.yaml
@@ -3130,7 +3130,8 @@ paths:
type: string
format: binary
previewfile:
- description: Video preview file
+ description: Deprecated in PeerTube v8.1, use thumbnailfile instead
+ deprecated: true
type: string
format: binary
category:
@@ -3724,7 +3725,8 @@ paths:
type: string
format: binary
previewfile:
- description: Live video/replay preview file
+ description: Deprecated in PeerTube v8.1, use thumbnailfile instead
+ deprecated: true
type: string
format: binary
privacy:
@@ -8898,6 +8900,14 @@ components:
nullable: true
allOf:
- $ref: '#/components/schemas/Video'
+ Thumbnail:
+ properties:
+ fileUrl:
+ type: string
+ width:
+ type: integer
+ height:
+ type: integer
VideoFile:
properties:
id:
@@ -9088,11 +9098,17 @@ components:
minLength: 3
maxLength: 120
thumbnailPath:
+ description: Deprecated in PeerTube v8.1, use thumbnails instead
+ deprecated: true
type: string
- example: /lazy-static/thumbnails/a65bc12f-9383-462e-81ae-8207e8b434ee.jpg
previewPath:
+ description: Deprecated in PeerTube v8.1, use thumbnails instead
+ deprecated: true
type: string
- example: /lazy-static/previews/a65bc12f-9383-462e-81ae-8207e8b434ee.jpg
+ thumbnails:
+ type: array
+ items:
+ $ref: '#/components/schemas/Thumbnail'
embedPath:
type: string
example: /videos/embed/a65bc12f-9383-462e-81ae-8207e8b434ee
@@ -9423,7 +9439,13 @@ components:
blacklisted:
type: boolean
thumbnailPath:
+ description: Deprecated in PeerTube v8.1, use thumbnails instead
+ deprecated: true
type: string
+ thumbnails:
+ type: array
+ items:
+ $ref: '#/components/schemas/Thumbnail'
channel:
$ref: '#/components/schemas/VideoChannel'
createdAt:
@@ -9505,7 +9527,13 @@ components:
type: integer
minimum: 0
thumbnailPath:
+ description: Deprecated in PeerTube v8.1, use thumbnails instead
+ deprecated: true
type: string
+ thumbnails:
+ type: array
+ items:
+ $ref: '#/components/schemas/Thumbnail'
privacy:
$ref: '#/components/schemas/VideoPlaylistPrivacyConstant'
type:
@@ -10787,7 +10815,8 @@ components:
type: string
format: binary
previewfile:
- description: Video preview file
+ description: Deprecated in PeerTube v8.1, use thumbnailfile instead
+ deprecated: true
type: string
format: binary
videoPasswords:
@@ -10823,7 +10852,8 @@ components:
type: string
format: binary
previewfile:
- description: Video preview file
+ description: Deprecated in PeerTube v8.1, use thumbnailfile instead
+ deprecated: true
type: string
format: binary
VideoUploadResponse:
diff --git a/support/doc/development/tests.md b/support/doc/development/tests.md
index 10cdea4b9f..81eb0cf602 100644
--- a/support/doc/development/tests.md
+++ b/support/doc/development/tests.md
@@ -80,6 +80,7 @@ Some env variables can be defined to disable/enable some tests:
* `OBJECT_STORAGE_SCALEWAY_KEY_ID` and `OBJECT_STORAGE_SCALEWAY_ACCESS_KEY`: specify Scaleway API keys to test object storage ACL (not supported by our `chocobozzz/s3-ninja` container)
* `YOUTUBE_DL_DOWNLOAD_BEARER_TOKEN`: bearer token to download youtube-dl binary
* `YOUTUBE_DL_PROXY`: custom proxy URL for youtube-dl HTTP video import
+ * `AUTO_UPDATE_IMAGES`: if we change image processing algorithm/quality/codecs, automatically update the image on failure
### Debug server logs
diff --git a/support/doc/tools.md b/support/doc/tools.md
index 454a3c47da..1c9b1b5bd5 100644
--- a/support/doc/tools.md
+++ b/support/doc/tools.md
@@ -598,26 +598,6 @@ cd /var/www/peertube-docker; \
:::
-### Update object storage URLs
-
-**PeerTube >= 6.2**
-
-Use this script after you migrated to another object storage provider so PeerTube updates its internal object URLs (a confirmation will be demanded first). Restart PeerTube after running the script.
-
-::: code-group
-
-```bash [Classic installation]
-cd /var/www/peertube/peertube-latest; \
- sudo -u peertube NODE_CONFIG_DIR=/var/www/peertube/config NODE_ENV=production npm run update-object-storage-url -- --from 'https://region.old-s3-provider.example.com' --to 'https://region.new-s3-provider.example.com'
-```
-
-```bash [Docker]
-cd /var/www/peertube-docker; \
- docker compose exec -u peertube peertube npm run update-object-storage-url -- --from 'https://region.old-s3-provider.example.com' --to 'https://region.new-s3-provider.example.com'
-```
-
-:::
-
### Cleanup remote files
**PeerTube >= 6.2**