]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/models/account/account-video-rate.ts
Refractor and optimize AP collections
[github/Chocobozzz/PeerTube.git] / server / models / account / account-video-rate.ts
... / ...
CommitLineData
1import { values } from 'lodash'
2import { Transaction } from 'sequelize'
3import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Model, Table, UpdatedAt } from 'sequelize-typescript'
4import { IFindOptions } from 'sequelize-typescript/lib/interfaces/IFindOptions'
5import { VideoRateType } from '../../../shared/models/videos'
6import { VIDEO_RATE_TYPES } from '../../initializers'
7import { VideoModel } from '../video/video'
8import { AccountModel } from './account'
9import { ActorModel } from '../activitypub/actor'
10
11/*
12 Account rates per video.
13*/
14@Table({
15 tableName: 'accountVideoRate',
16 indexes: [
17 {
18 fields: [ 'videoId', 'accountId' ],
19 unique: true
20 }
21 ]
22})
23export class AccountVideoRateModel extends Model<AccountVideoRateModel> {
24
25 @AllowNull(false)
26 @Column(DataType.ENUM(values(VIDEO_RATE_TYPES)))
27 type: VideoRateType
28
29 @CreatedAt
30 createdAt: Date
31
32 @UpdatedAt
33 updatedAt: Date
34
35 @ForeignKey(() => VideoModel)
36 @Column
37 videoId: number
38
39 @BelongsTo(() => VideoModel, {
40 foreignKey: {
41 allowNull: false
42 },
43 onDelete: 'CASCADE'
44 })
45 Video: VideoModel
46
47 @ForeignKey(() => AccountModel)
48 @Column
49 accountId: number
50
51 @BelongsTo(() => AccountModel, {
52 foreignKey: {
53 allowNull: false
54 },
55 onDelete: 'CASCADE'
56 })
57 Account: AccountModel
58
59 static load (accountId: number, videoId: number, transaction: Transaction) {
60 const options: IFindOptions<AccountVideoRateModel> = {
61 where: {
62 accountId,
63 videoId
64 }
65 }
66 if (transaction) options.transaction = transaction
67
68 return AccountVideoRateModel.findOne(options)
69 }
70
71 static listAndCountAccountUrlsByVideoId (rateType: VideoRateType, videoId: number, start: number, count: number, t?: Transaction) {
72 const query = {
73 start,
74 count,
75 where: {
76 videoId,
77 type: rateType
78 },
79 transaction: t,
80 include: [
81 {
82 attributes: [ 'actorId' ],
83 model: AccountModel.unscoped(),
84 required: true,
85 include: [
86 {
87 attributes: [ 'url' ],
88 model: ActorModel.unscoped(),
89 required: true
90 }
91 ]
92 }
93 ]
94 }
95
96 return AccountVideoRateModel.findAndCountAll(query)
97 }
98}