]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos/updater.ts
Try to speed up AP update transaction
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos / updater.ts
1 import { Transaction } from 'sequelize/types'
2 import { resetSequelizeInstance, runInReadCommittedTransaction } from '@server/helpers/database-utils'
3 import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger'
4 import { Notifier } from '@server/lib/notifier'
5 import { PeerTubeSocket } from '@server/lib/peertube-socket'
6 import { autoBlacklistVideoIfNeeded } from '@server/lib/video-blacklist'
7 import { VideoCaptionModel } from '@server/models/video/video-caption'
8 import { VideoLiveModel } from '@server/models/video/video-live'
9 import { MActor, MChannelAccountLight, MChannelId, MVideoAccountLightBlacklistAllFiles, MVideoFullLight } from '@server/types/models'
10 import { VideoObject, VideoPrivacy } from '@shared/models'
11 import { APVideoAbstractBuilder, getVideoAttributesFromObject } from './shared'
12
13 export class APVideoUpdater extends APVideoAbstractBuilder {
14 private readonly wasPrivateVideo: boolean
15 private readonly wasUnlistedVideo: boolean
16
17 private readonly videoFieldsSave: any
18
19 private readonly oldVideoChannel: MChannelAccountLight
20
21 protected lTags: LoggerTagsFn
22
23 constructor (
24 protected readonly videoObject: VideoObject,
25 private readonly video: MVideoAccountLightBlacklistAllFiles
26 ) {
27 super()
28
29 this.wasPrivateVideo = this.video.privacy === VideoPrivacy.PRIVATE
30 this.wasUnlistedVideo = this.video.privacy === VideoPrivacy.UNLISTED
31
32 this.oldVideoChannel = this.video.VideoChannel
33
34 this.videoFieldsSave = this.video.toJSON()
35
36 this.lTags = loggerTagsFactory('ap', 'video', 'update', video.uuid, video.url)
37 }
38
39 async update (overrideTo?: string[]) {
40 logger.debug(
41 'Updating remote video "%s".', this.videoObject.uuid,
42 { videoObject: this.videoObject, ...this.lTags() }
43 )
44
45 try {
46 const channelActor = await this.getOrCreateVideoChannelFromVideoObject()
47
48 const thumbnailModel = await this.tryToGenerateThumbnail(this.video)
49
50 this.checkChannelUpdateOrThrow(channelActor)
51
52 const videoUpdated = await this.updateVideo(channelActor.VideoChannel, undefined, overrideTo)
53
54 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel)
55
56 await runInReadCommittedTransaction(async t => {
57 await this.setWebTorrentFiles(videoUpdated, t)
58 await this.setStreamingPlaylists(videoUpdated, t)
59 })
60
61 await Promise.all([
62 runInReadCommittedTransaction(t => this.setTags(videoUpdated, t)),
63 runInReadCommittedTransaction(t => this.setTrackers(videoUpdated, t)),
64 this.setOrDeleteLive(videoUpdated),
65 this.setPreview(videoUpdated)
66 ])
67
68 await runInReadCommittedTransaction(t => this.setCaptions(videoUpdated, t))
69
70 await autoBlacklistVideoIfNeeded({
71 video: videoUpdated,
72 user: undefined,
73 isRemote: true,
74 isNew: false,
75 transaction: undefined
76 })
77
78 // Notify our users?
79 if (this.wasPrivateVideo || this.wasUnlistedVideo) {
80 Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
81 }
82
83 if (videoUpdated.isLive) {
84 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
85 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
86 }
87
88 logger.info('Remote video with uuid %s updated', this.videoObject.uuid, this.lTags())
89
90 return videoUpdated
91 } catch (err) {
92 this.catchUpdateError(err)
93 }
94 }
95
96 // Check we can update the channel: we trust the remote server
97 private checkChannelUpdateOrThrow (newChannelActor: MActor) {
98 if (!this.oldVideoChannel.Actor.serverId || !newChannelActor.serverId) {
99 throw new Error('Cannot check old channel/new channel validity because `serverId` is null')
100 }
101
102 if (this.oldVideoChannel.Actor.serverId !== newChannelActor.serverId) {
103 throw new Error(`New channel ${newChannelActor.url} is not on the same server than new channel ${this.oldVideoChannel.Actor.url}`)
104 }
105 }
106
107 private updateVideo (channel: MChannelId, transaction?: Transaction, overrideTo?: string[]) {
108 const to = overrideTo || this.videoObject.to
109 const videoData = getVideoAttributesFromObject(channel, this.videoObject, to)
110 this.video.name = videoData.name
111 this.video.uuid = videoData.uuid
112 this.video.url = videoData.url
113 this.video.category = videoData.category
114 this.video.licence = videoData.licence
115 this.video.language = videoData.language
116 this.video.description = videoData.description
117 this.video.support = videoData.support
118 this.video.nsfw = videoData.nsfw
119 this.video.commentsEnabled = videoData.commentsEnabled
120 this.video.downloadEnabled = videoData.downloadEnabled
121 this.video.waitTranscoding = videoData.waitTranscoding
122 this.video.state = videoData.state
123 this.video.duration = videoData.duration
124 this.video.createdAt = videoData.createdAt
125 this.video.publishedAt = videoData.publishedAt
126 this.video.originallyPublishedAt = videoData.originallyPublishedAt
127 this.video.privacy = videoData.privacy
128 this.video.channelId = videoData.channelId
129 this.video.views = videoData.views
130 this.video.isLive = videoData.isLive
131
132 // Ensures we update the updatedAt attribute, even if main attributes did not change
133 this.video.changed('updatedAt', true)
134
135 return this.video.save({ transaction }) as Promise<MVideoFullLight>
136 }
137
138 private async setCaptions (videoUpdated: MVideoFullLight, t: Transaction) {
139 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
140
141 await this.insertOrReplaceCaptions(videoUpdated, t)
142 }
143
144 private async setOrDeleteLive (videoUpdated: MVideoFullLight, transaction?: Transaction) {
145 if (!this.video.isLive) return
146
147 if (this.video.isLive) return this.insertOrReplaceLive(videoUpdated, transaction)
148
149 // Delete existing live if it exists
150 await VideoLiveModel.destroy({
151 where: {
152 videoId: this.video.id
153 },
154 transaction
155 })
156
157 videoUpdated.VideoLive = null
158 }
159
160 private catchUpdateError (err: Error) {
161 if (this.video !== undefined && this.videoFieldsSave !== undefined) {
162 resetSequelizeInstance(this.video, this.videoFieldsSave)
163 }
164
165 // This is just a debug because we will retry the insert
166 logger.debug('Cannot update the remote video.', { err, ...this.lTags() })
167 throw err
168 }
169 }