Begin activitypub
[oweals/peertube.git] / server / initializers / database.ts
1 import { join } from 'path'
2 import { flattenDepth } from 'lodash'
3 require('pg').defaults.parseInt8 = true // Avoid BIGINT to be converted to string
4 import * as Sequelize from 'sequelize'
5 import * as Bluebird from 'bluebird'
6
7 import { CONFIG } from './constants'
8 // Do not use barrel, we need to load database first
9 import { logger } from '../helpers/logger'
10 import { isTestInstance, readdirPromise } from '../helpers/core-utils'
11
12 import { VideoModel } from './../models/video/video-interface'
13 import { VideoTagModel } from './../models/video/video-tag-interface'
14 import { BlacklistedVideoModel } from './../models/video/video-blacklist-interface'
15 import { VideoFileModel } from './../models/video/video-file-interface'
16 import { VideoAbuseModel } from './../models/video/video-abuse-interface'
17 import { VideoChannelModel } from './../models/video/video-channel-interface'
18 import { UserModel } from '../models/account/user-interface'
19 import { AccountVideoRateModel } from '../models/account/account-video-rate-interface'
20 import { AccountFollowModel } from '../models/account/account-follow-interface'
21 import { TagModel } from './../models/video/tag-interface'
22 import { RequestModel } from './../models/request/request-interface'
23 import { RequestVideoQaduModel } from './../models/request/request-video-qadu-interface'
24 import { RequestVideoEventModel } from './../models/request/request-video-event-interface'
25 import { RequestToPodModel } from './../models/request/request-to-pod-interface'
26 import { PodModel } from './../models/pod/pod-interface'
27 import { OAuthTokenModel } from './../models/oauth/oauth-token-interface'
28 import { OAuthClientModel } from './../models/oauth/oauth-client-interface'
29 import { JobModel } from './../models/job/job-interface'
30 import { AccountModel } from './../models/account/account-interface'
31 import { ApplicationModel } from './../models/application/application-interface'
32
33 const dbname = CONFIG.DATABASE.DBNAME
34 const username = CONFIG.DATABASE.USERNAME
35 const password = CONFIG.DATABASE.PASSWORD
36
37 const database: {
38   sequelize?: Sequelize.Sequelize,
39   init?: (silent: boolean) => Promise<void>,
40
41   Application?: ApplicationModel,
42   Account?: AccountModel,
43   Job?: JobModel,
44   OAuthClient?: OAuthClientModel,
45   OAuthToken?: OAuthTokenModel,
46   Pod?: PodModel,
47   RequestToPod?: RequestToPodModel,
48   RequestVideoEvent?: RequestVideoEventModel,
49   RequestVideoQadu?: RequestVideoQaduModel,
50   Request?: RequestModel,
51   Tag?: TagModel,
52   AccountVideoRate?: AccountVideoRateModel,
53   AccountFollow?: AccountFollowModel,
54   User?: UserModel,
55   VideoAbuse?: VideoAbuseModel,
56   VideoChannel?: VideoChannelModel,
57   VideoFile?: VideoFileModel,
58   BlacklistedVideo?: BlacklistedVideoModel,
59   VideoTag?: VideoTagModel,
60   Video?: VideoModel
61 } = {}
62
63 const sequelize = new Sequelize(dbname, username, password, {
64   dialect: 'postgres',
65   host: CONFIG.DATABASE.HOSTNAME,
66   port: CONFIG.DATABASE.PORT,
67   benchmark: isTestInstance(),
68   isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE,
69   operatorsAliases: false,
70
71   logging: (message: string, benchmark: number) => {
72     let newMessage = message
73     if (isTestInstance() === true && benchmark !== undefined) {
74       newMessage += ' | ' + benchmark + 'ms'
75     }
76
77     logger.debug(newMessage)
78   }
79 })
80
81 database.sequelize = sequelize
82
83 database.init = async (silent: boolean) => {
84   const modelDirectory = join(__dirname, '..', 'models')
85
86   const filePaths = await getModelFiles(modelDirectory)
87
88   for (const filePath of filePaths) {
89     try {
90       const model = sequelize.import(filePath)
91
92       database[model['name']] = model
93     } catch (err) {
94       logger.error('Cannot import database model %s.', filePath, err)
95       process.exit(0)
96     }
97   }
98
99   for (const modelName of Object.keys(database)) {
100     if ('associate' in database[modelName]) {
101       database[modelName].associate(database)
102     }
103   }
104
105   if (!silent) logger.info('Database %s is ready.', dbname)
106
107   return
108 }
109
110 // ---------------------------------------------------------------------------
111
112 export {
113   database
114 }
115
116 // ---------------------------------------------------------------------------
117
118 async function getModelFiles (modelDirectory: string) {
119   const files = await readdirPromise(modelDirectory)
120   const directories = files.filter(directory => {
121     // Find directories
122     if (
123       directory.endsWith('.js.map') ||
124       directory === 'index.js' || directory === 'index.ts' ||
125       directory === 'utils.js' || directory === 'utils.ts'
126     ) return false
127
128     return true
129   })
130
131   const tasks: Promise<any>[] = []
132
133   // For each directory we read it and append model in the modelFilePaths array
134   for (const directory of directories) {
135     const modelDirectoryPath = join(modelDirectory, directory)
136
137     const promise = readdirPromise(modelDirectoryPath)
138       .then(files => {
139         const filteredFiles = files
140           .filter(file => {
141             if (
142               file === 'index.js' || file === 'index.ts' ||
143               file === 'utils.js' || file === 'utils.ts' ||
144               file.endsWith('-interface.js') || file.endsWith('-interface.ts') ||
145               file.endsWith('.js.map')
146             ) return false
147
148             return true
149           })
150           .map(file => join(modelDirectoryPath, file))
151
152         return filteredFiles
153       })
154
155     tasks.push(promise)
156   }
157
158   const filteredFilesArray: string[][] = await Promise.all(tasks)
159   return flattenDepth<string>(filteredFilesArray, 1)
160 }