video-redundancy.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import {
  2. AllowNull,
  3. BeforeDestroy,
  4. BelongsTo,
  5. Column,
  6. CreatedAt,
  7. DataType,
  8. ForeignKey,
  9. Is,
  10. Model,
  11. Scopes,
  12. Table,
  13. UpdatedAt
  14. } from 'sequelize-typescript'
  15. import { ActorModel } from '../activitypub/actor'
  16. import { getVideoSort, parseAggregateResult, throwIfNotValid } from '../utils'
  17. import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
  18. import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers/constants'
  19. import { VideoFileModel } from '../video/video-file'
  20. import { getServerActor } from '../../helpers/utils'
  21. import { VideoModel } from '../video/video'
  22. import { VideoRedundancyStrategy } from '../../../shared/models/redundancy'
  23. import { logger } from '../../helpers/logger'
  24. import { CacheFileObject, VideoPrivacy } from '../../../shared'
  25. import { VideoChannelModel } from '../video/video-channel'
  26. import { ServerModel } from '../server/server'
  27. import { sample } from 'lodash'
  28. import { isTestInstance } from '../../helpers/core-utils'
  29. import * as Bluebird from 'bluebird'
  30. import { col, FindOptions, fn, literal, Op, Transaction } from 'sequelize'
  31. import { VideoStreamingPlaylistModel } from '../video/video-streaming-playlist'
  32. import { CONFIG } from '../../initializers/config'
  33. import { MVideoRedundancy, MVideoRedundancyAP, MVideoRedundancyVideo } from '@server/typings/models'
  34. export enum ScopeNames {
  35. WITH_VIDEO = 'WITH_VIDEO'
  36. }
  37. @Scopes(() => ({
  38. [ ScopeNames.WITH_VIDEO ]: {
  39. include: [
  40. {
  41. model: VideoFileModel,
  42. required: false,
  43. include: [
  44. {
  45. model: VideoModel,
  46. required: true
  47. }
  48. ]
  49. },
  50. {
  51. model: VideoStreamingPlaylistModel,
  52. required: false,
  53. include: [
  54. {
  55. model: VideoModel,
  56. required: true
  57. }
  58. ]
  59. }
  60. ]
  61. }
  62. }))
  63. @Table({
  64. tableName: 'videoRedundancy',
  65. indexes: [
  66. {
  67. fields: [ 'videoFileId' ]
  68. },
  69. {
  70. fields: [ 'actorId' ]
  71. },
  72. {
  73. fields: [ 'url' ],
  74. unique: true
  75. }
  76. ]
  77. })
  78. export class VideoRedundancyModel extends Model<VideoRedundancyModel> {
  79. @CreatedAt
  80. createdAt: Date
  81. @UpdatedAt
  82. updatedAt: Date
  83. @AllowNull(false)
  84. @Column
  85. expiresOn: Date
  86. @AllowNull(false)
  87. @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
  88. @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
  89. fileUrl: string
  90. @AllowNull(false)
  91. @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
  92. @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
  93. url: string
  94. @AllowNull(true)
  95. @Column
  96. strategy: string // Only used by us
  97. @ForeignKey(() => VideoFileModel)
  98. @Column
  99. videoFileId: number
  100. @BelongsTo(() => VideoFileModel, {
  101. foreignKey: {
  102. allowNull: true
  103. },
  104. onDelete: 'cascade'
  105. })
  106. VideoFile: VideoFileModel
  107. @ForeignKey(() => VideoStreamingPlaylistModel)
  108. @Column
  109. videoStreamingPlaylistId: number
  110. @BelongsTo(() => VideoStreamingPlaylistModel, {
  111. foreignKey: {
  112. allowNull: true
  113. },
  114. onDelete: 'cascade'
  115. })
  116. VideoStreamingPlaylist: VideoStreamingPlaylistModel
  117. @ForeignKey(() => ActorModel)
  118. @Column
  119. actorId: number
  120. @BelongsTo(() => ActorModel, {
  121. foreignKey: {
  122. allowNull: false
  123. },
  124. onDelete: 'cascade'
  125. })
  126. Actor: ActorModel
  127. @BeforeDestroy
  128. static async removeFile (instance: VideoRedundancyModel) {
  129. if (!instance.isOwned()) return
  130. if (instance.videoFileId) {
  131. const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
  132. const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
  133. logger.info('Removing duplicated video file %s.', logIdentifier)
  134. videoFile.Video.removeFile(videoFile, true)
  135. .catch(err => logger.error('Cannot delete %s files.', logIdentifier, { err }))
  136. }
  137. if (instance.videoStreamingPlaylistId) {
  138. const videoStreamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(instance.videoStreamingPlaylistId)
  139. const videoUUID = videoStreamingPlaylist.Video.uuid
  140. logger.info('Removing duplicated video streaming playlist %s.', videoUUID)
  141. videoStreamingPlaylist.Video.removeStreamingPlaylist(true)
  142. .catch(err => logger.error('Cannot delete video streaming playlist files of %s.', videoUUID, { err }))
  143. }
  144. return undefined
  145. }
  146. static async loadLocalByFileId (videoFileId: number): Promise<MVideoRedundancyVideo> {
  147. const actor = await getServerActor()
  148. const query = {
  149. where: {
  150. actorId: actor.id,
  151. videoFileId
  152. }
  153. }
  154. return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
  155. }
  156. static async loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number): Promise<MVideoRedundancyVideo> {
  157. const actor = await getServerActor()
  158. const query = {
  159. where: {
  160. actorId: actor.id,
  161. videoStreamingPlaylistId
  162. }
  163. }
  164. return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
  165. }
  166. static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoRedundancy> {
  167. const query = {
  168. where: {
  169. url
  170. },
  171. transaction
  172. }
  173. return VideoRedundancyModel.findOne(query)
  174. }
  175. static async isLocalByVideoUUIDExists (uuid: string) {
  176. const actor = await getServerActor()
  177. const query = {
  178. raw: true,
  179. attributes: [ 'id' ],
  180. where: {
  181. actorId: actor.id
  182. },
  183. include: [
  184. {
  185. attributes: [ ],
  186. model: VideoFileModel,
  187. required: true,
  188. include: [
  189. {
  190. attributes: [ ],
  191. model: VideoModel,
  192. required: true,
  193. where: {
  194. uuid
  195. }
  196. }
  197. ]
  198. }
  199. ]
  200. }
  201. return VideoRedundancyModel.findOne(query)
  202. .then(r => !!r)
  203. }
  204. static async getVideoSample (p: Bluebird<VideoModel[]>) {
  205. const rows = await p
  206. if (rows.length === 0) return undefined
  207. const ids = rows.map(r => r.id)
  208. const id = sample(ids)
  209. return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
  210. }
  211. static async findMostViewToDuplicate (randomizedFactor: number) {
  212. // On VideoModel!
  213. const query = {
  214. attributes: [ 'id', 'views' ],
  215. limit: randomizedFactor,
  216. order: getVideoSort('-views'),
  217. where: {
  218. privacy: VideoPrivacy.PUBLIC
  219. },
  220. include: [
  221. await VideoRedundancyModel.buildVideoFileForDuplication(),
  222. VideoRedundancyModel.buildServerRedundancyInclude()
  223. ]
  224. }
  225. return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
  226. }
  227. static async findTrendingToDuplicate (randomizedFactor: number) {
  228. // On VideoModel!
  229. const query = {
  230. attributes: [ 'id', 'views' ],
  231. subQuery: false,
  232. group: 'VideoModel.id',
  233. limit: randomizedFactor,
  234. order: getVideoSort('-trending'),
  235. where: {
  236. privacy: VideoPrivacy.PUBLIC
  237. },
  238. include: [
  239. await VideoRedundancyModel.buildVideoFileForDuplication(),
  240. VideoRedundancyModel.buildServerRedundancyInclude(),
  241. VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
  242. ]
  243. }
  244. return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
  245. }
  246. static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
  247. // On VideoModel!
  248. const query = {
  249. attributes: [ 'id', 'publishedAt' ],
  250. limit: randomizedFactor,
  251. order: getVideoSort('-publishedAt'),
  252. where: {
  253. privacy: VideoPrivacy.PUBLIC,
  254. views: {
  255. [ Op.gte ]: minViews
  256. }
  257. },
  258. include: [
  259. await VideoRedundancyModel.buildVideoFileForDuplication(),
  260. VideoRedundancyModel.buildServerRedundancyInclude()
  261. ]
  262. }
  263. return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
  264. }
  265. static async loadOldestLocalExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number): Promise<MVideoRedundancyVideo> {
  266. const expiredDate = new Date()
  267. expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
  268. const actor = await getServerActor()
  269. const query = {
  270. where: {
  271. actorId: actor.id,
  272. strategy,
  273. createdAt: {
  274. [ Op.lt ]: expiredDate
  275. }
  276. }
  277. }
  278. return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
  279. }
  280. static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
  281. const actor = await getServerActor()
  282. const redundancyInclude = {
  283. attributes: [],
  284. model: VideoRedundancyModel,
  285. required: true,
  286. where: {
  287. actorId: actor.id,
  288. strategy
  289. }
  290. }
  291. const queryFiles: FindOptions = {
  292. include: [ redundancyInclude ]
  293. }
  294. const queryStreamingPlaylists: FindOptions = {
  295. include: [
  296. {
  297. attributes: [],
  298. model: VideoModel.unscoped(),
  299. required: true,
  300. include: [
  301. {
  302. required: true,
  303. attributes: [],
  304. model: VideoStreamingPlaylistModel.unscoped(),
  305. include: [
  306. redundancyInclude
  307. ]
  308. }
  309. ]
  310. }
  311. ]
  312. }
  313. return Promise.all([
  314. VideoFileModel.aggregate('size', 'SUM', queryFiles),
  315. VideoFileModel.aggregate('size', 'SUM', queryStreamingPlaylists)
  316. ]).then(([ r1, r2 ]) => {
  317. return parseAggregateResult(r1) + parseAggregateResult(r2)
  318. })
  319. }
  320. static async listLocalExpired () {
  321. const actor = await getServerActor()
  322. const query = {
  323. where: {
  324. actorId: actor.id,
  325. expiresOn: {
  326. [ Op.lt ]: new Date()
  327. }
  328. }
  329. }
  330. return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
  331. }
  332. static async listRemoteExpired () {
  333. const actor = await getServerActor()
  334. const query = {
  335. where: {
  336. actorId: {
  337. [Op.ne]: actor.id
  338. },
  339. expiresOn: {
  340. [ Op.lt ]: new Date()
  341. }
  342. }
  343. }
  344. return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
  345. }
  346. static async listLocalOfServer (serverId: number) {
  347. const actor = await getServerActor()
  348. const buildVideoInclude = () => ({
  349. model: VideoModel,
  350. required: true,
  351. include: [
  352. {
  353. attributes: [],
  354. model: VideoChannelModel.unscoped(),
  355. required: true,
  356. include: [
  357. {
  358. attributes: [],
  359. model: ActorModel.unscoped(),
  360. required: true,
  361. where: {
  362. serverId
  363. }
  364. }
  365. ]
  366. }
  367. ]
  368. })
  369. const query = {
  370. where: {
  371. actorId: actor.id
  372. },
  373. include: [
  374. {
  375. model: VideoFileModel,
  376. required: false,
  377. include: [ buildVideoInclude() ]
  378. },
  379. {
  380. model: VideoStreamingPlaylistModel,
  381. required: false,
  382. include: [ buildVideoInclude() ]
  383. }
  384. ]
  385. }
  386. return VideoRedundancyModel.findAll(query)
  387. }
  388. static async getStats (strategy: VideoRedundancyStrategy) {
  389. const actor = await getServerActor()
  390. const query: FindOptions = {
  391. raw: true,
  392. attributes: [
  393. [ fn('COALESCE', fn('SUM', col('VideoFile.size')), '0'), 'totalUsed' ],
  394. [ fn('COUNT', fn('DISTINCT', col('videoId'))), 'totalVideos' ],
  395. [ fn('COUNT', col('videoFileId')), 'totalVideoFiles' ]
  396. ],
  397. where: {
  398. strategy,
  399. actorId: actor.id
  400. },
  401. include: [
  402. {
  403. attributes: [],
  404. model: VideoFileModel,
  405. required: true
  406. }
  407. ]
  408. }
  409. return VideoRedundancyModel.findOne(query)
  410. .then((r: any) => ({
  411. totalUsed: parseAggregateResult(r.totalUsed),
  412. totalVideos: r.totalVideos,
  413. totalVideoFiles: r.totalVideoFiles
  414. }))
  415. }
  416. getVideo () {
  417. if (this.VideoFile) return this.VideoFile.Video
  418. return this.VideoStreamingPlaylist.Video
  419. }
  420. isOwned () {
  421. return !!this.strategy
  422. }
  423. toActivityPubObject (this: MVideoRedundancyAP): CacheFileObject {
  424. if (this.VideoStreamingPlaylist) {
  425. return {
  426. id: this.url,
  427. type: 'CacheFile' as 'CacheFile',
  428. object: this.VideoStreamingPlaylist.Video.url,
  429. expires: this.expiresOn.toISOString(),
  430. url: {
  431. type: 'Link',
  432. mediaType: 'application/x-mpegURL',
  433. href: this.fileUrl
  434. }
  435. }
  436. }
  437. return {
  438. id: this.url,
  439. type: 'CacheFile' as 'CacheFile',
  440. object: this.VideoFile.Video.url,
  441. expires: this.expiresOn.toISOString(),
  442. url: {
  443. type: 'Link',
  444. mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[ this.VideoFile.extname ] as any,
  445. href: this.fileUrl,
  446. height: this.VideoFile.resolution,
  447. size: this.VideoFile.size,
  448. fps: this.VideoFile.fps
  449. }
  450. }
  451. }
  452. // Don't include video files we already duplicated
  453. private static async buildVideoFileForDuplication () {
  454. const actor = await getServerActor()
  455. const notIn = literal(
  456. '(' +
  457. `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id} AND "videoFileId" IS NOT NULL` +
  458. ')'
  459. )
  460. return {
  461. attributes: [],
  462. model: VideoFileModel.unscoped(),
  463. required: true,
  464. where: {
  465. id: {
  466. [ Op.notIn ]: notIn
  467. }
  468. }
  469. }
  470. }
  471. private static buildServerRedundancyInclude () {
  472. return {
  473. attributes: [],
  474. model: VideoChannelModel.unscoped(),
  475. required: true,
  476. include: [
  477. {
  478. attributes: [],
  479. model: ActorModel.unscoped(),
  480. required: true,
  481. include: [
  482. {
  483. attributes: [],
  484. model: ServerModel.unscoped(),
  485. required: true,
  486. where: {
  487. redundancyAllowed: true
  488. }
  489. }
  490. ]
  491. }
  492. ]
  493. }
  494. }
  495. }