Skip to content
Snippets Groups Projects
functions.service.ts 8.83 KiB
Newer Older
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { LatinisePipe } from 'ngx-pipes';
import { of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { NotificationService } from './notification.service';

@Injectable({
    providedIn: 'root'
})
export class FunctionsService {

    constructor(
        public translate: TranslateService,
        private latinisePipe: LatinisePipe,
        private router: Router,
        private http: HttpClient,
        private notify: NotificationService,
    ) { }

    empty(value: any) {
        if (value === null || value === undefined || value === false) {
            return true;

        } else if (Array.isArray(value)) {
            if (value.length > 0) {
                return false;
            } else {
                return true;
            }
        } else if (String(value) !== '') {
            return false;
        } else {
            return true;
        }
    }

    isDate(value: any) {
        return value instanceof Date && !isNaN(value.valueOf());
    }

    formatFrenchDateToTechnicalDate(date: string) {
        if (!this.empty(date)) {
            let arrDate = date.split('-');
            arrDate = arrDate.concat(arrDate[arrDate.length - 1].split(' '));
            arrDate.splice(2, 1);

            if (this.empty(arrDate[3])) {
                arrDate[3] = '00:00:00';
            }

            const formatDate = `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDate[3]}`;

            return formatDate;
        } else {
            return date;
        }
    }

    formatFrenchDateToObjectDate(date: string, delimiter: string = '-') {
        if (!this.empty(date)) {
            let arrDate = date.split(delimiter);
            arrDate = arrDate.concat(arrDate[arrDate.length - 1].split(' '));
            arrDate.splice(2, 1);

            if (this.empty(arrDate[3])) {
                arrDate[3] = '00:00:00';
            }

            const formatDate = `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDate[3]}`;

            return new Date(formatDate);
        } else {
            return date;
        }
    }

    formatDateObjectToDateString(date: Date, limitMode: boolean = false, format: string = 'dd-mm-yyyy') {
        if (date !== null) {
            const formatDate: any[] = [];
            format.split('-').forEach((element: any) => {
                if (element === 'dd') {
                    let day: any = date.getDate();
                    day = ('00' + day).slice(-2);
                    formatDate.push(day);
                } else if (element === 'mm') {
                    let month: any = date.getMonth() + 1;
                    month = ('00' + month).slice(-2);
                    formatDate.push(month);
                } else if (element === 'yyyy') {
                    const year: any = date.getFullYear();
                    formatDate.push(year);
                }
            });

            let limit = '';
            if (limitMode) {
                limit = ' 23:59:59';
            }
            return `${formatDate.join('-')}${limit}`;
        } else {
            return date;
        }
    }

    formatSerializedDateToDateString(date: string) {
        return this.formatDateObjectToDateString(new Date(date));
    }

    listSortingDataAccessor(data: any, sortHeaderId: any) {
        if (typeof data[sortHeaderId] === 'string') {
            return data[sortHeaderId].toLowerCase();
        }
        return data[sortHeaderId];
    }

    filterUnSensitive(template: any, filter: string, filteredColumns: any) {
        let filterReturn = false;
        filter = this.latinisePipe.transform(filter);
        filteredColumns.forEach((column: any) => {
            let val = template[column];
            if (typeof template[column] !== 'string') {
                val = val === undefined || null ? '' : JSON.stringify(val);
            }
            filterReturn = filterReturn || this.latinisePipe.transform(val.toLowerCase()).includes(filter);
        });
        return filterReturn;
    }

    formatBytes(bytes: number, decimals = 2) {
        if (typeof bytes === 'number') {
            if (bytes === 0) {
                return '0 Octet';
            }

            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['Octets', 'KO', 'MO', 'GO', 'TO', 'PO', 'EO', 'ZO', 'YO'];

            const i = Math.floor(Math.log(bytes) / Math.log(k));

            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        } else {
            return bytes;
        }
    }

    getBaseUrl() {
        const baseUrl = window.location.href.replace(this.router.url, '');
        return baseUrl;
    }

    getDayOfWeekString(id: number) {
        const mapDayOfWeek = {
            1: this.translate.instant('lang.monday'),
            2: this.translate.instant('lang.tuesday'),
            3: this.translate.instant('lang.wednesday'),
            4: this.translate.instant('lang.thursday'),
            5: this.translate.instant('lang.friday'),
            6: this.translate.instant('lang.saturday'),
            7: this.translate.instant('lang.sunday'),
        };
        return mapDayOfWeek[id];
    }

    getMonthString(id: number) {
        const mapMonths = {
            1: this.translate.instant('lang.january'),
            2: this.translate.instant('lang.february'),
            3: this.translate.instant('lang.march'),
            4: this.translate.instant('lang.april'),
            5: this.translate.instant('lang.may'),
            6: this.translate.instant('lang.june'),
            7: this.translate.instant('lang.july'),
            8: this.translate.instant('lang.august'),
            9: this.translate.instant('lang.september'),
            10: this.translate.instant('lang.october'),
            11: this.translate.instant('lang.november'),
            12: this.translate.instant('lang.december'),
        };
        return mapMonths[id];
    }

    getPictureById(id: string) {
        return new Promise((resolve) => {
            this.http.get(`assets/${id}.png`, { responseType: 'blob' }).pipe(
                tap((response: any) => {
                    const reader = new FileReader();
                    reader.readAsDataURL(response);
                    reader.onloadend = () => {
                        resolve(reader.result as any);
                    };
                }),
                catchError((err: any) => {
                    this.notify.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

    isValidUrl(value: string): boolean {
        const pattern = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;
        return pattern.test(value);
    }

    /**
     * Sanitizes HTML content to remove all script elements, event attributes, and external script URLs.
     * @param {string} html - The HTML content to be sanitized.
     * @returns {string} - The sanitized HTML content without any scripts or related elements.
    */
    sanitizeHtml(html: string): string {
        // Parse the input HTML string into a DOM object
        const domParser = new DOMParser().parseFromString(html, 'text/html');

        // Remove all <script> tags from the DOM
        const scripts = domParser.querySelectorAll('script');
        scripts.forEach((script: any) => {
            script.remove();
        });

        // Remove event attributes (such as onclick, onerror, etc.) from all elements
        const elementsWithEventAttributes = domParser.querySelectorAll('*');
        elementsWithEventAttributes.forEach(element => {
            element.removeAttribute('onabort');
            element.removeAttribute('onblur');
            element.removeAttribute('onchange');
            element.removeAttribute('onclick');
            element.removeAttribute('ondblclick');
            element.removeAttribute('onerror');
            element.removeAttribute('onfocus');
            element.removeAttribute('onkeydown');
            element.removeAttribute('onkeypress');
            element.removeAttribute('onkeyup');
            element.removeAttribute('onload');
            element.removeAttribute('onmousedown');
            element.removeAttribute('onmousemove');
            element.removeAttribute('onmouseout');
            element.removeAttribute('onmouseover');
            element.removeAttribute('onmouseup');
            element.removeAttribute('onreset');
            element.removeAttribute('onresize');
            element.removeAttribute('onscroll');
            element.removeAttribute('onselect');
            element.removeAttribute('onsubmit');
            element.removeAttribute('onunload');
        });

        // Return the sanitized HTML content
        return domParser.body.innerHTML;
    }