|
| 1 | +const fs = require('fs') |
| 2 | +const path = require('path') |
| 3 | +const cheerio = require('cheerio') |
| 4 | +const LDP = require('../../lib/ldp') |
| 5 | +const { URL } = require('url') |
| 6 | +const debug = require('../../lib/debug') |
| 7 | +const { readFile } = require('../../lib/common/fs-utils') |
| 8 | + |
| 9 | +const { compileTemplate, writeTemplate } = require('../../lib/common/template-utils') |
| 10 | +const { loadConfig, loadAccounts } = require('./cli-utils') |
| 11 | +const { getName, getWebId } = require('../../lib/common/user-utils') |
| 12 | +const { initConfigDir, initTemplateDirs } = require('../../lib/server-config') |
| 13 | + |
| 14 | +module.exports = function (program) { |
| 15 | + program |
| 16 | + .command('updateindex') |
| 17 | + .description('Update index.html in root of all PODs that haven\'t been marked otherwise') |
| 18 | + .action(async (options) => { |
| 19 | + const config = loadConfig(program, options) |
| 20 | + const configPath = initConfigDir(config) |
| 21 | + const templates = initTemplateDirs(configPath) |
| 22 | + const indexTemplatePath = path.join(templates.account, 'index.html') |
| 23 | + const indexTemplate = await compileTemplate(indexTemplatePath) |
| 24 | + const ldp = new LDP(config) |
| 25 | + const accounts = loadAccounts(config) |
| 26 | + const usersProcessed = accounts.map(async account => { |
| 27 | + const accountDirectory = path.join(config.root, account) |
| 28 | + const indexFilePath = path.join(accountDirectory, '/index.html') |
| 29 | + if (!isUpdateAllowed(indexFilePath)) { |
| 30 | + return |
| 31 | + } |
| 32 | + const accountUrl = getAccountUrl(account, config) |
| 33 | + try { |
| 34 | + const webId = await getWebId(accountDirectory, accountUrl, ldp.suffixMeta, (filePath) => readFile(filePath)) |
| 35 | + const name = await getName(webId, ldp.fetchGraph) |
| 36 | + writeTemplate(indexFilePath, indexTemplate, { name, webId }) |
| 37 | + } catch (err) { |
| 38 | + debug.errors(`Failed to create new index for ${account}: ${JSON.stringify(err, null, 2)}`) |
| 39 | + } |
| 40 | + }) |
| 41 | + await Promise.all(usersProcessed) |
| 42 | + debug.accounts(`Processed ${usersProcessed.length} users`) |
| 43 | + }) |
| 44 | +} |
| 45 | + |
| 46 | +function getAccountUrl (name, config) { |
| 47 | + const serverUrl = new URL(config.serverUri) |
| 48 | + return `${serverUrl.protocol}//${name}.${serverUrl.host}/` |
| 49 | +} |
| 50 | + |
| 51 | +function isUpdateAllowed (indexFilePath) { |
| 52 | + const indexSource = fs.readFileSync(indexFilePath, 'utf-8') |
| 53 | + const $ = cheerio.load(indexSource) |
| 54 | + const allowAutomaticUpdateValue = $('meta[name="solid-allow-automatic-updates"]').prop('content') |
| 55 | + return !allowAutomaticUpdateValue || allowAutomaticUpdateValue === 'true' |
| 56 | +} |
0 commit comments