All files / src jobs.ts

100% Statements 211/211
100% Branches 75/75
100% Functions 99/99
100% Lines 186/186

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 3771x 1x 1x   1x 1x   1x       1x     4x 4x 4x   4x 4x 3x 1x   3x 2x     4x 2x     4x 24x 24x 24x 112x 112x 112x   112x 112x             112x         2x 2x           2x         2x   2x             1x 1x 1x 1x   2x 12x 12x 12x 56x 56x 56x 50x   50x   50x       6x         1x 1x   1x           1x 1x 1x 1x   2x 12x 12x 12x 56x 56x 56x 50x   50x   50x       6x         1x 1x   1x           2x 2x 2x 2x   4x 24x 24x 24x 112x 112x 112x 110x   110x 110x   110x 110x       110x 110x 94x 94x 94x 94x             110x   110x 110x   110x         2x         2x 2x   2x           2x 2x 2x 2x   4x 24x 24x 24x 112x 112x 112x 110x     110x   110x       110x   110x       2x         2x 2x   2x           1x 1x 1x 1x 1x   1x   1x       1x 1x   2x 2x 1x     1x         1x         1x 1x   1x           5x 5x 5x     5x 3x 1x   3x 1x 1x   3x 1x     5x 4x     5x       5x 21x 21x 21x   2x   19x 3x     16x   16x     5x 5x   5x           1x             17x 17x   17x 4x   17x 1x   17x 1x   17x 2x   17x 2x   17x 1x   17x 5x   17x 16x   14x   14x     2x   2x       1x    
import { Storage } from '@google-cloud/storage';
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';
import * as h2p from 'html2plaintext';
import * as sitemap from 'sitemap';
 
import { FUNCTIONS_CONFIG } from './config';
import { JobModel, LocaleAlternateModel } from './models/';
 
/** firestore instance */
const db = admin.firestore();
 
/** generate site map */
const generateSiteMap = async (snap: DocumentSnapshot, jobData: JobModel): Promise<any> => {
    console.log('generateSiteMap is started');
    let urlList: Array<sitemap.SitemapItemOptions> = [];
    let hostname: string;
    const collections = ['pages', 'articles', 'blogs', 'jokes', 'quotes', 'taxonomy'];
    if (jobData.hasOwnProperty('customData')) {
        if (jobData.customData.hasOwnProperty('urlList')) {
            urlList = jobData.customData.urlList;
        }
        if (jobData.customData.hasOwnProperty('hostname')) {
            hostname = jobData.customData.hostname;
        }
    }
    if (!hostname) {
        throw new Error('You have to provide a hostname with customData for sitemap!');
    }
 
    return Promise.all(FUNCTIONS_CONFIG.supportedCultureCodes.map(async cultureCode =>
        Promise.all(collections.map(async collectionPrefix =>
            db.collection(`${collectionPrefix}_${cultureCode}`).get()
                .then(async mainDocsSnapshot =>
                    Promise.all(mainDocsSnapshot.docs.map(async mainDoc => {
                        const mData = mainDoc.data();
                        const languageCode = cultureCode.substring(0, 2);
                        // tslint:disable-next-line:no-string-literal
                        const img = mData.hasOwnProperty('image') ? mData['image']['src'] : undefined;
                        urlList.push({
                            url: `${languageCode}/${mData.routePath}/${mainDoc.id}`.replace(/[\/]+/g, '/'),
                            changefreq: (collectionPrefix === 'pages' || collectionPrefix === 'taxonomy')
                                ? sitemap.EnumChangefreq.DAILY : sitemap.EnumChangefreq.WEEKLY,
                            img
                        });
 
                        return Promise.resolve();
                    }))
                )
        ))
    ))
        .then(async values => {
            const sm = sitemap.createSitemap({
                hostname,
                cacheTime: 600000, // 600 sec - cache purge period
                urls: urlList
            });
 
            return db.collection('firstResponses')
                .doc('sitemap.xml')
                .set({content: sm.toString(), changed: new Date()}, {merge: true})
                // tslint:disable-next-line:promise-function-async
                .then(() =>
                    snap.ref.set({result: `Count of urls: ${urlList.length}`}, {merge: true})
                        .then(() =>
                            Promise.resolve(`generateSiteMap is finished. Count of urls: ${urlList.length}`)
                        )
                );
        });
};
 
/** generate SEO data */
const generateSEOData = async (snap: DocumentSnapshot, jobData: JobModel): Promise<any> => {
    console.log('generateSEOData is started');
    let processedDocCount = 0;
    const collections = ['pages', 'articles', 'blogs', 'jokes', 'quotes', 'taxonomy'];
 
    return Promise.all(FUNCTIONS_CONFIG.supportedCultureCodes.map(async cultureCode =>
        Promise.all(collections.map(async collectionPrefix =>
            db.collection(`${collectionPrefix}_${cultureCode}`).get()
                .then(async mainDocsSnapshot =>
                    Promise.all(mainDocsSnapshot.docs.map(async mainDoc => {
                        const mData = mainDoc.data();
                        if (!mData.hasOwnProperty('seo') || jobData.overwrite) {
                            const seo = {};
 
                            return mainDoc.ref.set({seo}, {merge: true})
                                .then(() => {
                                    processedDocCount++;
                                });
                        }
 
                        return Promise.resolve();
                    }))
                )
        ))
    ))
        .then(async values =>
            snap.ref.set({result: `Count of processed documents: ${processedDocCount}`}, {merge: true})
                .then(() =>
                    Promise.resolve(`generateSEOData is finished. Count of processed documents: ${processedDocCount}`)
                )
        );
};
 
/** generate JsonLD */
const generateJsonLDs = async (snap: DocumentSnapshot, jobData: JobModel): Promise<any> => {
    console.log('generateJsonLDs is started');
    let processedDocCount = 0;
    const collections = ['pages', 'articles', 'blogs', 'jokes', 'quotes', 'taxonomy'];
 
    return Promise.all(FUNCTIONS_CONFIG.supportedCultureCodes.map(async cultureCode =>
        Promise.all(collections.map(async collectionPrefix =>
            db.collection(`${collectionPrefix}_${cultureCode}`).get()
                .then(async mainDocsSnapshot =>
                    Promise.all(mainDocsSnapshot.docs.map(async mainDoc => {
                        const mData = mainDoc.data();
                        if (!mData.hasOwnProperty('jsonLDs') || jobData.overwrite) {
                            const jsonLDs = [];
 
                            return mainDoc.ref.set({jsonLDs}, {merge: true})
                                .then(() => {
                                    processedDocCount++;
                                });
                        }
 
                        return Promise.resolve();
                    }))
                )
        ))
    ))
        .then(async values =>
            snap.ref.set({result: `Count of processed documents: ${processedDocCount}`}, {merge: true})
                .then(() =>
                    Promise.resolve(`generateJsonLDs is finished. Count of processed documents: ${processedDocCount}`)
                )
        );
};
 
/** generate locales */
const generateLocales = async (snap: DocumentSnapshot, jobData: JobModel): Promise<any> => {
    console.log('generateLocales is started');
    let processedDocCount = 0;
    const collections = ['pages', 'articles', 'blogs', 'jokes', 'quotes', 'taxonomy'];
 
    return Promise.all(FUNCTIONS_CONFIG.supportedCultureCodes.map(async cultureCode =>
        Promise.all(collections.map(async collectionPrefix =>
            db.collection(`${collectionPrefix}_${cultureCode}`).get()
                .then(async mainDocsSnapshot =>
                    Promise.all(mainDocsSnapshot.docs.map(async mainDoc => {
                        const mData = mainDoc.data();
                        if (!mData.hasOwnProperty('locales') || jobData.overwrite) {
                            const alternateCultureCodes = FUNCTIONS_CONFIG.supportedCultureCodes.slice();
                            // tslint:disable-next-line:no-dynamic-delete
                            delete alternateCultureCodes[alternateCultureCodes.indexOf(cultureCode)];
                            const locales = [] as Array<LocaleAlternateModel>;
 
                            return Promise.all(alternateCultureCodes.map(async cultureCodeAlt =>
                                db.collection(`${collectionPrefix}_${cultureCodeAlt}`)
                                    .where('i18nKey', '==', mData.i18nKey)
                                    .limit(1)
                                    .get()
                                    .then(async documentSnapshots => {
                                        if (documentSnapshots.docs.length > 0) {
                                            const languageCodeAlt = cultureCodeAlt.substring(0, 2);
                                            const mainDocAlt = documentSnapshots.docs[0];
                                            const mDataAlt = mainDocAlt.data();
                                            locales.push({
                                                cultureCode: cultureCodeAlt,
                                                slug: `${languageCodeAlt}/${mDataAlt.routePath}/${mainDocAlt.id}`
                                                    .replace(/[\/]+/g, '/')
                                            });
                                        }
 
                                        return Promise.resolve();
                                    })
                            )).then(async values =>
                                mainDoc.ref.set({locales}, {merge: true})
                                    .then(() => {
                                        processedDocCount++;
                                    })
                            );
                        }
 
                        return Promise.resolve();
                    }))
                )
        ))
    ))
        .then(async values =>
            snap.ref.set({result: `Count of processed documents: ${processedDocCount}`}, {merge: true})
                .then(() =>
                    Promise.resolve(`generateLocales is finished. Count of processed documents: ${processedDocCount}`)
                )
        );
};
 
/** generate description */
const generateDescription = async (snap: DocumentSnapshot, jobData: JobModel): Promise<any> => {
    console.log('generateDescription is started');
    let processedDocCount = 0;
    const collections = ['pages', 'articles', 'blogs', 'jokes', 'quotes', 'taxonomy'];
 
    return Promise.all(FUNCTIONS_CONFIG.supportedCultureCodes.map(async cultureCode =>
        Promise.all(collections.map(async collectionPrefix =>
            db.collection(`${collectionPrefix}_${cultureCode}`).get()
                .then(async mainDocsSnapshot =>
                    Promise.all(mainDocsSnapshot.docs.map(async mainDoc => {
                        const mData = mainDoc.data();
                        if (!mData.hasOwnProperty('description') || jobData.overwrite) {
                            let cleanText = mData.contentSummary ? h2p(mData.contentSummary) :
                                mData.content ? h2p(mData.content) :
                                    mData.title;
                            cleanText = cleanText.replace(/[\r\n]/g, ' ');
 
                            const description = cleanText.indexOf(' ', 150) > -1 ?
                                `${cleanText.substring(0, cleanText.indexOf(' ', 150))}...` :
                                `${cleanText.substring(0, 160)}...`;
 
                            return mainDoc.ref.set({description}, {merge: true})
                                .then(() => {
                                    processedDocCount++;
                                });
                        }
 
                        return Promise.resolve();
                    }))
                )
        ))
    ))
        .then(async values =>
            snap.ref.set({result: `Count of processed documents: ${processedDocCount}`}, {merge: true})
                .then(() =>
                    Promise.resolve(`generateDescription is finished. Count of processed documents: ${processedDocCount}`)
                )
        );
};
 
/** fix public files permissions on storage */
const fixPublicFilesPermissions = async (snap: DocumentSnapshot, jobData: JobModel): Promise<any> => {
    console.log('fixPublicFilesPermissions is started');
    const storage = new Storage();
    const bucketName = `${process.env.GCP_PROJECT}.appspot.com`;
    const bucket = admin.storage().bucket(bucketName);
 
    let processedDocCount = 0;
 
    return bucket.getFiles({
        prefix: 'publicFiles',
        autoPaginate: false
    })
         .then(async allFiles => {
             const files = allFiles[0];
 
             return Promise.all(files.map(async file => {
                     if (file.name.endsWith('/')) {
                         return Promise.resolve();
                     }
 
                     return file.acl.add({
                         entity: 'allUsers',
                         role: storage.acl.READER_ROLE
                     }).then(info => {
                         // console.log(info); // this "info" contains lots of cool info about file
                         processedDocCount++;
                     });
                 }
             ));
         })
         .then(async values =>
            snap.ref.set({result: `Count of processed files: ${processedDocCount}`}, {merge: true})
                .then(() =>
                    Promise.resolve(`fixPublicFilesPermissions is finished. Count of processed docs: ${processedDocCount}`)
                )
         );
};
 
/** clear caches */
const clearCaches = async (snap: DocumentSnapshot, jobData: JobModel): Promise<any> => {
    console.log('clearCaches is started');
    let processedDocCount = 0;
    let expireDate;
    let codeListToDelete;
    if (jobData.customData) {
        if (jobData.customData.hasOwnProperty('expireDate')) {
            expireDate = new Date(jobData.customData.expireDate.seconds * 1000);
        }
        if (jobData.customData.hasOwnProperty('expireDateDayDiff')) {
            expireDate = new Date();
            expireDate.setDate(Number(expireDate.getDate()) + Number(jobData.customData.expireDateDayDiff)); // add days
        }
        if (jobData.customData.hasOwnProperty('codeListToDelete')) {
            codeListToDelete = jobData.customData.codeListToDelete;
        }
    }
    if (!jobData.limit) {
        jobData.limit = 5000;
    }
 
    return db.collection('firstResponses')
        .where('type', '==', 'cache')
        .limit(jobData.limit)
        .get()
        .then(async mainDocsSnapshot =>
            Promise.all(mainDocsSnapshot.docs.map(async mainDoc => {
                const mainDocData = mainDoc.data();
                if (expireDate && mainDocData.expireDate && mainDocData.expireDate.seconds * 1000 > expireDate.getTime()) {
                    // to keep newly created caches
                    return Promise.resolve();
                }
                if (codeListToDelete && codeListToDelete.indexOf(mainDocData.code) === -1) {
                    return Promise.resolve();
                }
 
                return mainDoc.ref.delete()
                    .then(() => {
                        processedDocCount++;
                    });
            })))
        .then(async values =>
            snap.ref.set({result: `Count of processed documents: ${processedDocCount}`}, {merge: true})
                .then(() =>
                    Promise.resolve(`clearCaches is finished. Count of processed documents: ${processedDocCount}`)
                )
        );
};
 
/** job runner function */
export const jobRunner = functions
    // .region('europe-west1')
    // .runWith({ memory: '1GB', timeoutSeconds: 120 })
    .firestore
    .document('jobs/{jobId}')
    // tslint:disable-next-line:promise-function-async
    .onCreate((snap, context) => {
        console.log('jobRunner is started');
        const jobData = snap.data() as JobModel;
        let job: Promise<any>;
        if (jobData.actionKey === 'generateSiteMap') {
            job = generateSiteMap(snap, jobData);
        }
        if (jobData.actionKey === 'generateSEOData') {
            job = generateSEOData(snap, jobData);
        }
        if (jobData.actionKey === 'generateJsonLDs') {
            job = generateJsonLDs(snap, jobData);
        }
        if (jobData.actionKey === 'generateLocales') {
            job = generateLocales(snap, jobData);
        }
        if (jobData.actionKey === 'generateDescription') {
            job = generateDescription(snap, jobData);
        }
        if (jobData.actionKey === 'fixPublicFilesPermissions') {
            job = fixPublicFilesPermissions(snap, jobData);
        }
        if (jobData.actionKey === 'clearCaches') {
            job = clearCaches(snap, jobData);
        }
        if (job) {
            return job
                .then(value => {
                    console.log(value);
 
                    return value;
                })
                .catch(err => {
                    console.error('functions.onCreate', err);
 
                    return err;
                });
        }
 
        return Promise.resolve();
    });