PeerTube/server/core/models/server/tracker.ts

75 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-02-22 10:12:04 +01:00
import { AllowNull, BelongsToMany, Column, CreatedAt, Table, UpdatedAt } from 'sequelize-typescript'
import { Transaction } from 'sequelize'
import { MTracker } from '@server/types/models/server/tracker.js'
import { VideoModel } from '../video/video.js'
import { VideoTrackerModel } from './video-tracker.js'
2024-02-22 10:12:04 +01:00
import { SequelizeModel } from '../shared/sequelize-type.js'
2021-02-18 10:15:11 +01:00
@Table({
tableName: 'tracker',
indexes: [
{
fields: [ 'url' ],
unique: true
}
]
})
2024-02-22 10:12:04 +01:00
export class TrackerModel extends SequelizeModel<TrackerModel> {
2021-02-18 10:15:11 +01:00
@AllowNull(false)
@Column
url: string
@CreatedAt
createdAt: Date
@UpdatedAt
updatedAt: Date
@BelongsToMany(() => VideoModel, {
foreignKey: 'trackerId',
through: () => VideoTrackerModel,
onDelete: 'CASCADE'
})
Videos: Awaited<VideoModel>[]
2021-02-18 10:15:11 +01:00
static listUrlsByVideoId (videoId: number) {
const query = {
include: [
{
attributes: [ 'id' ],
2021-02-18 10:15:11 +01:00
model: VideoModel.unscoped(),
required: true,
where: { id: videoId }
}
]
}
return TrackerModel.findAll(query)
.then(rows => rows.map(rows => rows.url))
}
static findOrCreateTrackers (trackers: string[], transaction: Transaction): Promise<MTracker[]> {
if (trackers === null) return Promise.resolve([])
const tasks: Promise<MTracker>[] = []
trackers.forEach(tracker => {
const query = {
where: {
url: tracker
},
defaults: {
url: tracker
},
transaction
}
const promise = TrackerModel.findOrCreate<MTracker>(query)
.then(([ trackerInstance ]) => trackerInstance)
tasks.push(promise)
})
return Promise.all(tasks)
}
}