522eebeaf92206ca897c6b106aa138177ea6cc74
[oweals/peertube.git] / server / models / account / user-video-history.ts
1 import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, IsInt, Model, Table, UpdatedAt } from 'sequelize-typescript'
2 import { VideoModel } from '../video/video'
3 import { UserModel } from './user'
4 import { DestroyOptions, Op, Transaction } from 'sequelize'
5 import { MUserAccountId, MUserId } from '@server/typings/models'
6
7 @Table({
8   tableName: 'userVideoHistory',
9   indexes: [
10     {
11       fields: [ 'userId', 'videoId' ],
12       unique: true
13     },
14     {
15       fields: [ 'userId' ]
16     },
17     {
18       fields: [ 'videoId' ]
19     }
20   ]
21 })
22 export class UserVideoHistoryModel extends Model<UserVideoHistoryModel> {
23   @CreatedAt
24   createdAt: Date
25
26   @UpdatedAt
27   updatedAt: Date
28
29   @AllowNull(false)
30   @IsInt
31   @Column
32   currentTime: number
33
34   @ForeignKey(() => VideoModel)
35   @Column
36   videoId: number
37
38   @BelongsTo(() => VideoModel, {
39     foreignKey: {
40       allowNull: false
41     },
42     onDelete: 'CASCADE'
43   })
44   Video: VideoModel
45
46   @ForeignKey(() => UserModel)
47   @Column
48   userId: number
49
50   @BelongsTo(() => UserModel, {
51     foreignKey: {
52       allowNull: false
53     },
54     onDelete: 'CASCADE'
55   })
56   User: UserModel
57
58   static listForApi (user: MUserAccountId, start: number, count: number) {
59     return VideoModel.listForApi({
60       start,
61       count,
62       sort: '-"userVideoHistory"."updatedAt"',
63       nsfw: null, // All
64       includeLocalVideos: true,
65       withFiles: false,
66       user,
67       historyOfUser: user
68     })
69   }
70
71   static removeUserHistoryBefore (user: MUserId, beforeDate: string, t: Transaction) {
72     const query: DestroyOptions = {
73       where: {
74         userId: user.id
75       },
76       transaction: t
77     }
78
79     if (beforeDate) {
80       query.where['updatedAt'] = {
81         [Op.lt]: beforeDate
82       }
83     }
84
85     return UserVideoHistoryModel.destroy(query)
86   }
87
88   static removeOldHistory (beforeDate: string) {
89     const query: DestroyOptions = {
90       where: {
91         updatedAt: {
92           [Op.lt]: beforeDate
93         }
94       }
95     }
96
97     return UserVideoHistoryModel.destroy(query)
98   }
99 }