Skip to content

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

Don't notify again when a video is re-published

Chocobozzzdbf1da63e112
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 55c854eb3e..ff1ceaaba7 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
@@ -18,6 +18,7 @@ export interface VideoExportJSON {
updatedAt: string
publishedAt: string
originallyPublishedAt: string
+ firstPublishedAt: string
name: string
category: number
diff --git a/packages/tests/src/api/notifications/user-notifications.ts b/packages/tests/src/api/notifications/user-notifications.ts
index e30a298916..d1fd8a83bb 100644
--- a/packages/tests/src/api/notifications/user-notifications.ts
+++ b/packages/tests/src/api/notifications/user-notifications.ts
@@ -148,11 +148,12 @@ describe('Test user notifications', function () {
await checkNewVideoFromSubscription({ ...baseParams, videoName: name, shortUUID, checkType: 'absence' })
})
- it('Should send a new video notification when a video becomes public', async function () {
+ it('Should send a new video notification when a video becomes public for the first time', async function () {
this.timeout(50000)
for (const privacy of [ VideoPrivacy.PUBLIC, VideoPrivacy.INTERNAL ]) {
const { name, uuid, shortUUID } = await uploadRandomVideoOnServers(servers, 1, { privacy: VideoPrivacy.PRIVATE })
+ await waitJobs(servers)
await checkNewVideoFromSubscription({ ...baseParams, videoName: name, shortUUID, checkType: 'absence' })
@@ -160,14 +161,26 @@ describe('Test user notifications', function () {
await waitJobs(servers)
await checkNewVideoFromSubscription({ ...baseParams, videoName: name, shortUUID, checkType: 'presence' })
+
+ const beforeAnotherUpdate = new Date()
+ await servers[0].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.PRIVATE } })
+ await servers[0].videos.update({ id: uuid, attributes: { privacy } })
+ await waitJobs(servers)
+
+ const { data: notifications } = await servers[0].notifications.list({
+ token: userAccessToken,
+ typeOneOf: [ UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION ]
+ })
+ expect(notifications.filter(n => new Date(n.createdAt) > beforeAnotherUpdate)).to.have.lengthOf(0)
}
})
- it('Should send a new video notification when a remote video becomes public', async function () {
+ it('Should send a new video notification when a remote video becomes public for the first time', async function () {
this.timeout(120000)
const data = { privacy: VideoPrivacy.PRIVATE }
const { name, uuid, shortUUID } = await uploadRandomVideoOnServers(servers, 2, data)
+ await waitJobs(servers)
await checkNewVideoFromSubscription({ ...baseParams, videoName: name, shortUUID, checkType: 'absence' })
@@ -175,6 +188,17 @@ describe('Test user notifications', function () {
await waitJobs(servers)
await checkNewVideoFromSubscription({ ...baseParams, videoName: name, shortUUID, checkType: 'presence' })
+
+ const beforeAnotherUpdate = new Date()
+ await servers[1].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.PRIVATE } })
+ await servers[1].videos.update({ id: uuid, attributes: { privacy: VideoPrivacy.PUBLIC } })
+ await waitJobs(servers)
+
+ const { data: notifications } = await servers[0].notifications.list({
+ token: userAccessToken,
+ typeOneOf: [ UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION ]
+ })
+ expect(notifications.filter(n => new Date(n.createdAt) > beforeAnotherUpdate)).to.have.lengthOf(0)
})
it('Should not send a new video notification when a video becomes unlisted', async function () {
diff --git a/packages/tests/src/api/users/user-import.ts b/packages/tests/src/api/users/user-import.ts
index d9f06b4004..d5f84fc5ab 100644
--- a/packages/tests/src/api/users/user-import.ts
+++ b/packages/tests/src/api/users/user-import.ts
@@ -19,6 +19,7 @@ import { ObjectStorageCommand, PeerTubeServer, cleanupTests, waitJobs } from '@p
import { testAvatarSize, testImage } from '@tests/shared/checks.js'
import { prepareImportExportTests } from '@tests/shared/import-export.js'
import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'
+import { SQLCommand } from '@tests/shared/sql-command.js'
import { completeCheckHlsPlaylist } from '@tests/shared/streaming-playlists.js'
import { completeVideoCheck } from '@tests/shared/videos.js'
import { expect } from 'chai'
@@ -486,6 +487,15 @@ function runTest (withObjectStorage: boolean) {
})
}
+ // Imported video should preserve firstPublishedAt from the original
+ {
+ const sqlCommand = new SQLCommand(remoteServer)
+ const firstPublishedAt = await sqlCommand.getVideoField(otherVideo.uuid, 'firstPublishedAt')
+ expect(firstPublishedAt).to.exist
+
+ await sqlCommand.cleanup()
+ }
+
const { data: captions } = await remoteServer.captions.list({ videoId: otherVideo.uuid })
await completeCheckHlsPlaylist({
diff --git a/packages/tests/src/shared/sql-command.ts b/packages/tests/src/shared/sql-command.ts
index 54d4ed27e0..067371b620 100644
--- a/packages/tests/src/shared/sql-command.ts
+++ b/packages/tests/src/shared/sql-command.ts
@@ -24,6 +24,15 @@ export class SQLCommand {
return parseInt(total, 10)
}
+ async getVideoField (uuid: string, field: string) {
+ const rows = await this.selectQuery<{ value: any }>(
+ `SELECT ${this.escapeColumnName(field)} AS value FROM "video" WHERE uuid = :uuid`,
+ { uuid }
+ )
+
+ return rows[0]?.value
+ }
+
async getInternalFileUrl (fileId: number) {
return this.selectQuery<{ fileUrl: string }>(`SELECT "fileUrl" FROM "videoFile" WHERE id = :fileId`, { fileId })
.then(rows => rows[0].fileUrl)
diff --git a/server/core/controllers/api/videos/update.ts b/server/core/controllers/api/videos/update.ts
index f73e89dc42..a844efbe3a 100644
--- a/server/core/controllers/api/videos/update.ts
+++ b/server/core/controllers/api/videos/update.ts
@@ -11,14 +11,14 @@ 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 { isNewVideoForFederation, 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 { createLocalVideoThumbnailsFromImage } from '@server/lib/thumbnail.js'
import { replaceChaptersFromDescriptionIfNeeded } from '@server/lib/video-chapters.js'
-import { addVideoJobsAfterUpdate } from '@server/lib/video-jobs.js'
+import { onVideoLocalUpdate } from '@server/lib/video-jobs.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
-import { setVideoPrivacy } from '@server/lib/video-privacy.js'
+import { isNewVideoForSubscription, setVideoPrivacy } from '@server/lib/video-privacy.js'
import { setVideoTags } from '@server/lib/video.js'
import { openapiOperationDoc } from '@server/middlewares/doc.js'
import { getServerAccount } from '@server/models/application/application.js'
@@ -76,7 +76,7 @@ async function updateVideo (req: express.Request, res: express.Response) {
const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoFromReq.uuid)
try {
- const { videoInstanceUpdated, isNewVideoForFederation } = await sequelizeTypescript.transaction(async t => {
+ const { videoInstanceUpdated, newVideoForFederation, newVideoForSubscription } = await sequelizeTypescript.transaction(async t => {
// Refresh video since thumbnails to prevent concurrent updates
const video = await VideoModel.loadFull(videoFromReq.id, t)
@@ -118,10 +118,18 @@ async function updateVideo (req: express.Request, res: express.Response) {
}
// Privacy update?
- let isNewVideoForFederation = false
+ let newVideoForFederation = false
+ let newVideoForSubscription = false
if (body.privacy !== undefined) {
- isNewVideoForFederation = await updateVideoPrivacy({
+ newVideoForFederation = isNewVideoForFederation(video.privacy, body.privacy, video.firstPublishedAt)
+ newVideoForSubscription = isNewVideoForSubscription({
+ currentPrivacy: video.privacy,
+ newPrivacy: body.privacy,
+ firstPublishedAt: video.firstPublishedAt
+ })
+
+ await updateVideoPrivacy({
videoInstance: video,
videoInfoToUpdate: body,
hadPrivacyForFederation,
@@ -221,16 +229,17 @@ async function updateVideo (req: express.Request, res: express.Response) {
)
logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
- return { videoInstanceUpdated, isNewVideoForFederation }
+ return { videoInstanceUpdated, newVideoForFederation, newVideoForSubscription }
})
Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
- await addVideoJobsAfterUpdate({
+ await onVideoLocalUpdate({
video: videoInstanceUpdated,
nameChanged: !!body.name,
oldPrivacy,
- isNewVideoForFederation
+ isNewVideoForFederation: newVideoForFederation,
+ isNewVideoForSubscription: newVideoForSubscription
})
} catch (err) {
// If the transaction is retried, sequelize will think the object has not changed
@@ -255,7 +264,6 @@ async function updateVideoPrivacy (options: {
transaction: Transaction
}) {
const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
- const isNewVideoForFederation = isNewVideoPrivacyForFederation(videoInstance.privacy, videoInfoToUpdate.privacy)
const newPrivacy = forceNumber(videoInfoToUpdate.privacy) as VideoPrivacyType
setVideoPrivacy(videoInstance, newPrivacy)
@@ -274,8 +282,6 @@ async function updateVideoPrivacy (options: {
if (hadPrivacyForFederation && !isPrivacyForFederation(videoInstance.privacy)) {
await sendDeleteVideo({ video: videoInstance, deleteForPrivacyChange: true, transaction })
}
-
- return isNewVideoForFederation
}
async function updateSchedule (videoInstance: MVideoFull, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
diff --git a/server/core/helpers/custom-validators/videos.ts b/server/core/helpers/custom-validators/videos.ts
index 8ef369ef84..6ad05672b0 100644
--- a/server/core/helpers/custom-validators/videos.ts
+++ b/server/core/helpers/custom-validators/videos.ts
@@ -124,7 +124,7 @@ export function isScheduleVideoUpdatePrivacyValid (value: number) {
return value === VideoPrivacy.UNLISTED || value === VideoPrivacy.PUBLIC || value === VideoPrivacy.INTERNAL
}
-export function isVideoOriginallyPublishedAtValid (value: string | null) {
+export function isVideoPublicationDateValid (value: string | null) {
return value === null || isDateValid(value)
}
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.ts
index bbbcbfda27..c04a7613ad 100644
--- a/server/core/initializers/constants.ts
+++ b/server/core/initializers/constants.ts
@@ -62,7 +62,7 @@ import { CONFIG, registerConfigChangedHandler } from './config.js'
// ---------------------------------------------------------------------------
-export const LAST_MIGRATION_VERSION = 1065
+export const LAST_MIGRATION_VERSION = 1070
// ---------------------------------------------------------------------------
diff --git a/server/core/initializers/migrations/1070-video-first-published-at.ts b/server/core/initializers/migrations/1070-video-first-published-at.ts
new file mode 100644
index 0000000000..4b9fe361cf
--- /dev/null
+++ b/server/core/initializers/migrations/1070-video-first-published-at.ts
@@ -0,0 +1,28 @@
+import * as Sequelize from 'sequelize'
+
+async function up (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ await utils.queryInterface.addColumn('video', 'firstPublishedAt', {
+ type: Sequelize.DATE,
+ allowNull: true,
+ defaultValue: null
+ }, { transaction: utils.transaction })
+
+ // Backfill firstPublishedAt for videos that have already been published (state = 1 => PUBLISHED)
+ await utils.sequelize.query(
+ `UPDATE "video" SET "firstPublishedAt" = "publishedAt" WHERE "state" = 1 AND "firstPublishedAt" IS NULL`,
+ { transaction: utils.transaction }
+ )
+}
+
+function down (options) {
+ throw new Error('Not implemented.')
+}
+
+export {
+ down,
+ up
+}
diff --git a/server/core/lib/activitypub/videos/federate.ts b/server/core/lib/activitypub/videos/federate.ts
index c366a1dbb2..5a8b370fe4 100644
--- a/server/core/lib/activitypub/videos/federate.ts
+++ b/server/core/lib/activitypub/videos/federate.ts
@@ -39,6 +39,10 @@ export function isNewVideoPrivacyForFederation (currentPrivacy: VideoPrivacyType
return !isPrivacyForFederation(currentPrivacy) && isPrivacyForFederation(newPrivacy)
}
+export function isNewVideoForFederation (currentPrivacy: VideoPrivacyType, newPrivacy: VideoPrivacyType, firstPublishedAt?: Date) {
+ return isNewVideoPrivacyForFederation(currentPrivacy, newPrivacy) && !firstPublishedAt
+}
+
export function isPrivacyForFederation (privacy: VideoPrivacyType) {
const castedPrivacy = forceNumber(privacy)
diff --git a/server/core/lib/live/live-manager.ts b/server/core/lib/live/live-manager.ts
index c19fc45cb6..2f3b6b3d27 100644
--- a/server/core/lib/live/live-manager.ts
+++ b/server/core/lib/live/live-manager.ts
@@ -35,10 +35,10 @@ import { getLiveReplayBaseDirectory } from '../paths.js'
import { PeerTubeSocket } from '../peertube-socket.js'
import { Hooks } from '../plugins/hooks.js'
import { computeResolutionsToTranscode } from '../transcoding/transcoding-resolutions.js'
+import { isUserQuotaValid } from '../user.js'
import { LiveQuotaStore } from './live-quota-store.js'
import { cleanupAndDestroyPermanentLive, getLiveSegmentTime } from './live-utils.js'
import { MuxingSession } from './shared/index.js'
-import { isUserQuotaValid } from '../user.js'
// Disable node media server logs
nodeMediaServerLogger.setLogType(0)
@@ -519,7 +519,11 @@ class LiveManager {
logger.info('Will publish and federate live %s.', video.url, localLTags)
video.state = VideoState.PUBLISHED
- video.publishedAt = new Date()
+
+ const now = new Date()
+ video.publishedAt = now
+ video.firstPublishedAt = video.firstPublishedAt ?? now
+
video.aspectRatio = audioOnlyOutput
? 0
: ratio
diff --git a/server/core/lib/local-video-creator.ts b/server/core/lib/local-video-creator.ts
index 2931a401f2..abc7916e1c 100644
--- a/server/core/lib/local-video-creator.ts
+++ b/server/core/lib/local-video-creator.ts
@@ -47,6 +47,8 @@ type VideoAttributes = Omit<VideoCreate, 'channelId'> & {
state: VideoStateType
inputFilename: string
+ firstPublishedAt?: string
+
embedPrivacyPolicy?: VideoEmbedPrivacyPolicyType
}
@@ -300,6 +302,17 @@ export class LocalVideoCreator {
}
private buildVideo (videoInfo: VideoAttributes, channel: MChannel) {
+ const privacy = videoInfo.privacy || VideoPrivacy.PRIVATE
+
+ const now = new Date()
+
+ let firstPublishedAt: Date = null
+ if (videoInfo.firstPublishedAt) {
+ firstPublishedAt = new Date(videoInfo.firstPublishedAt)
+ } else if (privacy !== VideoPrivacy.PRIVATE) {
+ firstPublishedAt = now
+ }
+
return {
name: videoInfo.name,
state: videoInfo.state,
@@ -319,16 +332,18 @@ export class LocalVideoCreator {
description: videoInfo.description,
support: videoInfo.support,
- privacy: videoInfo.privacy || VideoPrivacy.PRIVATE,
+ privacy,
isLive: videoInfo.isLive,
channelId: channel.id,
originallyPublishedAt: videoInfo.originallyPublishedAt
? new Date(videoInfo.originallyPublishedAt)
: null,
+ firstPublishedAt,
+
publishedAt: this.videoAttributes.scheduleUpdate?.updateAt
? new Date(this.videoAttributes.scheduleUpdate?.updateAt)
- : undefined,
+ : now,
uuid: buildUUID(),
duration: videoInfo.duration
diff --git a/server/core/lib/schedulers/update-videos-scheduler.ts b/server/core/lib/schedulers/update-videos-scheduler.ts
index d35dd96808..ebb336539d 100644
--- a/server/core/lib/schedulers/update-videos-scheduler.ts
+++ b/server/core/lib/schedulers/update-videos-scheduler.ts
@@ -5,11 +5,11 @@ import { logger, loggerTagsFactory } from '../../helpers/logger.js'
import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants.js'
import { sequelizeTypescript } from '../../initializers/database.js'
import { ScheduleVideoUpdateModel } from '../../models/video/schedule-video-update.js'
-import { isNewVideoPrivacyForFederation } from '../activitypub/videos/federate.js'
+import { isNewVideoForFederation } from '../activitypub/videos/federate.js'
import { Notifier } from '../notifier/index.js'
-import { addVideoJobsAfterUpdate } from '../video-jobs.js'
+import { onVideoLocalUpdate } from '../video-jobs.js'
import { VideoPathManager } from '../video-path-manager.js'
-import { setVideoPrivacy } from '../video-privacy.js'
+import { isNewVideoForSubscription, setVideoPrivacy } from '../video-privacy.js'
import { AbstractScheduler } from './abstract-scheduler.js'
const lTags = loggerTagsFactory('schedulers', 'update-videos')
@@ -54,7 +54,8 @@ export class UpdateVideosScheduler extends AbstractScheduler {
private async updateAVideo (schedule: MScheduleVideoUpdate) {
let oldPrivacy: VideoPrivacyType
- let isNewVideoForFederation: boolean
+ let newVideoForFederation = false
+ let newVideoForSubscriptions = false
let published = false
const video = await sequelizeTypescript.transaction(async t => {
@@ -64,7 +65,13 @@ export class UpdateVideosScheduler extends AbstractScheduler {
logger.info('Executing scheduled video update on ' + video.uuid, lTags(video.uuid))
if (schedule.privacy) {
- isNewVideoForFederation = isNewVideoPrivacyForFederation(video.privacy, schedule.privacy)
+ newVideoForFederation = isNewVideoForFederation(video.privacy, schedule.privacy, video.firstPublishedAt)
+ newVideoForSubscriptions = isNewVideoForSubscription({
+ currentPrivacy: video.privacy,
+ newPrivacy: schedule.privacy,
+ firstPublishedAt: video.firstPublishedAt
+ })
+
oldPrivacy = video.privacy
setVideoPrivacy(video, schedule.privacy)
@@ -84,7 +91,13 @@ export class UpdateVideosScheduler extends AbstractScheduler {
return { video, published: false }
}
- await addVideoJobsAfterUpdate({ video, oldPrivacy, isNewVideoForFederation, nameChanged: false })
+ await onVideoLocalUpdate({
+ video,
+ oldPrivacy,
+ isNewVideoForFederation: newVideoForFederation,
+ isNewVideoForSubscription: newVideoForSubscriptions,
+ nameChanged: false
+ })
return { video, published }
}
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 3ac8657645..0d0748077c 100644
--- a/server/core/lib/user-import-export/exporters/videos-exporter.ts
+++ b/server/core/lib/user-import-export/exporters/videos-exporter.ts
@@ -147,6 +147,7 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {
createdAt: video.createdAt.toISOString(),
updatedAt: video.updatedAt.toISOString(),
publishedAt: video.publishedAt.toISOString(),
+ firstPublishedAt: video.firstPublishedAt?.toISOString(),
originallyPublishedAt: video.originallyPublishedAt
? video.originallyPublishedAt.toISOString()
: undefined,
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 025c53097f..02b66a530b 100644
--- a/server/core/lib/user-import-export/importers/videos-importer.ts
+++ b/server/core/lib/user-import-export/importers/videos-importer.ts
@@ -18,8 +18,8 @@ import {
isVideoLanguageValid,
isVideoLicenceValid,
isVideoNameValid,
- isVideoOriginallyPublishedAtValid,
isVideoPrivacyValid,
+ isVideoPublicationDateValid,
isVideoReplayPrivacyValid,
isVideoSourceFilenameValid,
isVideoSupportValid,
@@ -65,6 +65,7 @@ type SanitizedObject = Pick<
| 'downloadEnabled'
| 'videoEmbedPrivacy'
| 'waitTranscoding'
+ | 'firstPublishedAt'
| 'originallyPublishedAt'
| 'tags'
| 'live'
@@ -103,7 +104,8 @@ export class VideosImporter extends AbstractUserImporter<VideoExportJSON, Import
if (!isVideoSourceFilenameValid(o.source?.inputFilename)) o.source = undefined
- if (!isVideoOriginallyPublishedAtValid(o.originallyPublishedAt)) o.originallyPublishedAt = null
+ if (!o.originallyPublishedAt || !isVideoPublicationDateValid(o.originallyPublishedAt)) o.originallyPublishedAt = null
+ if (!o.firstPublishedAt || !isVideoPublicationDateValid(o.firstPublishedAt)) o.firstPublishedAt = null
if (!o.videoEmbedPrivacy) o.videoEmbedPrivacy = { policy: VideoEmbedPrivacyPolicy.ALL_ALLOWED, domains: [] }
if (!isVideoEmbedPrivacyPolicyValid(o.videoEmbedPrivacy.policy)) o.videoEmbedPrivacy.policy = VideoEmbedPrivacyPolicy.ALL_ALLOWED
@@ -166,6 +168,7 @@ export class VideosImporter extends AbstractUserImporter<VideoExportJSON, Import
'downloadEnabled',
'videoEmbedPrivacy',
'waitTranscoding',
+ 'firstPublishedAt',
'originallyPublishedAt',
'tags',
'captions',
@@ -245,7 +248,8 @@ export class VideosImporter extends AbstractUserImporter<VideoExportJSON, Import
'commentsPolicy',
'downloadEnabled',
'waitTranscoding',
- 'originallyPublishedAt'
+ 'originallyPublishedAt',
+ 'firstPublishedAt'
]),
videoPasswords: videoImportData.passwords,
diff --git a/server/core/lib/video-jobs.ts b/server/core/lib/video-jobs.ts
index ace3297cbe..a1ae69a7b5 100644
--- a/server/core/lib/video-jobs.ts
+++ b/server/core/lib/video-jobs.ts
@@ -1,16 +1,12 @@
-import {
- ManageVideoTorrentPayload,
- VideoFileStream,
- VideoPrivacy,
- VideoPrivacyType,
- VideoState,
- VideoStateType
-} from '@peertube/peertube-models'
+import { exists } from '@peertube/peertube-core-utils'
+import { ManageVideoTorrentPayload, VideoFileStream, VideoPrivacyType, VideoState, VideoStateType } from '@peertube/peertube-models'
+import { logger } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
import { VideoModel } from '@server/models/video/video.js'
import { MVideo, MVideoFile, MVideoFull, MVideoUUID } from '@server/types/models/index.js'
import { CreateJobOptions, CreateJobTypeAndPayload, JobQueue } from './job-queue/job-queue.js'
+import { lTags } from './object-storage/shared/index.js'
import { VideoStoryboardJobHandler } from './runners/index.js'
import { createTranscriptionTaskIfNeeded } from './video-captions.js'
import { moveFilesIfPrivacyChanged } from './video-privacy.js'
@@ -170,25 +166,34 @@ export async function addVideoJobsAfterCreation (options: {
}
}
-export async function addVideoJobsAfterUpdate (options: {
+export async function onVideoLocalUpdate (options: {
video: MVideoFull
+
isNewVideoForFederation: boolean
+ isNewVideoForSubscription: boolean
nameChanged: boolean
- oldPrivacy: VideoPrivacyType
+ oldPrivacy?: VideoPrivacyType
}) {
- const { video, nameChanged, oldPrivacy, isNewVideoForFederation } = options
+ const { video, nameChanged, oldPrivacy, isNewVideoForFederation, isNewVideoForSubscription } = options
const jobs: CreateJobTypeAndPayload[] = []
- const filePathChanged = await moveFilesIfPrivacyChanged(video, oldPrivacy)
+ const filePathChanged = exists(oldPrivacy)
+ ? await moveFilesIfPrivacyChanged(video, oldPrivacy)
+ : false
+
const hls = video.getHLSPlaylist()
if (filePathChanged && hls) {
+ logger.debug('Updating HLS playlist file paths after privacy change', lTags(video.uuid))
+
hls.assignP2PMediaLoaderInfoHashes(video, hls.VideoFiles)
await hls.save()
}
if (!video.isLive && (nameChanged || filePathChanged)) {
+ logger.debug('Updating video torrent metadata after name or file path change', lTags(video.uuid))
+
for (const file of (video.VideoFiles || [])) {
const payload: ManageVideoTorrentPayload = { action: 'update-metadata', videoId: video.id, videoFileId: file.id }
@@ -212,12 +217,9 @@ export async function addVideoJobsAfterUpdate (options: {
}
})
- const wasConfidentialVideoForNotification = new Set<VideoPrivacyType>([
- VideoPrivacy.PRIVATE,
- VideoPrivacy.UNLISTED
- ]).has(oldPrivacy)
+ if (isNewVideoForSubscription) {
+ logger.debug('Video is considered new for subscriptions: create the notification job', lTags(video.uuid))
- if (wasConfidentialVideoForNotification) {
jobs.push({
type: 'notify',
payload: {
diff --git a/server/core/lib/video-privacy.ts b/server/core/lib/video-privacy.ts
index 7780943799..6c824493c5 100644
--- a/server/core/lib/video-privacy.ts
+++ b/server/core/lib/video-privacy.ts
@@ -17,6 +17,10 @@ const validPrivacySet = new Set<VideoPrivacyType>([
export function setVideoPrivacy (video: MVideo, newPrivacy: VideoPrivacyType) {
if (video.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
video.publishedAt = new Date()
+
+ if (!video.firstPublishedAt) {
+ video.firstPublishedAt = video.publishedAt
+ }
}
video.privacy = newPrivacy
@@ -48,6 +52,22 @@ export async function moveFilesIfPrivacyChanged (video: MVideoFull, oldPrivacy:
return false
}
+// Return true if the video was private/unlisted/password protected and now is public/internal
+export function isNewVideoForSubscription (options: {
+ currentPrivacy: VideoPrivacyType
+ newPrivacy: VideoPrivacyType
+ firstPublishedAt: Date
+}) {
+ const { currentPrivacy, newPrivacy, firstPublishedAt } = options
+
+ if (currentPrivacy !== VideoPrivacy.PRIVATE) return false
+ if (firstPublishedAt) return false
+
+ if (newPrivacy !== VideoPrivacy.PUBLIC && newPrivacy !== VideoPrivacy.INTERNAL) return false
+
+ return true
+}
+
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
diff --git a/server/core/middlewares/validators/videos/videos.ts b/server/core/middlewares/validators/videos/videos.ts
index af0a8b97e9..45e242f8d6 100644
--- a/server/core/middlewares/validators/videos/videos.ts
+++ b/server/core/middlewares/validators/videos/videos.ts
@@ -44,8 +44,8 @@ import {
isVideoLanguageValid,
isVideoLicenceValid,
isVideoNameValid,
- isVideoOriginallyPublishedAtValid,
isVideoPrivacyValid,
+ isVideoPublicationDateValid,
isVideoSourceFilenameValid,
isVideoSupportValid
} from '../../../helpers/custom-validators/videos.js'
@@ -481,7 +481,7 @@ export function getCommonVideoEditAttributes () {
body('originallyPublishedAt')
.optional()
.customSanitizer(toValueOrNull)
- .custom(isVideoOriginallyPublishedAtValid),
+ .custom(isVideoPublicationDateValid),
body('scheduleUpdate')
.optional()
.customSanitizer(toValueOrNull),
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 406c023cdb..93c7449cfb 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
@@ -313,6 +313,7 @@ export class VideoTableAttributes {
'publishedAt',
'originallyPublishedAt',
'inputFileUpdatedAt',
+ 'firstPublishedAt',
'channelId',
'createdAt',
'updatedAt',
diff --git a/server/core/models/video/video.ts b/server/core/models/video/video.ts
index fe11fa9b42..23ed6b374f 100644
--- a/server/core/models/video/video.ts
+++ b/server/core/models/video/video.ts
@@ -619,6 +619,11 @@ export class VideoModel extends SequelizeModel<VideoModel> {
@Column
declare originallyPublishedAt: Date
+ @AllowNull(true)
+ @Default(null)
+ @Column
+ declare firstPublishedAt: Date
+
@ForeignKey(() => VideoChannelModel)
@Column
declare channelId: number