-
Notifications
You must be signed in to change notification settings - Fork 45
/
config.js
334 lines (283 loc) · 8.49 KB
/
config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/** The synchronization client configuration
*
* @module core/config
* @flow
*/
const fs = require('fs')
const fse = require('fs-extra')
const _ = require('lodash')
const path = require('path')
const { hideOnWindows } = require('./utils/fs')
const logger = require('./utils/logger')
const log = logger({
component: 'Config'
})
/*::
export type WatcherType = 'atom' | 'chokidar'
type FileConfig = Object
*/
/* Stat dates on Windows were previously truncated to the second while we now
* get the milliseconds as well.
* To avoid re-calculating all the local checksums during the initial scan
* because of the date migration, we'll truncate `scan` events dates to the
* second during the first initial scan following the publication of v3.28.1
* when checking if the checksum of a given file can be reused or not.
*
* When publishing v3.28.2 or greater, we can remove WINDOWS_DATE_MIGRATION_FLAG
* and stop truncating dates during the initial scan.
*
* Users who will have skipped the version introducing the flag will see all
* their checksums re-computed.
*/
const WINDOWS_DATE_MIGRATION_APP_VERSION = '3.28.1'
const WINDOWS_DATE_MIGRATION_FLAG = 'roundWindowsDatesToSecondInInitialDiff'
const INVALID_CONFIG_ERROR = 'InvalidConfigError'
const INVALID_CONFIG_MESSAGE = 'Invalid client configuration'
class InvalidConfigError extends Error {
constructor() {
super(INVALID_CONFIG_MESSAGE)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, InvalidConfigError)
}
this.name = INVALID_CONFIG_ERROR
}
}
// Config can keep some configuration parameters in a JSON file,
// like the devices credentials or the mount path
class Config {
/*::
configPath: string
dbPath: string
fileConfig: FileConfig
*/
// Create config file if it doesn't exist.
constructor(basePath /*: string */) {
this.configPath = path.join(basePath, 'config.json')
fse.ensureFileSync(this.configPath)
this.dbPath = path.join(basePath, 'db')
fse.ensureDirSync(this.dbPath)
hideOnWindows(basePath)
this.fileConfig = this.read()
}
// Read the configuration from disk
read() /*: FileConfig */ {
if (fse.existsSync(this.tmpConfigPath)) {
const tmpConfig = loadOrDeleteFile(this.tmpConfigPath)
if (_.size(tmpConfig) > 0) {
this._moveTmpConfig()
return tmpConfig
}
}
return loadOrDeleteFile(this.configPath)
}
// Reset the configuration
reset() {
this.fileConfig = Object.create(null)
this.clear()
this.persist()
}
// Save configuration to file system.
persist() {
this._writeTmpConfig(this.toJSON())
this._moveTmpConfig()
}
_writeTmpConfig(config /*: string */) {
fse.ensureFileSync(this.tmpConfigPath)
fse.writeFileSync(this.tmpConfigPath, config)
}
_moveTmpConfig() {
if (fs.copyFileSync && fs.constants.COPYFILE_FICLONE) {
fs.copyFileSync(this.tmpConfigPath, this.configPath)
} else {
// Fallback for old node versions
fse.copySync(this.tmpConfigPath, this.configPath)
}
fse.unlinkSync(this.tmpConfigPath)
}
// Transform the config to a JSON string
toJSON() /*: string */ {
return JSON.stringify(this.fileConfig, null, 2)
}
// Get the tmp config path associated with the current config path
get tmpConfigPath() /*: string */ {
return this.configPath + '.tmp'
}
// Get the path on the local file system of the synchronized folder
get syncPath() /*: string */ {
return this.fileConfig.path
}
// Set the path on the local file system of the synchronized folder
set syncPath(path /*: string */) {
this.fileConfig.path = path
}
// Return the URL of the cozy instance
get cozyUrl() /*: string */ {
return this.fileConfig.url
}
// Set the URL of the cozy instance
set cozyUrl(url /*: string */) {
this.fileConfig.url = url
}
get gui() /*: * */ {
return this.fileConfig.gui || {}
}
// Return true if a device has been configured
isValid() /*: bool */ {
return !!(this.fileConfig.creds && this.cozyUrl)
}
// Return the name of the registered client
get deviceName() /*: ?string */ {
return _.get(this.fileConfig, 'creds.client.clientName', '')
}
// Return config related to the OAuth client
get client() /*: * */ {
if (!this.fileConfig.creds) {
throw new Error(`Device not configured`)
}
return this.fileConfig.creds.client
}
get capabilities() /*: * */ {
return _.get(this.fileConfig, 'instance.capabilities', {})
}
set capabilities({ flatSubdomains } /*: { flatSubdomains?: boolean } */) {
if (flatSubdomains != null) {
_.set(
this.fileConfig,
'instance.capabilities.flatSubdomains',
flatSubdomains
)
this.persist()
}
}
// Flags are options that can be activated by the user via the config file.
// They can be used to activate incomplete features for example.
get flags() /*: { [string]: boolean } */ {
return _.get(this.fileConfig, 'flags', {})
}
isFlagActive(flagName /*: string */) /*: boolean */ {
return this.flags[flagName] || false
}
setFlag(flag /*: string */, isActive /*: boolean */) {
if (
typeof flag !== 'string' ||
typeof isActive !== 'boolean' ||
flag === ''
) {
throw new Error(
`Invalid flag or value: [String(${flag})] → "${String(isActive)}"`
)
}
_.set(this.fileConfig, `flags.${flag}`, isActive)
this.persist()
}
get version() /*: ?string */ {
return _.get(this.fileConfig, 'creds.client.softwareVersion', '')
}
set version(newVersion /*: string */) /*: * */ {
_.set(this.fileConfig, 'creds.client.softwareVersion', newVersion)
this.persist()
}
get permissions() /*: string[] */ {
const scope = _.get(this.fileConfig, 'creds.token.scope', '')
return scope ? scope.split(' ') : []
}
// Set the remote configuration
set client(options /*: * */) {
this.fileConfig.creds = { client: options }
this.persist()
}
get watcherType() /*: WatcherType */ {
return watcherType(this.fileConfig)
}
// Implement the Storage interface for cozy-client-js oauth
save(key /*: string */, value /*: * */) {
this.fileConfig[key] = value
if (key === 'creds') {
// Persist the access token after it has been refreshed
this.persist()
}
return Promise.resolve(value)
}
load(key /*: string */) /*: Promise<*> */ {
return Promise.resolve(this.fileConfig[key])
}
delete(key /*: string */) /*: Promise<*> */ {
const deleted = delete this.fileConfig[key]
return Promise.resolve(deleted)
}
clear() /*: Promise<void> */ {
delete this.fileConfig.creds
delete this.fileConfig.state
return Promise.resolve()
}
}
function load(dir /*: string */) /*: Config */ {
return new Config(dir)
}
/** Load raw config from a JSON file.
*
* When file is invalid, delete it and return an empty object.
*/
function loadOrDeleteFile(configPath /*: string */) /*: FileConfig */ {
try {
const content = fs.readFileSync(configPath, 'utf8')
if (content === '') return {}
return JSON.parse(content)
} catch (e) {
if (e instanceof SyntaxError) {
log.error({ err: e }, `Could not read config file at ${configPath}`)
fse.unlinkSync(configPath)
return {}
} else {
throw e
}
}
}
/** Detect which local watcher will be used. */
function watcherType(
fileConfig /*: FileConfig */ = {},
{ env, platform } /*: * */ = process
) /*: WatcherType */ {
return (
fileWatcherType(fileConfig) ||
environmentWatcherType(env) ||
platformDefaultWatcherType(platform)
)
}
function fileWatcherType(fileConfig /*: FileConfig */) /*: ?WatcherType */ {
return validateWatcherType(fileConfig.watcherType)
}
function environmentWatcherType(
env /*: * */ = process.env
) /*: ?WatcherType */ {
const { COZY_FS_WATCHER } = env
return validateWatcherType(COZY_FS_WATCHER)
}
function platformDefaultWatcherType(
platform /*: string */ = process.platform
) /*: WatcherType */ {
if (platform === 'darwin') {
return 'chokidar'
}
return 'atom'
}
function validateWatcherType(watcherType /*: ?string */) /*: ?WatcherType */ {
if (watcherType === 'atom' || watcherType === 'chokidar') {
return watcherType
} else {
if (watcherType) log.warn({ watcherType }, 'Invalid watcher type')
return null
}
}
module.exports = {
INVALID_CONFIG_ERROR,
WINDOWS_DATE_MIGRATION_APP_VERSION,
WINDOWS_DATE_MIGRATION_FLAG,
InvalidConfigError,
Config,
environmentWatcherType,
load,
loadOrDeleteFile,
platformDefaultWatcherType,
watcherType
}