Passed
Push — develop ( 71622a...619f39 )
by Bjarn
01:49
created

SitesController.listLinks   B

Complexity

Conditions 8

Size

Total Lines 21
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 19
dl 0
loc 21
rs 7.3333
c 0
b 0
f 0
1
import Table from 'cli-table'
2
import {existsSync, readdirSync, unlinkSync, writeFileSync} from 'fs'
3
import Nginx from '../services/nginx'
4
import nginxLaravelTemplate from '../templates/nginx/apps/laravel'
5
import nginxMagento1Template from '../templates/nginx/apps/magento1'
6
import nginxMagento2Template from '../templates/nginx/apps/magento2'
7
import {error, info, success, url} from '../utils/console'
8
import {ensureDirectoryExists} from '../utils/filesystem'
9
import {getConfig, jaleSitesPath} from '../utils/jale'
10
import SecureController from './secureController'
11
import kleur from 'kleur'
12
13
class SitesController {
14
15
    appTypes = ['laravel', 'magento2', 'magento1']
16
17
    listLinks = async (): Promise<void> => {
18
        const config = await getConfig()
19
        await ensureDirectoryExists(jaleSitesPath)
20
        const sites = readdirSync(jaleSitesPath).map(fileName => fileName.replace(`.${config.tld}.conf`, ''))
21
22
        if (sites.length) {
23
            info(`Currently there ${sites.length > 1 ? 'are' : 'is'} ${sites.length} active Nginx vhost ${sites.length > 1 ? 'configurations' : 'configuration'}\n`)
24
25
            const table = new Table({
26
                head: ['Project', 'Secure'],
27
                colors: false
28
            })
29
30
            for (const site of sites) {
31
                const secure = new SecureController(site).isSecure()
32
                table.push([`${site}.${config.tld}`, (secure ? kleur.green('Yes') : kleur.red('No'))])
33
            }
34
35
            console.log(table.toString())
36
        } else {
37
            info(`Currently there ${sites.length > 1 ? 'are' : 'is'} no active Nginx vhost ${sites.length > 1 ? 'configurations' : 'configuration'}`)
38
        }
39
    }
40
41
    executeLink = async (type: string | undefined, name: string | undefined): Promise<void> => {
42
        const config = await getConfig()
43
        let appType = config.defaultTemplate
44
45
        if (type)
46
            appType = type
47
48
        if (!this.appTypes.includes(appType)) {
49
            error(`Invalid app type ${appType}. Please select one of: ${this.appTypes.join(', ')}`)
50
            return
51
        }
52
53
        const project = process.cwd().substring(process.cwd().lastIndexOf('/') + 1)
54
        const domain = name || project
55
        const hostname = `${domain}.${config.tld}`
56
57
        info(`Linking ${project} to ${hostname}...`)
58
59
        await ensureDirectoryExists(jaleSitesPath)
60
61
        this.createNginxConfig(appType, hostname, project)
62
63
        await (new Nginx()).reload()
64
65
        success(`Successfully linked ${domain}. Access it from ${url(`http://${hostname}`)}.`)
66
    }
67
68
    executeUnlink = async (): Promise<void> => {
69
        const config = await getConfig()
70
71
        const project = process.cwd().substring(process.cwd().lastIndexOf('/') + 1)
72
73
        let filename = `${project}.${config.tld}.conf`
74
75
        readdirSync(jaleSitesPath).forEach(file => {
76
            if (file.includes(project)) {
77
                filename = file
78
            }
79
        })
80
81
        if (!existsSync(`${jaleSitesPath}/${filename}`)) {
82
            error(`This project doesn't seem to be linked because the configuration file can't be found: ${jaleSitesPath}/${filename}`)
83
            return
84
        }
85
86
        info(`Unlinking ${project}...`)
87
88
        const secureController = new SecureController
89
90
        if (existsSync(secureController.crtPath))
91
            await secureController.executeUnsecure()
92
93
        unlinkSync(`${jaleSitesPath}/${filename}`)
94
95
        await (new Nginx()).reload()
96
97
        success(`Successfully unlinked ${project}.`)
98
    }
99
100
    /**
101
     * Create a Nginx template for the provided hostname with a specific template.
102
     *
103
     * @param appType
104
     * @param hostname
105
     * @param project
106
     */
107
    createNginxConfig = (appType: string, hostname: string, project: string): void => {
108
        switch (appType) {
109
        case 'magento2':
110
            writeFileSync(`${jaleSitesPath}/${project}.conf`, nginxMagento2Template(hostname, process.cwd()))
111
            break
112
        case 'magento1':
113
            writeFileSync(`${jaleSitesPath}/${project}.conf`, nginxMagento1Template(hostname, process.cwd()))
114
            break
115
        default:
116
            writeFileSync(`${jaleSitesPath}/${project}.conf`, nginxLaravelTemplate(hostname, process.cwd()))
117
            break
118
        }
119
    }
120
121
122
}
123
124
export default SitesController