{"size": 3378, "ext": "js", "max_stars_repo_path": "imports/server/exportimport/expImpFilesDocuments.js", "max_stars_repo_name": "4minutes/4minutes", "max_stars_repo_stars_event_min_datetime": "2016-04-19T14:42:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T09:31:45.000Z", "max_issues_repo_path": "imports/server/exportimport/expImpFilesDocuments.js", "max_issues_repo_name": "4minutes/4minutes", "max_issues_repo_issues_event_min_datetime": "2016-04-27T15:29:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T10:15:39.000Z", "max_forks_repo_path": "imports/server/exportimport/expImpFilesDocuments.js", "max_forks_repo_name": "4minutes/4minutes", "max_forks_repo_forks_event_min_datetime": "2016-10-12T07:20:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T13:17:00.000Z"}
{"max_stars_count": 155, "max_issues_count": 497, "max_forks_count": 76, "avg_line_length": 41.1951219512, "max_line_length": 118, "alphanum_fraction": 0.4777975133}
const fs = require('fs');
const EJSON = require('mongodb-extended-json');

class ExpImpFilesDocuments {
    static get FILENAME_POSTFIX() {
        return '_filesDocuments.json';
    }

    static doExport (db, msID, userIDs) {
        return new Promise((resolve, reject) => {
            db.collection('DocumentsCollection')
                .find({'meta.meetingSeriesId': msID})
                .toArray()
                .then(doc => {
                    if (doc) {
                        const protFile = msID + ExpImpFilesDocuments.FILENAME_POSTFIX;
                        fs.writeFileSync(protFile, EJSON.stringify(doc,null,2));
                        console.log('Saved: '+protFile + ' with '+doc.length+' protocol documents');
                        if (doc[0]) {
                            console.log('      *** Hint *** Please manually copy all files below:');
                            console.log('      '+doc[0]._storagePath.substr(0, doc[0]._storagePath.lastIndexOf('/')));
                        }
                        resolve({db, userIDs});
                    } else {
                        return reject ('Unknown meeting series ID: '+ msID);
                    }
                });
        });
    }

    static doImport (db, msID, usrMap) {
        return new Promise((resolve, reject) => {
            const protFile = msID + ExpImpFilesDocuments.FILENAME_POSTFIX;
            let AllProtocolsDoc = undefined;
            try {
                AllProtocolsDoc = EJSON.parse(fs.readFileSync(protFile, 'utf8'));
                if (!AllProtocolsDoc) {
                    return reject('Could not read documents file '+protFile);
                }
            } catch (e) {
                return reject('Could not read documents file '+protFile+'\n'+e);
            }

            // Replace old user IDs with new users IDs
            let protcolsIDs = [];
            for(let p=0; p<AllProtocolsDoc.length; p++) {
                protcolsIDs.push(AllProtocolsDoc[p]._id);
                AllProtocolsDoc[p] = ExpImpFilesDocuments.patchUsers(AllProtocolsDoc[p], usrMap);
            }


            return db.collection('DocumentsCollection')
                .deleteMany({ _id : { $in : protcolsIDs } })     // delete existing attachments with same IDs
                .then(function (res) {
                    if (res.result && ! res.result.ok) {
                        console.log(res);
                    }
                    return db.collection('DocumentsCollection')
                        .insertMany(AllProtocolsDoc)                         // insert imported minutes
                        .then(function (res) {
                            if (res.result.ok === 1 && res.result.n === AllProtocolsDoc.length) {
                                console.log('OK, inserted '+res.result.n+' protocol files meta data.');
                                resolve({db, usrMap});
                            } else {
                                reject('Could not insert protocol files meta data');
                            }
                        });
                });
        });
    }

    static patchUsers(protocolDoc, usrMap) {
        if (usrMap[protocolDoc.userId]) {
            protocolDoc.userId = usrMap[protocolDoc.userId];
        }
        return protocolDoc;
    }

}

module.exports = ExpImpFilesDocuments;
