2
1

video-channel.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. import {
  2. AllowNull,
  3. BeforeDestroy,
  4. BelongsTo,
  5. Column,
  6. CreatedAt,
  7. DataType,
  8. Default,
  9. DefaultScope,
  10. ForeignKey,
  11. HasMany,
  12. Is,
  13. Model,
  14. Scopes,
  15. Sequelize,
  16. Table,
  17. UpdatedAt
  18. } from 'sequelize-typescript'
  19. import { ActivityPubActor } from '../../../shared/models/activitypub'
  20. import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
  21. import {
  22. isVideoChannelDescriptionValid,
  23. isVideoChannelNameValid,
  24. isVideoChannelSupportValid
  25. } from '../../helpers/custom-validators/video-channels'
  26. import { sendDeleteActor } from '../../lib/activitypub/send'
  27. import { AccountModel, ScopeNames as AccountModelScopeNames } from '../account/account'
  28. import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
  29. import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
  30. import { VideoModel } from './video'
  31. import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
  32. import { ServerModel } from '../server/server'
  33. import { FindOptions, ModelIndexesOptions, Op } from 'sequelize'
  34. import { AvatarModel } from '../avatar/avatar'
  35. import { VideoPlaylistModel } from './video-playlist'
  36. // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
  37. const indexes: ModelIndexesOptions[] = [
  38. buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
  39. {
  40. fields: [ 'accountId' ]
  41. },
  42. {
  43. fields: [ 'actorId' ]
  44. }
  45. ]
  46. export enum ScopeNames {
  47. AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
  48. WITH_ACCOUNT = 'WITH_ACCOUNT',
  49. WITH_ACTOR = 'WITH_ACTOR',
  50. WITH_VIDEOS = 'WITH_VIDEOS',
  51. SUMMARY = 'SUMMARY'
  52. }
  53. type AvailableForListOptions = {
  54. actorId: number
  55. }
  56. @DefaultScope(() => ({
  57. include: [
  58. {
  59. model: ActorModel,
  60. required: true
  61. }
  62. ]
  63. }))
  64. @Scopes(() => ({
  65. [ScopeNames.SUMMARY]: (withAccount = false) => {
  66. const base: FindOptions = {
  67. attributes: [ 'name', 'description', 'id', 'actorId' ],
  68. include: [
  69. {
  70. attributes: [ 'preferredUsername', 'url', 'serverId', 'avatarId' ],
  71. model: ActorModel.unscoped(),
  72. required: true,
  73. include: [
  74. {
  75. attributes: [ 'host' ],
  76. model: ServerModel.unscoped(),
  77. required: false
  78. },
  79. {
  80. model: AvatarModel.unscoped(),
  81. required: false
  82. }
  83. ]
  84. }
  85. ]
  86. }
  87. if (withAccount === true) {
  88. base.include.push({
  89. model: AccountModel.scope(AccountModelScopeNames.SUMMARY),
  90. required: true
  91. })
  92. }
  93. return base
  94. },
  95. [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
  96. // Only list local channels OR channels that are on an instance followed by actorId
  97. const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
  98. return {
  99. include: [
  100. {
  101. attributes: {
  102. exclude: unusedActorAttributesForAPI
  103. },
  104. model: ActorModel,
  105. where: {
  106. [Op.or]: [
  107. {
  108. serverId: null
  109. },
  110. {
  111. serverId: {
  112. [ Op.in ]: Sequelize.literal(inQueryInstanceFollow)
  113. }
  114. }
  115. ]
  116. }
  117. },
  118. {
  119. model: AccountModel,
  120. required: true,
  121. include: [
  122. {
  123. attributes: {
  124. exclude: unusedActorAttributesForAPI
  125. },
  126. model: ActorModel, // Default scope includes avatar and server
  127. required: true
  128. }
  129. ]
  130. }
  131. ]
  132. }
  133. },
  134. [ScopeNames.WITH_ACCOUNT]: {
  135. include: [
  136. {
  137. model: AccountModel,
  138. required: true
  139. }
  140. ]
  141. },
  142. [ScopeNames.WITH_VIDEOS]: {
  143. include: [
  144. VideoModel
  145. ]
  146. },
  147. [ScopeNames.WITH_ACTOR]: {
  148. include: [
  149. ActorModel
  150. ]
  151. }
  152. }))
  153. @Table({
  154. tableName: 'videoChannel',
  155. indexes
  156. })
  157. export class VideoChannelModel extends Model<VideoChannelModel> {
  158. @AllowNull(false)
  159. @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
  160. @Column
  161. name: string
  162. @AllowNull(true)
  163. @Default(null)
  164. @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
  165. @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
  166. description: string
  167. @AllowNull(true)
  168. @Default(null)
  169. @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
  170. @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
  171. support: string
  172. @CreatedAt
  173. createdAt: Date
  174. @UpdatedAt
  175. updatedAt: Date
  176. @ForeignKey(() => ActorModel)
  177. @Column
  178. actorId: number
  179. @BelongsTo(() => ActorModel, {
  180. foreignKey: {
  181. allowNull: false
  182. },
  183. onDelete: 'cascade'
  184. })
  185. Actor: ActorModel
  186. @ForeignKey(() => AccountModel)
  187. @Column
  188. accountId: number
  189. @BelongsTo(() => AccountModel, {
  190. foreignKey: {
  191. allowNull: false
  192. },
  193. hooks: true
  194. })
  195. Account: AccountModel
  196. @HasMany(() => VideoModel, {
  197. foreignKey: {
  198. name: 'channelId',
  199. allowNull: false
  200. },
  201. onDelete: 'CASCADE',
  202. hooks: true
  203. })
  204. Videos: VideoModel[]
  205. @HasMany(() => VideoPlaylistModel, {
  206. foreignKey: {
  207. allowNull: true
  208. },
  209. onDelete: 'CASCADE',
  210. hooks: true
  211. })
  212. VideoPlaylists: VideoPlaylistModel[]
  213. @BeforeDestroy
  214. static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
  215. if (!instance.Actor) {
  216. instance.Actor = await instance.$get('Actor', { transaction: options.transaction }) as ActorModel
  217. }
  218. if (instance.Actor.isOwned()) {
  219. return sendDeleteActor(instance.Actor, options.transaction)
  220. }
  221. return undefined
  222. }
  223. static countByAccount (accountId: number) {
  224. const query = {
  225. where: {
  226. accountId
  227. }
  228. }
  229. return VideoChannelModel.count(query)
  230. }
  231. static listForApi (actorId: number, start: number, count: number, sort: string) {
  232. const query = {
  233. offset: start,
  234. limit: count,
  235. order: getSort(sort)
  236. }
  237. const scopes = {
  238. method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId } as AvailableForListOptions ]
  239. }
  240. return VideoChannelModel
  241. .scope(scopes)
  242. .findAndCountAll(query)
  243. .then(({ rows, count }) => {
  244. return { total: count, data: rows }
  245. })
  246. }
  247. static listLocalsForSitemap (sort: string) {
  248. const query = {
  249. attributes: [ ],
  250. offset: 0,
  251. order: getSort(sort),
  252. include: [
  253. {
  254. attributes: [ 'preferredUsername', 'serverId' ],
  255. model: ActorModel.unscoped(),
  256. where: {
  257. serverId: null
  258. }
  259. }
  260. ]
  261. }
  262. return VideoChannelModel
  263. .unscoped()
  264. .findAll(query)
  265. }
  266. static searchForApi (options: {
  267. actorId: number
  268. search: string
  269. start: number
  270. count: number
  271. sort: string
  272. }) {
  273. const attributesInclude = []
  274. const escapedSearch = VideoModel.sequelize.escape(options.search)
  275. const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
  276. attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
  277. const query = {
  278. attributes: {
  279. include: attributesInclude
  280. },
  281. offset: options.start,
  282. limit: options.count,
  283. order: getSort(options.sort),
  284. where: {
  285. [Op.or]: [
  286. Sequelize.literal(
  287. 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
  288. ),
  289. Sequelize.literal(
  290. 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
  291. )
  292. ]
  293. }
  294. }
  295. const scopes = {
  296. method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId: options.actorId } as AvailableForListOptions ]
  297. }
  298. return VideoChannelModel
  299. .scope(scopes)
  300. .findAndCountAll(query)
  301. .then(({ rows, count }) => {
  302. return { total: count, data: rows }
  303. })
  304. }
  305. static listByAccount (options: {
  306. accountId: number,
  307. start: number,
  308. count: number,
  309. sort: string
  310. }) {
  311. const query = {
  312. offset: options.start,
  313. limit: options.count,
  314. order: getSort(options.sort),
  315. include: [
  316. {
  317. model: AccountModel,
  318. where: {
  319. id: options.accountId
  320. },
  321. required: true
  322. }
  323. ]
  324. }
  325. return VideoChannelModel
  326. .findAndCountAll(query)
  327. .then(({ rows, count }) => {
  328. return { total: count, data: rows }
  329. })
  330. }
  331. static loadByIdAndPopulateAccount (id: number) {
  332. return VideoChannelModel.unscoped()
  333. .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
  334. .findByPk(id)
  335. }
  336. static loadByIdAndAccount (id: number, accountId: number) {
  337. const query = {
  338. where: {
  339. id,
  340. accountId
  341. }
  342. }
  343. return VideoChannelModel.unscoped()
  344. .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
  345. .findOne(query)
  346. }
  347. static loadAndPopulateAccount (id: number) {
  348. return VideoChannelModel.unscoped()
  349. .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
  350. .findByPk(id)
  351. }
  352. static loadByUrlAndPopulateAccount (url: string) {
  353. const query = {
  354. include: [
  355. {
  356. model: ActorModel,
  357. required: true,
  358. where: {
  359. url
  360. }
  361. }
  362. ]
  363. }
  364. return VideoChannelModel
  365. .scope([ ScopeNames.WITH_ACCOUNT ])
  366. .findOne(query)
  367. }
  368. static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
  369. const [ name, host ] = nameWithHost.split('@')
  370. if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
  371. return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
  372. }
  373. static loadLocalByNameAndPopulateAccount (name: string) {
  374. const query = {
  375. include: [
  376. {
  377. model: ActorModel,
  378. required: true,
  379. where: {
  380. preferredUsername: name,
  381. serverId: null
  382. }
  383. }
  384. ]
  385. }
  386. return VideoChannelModel.unscoped()
  387. .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
  388. .findOne(query)
  389. }
  390. static loadByNameAndHostAndPopulateAccount (name: string, host: string) {
  391. const query = {
  392. include: [
  393. {
  394. model: ActorModel,
  395. required: true,
  396. where: {
  397. preferredUsername: name
  398. },
  399. include: [
  400. {
  401. model: ServerModel,
  402. required: true,
  403. where: { host }
  404. }
  405. ]
  406. }
  407. ]
  408. }
  409. return VideoChannelModel.unscoped()
  410. .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
  411. .findOne(query)
  412. }
  413. static loadAndPopulateAccountAndVideos (id: number) {
  414. const options = {
  415. include: [
  416. VideoModel
  417. ]
  418. }
  419. return VideoChannelModel.unscoped()
  420. .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
  421. .findByPk(id, options)
  422. }
  423. toFormattedJSON (): VideoChannel {
  424. const actor = this.Actor.toFormattedJSON()
  425. const videoChannel = {
  426. id: this.id,
  427. displayName: this.getDisplayName(),
  428. description: this.description,
  429. support: this.support,
  430. isLocal: this.Actor.isOwned(),
  431. createdAt: this.createdAt,
  432. updatedAt: this.updatedAt,
  433. ownerAccount: undefined
  434. }
  435. if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
  436. return Object.assign(actor, videoChannel)
  437. }
  438. toFormattedSummaryJSON (): VideoChannelSummary {
  439. const actor = this.Actor.toFormattedJSON()
  440. return {
  441. id: this.id,
  442. name: actor.name,
  443. displayName: this.getDisplayName(),
  444. url: actor.url,
  445. host: actor.host,
  446. avatar: actor.avatar
  447. }
  448. }
  449. toActivityPubObject (): ActivityPubActor {
  450. const obj = this.Actor.toActivityPubObject(this.name, 'VideoChannel')
  451. return Object.assign(obj, {
  452. summary: this.description,
  453. support: this.support,
  454. attributedTo: [
  455. {
  456. type: 'Person' as 'Person',
  457. id: this.Account.Actor.url
  458. }
  459. ]
  460. })
  461. }
  462. getDisplayName () {
  463. return this.name
  464. }
  465. isOutdated () {
  466. return this.Actor.isOutdated()
  467. }
  468. }