@dicdikshaorg/epub-player-v9
Version:
Contains Epub player library components powered by angular. These components are designed to be used in sunbird consumption platforms *(mobile app, web portal, offline desktop app)* to drive reusability, maintainability hence reducing the redundant develo
1,665 lines • 85.7 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@project-sunbird/client-services/telemetry'), require('@angular/common/http'), require('@project-sunbird/sunbird-player-sdk-v9'), require('rxjs'), require('rxjs/operators'), require('lodash'), require('epubjs'), require('@dicdikshaorg/player-sdk-v9'), require('@angular/common')) :
typeof define === 'function' && define.amd ? define('@dicdikshaorg/epub-player-v9', ['exports', '@angular/core', '@project-sunbird/client-services/telemetry', '@angular/common/http', '@project-sunbird/sunbird-player-sdk-v9', 'rxjs', 'rxjs/operators', 'lodash', 'epubjs', '@dicdikshaorg/player-sdk-v9', '@angular/common'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.dicdikshaorg = global.dicdikshaorg || {}, global.dicdikshaorg["epub-player-v9"] = {}), global.ng.core, global.telemetry, global.ng.common.http, global.sunbirdPlayerSdkV9, global.rxjs, global.rxjs.operators, global._, global.Epub, global.playerSdkV9, global.ng.common));
})(this, (function (exports, i0, telemetry, i3, sunbirdPlayerSdkV9, rxjs, operators, _, Epub, playerSdkV9, common) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var i0__namespace = /*#__PURE__*/_interopNamespace(i0);
var i3__namespace = /*#__PURE__*/_interopNamespace(i3);
var ___namespace = /*#__PURE__*/_interopNamespace(_);
var Epub__default = /*#__PURE__*/_interopDefaultLegacy(Epub);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (Object.prototype.hasOwnProperty.call(b, p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function () { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
__createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n])
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
}
else {
cooked.raw = raw;
}
return cooked;
}
;
var __setModuleDefault = Object.create ? (function (o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function (o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
__createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m")
throw new TypeError("Private method is not writable");
if (kind === "a" && !f)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function __classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function"))
throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
var epubPlayerConstants;
(function (epubPlayerConstants) {
epubPlayerConstants["LOADING"] = "LOADING";
epubPlayerConstants["START"] = "START";
epubPlayerConstants["END"] = "END";
epubPlayerConstants["EPUBLOADED"] = "epubLoaded";
epubPlayerConstants["PAGECHANGE"] = "pageChange";
epubPlayerConstants["NEXT"] = "NEXT";
epubPlayerConstants["PREVIOUS"] = "PREVIOUS";
epubPlayerConstants["ERROR"] = "error";
epubPlayerConstants["UNABLE_TO_FETCH_URL_ONLINE"] = "Internet is avialable but unable to fetch the url";
epubPlayerConstants["NAVIGATE_TO_PAGE"] = "NAVIGATE_TO_PAGE";
epubPlayerConstants["INVALID_PAGE_ERROR"] = "INVALID_PAGE_ERROR";
})(epubPlayerConstants || (epubPlayerConstants = {}));
var telemetryType;
(function (telemetryType) {
telemetryType["INTERACT"] = "INTERACT";
telemetryType["IMPRESSION"] = "IMPRESSION";
})(telemetryType || (telemetryType = {}));
var pageId;
(function (pageId) {
pageId["startPage"] = "START_PAGE";
pageId["submitPage"] = "SUBMIT_PAGE";
pageId["endPage"] = "END_PAGE";
pageId["shortAnswer"] = "SHORT_ANSWER";
})(pageId || (pageId = {}));
var eventName;
(function (eventName) {
eventName["pageScrolled"] = "PAGE_SCROLLED";
eventName["viewHint"] = "VIEW_HINT";
eventName["showAnswer"] = "SHOW_ANSWER_CLICKED";
eventName["nextClicked"] = "NEXT_CLICKED";
eventName["prevClicked"] = "PREV_CLICKED";
eventName["progressBar"] = "PROGRESSBAR_CLICKED";
eventName["replayClicked"] = "REPLAY_CLICKED";
eventName["startPageLoaded"] = "START_PAGE_LOADED";
eventName["viewSolutionClicked"] = "VIEW_SOLUTION_CLICKED";
eventName["solutionClosed"] = "SOLUTION_CLOSED";
eventName["closedFeedBack"] = "CLOSED_FEEDBACK";
eventName["tryAgain"] = "TRY_AGAIN";
eventName["optionClicked"] = "OPTION_CLICKED";
eventName["scoreBoardSubmitClicked"] = "SCORE_BOARD_SUBMIT_CLICKED";
eventName["endPageExitClicked"] = "EXIT";
eventName["zoomClicked"] = "ZOOM_CLICKED";
eventName["zoomInClicked"] = "ZOOM_IN_CLICKED";
eventName["zoomOutClicked"] = "ZOOM_OUT_CLICKED";
eventName["zoomCloseClicked"] = "ZOOM_CLOSE_CLICKED";
eventName["goToQuestion"] = "GO_TO_QUESTION";
eventName["nextContentPlay"] = "NEXT_CONTENT_PLAY";
})(eventName || (eventName = {}));
var UtilService = /** @class */ (function () {
function UtilService() {
this.fromConst = epubPlayerConstants;
}
UtilService.prototype.uniqueId = function (length) {
if (length === void 0) { length = 32; }
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
UtilService.prototype.getTimeSpentText = function (pdfPlayerStartTime) {
var duration = new Date().getTime() - pdfPlayerStartTime;
var minutes = Math.floor(duration / 60000);
var seconds = Number(((duration % 60000) / 1000).toFixed(0));
return (minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
};
UtilService.prototype.getCurrentIndex = function (event, currentPageIndex) {
if ((event === null || event === void 0 ? void 0 : event.interaction) === this.fromConst.NEXT) {
return currentPageIndex + 1;
}
if ((event === null || event === void 0 ? void 0 : event.interaction) === this.fromConst.PREVIOUS) {
return currentPageIndex - 1 === 0 ? 1 : currentPageIndex - 1;
}
};
UtilService.prototype.fulfillWithTimeLimit = function (timeLimit, task, failureValue) {
return __awaiter(this, void 0, void 0, function () {
var timeout, timeoutPromise, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
timeoutPromise = new Promise(function (resolve, reject) {
timeout = setTimeout(function () {
resolve(failureValue);
}, timeLimit);
});
return [4 /*yield*/, Promise.race([task, timeoutPromise])];
case 1:
response = _a.sent();
if (timeout) {
clearTimeout(timeout);
}
return [2 /*return*/, response];
}
});
});
};
return UtilService;
}());
/** @nocollapse */ UtilService.ɵprov = i0__namespace.ɵɵdefineInjectable({ factory: function UtilService_Factory() { return new UtilService(); }, token: UtilService, providedIn: "root" });
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
UtilService.decorators = [
{ type: i0.Injectable, args: [{
providedIn: 'root'
},] }
];
/**
* @type {function(): !Array<(null|{
* type: ?,
* decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
* })>}
* @nocollapse
*/
UtilService.ctorParameters = function () { return []; };
var EpubPlayerService = /** @class */ (function () {
function EpubPlayerService(utilService) {
this.utilService = utilService;
this.contentSessionId = this.utilService.uniqueId();
}
EpubPlayerService.prototype.initialize = function (_a) {
var context = _a.context, config = _a.config, metadata = _a.metadata;
this.context = context;
this.config = config;
this.playSessionId = this.utilService.uniqueId();
this.channel = this.context.channel;
this.pdata = this.context.pdata;
this.sid = this.context.sid;
this.uid = this.context.uid;
this.rollup = this.context.rollup;
if (!telemetry.CsTelemetryModule.instance.isInitialised) {
telemetry.CsTelemetryModule.instance.init({});
var telemetryConfig = {
config: {
pdata: context.pdata,
env: 'contentplayer',
channel: context.channel,
did: context.did,
authtoken: context.authToken || '',
uid: context.uid || '',
sid: context.sid,
batchsize: 20,
mode: context.mode,
host: context.host || '',
endpoint: context.endpoint || '/data/v3/telemetry',
tags: context.tags,
cdata: [{ id: this.contentSessionId, type: 'ContentSession' },
{ id: this.playSessionId, type: 'PlaySession' },
{ id: '2.0', type: 'PlayerVersion' }],
},
userOrgDetails: {}
};
if (context.dispatcher) {
telemetryConfig.config.dispatcher = context.dispatcher;
}
telemetry.CsTelemetryModule.instance.telemetryService.initTelemetry(telemetryConfig);
}
this.telemetryObject = {
id: metadata.identifier,
type: 'Content',
ver: metadata.pkgVersion + '' || '1.0',
rollup: context.objectRollup || {}
};
};
EpubPlayerService.prototype.start = function (duration) {
telemetry.CsTelemetryModule.instance.telemetryService.raiseStartTelemetry({
options: this.getEventOptions(),
edata: { type: 'content', mode: 'play', pageid: '', duration: Number((duration / 1e3).toFixed(2)) }
});
};
EpubPlayerService.prototype.interact = function (id, currentPage) {
telemetry.CsTelemetryModule.instance.telemetryService.raiseInteractTelemetry({
options: this.getEventOptions(),
edata: { type: 'TOUCH', subtype: '', id: id, pageid: currentPage + '' }
});
};
EpubPlayerService.prototype.impression = function (currentPage) {
telemetry.CsTelemetryModule.instance.telemetryService.raiseImpressionTelemetry({
options: this.getEventOptions(),
edata: { type: 'workflow', subtype: '', pageid: currentPage + '', uri: '' }
});
};
EpubPlayerService.prototype.end = function (duration, percentage, curentPage, endpageseen) {
var durationSec = Number((duration / 1e3).toFixed(2));
telemetry.CsTelemetryModule.instance.telemetryService.raiseEndTelemetry({
edata: {
type: 'content',
mode: 'play',
pageid: 'sunbird-player-Endpage',
summary: [
{
progress: percentage
},
{
totallength: (percentage === 100 ? curentPage : 1)
},
{
visitedlength: curentPage
},
{
visitedcontentend: (percentage === 100)
},
{
totalseekedlength: 0
},
{
endpageseen: endpageseen
}
],
duration: durationSec
},
options: this.getEventOptions()
});
};
EpubPlayerService.prototype.error = function (errorCode, errorType, pageid, stacktrace) {
telemetry.CsTelemetryModule.instance.telemetryService.raiseErrorTelemetry({
options: this.getEventOptions(),
edata: {
err: errorCode,
errtype: errorType,
stacktrace: stacktrace.toString(),
pageid: pageid || ''
}
});
};
EpubPlayerService.prototype.getEventOptions = function () {
return ({
object: this.telemetryObject,
context: {
channel: this.channel,
pdata: this.pdata,
env: 'contentplayer',
sid: this.sid,
uid: this.uid,
cdata: [{ id: this.contentSessionId, type: 'ContentSession' },
{ id: this.playSessionId, type: 'PlaySession' },
{ id: '2.0', type: 'PlayerVersion' }],
rollup: this.rollup || {}
}
});
};
return EpubPlayerService;
}());
/** @nocollapse */ EpubPlayerService.ɵprov = i0__namespace.ɵɵdefineInjectable({ factory: function EpubPlayerService_Factory() { return new EpubPlayerService(i0__namespace.ɵɵinject(UtilService)); }, token: EpubPlayerService, providedIn: "root" });
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
EpubPlayerService.decorators = [
{ type: i0.Injectable, args: [{
providedIn: 'root'
},] }
];
/**
* @type {function(): !Array<(null|{
* type: ?,
* decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
* })>}
* @nocollapse
*/
EpubPlayerService.ctorParameters = function () { return [
{ type: UtilService }
]; };
var ViwerService = /** @class */ (function () {
function ViwerService(utilService, epubPlayerService, http) {
this.utilService = utilService;
this.epubPlayerService = epubPlayerService;
this.http = http;
this.currentIndex = 0;
this.totalNumberOfPages = 0;
this.endPageSeen = false;
this.timeSpent = '0:0';
this.version = '1.0';
this.playerEvent = new i0.EventEmitter();
this.isAvailableLocally = false;
this.isEndEventRaised = false;
}
ViwerService.prototype.initialize = function (_a) {
var context = _a.context, config = _a.config, metadata = _a.metadata;
this.epubPlayerStartTime = this.epubLastPageTime = new Date().getTime();
this.totalNumberOfPages = 0;
this.currentIndex = 0;
this.contentName = metadata.name;
this.identifier = metadata.identifier;
this.artifactUrl = metadata.artifactUrl;
this.isAvailableLocally = metadata.isAvailableLocally;
if (this.isAvailableLocally) {
var basePath = (metadata.streamingUrl) ? (metadata.streamingUrl) : (metadata.basePath || metadata.baseDir);
this.src = basePath + "/" + metadata.artifactUrl;
}
else {
this.src = metadata.streamingUrl || metadata.artifactUrl;
}
if (context.userData) {
var _b = context.userData, firstName = _b.firstName, lastName = _b.lastName;
this.userName = firstName === lastName ? firstName : firstName + " " + lastName;
}
this.metaData = {
pagesVisited: [],
totalPages: 0,
duration: [],
zoom: [],
rotation: []
};
this.showDownloadPopup = false;
this.endPageSeen = false;
};
ViwerService.prototype.raiseStartEvent = function (event) {
this.currentIndex = event.items[0].index;
var duration = new Date().getTime() - this.epubPlayerStartTime;
var startEvent = {
eid: 'START',
ver: this.version,
edata: {
type: 'START',
currentPage: this.currentIndex,
duration: duration
},
metaData: this.metaData
};
this.playerEvent.emit(startEvent);
this.epubLastPageTime = this.epubPlayerStartTime = new Date().getTime();
this.epubPlayerService.start(duration);
};
ViwerService.prototype.raiseHeartBeatEvent = function (event, teleType) {
if (event.data) {
this.currentIndex = event.data.index;
}
var eventType = event.type ? event.type : event;
var heartBeatEvent = {
eid: 'HEARTBEAT',
ver: this.version,
edata: {
type: eventType,
currentPage: this.currentIndex
},
metaData: this.metaData
};
this.playerEvent.emit(heartBeatEvent);
if (telemetryType.IMPRESSION === teleType) {
this.epubPlayerService.impression(this.currentIndex);
}
if (telemetryType.INTERACT === teleType) {
this.epubPlayerService.interact(eventType.toLowerCase(), this.currentIndex);
}
};
ViwerService.prototype.raiseEndEvent = function (event) {
if (!this.isEndEventRaised) {
this.currentIndex = event.data.index;
var percentage = event.data.percentage || 0;
if (event.data.percentage) {
this.endPageSeen = true;
}
var duration = new Date().getTime() - this.epubPlayerStartTime;
this.metaData.duration = duration;
this.metaData.totalPages = this.totalNumberOfPages;
var endEvent = {
eid: 'END',
ver: this.version,
edata: {
type: 'END',
currentPage: event.data.index,
totalPages: this.totalNumberOfPages,
duration: duration
},
metaData: this.metaData
};
this.playerEvent.emit(endEvent);
var visitedlength = this.currentIndex;
this.timeSpent = this.utilService.getTimeSpentText(this.epubPlayerStartTime);
this.epubPlayerService.end(duration, percentage, this.currentIndex, this.endPageSeen);
}
};
ViwerService.prototype.raiseExceptionLog = function (errorCode, pageIndex, errorType, traceId, stacktrace) {
var exceptionLogEvent = {
eid: 'ERROR',
edata: {
err: errorCode,
errtype: errorType,
requestid: traceId || '',
stacktrace: stacktrace
}
};
this.playerEvent.emit(exceptionLogEvent);
this.epubPlayerService.error(errorCode, errorType, pageIndex, stacktrace);
};
ViwerService.prototype.isValidEpubSrc = function (src) {
var _this = this;
return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.http.get(src, { responseType: 'blob' }).toPromise().then(function (res) {
resolve(res);
}).catch(function (error) {
reject(error);
});
return [2 /*return*/];
});
}); });
};
ViwerService.prototype.raiseHeartBeatEventNew = function (type, telemetryType1, pageId, nextContentId) {
var hearBeatEvent = {
eid: 'HEARTBEAT',
ver: this.version,
edata: {
type: type,
currentPage: this.currentIndex
},
metaData: this.metaData
};
if (type === eventName.nextContentPlay && nextContentId) {
hearBeatEvent.edata.nextContentId = nextContentId;
}
// if (this.isSectionsAvailable) {
// hearBeatEvent.edata.sectionId = this.questionSetId;
// }
this.playerEvent.emit(hearBeatEvent);
if (telemetryType.INTERACT === telemetryType1) {
this.epubPlayerService.interact(type.toLowerCase(), pageId);
}
else if (telemetryType.IMPRESSION === telemetryType1) {
this.epubPlayerService.impression(pageId);
}
};
return ViwerService;
}());
/** @nocollapse */ ViwerService.ɵprov = i0__namespace.ɵɵdefineInjectable({ factory: function ViwerService_Factory() { return new ViwerService(i0__namespace.ɵɵinject(UtilService), i0__namespace.ɵɵinject(EpubPlayerService), i0__namespace.ɵɵinject(i3__namespace.HttpClient)); }, token: ViwerService, providedIn: "root" });
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
ViwerService.decorators = [
{ type: i0.Injectable, args: [{
providedIn: 'root'
},] }
];
/**
* @type {function(): !Array<(null|{
* type: ?,
* decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
* })>}
* @nocollapse
*/
ViwerService.ctorParameters = function () { return [
{ type: UtilService },
{ type: EpubPlayerService },
{ type: i3.HttpClient }
]; };
var ToastrService = /** @class */ (function () {
function ToastrService() {
this.toastSubject = new rxjs.Subject();
this.toastState$ = this.toastSubject.asObservable();
}
ToastrService.prototype.show = function (message, type) {
if (message === void 0) { message = ''; }
if (type === void 0) { type = ''; }
console.log(message, "this is message");
console.log(type, "this is type");
this.toastSubject.next({ message: message, type: type });
};
return ToastrService;
}());
/** @nocollapse */ ToastrService.ɵprov = i0__namespace.ɵɵdefineInjectable({ factory: function ToastrService_Factory() { return new ToastrService(); }, token: ToastrService, providedIn: "root" });
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
ToastrService.decorators = [
{ type: i0.Injectable, args: [{
providedIn: 'root'
},] }
];
/**
* @type {function(): !Array<(null|{
* type: ?,
* decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
* })>}
* @nocollapse
*/
ToastrService.ctorParameters = function () { return []; };
var EpubPlayerComponent = /** @class */ (function () {
function EpubPlayerComponent(viwerService, epubPlayerService, errorService, utilService, renderer2, http, toastrService) {
this.viwerService = viwerService;
this.epubPlayerService = epubPlayerService;
this.errorService = errorService;
this.utilService = utilService;
this.renderer2 = renderer2;
this.http = http;
this.toastrService = toastrService;
this.fromConst = epubPlayerConstants;
this.showFullScreen = false;
this.headerActionsEvent = new i0.EventEmitter();
this.telemetryEvent = new i0.EventEmitter();
this.showControls = true;
this.validPage = true;
this.sideMenuConfig = {
showShare: false,
showDownload: false,
showReplay: false,
showExit: false,
showPrint: false
};
this.urlTTS = 'https://dhruva-api.bhashini.gov.in/services/inference/pipeline';
this.urlDetectLang = 'https://dhruva-api.bhashini.gov.in/services/inference/txtlangdetection';
this.audio = '';
this.audioQueue = [];
this.playerState = { isPlaying: false };
this.counter = 0;
this.loading = false;
this.chunks = [];
this.isStreamIntrupted = false;
this.cancelRequests$ = new rxjs.Subject();
this.languageList = [
{ languageCode: 'en', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'hi', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'as', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'bn', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'gu', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'kn', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'mr', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'or', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'pa', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'ta', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'te', modelId: 'Bhashini/IITM/TTS' },
{ languageCode: 'ur', modelId: 'Bhashini/IITM/TTS' }
];
this.isInitialized = false;
this.viewState = this.fromConst.LOADING;
this.progress = 0;
this.currentPageIndex = 1;
this.headerConfiguration = {
rotation: false,
goto: true,
navigation: true,
zoom: false
};
this.playbackRate = 1.0;
this.langCode = '';
this.playerEvent = this.viwerService.playerEvent;
}
EpubPlayerComponent.prototype.onTelemetryEvent = function (event) {
this.telemetryEvent.emit(event.detail);
};
EpubPlayerComponent.prototype.ngOnInit = function () {
var _a, _b, _c, _d;
return __awaiter(this, void 0, void 0, function () {
var contentCompabilityLevel, checkContentCompatible;
return __generator(this, function (_e) {
this.mimeType = ___namespace.get(this.playerConfig, 'metadata.mimeType');
this.isInitialized = true;
if (this.playerConfig) {
if (typeof this.playerConfig === 'string') {
try {
this.playerConfig = JSON.parse(this.playerConfig);
}
catch (error) {
console.error('Invalid playerConfig: ', error);
}
}
}
// initializing services
this.viwerService.initialize(this.playerConfig);
this.epubPlayerService.initialize(this.playerConfig);
this.traceId = (_b = (_a = this.playerConfig) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.traceId;
// checks online error while loading epub
if (!navigator.onLine && !this.viwerService.isAvailableLocally) {
// tslint:disable-next-line:max-line-length
this.viwerService.raiseExceptionLog(sunbirdPlayerSdkV9.errorCode.internetConnectivity, this.currentPageIndex, sunbirdPlayerSdkV9.errorMessage.internetConnectivity, this.traceId, new Error(sunbirdPlayerSdkV9.errorMessage.internetConnectivity));
}
contentCompabilityLevel = (_d = (_c = this.playerConfig) === null || _c === void 0 ? void 0 : _c.metadata) === null || _d === void 0 ? void 0 : _d.compatibilityLevel;
if (contentCompabilityLevel) {
checkContentCompatible = this.errorService.checkContentCompatibility(contentCompabilityLevel);
if (!(checkContentCompatible === null || checkContentCompatible === void 0 ? void 0 : checkContentCompatible.isCompitable)) {
// tslint:disable-next-line:max-line-length
this.viwerService.raiseExceptionLog(sunbirdPlayerSdkV9.errorCode.contentCompatibility, this.currentPageIndex, sunbirdPlayerSdkV9.errorCode.contentCompatibility, this.traceId, checkContentCompatible.error);
}
}
this.showEpubViewer = true;
this.sideMenuConfig = Object.assign(Object.assign({}, this.sideMenuConfig), this.playerConfig.config.sideMenu);
this.getEpubLoadingProgress();
this.nextContent = this.playerConfig.config.nextContent;
return [2 /*return*/];
});
});
};
EpubPlayerComponent.prototype.ngOnChanges = function (changes) {
var _a;
if (changes.showFullScreen && !((_a = changes === null || changes === void 0 ? void 0 : changes.showFullScreen) === null || _a === void 0 ? void 0 : _a.firstChange)) {
this.showFullScreen = changes.showFullScreen.currentValue;
}
if (changes.playerConfig.firstChange && this.isInitialized) {
// Calling for web component explicitly and life cycle works in different order
this.ngOnInit();
}
};
EpubPlayerComponent.prototype.ngAfterViewInit = function () {
var _this = this;
var epubPlayerElement = this.epubPlayerRef.nativeElement;
this.unlistenMouseEnter = this.renderer2.listen(epubPlayerElement, 'mouseenter', function () {
_this.showControls = true;
});
this.unlistenMouseLeave = this.renderer2.listen(epubPlayerElement, 'mouseleave', function () {
_this.showControls = false;
});
};
EpubPlayerComponent.prototype.headerActions = function (eventdata) {
this.headerActionsEvent.emit(eventdata);
};
EpubPlayerComponent.prototype.onPlaybackRateChange = function (event) {
this.playbackRate = parseFloat(event.target.value);
if (this.audio) {
this.audio.playbackRate = this.playbackRate;
}
};
EpubPlayerComponent.prototype.handleNotification = function () {
this.handleButtonstop();
};
EpubPlayerComponent.prototype.handleButtonplay = function () {
this.audio.play();
};
EpubPlayerComponent.prototype.handleButtonpause = function () {
this.audio.pause();
};
EpubPlayerComponent.prototype.handleButtonstop = function () {
if (this.audio && typeof this.audio.pause === 'function') {
this.audio.pause();
this.audio.src = '';
this.isStreamIntrupted = true;
this.counter = 0;
this.playerState.isPlaying = false;
}
this.cancelRequests();
this.audioQueue = [];
};
EpubPlayerComponent.prototype.getModelId = function (languageCode) {
if (languageCode == 'unknown') {
this.toastrService.show('Sorry, we are currently unable to provide Audio for this document.', 'error');
}
var language = this.languageList.find(function (lang) { return lang.languageCode === languageCode; });
return language ? language.modelId : null;
};
EpubPlayerComponent.prototype.detectLanguage = function (chunk) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_e) {
return [2 /*return*/, new Promise(function (resolve, reject) {
var headers = new i3.HttpHeaders({
Authorization: 'Rl1KVAwFU5lUDH2fLfJ_4EJrroYZUGhG06oJbWemJOC3pFw9XA0tVpqKhroKQirW',
});
var payload = {
config: {
serviceId: "bhashini/iiiith/indic-lang-detection-all"
},
input: [
{
source: chunk
}
]
};
_this.http.post(_this.urlDetectLang, payload, { headers: headers }).subscribe(function (res) {
_this.langCode = res.output[0].langPrediction[0].langCode;
var modelId = _this.getModelId(_this.langCode);
resolve(modelId);
}, function (error) {
console.error('Error detecting language:', error);
_this.toastrService.show('Something Went Wrong', 'error');
resolve(null); // Resolve with null if there's an error
});
})];
});
});
};
EpubPlayerComponent.prototype.handleButtonClick = function (gender) {
return __awaiter(this, void 0, void 0, function () {
var epubjsId, epubHTML, parser, htmlDoc, hTags, speechText, serviceId, i;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
this.toastrService.show('Please wait , Audio Processing...', 'info');
this.isStreamIntrupted = false;
this.audioQueue = [];
epubjsId = document.querySelector('[id^="epubjs-view-"]').id;
if (!epubjsId) return [3 /*break*/, 7];
epubHTML = document.getElementById(epubjsId).getAttribute("srcdoc");
parser = new DOMParser();
htmlDoc = parser.parseFromString(epubHTML, "text/html");
hTags = htmlDoc.querySelector("body");
if (!hTags) return [3 /*break*/, 6];
speechText = this.extractTextFromElement(hTags);
this.chunks = this.chunkText(speechText, 250);
if (!this.chunks || this.chunks.length === 0) {
this.toastrService.show('Text is unavailable in current Page', 'error');
}
return [4 /*yield*/, this.detectLanguage(this.chunks[0])];
case 1:
serviceId = _e.sent();
i = 0;
_e.label = 2;
case 2:
if (!(i < this.chunks.length)) return [3 /*break*/, 6];
if (!!this.isStreamIntrupted) return [3 /*break*/, 4];
return [4 /*yield*/, this.processChunk(this.chunks[i], gender, serviceId)];
case 3:
_e.sent();
return [3 /*break*/, 5];
case 4:
this.chunks = [];
return [3 /*break*/, 6];
case 5:
i++;
return [3 /*break*/, 2];
case 6: return [3 /*break*/, 8];
case 7:
console.log("No epubjsId found");
_e.label = 8;
case 8: return [2 /*return*/];
}
});
});
};
EpubPlayerComponent.prototype.extractTextFromElement = function (element) {
var _this = this;
if (!element)
return "";
var text = "";
element.childNodes.forEach(function (node) {
if (node.nodeType === Node.TEXT_NODE) {
text += node.textContent.trim() + " ";
}
else if (node.nodeType === Node.ELEMENT_NODE) {
text += _this.extractTextFromElement(node);
}
});
return text.trim();
};
EpubPlayerComponent.prototype.processChunk = function (chunk, gender, serviceId) {
return __awaiter(this, void 0, void 0, function () {
var headers, payload, response, audioContent, base64Audio, audioUrl, error_1;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
if (!serviceId) {
console.error('Model ID not found.');
return [2 /*return*/];
}
headers = new i3.HttpHeaders({
Authorization: 'Rl1KVAwFU5lUDH2fLfJ_4EJrroYZUGhG06oJbWemJOC3pFw9XA0tVpqKhroKQirW',
});
payload = {
pipelineTasks: [
{
taskType: 'tts',
config: {
language: {
sourceLanguage: this.langCode,
},
serviceId: serviceId,
gender: gender,
speed: 1,
samplingRate: 16000,
},
},
],
inputData: {
input: [
{
source: chunk,
},
],
},
};
_e.label = 1;
case 1:
_e.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.http
.post(this.urlTTS, payload, { headers: headers })
.pipe(operators.takeUntil(this.cancelRequests$))
.toPromise()];
case 2:
response = _e.sent();
if (response) {
audioContent = response.pipelineResponse[0].audio[0].audioContent;
base64Audio = audioContent;
audioUrl = 'data:audio/mp3;base64,' + base64Audio;
this.audioQueue.push(audioUrl);
if (!this.playerState.isPlaying) {
this.playNextAudio();
}
}
return [3 /*break*/, 4];
case 3:
error_1 = _e.sent();
this.loading = false;
this.toastrService.show('Something Went Wrong', 'error');
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
});
};
EpubPlayerComponent.prototype.cancelRequests = function () {
this.cancelRequests$.next();
this.cancelRequests$.complete();
this.cancelRequests$ = new rxjs.Subject();
};
EpubPlayerComponent.prototype.playNextAudio = function () {
var _this = this;
if (this.audioQueue.length > 0 && !this.isStreamIntrupted) {
this.loading = false;
var audioUrl = this.audioQueue[this.counter++];
this.audio = new Audio(audioUrl);
this.audio.controls = true;
this.audio.playbackRate = this.playbackRate;
this.playerState.isPlaying = true;
this.audio.play();
this.audio.addEventListener('ended', function () {
_this.playerState.isPlaying = false;
_this.playNextAudio();
});
}
else {
this.playerState.isPlaying = false;
}
};
EpubPlayerComponent.prototype.chunkText = function (text, chunkSize) {
var chunks = [];
if (!text)
return chunks;
var startIndex = 0;
while (startIndex < text.length) {
var endIndex = Math.min(startIndex + chunkSize, text.length);
// Ensure we don't split a word
if (endIndex < text.length && text[endIndex] !== ' ') {
while (endIndex > startIndex && text[endIndex] !== ' ') {
endIndex--;
}
// If no space was found, set endIndex to chunkSize
if (endIndex === startIndex) {
endIndex = Math.min(startIndex + chunkSize, text.length);
}
}
chunks.push(text.substring(startIndex, endIndex).trim());
startIndex = endIndex + 1; // Move past the space
}
return chunks;
};
EpubPlayerComponent.prototype.viewerEvent = function (event) {
if (event.type === this.fromConst.EPUBLOADED) {
this.onEpubLoaded(event);
}
if (event.type === this.fromConst.PAGECHANGE) {
this.onPageChange(event);
}
if (event.type === this.fromConst.END) {
this.onEpubEnded(event);
}
if (event.type === this.fromConst.ERROR) {
this.onEpubLoadFailed(event);
}
if (event.type === this.fromConst.NAVIGATE_TO_PAGE) {
this.onJumpToPage(event);
}
if (event.type === this.fromConst.INVALID_PAGE_ERROR) {
this.validPage = event.data;
this.resetValidPage();
}
};
EpubPlayerComponent.prototype.resetValidPage = function () {
var _this = this;
setTimeout(function () {
_this.validPage = true;
}, 5000);
};
EpubPlayerComponent.prototype.onEpubLoaded = function (event) {
var _a, _b, _c;
clearInterval(this.intervalRef);
this.viewState = this.fromConst.START;
this.viwerService.raiseStartEvent(event.data);
if (((_b = (_a = this.playerConfig.config) === null || _a === void 0 ? void 0 : _a.pagesVisited) === null || _b === void 0 ? void 0 : _b.length) && ((_c = this.playerConfig.config) === null || _c === void 0 ? void 0 : _c.currentLocation)) {
this.currentPageIndex = this.playerConfig.config.pagesVisited[this.playerConfig.config.pagesVisited.length - 1];
}
this.viwerService.metaData.pagesVisited.push(this.currentPageIndex);
};
EpubPlayerComponent.prototype.onPageChange = function (event) {
var _a;
if ((_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.index) {
this.currentPageIndex = event.data.index;
}
this.currentPageIndex = this.utilService.getCurrentIndex(event, this.currentPageIndex);
this.viwerService.raiseHeartBeatEvent(event, telemetryType.INTERACT);
this.viwerService.raiseHeartBeatEvent(event, telemetryType.IMPRESSION);
this.viwerService.metaData.pagesVisited.push(this.currentPageIndex);
};
EpubPlayerComponent.prototype.onJumpToPage = function (type) {
var _a;
this.currentPageIndex = (_a = type === null || type === void 0 ? void 0 : type.event) === null || _a === void 0 ? void 0 : _a.data;
this.viwerService.raiseHeartBeatEvent(type, telemetryType.INTERACT);
this.viwerService.raiseHeartBeatEvent(type, telemetryType.IMPRESSION);
this.viwerService.metaData.pagesVisited.push(this.currentPageIndex);
};
EpubPlayerComponent.prototype.onEpubEnded = function (event) {
this.handleButtonstop();
this.viewState = this.fromConst.END;
this.showEpubViewer = false;
event.data.index = this.currentPageIndex;
this.viwerService.raiseEndEvent(event);
};
EpubPlayerComponent.prototype.onEpubLoadFailed = function (error) {
this.showContentError = true;
this.viewState = this.fromConst.LOADING;
// tslint:disable-next-line:max-line-length
this.viwerService.raiseExceptionLog(error.errorCode, this.currentPageIndex, error.errorMessage, this.traceId, new Error(error.errorMessage));
};
EpubPlayerComponent.prototype.replayContent = function (event) {
this.currentPageIndex = 1;
this.viwerService.raiseHeartBeatEvent(event, telemetryType.INTERACT);
this.viewState = this.fromConst.START;
this.viwerService.metaData.pagesVisited.push(this.currentPageIndex);
this.ngOnInit();
};
EpubPlayerComponent.prototype.exitContent = function (event) {
this.viwerService.raiseHeartBeatEvent(event, telemetryType.INTERACT);
};
EpubPlayerComponent.prototype.sideBarEvents = function (event) {
this.viwerService.raiseHeartBeatEvent(event, telemetryType.INTERACT);
if (event.type === 'DOWNLOAD') {
this.downloadEpub();
}
};
EpubPlayerComponent.prototype.sidebarMenuEvent = function (event) {
this.viwerService.raiseHeartBeatEvent(event, telemetryType.INTERACT);
};
EpubPlayerComponent.prototype.getEpubLoadingProgress = function () {
var _this = this;
this.intervalRef = setInterval(function () {
if (_this.progress < 95) {
_this.progress = _this.progress + 5;
}
}, 10);
};
EpubPlayerComponent.prototype.downloadEpub = function () {
var a = document.createElement('a');
a.href = this.viwerService.artifactUrl;
a.download = this.viwerService.contentName;
a.target = '_blank';
document.body.appendChild(a);
a.click();
a.remove();
this.viwerService.raiseHeartBeatEvent('DOWNLOAD');
};
EpubPlayerComponent.prototype.ngOnDestroy = function () {
this.handleButtonstop();
var EndEvent = {
type: this.fromConst.END,
data: {
index: this.currentPageIndex
}
};
this.viwerService.raiseEndEvent(EndEvent);
this.viwerService.isEndEventRaised = false;
this.unlistenMouseEnter();
this.unlistenMouseLeave();
};
// Function to play next content
EpubPlayerComponent.prototype.playNextContent = function (event) {
this.viwerService.raiseHeartBeatEventNew(event === null || event === void 0 ? void 0 : event.type, telemetryType.INTERACT, pageId.endPage, event === null || event === void 0 ? void 0 : event.identifier);
};
return EpubPlayerComponent;
}());
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
EpubPlayerComponent.decorators = [
{ type: i0.Component, args: [{
// tslint:disable-next-line:component-selector
selector: 'sunbird-epub-player',
template: "<div class=\"sunbird-epub-container\" #epubPlayer>\r\n<div *ngIf=\"viewState === fromConst.LOADING\">\r\n <sb-player-start-page [title]=\"viwerService.contentName\" [progress]=\"progress\"></sb-player-start-page>\r\n</div>\r\n<div class=\"epub-container\" *ngIf=\"showEpubViewer\">\r\n <ng-container *ngIf=\"viewState === fromConst.START\">\r\n <sb-player-header class=\"notVisible\" [playerState]=\"playerState\" [mimeType]=\"mimeType\" (buttonclick)=\"handleButtonClick($event)\" (buttonstop)=\"handleButtonstop()\" (buttonPause)=\"handleButtonpause()\" (buttonPlay)=\"handleButtonplay()\" (notify)=\"handleNotification()\" (changePlaybackrate)=\"onPlaybackRateChange($event)\" [totalPages]=\"viwerService?.totalNumberOfPages\" [pageNumber]=\"currentPageIndex\" [config]=\"headerConfiguration\" (actions)=\"headerActions($event)\" [ngClass]=\"{'isVisible': showControls}\"></sb-player-header>\r\n <sb-player-side-menu-icon class=\"notVisible\" [ngClass]=\"{'isVisible': showControls}\" (sidebarMenuEvent)=\"sidebarMenuEvent($event)\">\r\n </sb-player-side-menu-icon>\r\n <sb-player-sidebar [title]=\"viwerService.contentName\" (sidebarEvent)=\"sideBarEvents($event)\"\r\n [config]=\"sideMenuConfig\"></sb-player-sidebar>\r\n <div class=\"sb-epub-reading-status\" *ngIf=\"currentPageIndex && viwerService?.totalNumberOfPages\">\r\n Page {{currentPageIndex}} of {{viwerService?.totalNumberOfPages}} <span></span> {{((currentPageIndex/viwerService?.totalNumberOfPages) * 100).toFixed(0)}}%\r\n </div>\r\n \r\n </ng-container>\r\n <epub-viewer [actions]=\"headerActionsEvent\" [epubSrc]=\"viwerService.src\" [identifier]=\"viwerService.identifier\"\r\n (viewerEvent)=\"viewerEvent($event)\" [config]=\"playerConfig.config\" [showFullScreen]=\"showFullScreen\">\r\n </epub-viewer>\r\n</div>\r\n<sb-player-end-page *ngIf=\"viewState === fromConst.END\" [contentName]=\"viwerService.contentName\"\r\n [outcomeLabel]=\"'Pages read: '\" [outcome]=\"(currentPageIndex -1)\" [showExit]=\"sideMenuConfig.showExit\" [userName]=\"viwerService.userName\"\r\n [timeSpentLabel]=\"viwerService.timeSpent\" (replayContent)=\"replayContent($event)\" (exitContent)=\"exitContent($event)\" [nextContent]=\"nextContent\" (playNextContent)=\"playNextContent($event)\">\r\n</sb-player-end-page>\r\n<sb-player-contenterror *ngIf=\"showContentError\"></sb-player-contenterror>\r\n</div>\r\n<div class=\"pagenotfound__tooltip\" *ngIf=\"!validPage\">\r\n <div class=\"pagenotfound__icon\"></div>\r\n <div class=\"pagenotfound__text\">Page Not Found</div>\r\n</div>\r\n\r\n<toastr></toastr>",
styles: [".sunbird-epub-container{height:100%;width:100%;background-color:#fff}.sunbird-epub-palyer-container{width:100%;height:100%;overflow:hidden;position:relative}.sb-epub-reading-status{color:var(--gray-800);font-size:.75rem;position:absolute;left:1rem;bottom:.75rem;display:flex;align-items:center;background:var(--white);border-radius:.5rem;padding:.25em .5rem;z-index:5;line-height:normal}.sb-epub-reading-status span{background:var(--gray-800);width:4px;height:4px;display:block;margin:0 .5em;border-radius:50%}.notVisible,.BtmNotVisible{transition:all .3s ease-in-out;position:absolute;width:100%}.notVisible{top:-10rem}.notVisible.isVisible{top:0rem}.BtmNotVisible{bottom:-10rem}.BtmNotVisible.isVisible{bottom:0rem}:host::ng-deep .sb-player-splash-container{height:100vh!important}:host::ng-deep epub-viewer{position:absolute;top:48px;width:100%;height:calc(100% - 48px);overflow-y:auto;overflow-x:hidden;left:0;background-color:#fff}:host::ng-deep .epub-container{height:100%;position:relative;overflow-x:hidden!important}.pagenotfound__tooltip{position:absolute;top:10%;left:50%;transform:translate(-50%);background:#333;z-index:11111;padding:calculateRem(8px) calculateRem(20px);font-size:calculateRem(14px);color:#fff;border-radius:calculateRem(4px);display:flex;align-items:center}.pagenotfound__icon{width:calculateRem(22px);height:calculateRem(22px);margin-right:calculateRem(12px);background:white;border-radius:50%;position:relative}.pagenotfound__icon:after{content:\"!\";position:absolute;top:50%;left:50%;color:#333;font-size:18px;transform:translate(-50%,-50%)}\n"]
},] }
];
/**
* @type {function(): !Array<(null|{
* type: ?,
* decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
* })>}
* @nocollapse
*/
EpubPlayerComponent.ctorParameters = function () { return [
{ type: ViwerService },
{ type: EpubPlayerService },
{ type: sunbirdPlayerSdkV9.ErrorService },
{ type: UtilService },
{ type: i0.Renderer2 },
{ type: i3.HttpClient },
{ type: ToastrService }
]; };
/** @type {!Object<string, !Array<{type: !Function, args: (undefined|!Array<?>)}>>} */
EpubPlayerComponent.propDecorators = {
epubPlayerRef: [{ type: i0.ViewChild, args: ['epubPlayer', { static: true },] }],
playerConfig: [{ type: i0.Input }],
showFullScreen: [{ type: i0.Input }],
headerActionsEvent: [{ type: i0.Output }],
telemetryEvent: [{ type: i0.Output }],
playerEvent: [{ type: i0.Output }],
onTelemetryEvent: [{ type: i0.HostListener, args: ['document:TelemetryEvent', ['$event'],] }],
ngOnDestroy: [{ type: i0.HostListener, args: ['window:beforeunload',] }]
};
var MAX_TIME_TO_LOAD_SPINE = 5 * 60 * 1000; // 5 minutes
var EpubViewerComponent = /** @class */ (function () {
function EpubViewerComponent(viwerService, utilService) {
this.viwerService = viwerService;
this.utilService = utilService;
this.actions = new i0.EventEmitter();
this.showFullScreen = false;
this.viewerEvent = new i0.EventEmitter();
}
EpubViewerComponent.prototype.ngOnInit = function () {
this.idForRendition = this.identifier + "-content";
};
EpubViewerComponent.prototype.ngOnChanges = function (changes) {
var _a;
if (this.rendition && !((_a = changes === null || changes === void 0 ? void 0 : changes.showFullScreen) === null || _a === void 0 ? void 0 : _a.firstChange)) {
this.rendition.resize();
}
};
EpubViewerComponent.prototype.ngAfterViewInit = function () {
return __awaiter(this, void 0, void 0, function () {
var _c, spine, error_1;
var _this = this;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_d.trys.push([0, 5, , 6]);
if (!!this.viwerService.isAvailableLocally) return [3 /*break*/, 2];
_c = this;
return [4 /*yield*/, this.viwerService.isValidEpubSrc(this.epubSrc)];
case 1:
_c.epubBlob = _d.sent();
this.eBook = Epub__default["default"](this.epubBlob);
return [3 /*break*/, 3];
case 2:
if (this.viwerService.isAvailableLocally) {
this.eBook = Epub__default["default"](this.epubSrc);
}
_d.label = 3;
case 3:
this.rendition = this.eBook.renderTo(this.idForRendition, {
flow: 'paginated',
width: '100%',
});
this.rendition.on('layout', function (layout) {
var _a, _b;
_this.viwerService.totalNumberOfPages = (_b = (_a = _this.eBook) === null || _a === void 0 ? void 0 : _a.navigation) === null || _b === void 0 ? void 0 : _b.length;
if (_this.eBook.navigation.length > 2) {
_this.rendition.spread('none');
_this.rendition.flow('scrolled');
_this.scrolled = true;
}
else {
_this.rendition.spread('auto');
_this.scrolled = false;
}
});
this.rendition.on('displayError', function (error) {
_this.emitErrorEvent();
});
return [4 /*yield*/, this.utilService.fulfillWithTimeLimit(MAX_TIME_TO_LOAD_SPINE, this.eBook.loaded.spine, null)];
case 4:
spine = _d.sent();
if (spine) {
this.displayEpub();
this.lastSection = spine.last();
this.viewerEvent.emit({
type: epubPlayerConstants.EPUBLOADED,
data: spine
});
this.handleActions(spine);
}
else {
this.emitErrorEvent();
}
return [3 /*break*/, 6];
case 5:
error_1 = _d.sent();
this.emitErrorEvent();
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
});
};
EpubViewerComponent.prototype.displayEpub = function () {
var _this = this;
var currentLocation = this.config.currentLocation;
if (!currentLocation) {
this.rendition.display();
}
this.eBook.ready.then(function () {
return _this.eBook.locations.generate(1000);
}).then(function (locations) {
var _a, _b;
var totalPages = (_b = (_a = _this.eBook) === null || _a === void 0 ? void 0 : _a.spine) === null || _b === void 0 ? void 0 : _b.length;
_this.viwerService.totalNumberOfPages = totalPages ? (totalPages - 1) : 0;
if (currentLocation) {
var cfi = _this.eBook.locations.cfiFromPercentage(Number(currentLocation));
_this.rendition.display(cfi);
}
});
};
EpubViewerComponent.prototype.handleActions = function (spine) {
var _this = this;
this.actions.subscribe(function (event) {
var _a, _b;
var type = event.type;
if ((_b = (_a = _this.rendition) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.start) {
var data_1 = _this.rendition.location.start;
if (_this.scrolled && data_1.href === _this.lastSection.href) {
_this.viwerService.metaData.currentLocation = 0;
_this.emitEndEvent();
}
else {
if (_this.rendition.location.atEnd || (spine.length === 1 &&
(_this.rendition.location.end.displayed.page + 1 >= _this.rendition.location.end.displayed.total))) {
_this.viwerService.metaData.currentLocation = 0;
_this.emitEndEvent();
}
}
if (type === epubPlayerConstants.NEXT) {
_this.rendition.next().then(function () {
_this.saveCurrentLocation();
_this.viewerEvent.emit({
type: epubPlayerConstants.PAGECHANGE,
data: data_1,
interaction: epubPlayerConstants.NEXT
});
});
}
else if (type === epubPlayerConstants.PREVIOUS) {
_this.rendition.prev().then(function () {
_this.saveCurrentLocation();
_this.viewerEvent.emit({
type: epubPlayerConstants.PAGECHANGE,
data: data_1,
interaction: epubPlayerConstants.PREVIOUS
});
});
}
if (type === epubPlayerConstants.NAVIGATE_TO_PAGE) {
_this.rendition.display(event.data);
_this.viewerEvent.emit({
type: epubPlayerConstants.NAVIGATE_TO_PAGE,
event: event,
interaction: epubPlayerConstants.NAVIGATE_TO_PAGE
});
}
if (type === epubPlayerConstants.INVALID_PAGE_ERROR) {
_this.viewerEvent.emit({
type: epubPlayerConstants.INVALID_PAGE_ERROR,
event: event,
interaction: epubPlayerConstants.INVALID_PAGE_ERROR
});
}
}
});
};
EpubViewerComponent.prototype.saveCurrentLocation = function () {
var _a;
var currentLocation = this.rendition.currentLocation();
if ((_a = currentLocation === null || currentLocation === void 0 ? void 0 : currentLocation.start) === null || _a === void 0 ? void 0 : _a.cfi) {
// Get the Percentage (or location) from that CFI
var currentPageLocation = this.eBook.locations.percentageFromCfi(currentLocation.start.cfi);
this.viwerService.metaData.currentLocation = currentPageLocation;
}
};
EpubViewerComponent.prototype.emitEndEvent = function () {
this.viewerEvent.emit({
type: epubPlayerConstants.END,
data: {
percentage: 100
}
});
};
EpubViewerComponent.prototype.emitErrorEvent = function () {
this.viewerEvent.emit({
type: epubPlayerConstants.ERROR,
errorCode: sunbirdPlayerSdkV9.errorCode.contentLoadFails,
errorMessage: sunbirdPlayerSdkV9.errorMessage.contentLoadFails
});
};
EpubViewerComponent.prototype.ngOnDestroy = function () {
var _a;
(_a = this.eBook) === null || _a === void 0 ? void 0 : _a.destroy();
};
return EpubViewerComponent;
}());
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
EpubViewerComponent.decorators = [
{ type: i0.Component, args: [{
// tslint:disable-next-line:component-selector
selector: 'epub-viewer',
template: "<div class=\"rendition\" [id]=\"idForRendition\" #epubViewer></div>",
styles: [""]
},] }
];
/**
* @type {function(): !Array<(null|{
* type: ?,
* decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
* })>}
* @nocollapse
*/
EpubViewerComponent.ctorParameters = function () { return [
{ type: ViwerService },
{ type: UtilService }
]; };
/** @type {!Object<string, !Array<{type: !Function, args: (undefined|!Array<?>)}>>} */
EpubViewerComponent.propDecorators = {
epubViewer: [{ type: i0.ViewChild, args: ['epubViewer', { static: true },] }],
epubSrc: [{ type: i0.Input }],
config: [{ type: i0.Input }],
identifier: [{ type: i0.Input }],
actions: [{ type: i0.Input }],
showFullScreen: [{ type: i0.Input }],
viewerEvent: [{ type: i0.Output }]
};
var ToastrComponent = /** @class */ (function () {
function ToastrComponent(toastrService) {
this.toastrService = toastrService;
this.toastr = [];
}
ToastrComponent.prototype.ngOnInit = function () {
var _this = this;
console.log("ngoninit called");
this.toastSubscription = this.toastrService.toastState$.subscribe(function (toast) {
_this.toastr.push(toast);
console.log(_this.toastr, "this is toast");
setTimeout(function () {
_this.toastr.shift();
}, 3000);
});
};
ToastrComponent.prototype.ngOnDestroy = function () {
if (this.toastSubscription) {
this.toastSubscription.unsubscribe();
}
};
return ToastrComponent;
}());
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
ToastrComponent.decorators = [
{ type: i0.Component, args: [{
selector: 'toastr',
template: "<div class=\"toast-container\">\n <div *ngFor=\"let toast of toastr\" class=\"toast\" [ngClass]=\"toast.type\">\n {{ toast.message }}\n </div>\n</div>\n",
styles: [".toast-container{position:absolute;top:53px;right:6px;z-index:99999}.toast{padding:15px 20px;margin-bottom:10px;border-radius:4px;color:#fff;font-weight:bold;opacity:.9;transition:opacity .5s ease-out}.toast.info{background-color:#2196f3}.toast.success{background-color:#4caf50}.toast.error{background-color:#dc281a}\n"]
},] }
];
/**
* @type {function(): !Array<(null|{
* type: ?,
* decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
* })>}
* @nocollapse
*/
ToastrComponent.ctorParameters = function () { return [
{ type: ToastrService }
]; };
var SunbirdEpubPlayerModule = /** @class */ (function () {
function SunbirdEpubPlayerModule() {
}
return SunbirdEpubPlayerModule;
}());
/** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
SunbirdEpubPlayerModule.decorators = [
{ type: i0.NgModule, args: [{
declarations: [EpubPlayerComponent, EpubViewerComponent, ToastrComponent],
imports: [
common.CommonModule,
playerSdkV9.SunbirdPlayerSdkModule,
i3.HttpClientModule
],
schemas: [
i0.CUSTOM_ELEMENTS_SCHEMA
],
exports: [EpubPlayerComponent]
},] }
];
/*
* Public API Surface of epub-player
*/
/**
* Generated bundle index. Do not edit.
*/
exports.EpubPlayerComponent = EpubPlayerComponent;
exports.EpubPlayerService = EpubPlayerService;
exports.SunbirdEpubPlayerModule = SunbirdEpubPlayerModule;
exports["ɵa"] = UtilService;
exports["ɵb"] = ViwerService;
exports["ɵc"] = ToastrService;
exports["ɵd"] = EpubViewerComponent;
exports["ɵe"] = ToastrComponent;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=dicdikshaorg-epub-player-v9.umd.js.map