All files / src/app/services seo.service.ts

100% Statements 99/99
100% Branches 31/31
100% Functions 17/17
100% Lines 97/97

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 2981x 1x 1x 1x 1x 1x 1x   1x           1x                                 161x     161x                                 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x               215x 215x 215x 215x 215x   215x 25x   190x     215x   215x 215x 215x 215x               215x 211x   215x 215x 215x 215x 215x   215x   215x   215x   215x 215x     215x 215x 215x 4x 4x           215x         215x                     215x 1x     215x 1x     215x 1x     215x 1x                   215x 130x 45x     85x   215x 27x 11x   69x 69x     27x 11x   43x 43x                       649x 72x             649x 649x 649x   1732x   649x               864x 430x   1975x                 1x             8x                 769x 769x                             1x                       2668x 2664x 2664x             4x                     31x        
import { DOCUMENT, isPlatformBrowser, PlatformLocation } from '@angular/common';
import { Inject, Injectable, LOCALE_ID, NgZone, PLATFORM_ID, Renderer2, RendererFactory2, ViewEncapsulation } from '@angular/core';
import { DomSanitizer, Meta, SafeHtml, Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { Observable, Subject } from 'rxjs';
import { environment } from '../../environments/environment';
import { APP_CONFIG, InterfaceAppConfig } from '../app-config';
import { ConfigSeoModel, HtmlLinkElementModel, HttpStatusModel, PageBaseModel } from '../models';
import { JsonLDService } from './jsonld.service';
 
/**
 * Seo Service
 */
@Injectable()
export class SeoService {
    /** locale */
    locale: string;
    /** Renderer2 object */
    renderer: Renderer2;
    /**
     * custom SEO Meta Tags
     * We need to keep them in order to remove them before load tags of next page
     */
    customSEOMetaTags: Array<{
        /** type of meta tag; name or property */
        type: string,
        /** value of name or property, NOT content value */
        value: string
    }>;
 
    /** config for SEO */
    configSEO: ConfigSeoModel = {};
 
    /** http status */
    private readonly httpStatus$ = new Subject<HttpStatusModel>();
 
    /**
     * constructor of SeoService
     * @param meta: Meta
     * @param titleService: Title
     * @param router: Router
     * @param ngZone: NgZone
     * @param rendererFactory: RendererFactory2
     * @param platformLocation: PlatformLocation
     * @param sanitizer: DomSanitizer
     * @param platformId: PLATFORM_ID
     * @param appConfig: APP_CONFIG
     * @param localeP: LOCALE_ID
     * @param doc: DOCUMENT
     * @param jsonLDService: JsonLDService
     */
    constructor(private readonly meta: Meta,
                private readonly titleService: Title,
                private readonly router: Router,
                private readonly ngZone: NgZone,
                private readonly rendererFactory: RendererFactory2,
                private readonly platformLocation: PlatformLocation,
                private readonly sanitizer: DomSanitizer,
                @Inject(PLATFORM_ID) private readonly platformId: string,
                @Inject(APP_CONFIG) private readonly appConfig: InterfaceAppConfig,
                @Inject(LOCALE_ID) private readonly localeP: string,
                @Inject(DOCUMENT) public doc: Document,
                private readonly jsonLDService: JsonLDService) {
        this.locale = localeP === 'tr' ? 'tr-TR' : 'en-US'; // TODO: fix for other locales, this is quick fix to force to use with culture codes
    }
 
    /**
     * Set Html Tags
     * @param page: current page
     */
    setSEOData(page: PageBaseModel): void {
        const tempPage = {...page};
        this.titleService.setTitle(tempPage.title);
        this.meta.updateTag({itemprop: 'name', content: tempPage.title}, "itemprop='name'");
        this.meta.updateTag({name: 'description', content: tempPage.description}, "name='description'");
        this.meta.updateTag({itemprop: 'description', content: tempPage.description}, "itemprop='description'");
 
        if (tempPage.image) {
            this.meta.updateTag({itemprop: 'image', content: tempPage.image.src}, "itemprop='image'");
        } else {
            this.meta.removeTag("itemprop='image'");
        }
 
        this.meta.updateTag({name: 'apple-mobile-web-app-title', content: tempPage.title}, "name='apple-mobile-web-app-title'");
 
        this.setLocalAndUrlHtmlTags(tempPage);
        this.setProjectSpecifiedHtmlTags();
        this.setCustomSEOHtmlTags(tempPage);
        this.jsonLDService.setJsonLD(tempPage, this.configSEO);
    }
 
    /**
     * Set Locale and Url Html Tags
     * @param tempPage: current page
     */
    setLocalAndUrlHtmlTags(tempPage: PageBaseModel): void {
        if (!tempPage.hasOwnProperty('locales')) {
            tempPage.locales = [];
        }
        const protocol = environment.protocol;
        const host = environment.host;
        const cultureCode = this.locale;
        const languageCode = this.locale.substr(0, 2);
        const slug = this.platformLocation.pathname;
 
        tempPage.canonicalUrl = `${protocol}${host}${slug}`;
 
        this.updateLink({rel: 'canonical', href: tempPage.canonicalUrl}, "link[rel='canonical']");
 
        this.meta.updateTag({httpEquiv: 'Content-Language', content: languageCode}, "httpEquiv='Content-Language'");
 
        this.meta.updateTag({property: 'og:url', content: tempPage.canonicalUrl}, "property='og:url'");
        this.meta.updateTag({property: 'og:locale', content: cultureCode.replace('-', '_')},
            "property='og:locale'");
 
        this.meta.removeTag("property='og:locale:alternate'");
        this.removeLink("link[rel='alternate']");
        for (const langAlternate of tempPage.locales) {
            this.meta.updateTag({property: 'og:locale:alternate', content: langAlternate.cultureCode.replace('-', '_')});
            this.updateLink({
                rel: 'alternate',
                href: `${protocol}${host}/${langAlternate.slug}`,
                hreflang: langAlternate.cultureCode
            });
        }
        this.updateLink({
            rel: 'alternate',
            href: tempPage.canonicalUrl,
            hreflang: cultureCode
        });
        this.updateLink({
            rel: 'alternate',
            href: tempPage.canonicalUrl,
            hreflang: 'x-default'
        });
    }
 
    /**
     * Set Project Specified Html Tags
     */
    setProjectSpecifiedHtmlTags(): void {
        if (environment.defaultData['twitter:site']) {
            this.meta.updateTag({name: 'twitter:site', content: environment.defaultData['twitter:site']},
                "name='twitter:site'");
        }
        if (environment.defaultData['twitter:creator']) {
            this.meta.updateTag({name: 'twitter:creator', content: environment.defaultData['twitter:creator']},
                "name='twitter:creator'");
        }
        if (environment.defaultData['fb:app_id']) {
            this.meta.updateTag({property: 'fb:app_id', content: environment.defaultData['fb:app_id']},
                "property='fb:app_id'");
        }
        if (environment.defaultData['fb:admins']) {
            this.meta.updateTag({property: 'fb:admins', content: environment.defaultData['fb:admins']},
                "property='fb:admins'");
        }
    }
 
    /**
     * Set Custom SEO Html Tags
     * @param tempPage: current page
     */
    setCustomSEOHtmlTags(tempPage: PageBaseModel): void {
        if (this.customSEOMetaTags) {
            for (const customSEO of this.customSEOMetaTags) {
                this.meta.removeTag(`${customSEO.type}='${customSEO.value}'`);
            }
        } else {
            this.customSEOMetaTags = [];
        }
        if (tempPage.hasOwnProperty('seo')) {
            if (tempPage.seo.hasOwnProperty('names')) {
                Object.keys(tempPage.seo.names)
                    .forEach((prop: string) => {
                        this.meta.updateTag({name: prop, content: tempPage.seo.names[prop]}, `name='${prop}'`);
                        this.customSEOMetaTags.push({type: 'name', value: prop});
                    });
            }
            if (tempPage.seo.hasOwnProperty('properties')) {
                Object.keys(tempPage.seo.properties)
                    .forEach((prop: string) => {
                        this.meta.updateTag({property: prop, content: tempPage.seo.properties[prop]}, `property='${prop}'`);
                        this.customSEOMetaTags.push({type: 'property', value: prop});
                    });
            }
        }
    }
 
    /**
     * add or update link to head of document
     * @param linkObject: tags of link
     * @param attrSelector: selector to remove old link elements
     */
    updateLink(linkObject: HtmlLinkElementModel, attrSelector?: string): void {
        if (this.renderer === undefined) {
            this.renderer = this.rendererFactory.createRenderer(this.doc, {
                id: '-1',
                encapsulation: ViewEncapsulation.None,
                styles: [],
                data: {}
            });
        }
        this.removeLink(attrSelector);
        const link = this.renderer.createElement('link');
        Object.keys(linkObject)
            .forEach((prop: string) => {
                this.renderer.setAttribute(link, prop, linkObject[prop]);
            });
        this.renderer.appendChild(this.doc.head, link);
    }
 
    /**
     * add or remove link from head of document
     * @param attrSelector: selector to remove old link elements
     */
    removeLink(attrSelector: string): void {
        if (attrSelector) {
            this.doc.querySelectorAll(attrSelector)
                .forEach((oldLink: Element) => {
                    this.renderer.removeChild(this.doc.head, oldLink);
                });
        }
    }
 
    /**
     * get title of current page
     */
    getTitle(): string {
        return this.titleService.getTitle();
    }
 
    /**
     * get meta object of current page
     */
    getMeta(): Meta {
        return this.meta;
    }
 
    /**
     * http 301 redirection
     * @param destinationURL: destination URL
     * @param isExternal: is this url external?
     */
    http301(destinationURL: string, isExternal = false): void {
        const destURL = destinationURL.replace(/[\/]+/g, '/');
        if (isPlatformBrowser(this.platformId)) {
            // istanbul ignore next
            if (isExternal && !this.appConfig.isUnitTest) {
                // this.router.navigate can't work because it is out of base url
                window.location.href = destURL;
            } else {
                this.ngZone.run(() => {
                    this.router.navigate([destURL])
                        .catch(// istanbul ignore next
                            reason => {
                                console.error(reason);
                            });
                });
            }
        } else {
            this.httpStatus$.next({
                code: 301,
                htmlContent: `--http-redirect-301--${destURL}--end-of-http-redirect-301--`
            });
        }
    }
 
    /**
     * http 404 not found
     * @param htmlContent: html content, can be useful for debugging
     */
    http404(htmlContent?: string): void {
        if (isPlatformBrowser(this.platformId)) {
            this.ngZone.run(() => {
                this.router.navigate([this.router.url, 'http-404'])
                    .catch(// istanbul ignore next
                        reason => {
                            console.error(reason);
                        });
            });
        } else {
            this.httpStatus$.next({
                code: 404,
                htmlContent
            });
        }
    }
 
    /**
     * get http status
     */
    getHttpStatus(): Observable<HttpStatusModel> {
        return this.httpStatus$.asObservable();
    }
 
}