<commit_before>/*eslint-env node*/
'use strict'

const fs = require('fs')
const path = require('path')
const parser = require('./parseFile')
const glob = require('glob')
const stripJs = require('strip-js')
const winston = require('winston')

let mods = []

function readModFile(modId, dir = '/mods/', test = false) {
    let modData
    //Find in mods
    mods.forEach(mod => {
        if(mod.id == modId) modData = mod
    })
    if(!modData){
        try{
            let fileName = path.join(__dirname, dir, modId, '/mod.txt')
            modData = parser.readNewFile(fileName, test)
            //Add mod id
            modData.id = modId
            if(!test){
                winston.log('New mod id: ' + modId)
                mods.push(modData)
            }
        } catch(e){
            if(!test) winston.log('Did not find mod file: ' + modId + e)
            return false
        }
    }
    modData.description = stripJs(modData.description)
    return modData
}

function updateMod(newVersion){
    let updatedMod
    mods = mods.map(mod => {
        if(mod.id === newVersion.id){
            mod = newVersion
            updatedMod = mod
        }
        return mod
    })
    return updatedMod
}

function saveModFile(mod) {
    if (typeof mod !== 'object') {
        //Act as if mod id
        mods.forEach(_mod => {
            if(_mod.id === mod) mod = _mod
        })
    }
    fs.writeFileSync('./mods/' + mod.id + '/mod.txt', parser.toString(mod))
    return updateMod(mod)
}

module.exports = {
    readModFile,

    listMods: (req, res) => {
        glob('mods/*/mod.txt', (err, files) => {
            res.json({
                mods: files.map(file => {
                    let mod = Object.assign({},readModFile(file.replace(/mods\/(.*?)\/mod.txt/, '$1')))
                    if(!mod) {winston.log('error', 'This mod failed to load. Is the mod.txt correct? '); return null}
                    if(mod.name !== undefined) mod.logo = '/mods/' + mod.id + '/media/' + mod.logo
                    return mod
                }).filter(mod => mod)
            })
        })
    },
    getMediaFile: (req, res) => {
        let file = path.join(__dirname, 'mods', req.params.mod, req.params.file)
        if (fs.existsSync(file)) {
            res.sendFile(file)
        } else {
            res.sendFile(path.join(__dirname, 'plug.png'))
        }
    },

    createMod: (req,res) => {
        if(readModFile(req.body.id)) {
            winston.log('debug','Project already exits!')
            res.json({error:'A mod with this ID already exists!'})
            return
        }
        const dPath = path.join(__dirname, 'mods', req.body.id)
        fs.mkdirSync(dPath)
        //Create Text
        let txt = ''
        let rules = JSON.parse(fs.readFileSync('./templates/mod.json','utf8'))
        rules.forEach(line => {
            switch(line.typ){
                case 'copy':
                    txt += line.text + '\n'
                    break
                case 'combine':
                    if(line.quote){
                        txt += line.text + '\'' + req.body[line.value] + '\' \n'
                    } else{
                        txt += line.text + req.body[line.value] + '\n'
                    }
                    break
                default:
                    winston.log('error', 'An unknown type of line was trying to be inserted into a new mod: ' + line.typ)
            }
        })
        //Create mod.txt and laod it into the mods via readModFile()
        fs.writeFile(path.join(__dirname, '/mods/', req.body.id, '/mod.txt'), txt, err => {
            if (err) {
                res.json({error: err})
            } else {
                res.json(readModFile(req.body.id))
            }
        })
    },

    uploadPicture: (req,res) => {
        if (req.busboy) {
            req.busboy.on('file', (fieldName, fileStream, fileName) => {
                //Save picture
                const modName = req.params.mod
                let newPath = path.join(__dirname, 'mods', modName, fileName)
                fileStream.pipe(fs.createWriteStream(newPath))
                //Change the mod in mods
                mods.forEach(mod => {
                    if (mod.id === req.params.mod) {
                        winston.log('info', 'Uploaded picture to mod: ' + mod.id)
                        mod.logo = fileName
                        saveModFile(mod)
                    }
                })
                //Send back new logo path
                res.json('mods/' + modName + '/media/' + fileName)
            })
            req.pipe(req.busboy)
        } else{
            winston.log('error', 'req.busboy was not added to the picture upload!')
            res.json('Error!')
        }
    },

    addPartForReal: (req, res) => {
        res.send(200)
    },

    updateMod: (req, res) => {
        let toUpdate
        if ((toUpdate = readModFile(req.params.mod))) {
            toUpdate.name = req.body.name
            toUpdate.version = req.body.version
            toUpdate.author = req.body.author
            toUpdate.description = req.body.description
            res.json(saveModFile(toUpdate))
        }else{
            res.json({error: 'Mod has not been found!'})
        }
    },

    mainModData: (req, res) => {
        const needed = ["stringsfolder"]
        mods.forEach(mod => {
            if(mod.id === req.params.mod) {
                let data = []
                needed.forEach(part => {
                    if (mod[part] !== undefined) data.push({part: mod[part]})
                    else data.push({part: ""})
                })
                res.json(data)
            }
        })
        res.json({error: "Did not find mod!"})
    },

    changeMainModData: (req, res) => {
        let found = false
        mods.forEach(mod => {
            if(mod == req.params.mod){
                mod[req.params.id] = req.params.value
                winston.log('Debug', mod)
                mod.ignore.toAdd.filter(thing => !(thing === req.params.id))
                res.json('OK')<commit_msg>Fixed quotes<commit_after>/*eslint-env node*/
'use strict'

const fs = require('fs')
const path = require('path')
const parser = require('./parseFile')
const glob = require('glob')
const stripJs = require('strip-js')
const winston = require('winston')

let mods = []

function readModFile(modId, dir = '/mods/', test = false) {
    let modData
    //Find in mods
    mods.forEach(mod => {
        if(mod.id == modId) modData = mod
    })
    if(!modData){
        try{
            let fileName = path.join(__dirname, dir, modId, '/mod.txt')
            modData = parser.readNewFile(fileName, test)
            //Add mod id
            modData.id = modId
            if(!test){
                winston.log('New mod id: ' + modId)
                mods.push(modData)
            }
        } catch(e){
            if(!test) winston.log('Did not find mod file: ' + modId + e)
            return false
        }
    }
    modData.description = stripJs(modData.description)
    return modData
}

function updateMod(newVersion){
    let updatedMod
    mods = mods.map(mod => {
        if(mod.id === newVersion.id){
            mod = newVersion
            updatedMod = mod
        }
        return mod
    })
    return updatedMod
}

function saveModFile(mod) {
    if (typeof mod !== 'object') {
        //Act as if mod id
        mods.forEach(_mod => {
            if(_mod.id === mod) mod = _mod
        })
    }
    fs.writeFileSync('./mods/' + mod.id + '/mod.txt', parser.toString(mod))
    return updateMod(mod)
}

module.exports = {
    readModFile,

    listMods: (req, res) => {
        glob('mods/*/mod.txt', (err, files) => {
            res.json({
                mods: files.map(file => {
                    let mod = Object.assign({},readModFile(file.replace(/mods\/(.*?)\/mod.txt/, '$1')))
                    if(!mod) {winston.log('error', 'This mod failed to load. Is the mod.txt correct? '); return null}
                    if(mod.name !== undefined) mod.logo = '/mods/' + mod.id + '/media/' + mod.logo
                    return mod
                }).filter(mod => mod)
            })
        })
    },
    getMediaFile: (req, res) => {
        let file = path.join(__dirname, 'mods', req.params.mod, req.params.file)
        if (fs.existsSync(file)) {
            res.sendFile(file)
        } else {
            res.sendFile(path.join(__dirname, 'plug.png'))
        }
    },

    createMod: (req,res) => {
        if(readModFile(req.body.id)) {
            winston.log('debug','Project already exits!')
            res.json({error:'A mod with this ID already exists!'})
            return
        }
        const dPath = path.join(__dirname, 'mods', req.body.id)
        fs.mkdirSync(dPath)
        //Create Text
        let txt = ''
        let rules = JSON.parse(fs.readFileSync('./templates/mod.json','utf8'))
        rules.forEach(line => {
            switch(line.typ){
                case 'copy':
                    txt += line.text + '\n'
                    break
                case 'combine':
                    if(line.quote){
                        txt += line.text + '\'' + req.body[line.value] + '\' \n'
                    } else{
                        txt += line.text + req.body[line.value] + '\n'
                    }
                    break
                default:
                    winston.log('error', 'An unknown type of line was trying to be inserted into a new mod: ' + line.typ)
            }
        })
        //Create mod.txt and laod it into the mods via readModFile()
        fs.writeFile(path.join(__dirname, '/mods/', req.body.id, '/mod.txt'), txt, err => {
            if (err) {
                res.json({error: err})
            } else {
                res.json(readModFile(req.body.id))
            }
        })
    },

    uploadPicture: (req,res) => {
        if (req.busboy) {
            req.busboy.on('file', (fieldName, fileStream, fileName) => {
                //Save picture
                const modName = req.params.mod
                let newPath = path.join(__dirname, 'mods', modName, fileName)
                fileStream.pipe(fs.createWriteStream(newPath))
                //Change the mod in mods
                mods.forEach(mod => {
                    if (mod.id === req.params.mod) {
                        winston.log('info', 'Uploaded picture to mod: ' + mod.id)
                        mod.logo = fileName
                        saveModFile(mod)
                    }
                })
                //Send back new logo path
                res.json('mods/' + modName + '/media/' + fileName)
            })
            req.pipe(req.busboy)
        } else{
            winston.log('error', 'req.busboy was not added to the picture upload!')
            res.json('Error!')
        }
    },

    addPartForReal: (req, res) => {
        res.send(200)
    },

    updateMod: (req, res) => {
        let toUpdate
        if ((toUpdate = readModFile(req.params.mod))) {
            toUpdate.name = req.body.name
            toUpdate.version = req.body.version
            toUpdate.author = req.body.author
            toUpdate.description = req.body.description
            res.json(saveModFile(toUpdate))
        }else{
            res.json({error: 'Mod has not been found!'})
        }
    },

    mainModData: (req, res) => {
        const needed = ['stringsfolder']
        mods.forEach(mod => {
            if(mod.id === req.params.mod) {
                let data = []
                needed.forEach(part => {
                    if (mod[part] !== undefined) data.push({part: mod[part]})
                    else data.push({part: ''})
                })
                res.json(data)
            }
        })
        res.json({error: "Did not find mod!"})
    },

    changeMainModData: (req, res) => {
        let found = false
        mods.forEach(mod => {
            if(mod == req.params.mod){
                mod[req.params.id] = req.params.value
                winston.log('Debug', mod)
                mod.ignore.toAdd.filter(thing => !(thing === req.params.id))
                res.json('OK')
{'fraction_non_alphanumeric': 0.14291574370333907, 'fraction_numerical': 0.000820411846747067, 'mean_word_length': 1.4263535031847134, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2718642', 'n_tokens_mistral': 3638, 'n_tokens_neox': 3531, 'n_words': 770}