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