]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/server/tracker.ts
Merge branch 'develop' into shorter-URLs-channels-accounts
[github/Chocobozzz/PeerTube.git] / server / models / server / tracker.ts
1 import { AllowNull, BelongsToMany, Column, CreatedAt, Model, Table, UpdatedAt } from 'sequelize-typescript'
2 import { Transaction } from 'sequelize/types'
3 import { MTracker } from '@server/types/models/server/tracker'
4 import { AttributesOnly } from '@shared/core-utils'
5 import { VideoModel } from '../video/video'
6 import { VideoTrackerModel } from './video-tracker'
7
8 @Table({
9 tableName: 'tracker',
10 indexes: [
11 {
12 fields: [ 'url' ],
13 unique: true
14 }
15 ]
16 })
17 export class TrackerModel extends Model<Partial<AttributesOnly<TrackerModel>>> {
18
19 @AllowNull(false)
20 @Column
21 url: string
22
23 @CreatedAt
24 createdAt: Date
25
26 @UpdatedAt
27 updatedAt: Date
28
29 @BelongsToMany(() => VideoModel, {
30 foreignKey: 'trackerId',
31 through: () => VideoTrackerModel,
32 onDelete: 'CASCADE'
33 })
34 Videos: VideoModel[]
35
36 static listUrlsByVideoId (videoId: number) {
37 const query = {
38 include: [
39 {
40 attributes: [ 'id' ],
41 model: VideoModel.unscoped(),
42 required: true,
43 where: { id: videoId }
44 }
45 ]
46 }
47
48 return TrackerModel.findAll(query)
49 .then(rows => rows.map(rows => rows.url))
50 }
51
52 static findOrCreateTrackers (trackers: string[], transaction: Transaction): Promise<MTracker[]> {
53 if (trackers === null) return Promise.resolve([])
54
55 const tasks: Promise<MTracker>[] = []
56 trackers.forEach(tracker => {
57 const query = {
58 where: {
59 url: tracker
60 },
61 defaults: {
62 url: tracker
63 },
64 transaction
65 }
66
67 const promise = TrackerModel.findOrCreate<MTracker>(query)
68 .then(([ trackerInstance ]) => trackerInstance)
69 tasks.push(promise)
70 })
71
72 return Promise.all(tasks)
73 }
74 }