All files / dash.js/src/streaming/models CustomParametersModel.js

91.08% Statements 92/101
93.18% Branches 41/44
85.41% Functions 41/48
91.08% Lines 92/101

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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493                                                                          1x                               122x 122x     122x     122x       188x 188x 188x 188x 188x 188x 188x 188x 188x         66x       2x                       3x             1x               41x               7x               7x                   4x                   4x               3x               3x               35x                   10x               3x                   9x 9x 9x 6x 6x     9x 3x   6x                   8x 8x 2x     6x                         11x   5x   6x 6x   6x                                   4x 2x   2x   2x       2x                               211x                                                                                       6x               6x       16x 7x   9x 9x 7x         2x 2x 1x           2x 2x 1x           17x 17x 3x 2x     17x       20x                 57x 51x 51x 51x 51x               10x                 65x 57x 53x 45x 43x                 2x             47x 47x       1x         1x         10x   10x     122x                                                                             122x   122x     1x    
/**
 * The copyright in this software is being made available under the BSD License,
 * included below. This software may be subject to other third party and contributor
 * rights, including patent rights, and no such rights are granted under this license.
 *
 * Copyright (c) 2013, Dash Industry Forum.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *  * Redistributions of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation and/or
 *  other materials provided with the distribution.
 *  * Neither the name of Dash Industry Forum nor the names of its
 *  contributors may be used to endorse or promote products derived from this software
 *  without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
 *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */
import UTCTiming from '../../dash/vo/UTCTiming.js';
import FactoryMaker from '../../core/FactoryMaker.js';
import Settings from '../../core/Settings.js';
import {checkParameterType} from '../utils/SupervisorTools.js';
import Constants from '../constants/Constants.js';
import ExternalSubtitle from '../vo/ExternalSubtitle.js';
 
const DEFAULT_XHR_WITH_CREDENTIALS = false;
 
function CustomParametersModel() {
 
    let instance,
        utcTimingSources,
        xhrWithCredentials,
        requestInterceptors,
        responseInterceptors,
        licenseRequestFilters,
        licenseResponseFilters,
        customCapabilitiesFilters,
        customInitialTrackSelectionFunction,
        externalSubtitles,
        customAbrRules;
 
    const context = this.context;
    const settings = Settings(context).getInstance();
 
    function setup() {
        xhrWithCredentials = {
            default: DEFAULT_XHR_WITH_CREDENTIALS
        };
        _resetInitialSettings();
    }
 
    function _resetInitialSettings() {
        requestInterceptors = [];
        responseInterceptors = [];
        licenseRequestFilters = [];
        licenseResponseFilters = [];
        customCapabilitiesFilters = [];
        customAbrRules = [];
        customInitialTrackSelectionFunction = null;
        utcTimingSources = [];
        externalSubtitles = new Set();
    }
 
 
    function reset() {
        _resetInitialSettings();
    }
 
    function resetPlaybackSessionSpecificSettings() {
        externalSubtitles = new Set();
    }
 
    function setConfig() {
 
    }
 
    /**
     * Registers a custom initial track selection function. Only one function is allowed. Calling this method will overwrite a potentially existing function.
     * @param {function} customFunc - the custom function that returns the initial track
     */
    function setCustomInitialTrackSelectionFunction(customFunc) {
        customInitialTrackSelectionFunction = customFunc;
    }
 
    /**
     * Resets the custom initial track selection
     */
    function resetCustomInitialTrackSelectionFunction() {
        customInitialTrackSelectionFunction = null;
    }
 
    /**
     * Returns the initial track selection function
     * @return {function}
     */
    function getCustomInitialTrackSelectionFunction() {
        return customInitialTrackSelectionFunction;
    }
 
    /**
     * Returns all license request filters
     * @return {array}
     */
    function getLicenseRequestFilters() {
        return licenseRequestFilters;
    }
 
    /**
     * Returns all license response filters
     * @return {array}
     */
    function getLicenseResponseFilters() {
        return licenseResponseFilters;
    }
 
    /**
     * Registers a license request filter. This enables application to manipulate/overwrite any request parameter and/or request data.
     * The provided callback function shall return a promise that shall be resolved once the filter process is completed.
     * The filters are applied in the order they are registered.
     * @param {function} filter - the license request filter callback
     */
    function registerLicenseRequestFilter(filter) {
        licenseRequestFilters.push(filter);
    }
 
    /**
     * Registers a license response filter. This enables application to manipulate/overwrite the response data
     * The provided callback function shall return a promise that shall be resolved once the filter process is completed.
     * The filters are applied in the order they are registered.
     * @param {function} filter - the license response filter callback
     */
    function registerLicenseResponseFilter(filter) {
        licenseResponseFilters.push(filter);
    }
 
    /**
     * Unregisters a license request filter.
     * @param {function} filter - the license request filter callback
     */
    function unregisterLicenseRequestFilter(filter) {
        _unregisterFilter(licenseRequestFilters, filter);
    }
 
    /**
     * Unregisters a license response filter.
     * @param {function} filter - the license response filter callback
     */
    function unregisterLicenseResponseFilter(filter) {
        _unregisterFilter(licenseResponseFilters, filter);
    }
 
    /**
     * Returns all custom capabilities filter
     * @return {array}
     */
    function getCustomCapabilitiesFilters() {
        return customCapabilitiesFilters;
    }
 
    /**
     * Registers a custom capabilities filter. This enables application to filter representations to use.
     * The provided callback function shall return a boolean or promise resolving to a boolean based on whether or not to use the representation.
     * The filters are applied in the order they are registered.
     * @param {function} filter - the custom capabilities filter callback
     */
    function registerCustomCapabilitiesFilter(filter) {
        customCapabilitiesFilters.push(filter);
    }
 
    /**
     * Unregisters a custom capabilities filter.
     * @param {function} filter - the custom capabilities filter callback
     */
    function unregisterCustomCapabilitiesFilter(filter) {
        _unregisterFilter(customCapabilitiesFilters, filter);
    }
 
    /**
     * Unregister a filter from the list of existing filers.
     * @param {array} filters
     * @param {function} filter
     * @private
     */
    function _unregisterFilter(filters, filter) {
        let index = -1;
        filters.some((item, i) => {
            if (item === filter) {
                index = i;
                return true;
            }
        });
        if (index < 0) {
            return;
        }
        filters.splice(index, 1);
    }
 
    /**
     * Iterate through the list of custom ABR rules and find the right rule by name
     * @param {string} rulename
     * @return {number} rule number
     */
    function _findAbrCustomRuleIndex(rulename) {
        let i;
        for (i = 0; i < customAbrRules.length; i++) {
            if (customAbrRules[i].rulename === rulename) {
                return i;
            }
        }
        return -1;
    }
 
    /**
     * Add a custom ABR Rule
     * Rule will be apply on next stream if a stream is being played
     *
     * @param {string} type - rule type (one of ['qualitySwitchRules','abandonFragmentRules'])
     * @param {string} rulename - name of rule (used to identify custom rule). If one rule of same name has been added, then existing rule will be updated
     * @param {object} rule - the rule object instance
     * @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with invalid arguments.
     */
    function addAbrCustomRule(type, rulename, rule) {
        if (typeof type !== 'string' || (type !== Constants.RULES_TYPES.ABANDON_FRAGMENT_RULES && type !== Constants.RULES_TYPES.QUALITY_SWITCH_RULES) ||
            typeof rulename !== 'string') {
            throw Constants.BAD_ARGUMENT_ERROR;
        }
        let index = _findAbrCustomRuleIndex(rulename);
        if (index === -1) {
            // add rule
            customAbrRules.push({
                type: type,
                rulename: rulename,
                rule: rule
            });
        } else E{
            // update rule
            customAbrRules[index].type = type;
            customAbrRules[index].rule = rule;
        }
    }
 
    /**
     * Remove a custom ABR Rule
     *
     * @param {string} rulename - name of the rule to be removed
     */
    function removeAbrCustomRule(rulename) {
        if (rulename) {
            let index = _findAbrCustomRuleIndex(rulename);
            //if no rulename custom rule has been found, do nothing
            if (index !== -1) {
                // remove rule
                customAbrRules.splice(index, 1);
            }
        } else {
            //if no rulename is defined, remove all ABR custome rules
            customAbrRules = [];
        }
    }
 
    /**
     * Remove all custom rules
     */
    function removeAllAbrCustomRule() {
        customAbrRules = [];
    }
 
    /**
     * Return all ABR custom rules
     * @return {array}
     */
    function getAbrCustomRules() {
        return customAbrRules;
    }
 
    /**
     * Adds a request interceptor. This enables application to monitor, manipulate, overwrite any request parameter and/or request data.
     * The provided callback function shall return a promise with updated request that shall be resolved once the process of the request is completed.
     * The interceptors are applied in the order they are added.
     * @param {function} interceptor - the request interceptor callback
     */
    function addRequestInterceptor(interceptor) {
        requestInterceptors.push(interceptor);
    }
 
    /**
     * Adds a response interceptor. This enables application to monitor, manipulate, overwrite the response data
     * The provided callback function shall return a promise with updated response that shall be resolved once the process of the response is completed.
     * The interceptors are applied in the order they are added.
     * @param {function} interceptor - the response interceptor callback
     */
    function addResponseInterceptor(interceptor) {
        responseInterceptors.push(interceptor);
    }
 
    /**
     * Unregisters a request interceptor.
     * @param {function} interceptor - the request interceptor callback
     */
    function removeRequestInterceptor(interceptor) {
        _unregisterFilter(requestInterceptors, interceptor);
    }
 
    /**
     * Unregisters a response interceptor.
     * @param {function} interceptor - the request interceptor callback
     */
    function removeResponseInterceptor(interceptor) {
        _unregisterFilter(responseInterceptors, interceptor);
    }
 
    /**
     * Returns all request interceptors
     * @return {array}
     */
    function getRequestInterceptors() {
        return requestInterceptors;
    }
 
    /**
     * Returns all response interceptors
     * @return {array}
     */
    function getResponseInterceptors() {
        return responseInterceptors;
    }
 
    function addExternalSubtitle(externalSubtitleObj) {
        if (!externalSubtitleObj || typeof externalSubtitleObj.id === 'undefined' || !externalSubtitleObj.url || !externalSubtitleObj.language || !externalSubtitleObj.mimeType || typeof externalSubtitleObj.bandwidth === 'undefined') {
            return
        }
        const externalSubtitle = new ExternalSubtitle(externalSubtitleObj);
        if (!_hasExternalSubtitleByKeyValue('url', externalSubtitle.url) && !_hasExternalSubtitleByKeyValue('id', externalSubtitle.id)) {
            externalSubtitles.add(externalSubtitle);
        }
    }
 
    function removeExternalSubtitleByUrl(url) {
        externalSubtitles.forEach((externalSubtitle) => {
            if (externalSubtitle.url === url) {
                externalSubtitles.delete(externalSubtitle);
            }
        })
    }
 
    function removeExternalSubtitleById(id) {
        externalSubtitles.forEach((externalSubtitle) => {
            if (externalSubtitle.id === id) {
                externalSubtitles.delete(externalSubtitle);
            }
        })
    }
 
    function _hasExternalSubtitleByKeyValue(key, value) {
        let found = false;
        externalSubtitles.forEach((externalSubtitle) => {
            if (externalSubtitle[key] === value) {
                found = true;
            }
        });
        return found;
    }
 
    function getExternalSubtitles() {
        return externalSubtitles;
    }
 
    /**
     * Add a UTC timing source at the top of the list
     * @param {string} schemeIdUri
     * @param {string} value
     */
    function addUTCTimingSource(schemeIdUri, value) {
        removeUTCTimingSource(schemeIdUri, value); //check if it already exists and remove if so.
        let vo = new UTCTiming();
        vo.schemeIdUri = schemeIdUri;
        vo.value = value;
        utcTimingSources.push(vo);
    }
 
    /**
     * Return all UTC timing sources
     * @return {array}
     */
    function getUTCTimingSources() {
        return utcTimingSources;
    }
 
    /**
     * Remove a specific timing source from the array
     * @param {string} schemeIdUri
     * @param {string} value
     */
    function removeUTCTimingSource(schemeIdUri, value) {
        checkParameterType(schemeIdUri, 'string');
        checkParameterType(value, 'string');
        utcTimingSources.forEach(function (obj, idx) {
            if (obj.schemeIdUri === schemeIdUri && obj.value === value) {
                utcTimingSources.splice(idx, 1);
            }
        });
    }
 
    /**
     * Remove all timing sources
     */
    function clearDefaultUTCTimingSources() {
        utcTimingSources = [];
    }
 
    /**
     * Add the default timing source to the list
     */
    function restoreDefaultUTCTimingSources() {
        let defaultUtcTimingSource = settings.get().streaming.utcSynchronization.defaultTimingSource;
        addUTCTimingSource(defaultUtcTimingSource.scheme, defaultUtcTimingSource.value);
    }
 
    function setXHRWithCredentialsForType(type, value) {
        Iif (!type) {
            Object.keys(xhrWithCredentials).forEach(key => {
                setXHRWithCredentialsForType(key, value);
            });
        } else {
            xhrWithCredentials[type] = !!value;
        }
    }
 
    function getXHRWithCredentialsForType(type) {
        const useCreds = xhrWithCredentials[type];
 
        return useCreds === undefined ? xhrWithCredentials.default : useCreds;
    }
 
    instance = {
        addAbrCustomRule,
        addExternalSubtitle,
        addRequestInterceptor,
        addResponseInterceptor,
        addUTCTimingSource,
        clearDefaultUTCTimingSources,
        getAbrCustomRules,
        getCustomCapabilitiesFilters,
        getCustomInitialTrackSelectionFunction,
        getExternalSubtitles,
        getLicenseRequestFilters,
        getLicenseResponseFilters,
        getRequestInterceptors,
        getResponseInterceptors,
        getUTCTimingSources,
        getXHRWithCredentialsForType,
        registerCustomCapabilitiesFilter,
        registerLicenseRequestFilter,
        registerLicenseResponseFilter,
        removeAbrCustomRule,
        removeAllAbrCustomRule,
        removeExternalSubtitleById,
        removeExternalSubtitleByUrl,
        removeRequestInterceptor,
        removeResponseInterceptor,
        removeUTCTimingSource,
        reset,
        resetCustomInitialTrackSelectionFunction,
        resetPlaybackSessionSpecificSettings,
        restoreDefaultUTCTimingSources,
        setConfig,
        setCustomInitialTrackSelectionFunction,
        setXHRWithCredentialsForType,
        unregisterCustomCapabilitiesFilter,
        unregisterLicenseRequestFilter,
        unregisterLicenseResponseFilter,
    };
 
    setup();
 
    return instance;
}
 
CustomParametersModel.__dashjs_factory_name = 'CustomParametersModel';
export default FactoryMaker.getSingletonFactory(CustomParametersModel);