globular-element
Version:
Collection of webcomponent to work with globular
40 lines (35 loc) • 54 MB
JavaScript
/*
* ATTENTION: An "eval-source-map" devtool has been used.
* This devtool is neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["GlobularElement"] = factory();
else
root["GlobularElement"] = factory();
})(this, () => {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./Utility.ts":
/*!********************!*\
!*** ./Utility.ts ***!
\********************/
/***/ ((__unused_webpack_module, exports) => {
"use strict";
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.mergeTypedArrays = mergeTypedArrays;\nexports.uint8arrayToStringMethod = uint8arrayToStringMethod;\nexports.dataURItoBlob = dataURItoBlob;\nexports.fireResize = fireResize;\nfunction mergeTypedArrays(a, b) {\n // Checks for truthy values on both arrays\n if (!a && !b)\n throw \"Please specify valid arguments for parameters a and b.\";\n // Checks for truthy values or empty arrays on each argument\n // to avoid the unnecessary construction of a new array and\n // the type comparison\n if (!b || b.length === 0)\n return a;\n if (!a || a.length === 0)\n return b;\n // Make sure that both typed arrays are of the same type\n if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b))\n throw \"The types of the two arguments passed for parameters a and b do not match.\";\n var c = new a.constructor(a.length + b.length);\n c.set(a);\n c.set(b, a.length);\n return c;\n}\nfunction uint8arrayToStringMethod(uint8arr, callback) {\n var bb = new Blob([uint8arr]);\n var f = new FileReader();\n f.onload = function (evt) {\n callback(evt.target.result);\n };\n f.readAsText(bb);\n}\n// Convert data url to blob.\nfunction dataURItoBlob(dataURI) {\n // convert base64/URLEncoded data component to raw binary data held in a string\n var byteString;\n if (dataURI.split(',')[0].indexOf('base64') >= 0)\n byteString = atob(dataURI.split(',')[1]);\n else\n byteString = unescape(dataURI.split(',')[1]);\n // separate out the mime component\n var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];\n // write the bytes of the string to a typed array\n var ia = new Uint8Array(byteString.length);\n for (var i = 0; i < byteString.length; i++) {\n ia[i] = byteString.charCodeAt(i);\n }\n return new Blob([ia], { type: mimeString });\n}\nfunction fireResize() {\n if (document.createEvent) {\n // W3C\n var ev = document.createEvent('Event');\n ev.initEvent('resize', true, true);\n window.dispatchEvent(ev);\n }\n else {\n // IE\n var event = document.createEventObject();\n document.fireEvent(\"onresize\", event);\n }\n}\n;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9VdGlsaXR5LnRzIiwibWFwcGluZ3MiOiJBQUFhO0FBQ2IsOENBQTZDLEVBQUUsYUFBYSxFQUFDO0FBQzdELHdCQUF3QjtBQUN4QixnQ0FBZ0M7QUFDaEMscUJBQXFCO0FBQ3JCLGtCQUFrQjtBQUNsQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxpRUFBaUU7QUFDakU7QUFDQTtBQUNBLG9CQUFvQix1QkFBdUI7QUFDM0M7QUFDQTtBQUNBLDRCQUE0QixrQkFBa0I7QUFDOUM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Q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wibmFtZXMiOltdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./Utility.ts\n");
/***/ }),
/***/ "./backend/account.ts":
/*!****************************!*\
!*** ./backend/account.ts ***!
\****************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _this = this;\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.AccountController = void 0;\nvar resource_pb_1 = __webpack_require__(/*! globular-web-client/resource/resource_pb */ \"./node_modules/globular-web-client/resource/resource_pb.js\");\nvar backend_1 = __webpack_require__(/*! ./backend */ \"./backend/backend.ts\");\nvar authentication_pb_1 = __webpack_require__(/*! globular-web-client/authentication/authentication_pb */ \"./node_modules/globular-web-client/authentication/authentication_pb.js\");\nvar jwt_decode_1 = __importDefault(__webpack_require__(/*! jwt-decode */ \"./node_modules/jwt-decode/build/jwt-decode.esm.js\"));\nvar rbac_pb_1 = __webpack_require__(/*! globular-web-client/rbac/rbac_pb */ \"./node_modules/globular-web-client/rbac/rbac_pb.js\");\nvar persistence_pb_1 = __webpack_require__(/*! globular-web-client/persistence/persistence_pb */ \"./node_modules/globular-web-client/persistence/persistence_pb.js\");\nvar notification_1 = __webpack_require__(/*! ./notification */ \"./backend/notification.ts\");\nvar Utility_1 = __webpack_require__(/*! ../Utility */ \"./Utility.ts\");\ndocument.addEventListener(\"backend-ready\", function () {\n // Invite contact event.\n backend_1.Backend.eventHub.subscribe(\"invite_contact_event_\", function (uuid) {\n }, function (contact) {\n // Here I will try to login the user.\n AccountController.onInviteContact(contact);\n }, true, _this);\n // Revoke contact invitation.\n backend_1.Backend.eventHub.subscribe(\"revoke_contact_invitation_event_\", function (uuid) {\n }, function (contact) {\n // Here I will try to login the user.\n AccountController.onRevokeContactInvitation(contact);\n }, true, _this);\n // Accept contact invitation\n backend_1.Backend.eventHub.subscribe(\"accept_contact_invitation_event_\", function (uuid) {\n }, function (contact) {\n // Here I will try to login the user.\n AccountController.onAcceptContactInvitation(contact);\n }, true, _this);\n // Decline contact invitation\n backend_1.Backend.eventHub.subscribe(\"decline_contact_invitation_event_\", function (uuid) {\n }, function (contact) {\n // Here I will try to login the user.\n AccountController.onDeclineContactInvitation(contact);\n }, true, _this);\n // Decline contact invitation\n backend_1.Backend.eventHub.subscribe(\"delete_contact_event_\", function (uuid) {\n }, function (contact) {\n // Here I will try to login the user.\n AccountController.onDeleteContact(contact);\n }, true, _this);\n});\nvar AccountController = /** @class */ (function () {\n function AccountController() {\n }\n Object.defineProperty(AccountController, \"account\", {\n // Get the account.\n get: function () {\n // If the account is not set, then create a new account.\n if (AccountController.__account__ == null) {\n AccountController.__account__ = new resource_pb_1.Account();\n // first check if a token is available in the local storage\n var token = localStorage.getItem(\"user_token\");\n if (token != null) {\n var decoded = (0, jwt_decode_1.default)(token);\n var id = decoded.id;\n var userName = decoded.username;\n var email = decoded.email;\n var domain = decoded.user_domain;\n AccountController.__account__.setId(id);\n AccountController.__account__.setName(userName);\n AccountController.__account__.setEmail(email);\n AccountController.__account__.setDomain(domain);\n // init the \n AccountController.getAccount(id, function (account) {\n AccountController.__account__ = account;\n }, function (err) { return console.log(err); });\n }\n else {\n // Set the account to be the sa account.\n AccountController.__account__.setId(\"sa\");\n AccountController.__account__.setName(\"sa\");\n var domain = backend_1.Backend.globular.domain;\n if (domain != null) {\n AccountController.__account__.setDomain(domain);\n }\n }\n }\n return AccountController.__account__;\n },\n // Set the account.\n set: function (account) {\n AccountController.__account__ = account;\n },\n enumerable: false,\n configurable: true\n });\n // Get all account data from a give globule...\n AccountController.getAccounts = function (query, init, callback, errorCallback, globule) {\n if (globule === void 0) { globule = backend_1.Backend.globular; }\n (0, backend_1.generatePeerToken)(globule, function (token) {\n var rqst = new resource_pb_1.GetAccountsRqst;\n rqst.setQuery(query);\n if (globule.resourceService == null) {\n errorCallback(\"Resource service not found\");\n return;\n }\n var stream = globule.resourceService.getAccounts(rqst, { domain: globule.domain, token: token });\n var accounts_ = new Array();\n stream.on(\"data\", function (rsp) {\n accounts_ = accounts_.concat(rsp.getAccountsList());\n });\n stream.on(\"status\", function (status) {\n if (status.code == 0) {\n var accounts_1 = new Array();\n if (accounts_.length == 0) {\n callback(accounts_1);\n return;\n }\n // In that case I will return the list of account without init ther data\n if (init == false) {\n accounts_.forEach(function (a_) {\n if (AccountController.__accounts__[a_.getId() + \"@\" + a_.getDomain()] != undefined) {\n accounts_1.push(AccountController.__accounts__[a_.getId() + \"@\" + a_.getDomain()]);\n }\n else {\n accounts_1.push(a_);\n AccountController.__accounts__[a_.getId() + \"@\" + a_.getDomain()] = a_;\n }\n });\n callback(accounts_1);\n return;\n }\n var initAccountData_1 = function () {\n var a_ = accounts_.pop();\n if (a_ == undefined) {\n errorCallback(accounts_1);\n return;\n }\n if (AccountController.__accounts__[a_.getId() + \"@\" + a_.getDomain()] == undefined) {\n if (accounts_.length > 0) {\n AccountController.initData(a_, function () {\n if (a_ == undefined) {\n errorCallback(accounts_1);\n return;\n }\n AccountController.__accounts__[a_.getId() + \"@\" + a_.getDomain()] = a_;\n initAccountData_1();\n }, errorCallback);\n }\n else {\n AccountController.initData(a_, function () {\n if (a_ == undefined) {\n errorCallback(accounts_1);\n return;\n }\n AccountController.__accounts__[a_.getId() + \"@\" + a_.getDomain()] = a_;\n callback(accounts_1);\n }, errorCallback);\n }\n }\n else {\n AccountController.__accounts__[a_.getId() + \"@\" + a_.getDomain()] = a_;\n if (accounts_.length > 0) {\n initAccountData_1();\n }\n else {\n callback(accounts_1);\n }\n }\n };\n // intialyse the account data.\n if (init == true)\n initAccountData_1();\n }\n else {\n // In case of error I will return an empty array\n errorCallback(status.details);\n }\n });\n }, errorCallback);\n };\n AccountController.getSession = function (account, callback, errorCallback) {\n // In that case I will get the values from the database...\n var rqst = new resource_pb_1.GetSessionRequest;\n rqst.setAccountid(account.getId() + \"@\" + account.getDomain());\n var globule = backend_1.Backend.getGlobule(account.getDomain());\n if (globule == null) {\n return;\n }\n (0, backend_1.generatePeerToken)(globule, function (token) {\n if (globule.resourceService == null) {\n errorCallback(\"Resource service not found\");\n return;\n }\n // call persist data\n globule.resourceService\n .getSession(rqst, {\n token: token,\n domain: globule.domain\n })\n .then(function (rsp) {\n // get the response\n var lastDomain = globule.domain;\n var lastSession = rsp.getSession();\n if (lastSession == null) {\n errorCallback(\"No session found for the account\");\n return;\n }\n account.session = lastSession;\n callback(account.session);\n }).catch(errorCallback);\n }, errorCallback);\n };\n /**\n *\n * @param account\n * @param initCallback\n * @param errorCallback\n */\n AccountController.initSession = function (account, successCallback, errorCallback) {\n var _this = this;\n (0, backend_1.generatePeerToken)(backend_1.Backend.globular, function (token) {\n var accountId = account.getId() + \"@\" + account.getDomain();\n var globule = backend_1.Backend.getGlobule(account.getDomain());\n AccountController.getSession(account, function (session) {\n // load available space for the account on the globule...\n if (account.getId() != \"sa\") {\n var rqst = new rbac_pb_1.GetSubjectAvailableSpaceRqst;\n rqst.setSubject(accountId);\n rqst.setType(rbac_pb_1.SubjectType.ACCOUNT);\n if (globule.rbacService == null) {\n errorCallback(\"RBAC service not found\");\n return;\n }\n globule.rbacService\n .getSubjectAvailableSpace(rqst, {\n token: token,\n domain: globule.domain\n })\n .then(function (rsp) {\n successCallback(session);\n })\n .catch(function (err) {\n errorCallback(err);\n });\n }\n else {\n successCallback(session);\n }\n // So here I will lisen on session change event and keep this object with it.\n globule.eventHub.subscribe(\"session_state_\".concat(account.getId() + \"@\" + account.getDomain(), \"_change_event\"), function (uuid) {\n /** nothing special here... */\n }, function (evt) {\n account.session = resource_pb_1.Session.deserializeBinary(Uint8Array.from(evt.split(\",\")));\n // Here I will ask the user for confirmation before actually delete the contact informations.\n var getSessionStateColor = function (state) {\n switch (state) {\n case resource_pb_1.SessionState.ONLINE:\n return \"green\";\n case resource_pb_1.SessionState.OFFLINE:\n return \"red\";\n case resource_pb_1.SessionState.AWAY:\n return \"orange\";\n default:\n return \"gray\";\n }\n };\n var getSessionStateMessage = function (state, name) {\n switch (state) {\n case resource_pb_1.SessionState.ONLINE:\n return \"\".concat(name, \" is now online.\");\n case resource_pb_1.SessionState.OFFLINE:\n return \"\".concat(name, \" has gone offline.\");\n case resource_pb_1.SessionState.AWAY:\n return \"\".concat(name, \" is away.\");\n default:\n return \"Unknown session state.\";\n }\n };\n var state = account.session.getState();\n var color = getSessionStateColor(state);\n var name = account.getName();\n if (account.getFirstname() != \"\" && account.getLastname() != \"\") {\n name = account.getFirstname() + \" \" + account.getLastname();\n }\n var message = getSessionStateMessage(state, name);\n var id = \"contact-session-info-toast-\" + account.getId() + \"@\" + account.getDomain();\n if (document.getElementById(id)) {\n var toastElement = document.getElementById(id);\n toastElement.remove();\n }\n var toast = (0, backend_1.displayMessage)(\" <style>\\n #contact-session-info-box {\\n display: flex;\\n flex-direction: column;\\n padding: 10px;\\n }\\n #contact-session-info-box globular-contact-card {\\n padding-bottom: 10px;\\n }\\n #contact-session-info-box div {\\n display: flex;\\n align-items: center;\\n font-size: 1.2rem;\\n padding-bottom: 10px;\\n }\\n .status-indicator {\\n width: 12px;\\n height: 12px;\\n border-radius: 50%;\\n background-color: \".concat(color, \";\\n margin-right: 10px;\\n }\\n </style>\\n <div id=\\\"contact-session-info-box\\\">\\n <div>\\n <span class=\\\"status-indicator\\\"></span>\\n \").concat(message, \"\\n </div>\\n <globular-contact-card contact=\\\"\").concat(account.getId() + \"@\" + account.getDomain(), \"\\\"></globular-contact-card>\\n </div>\"), 5000 // Display for 5 seconds\n );\n if (toast.toastElement)\n toast.toastElement.id = id;\n }, false, _this);\n }, errorCallback);\n }, errorCallback);\n };\n // Save session state in the databese.\n AccountController.saveSession = function (onSave, onError) {\n var _this = this;\n var rqst = new resource_pb_1.UpdateSessionRequest;\n var user_token = localStorage.getItem(\"user_token\");\n if (user_token == null) {\n onError(\"No user token found\");\n return;\n }\n // I will get the token expiration date.\n var decoded = (0, jwt_decode_1.default)(user_token);\n var token_expired = decoded.exp;\n // I will check if the token is still valid\n if (Math.round(new Date().getTime() / 1000) > token_expired) {\n onError(\"The user token is expired\");\n return;\n }\n // I will set the session expiration date to the token expiration date.\n this.account.session.setExpireAt(Math.round(token_expired));\n rqst.setSession(this.account.session);\n // TEST if session must be on the user globule or the actual session store.\n var globule = backend_1.Backend.getGlobule(this.account.getDomain());\n (0, backend_1.generatePeerToken)(globule, function (token) {\n if (globule.resourceService == null) {\n onError(\"Resource service not found\");\n return;\n }\n // call persist data\n globule.resourceService\n .updateSession(rqst, {\n token: token,\n domain: _this.account.getDomain()\n })\n .then(function (rsp) {\n // Here I will return the value with it\n globule.eventHub.publish(\"session_state_\".concat(_this.account.session.getAccountid(), \"_change_event\"), _this.account.session.serializeBinary(), false);\n onSave();\n })\n .catch(function (err) {\n if (onError) {\n onError(err);\n }\n console.log(\"fail to save session\", err);\n });\n }, function (err) { return console.log(err); });\n };\n /**\n * Get an account with a given id.\n * @param id The id of the account to retreive\n * @param successCallback Callback when succed\n * @param errorCallback Error Callback.\n */\n AccountController.getAccount = function (id, successCallback, errorCallback) {\n if (id == null || id == \"\") {\n errorCallback(\"No account id given to getAccount function!\");\n return;\n }\n var accountId = id;\n var domain = backend_1.Backend.globular.domain;\n if (accountId.indexOf(\"@\") == -1) {\n accountId = id + \"@\" + domain;\n }\n else {\n domain = accountId.split(\"@\")[1];\n id = accountId.split(\"@\")[0];\n }\n if (AccountController.__accounts__[accountId] != null) {\n successCallback(AccountController.__accounts__[accountId]);\n return;\n }\n var globule = backend_1.Backend.getGlobule(domain);\n if (globule == null) {\n errorCallback(\"Globule not found\");\n return;\n }\n (0, backend_1.generatePeerToken)(globule, function (token) {\n var rqst = new resource_pb_1.GetAccountsRqst;\n rqst.setQuery(\"{\\\"_id\\\":\\\"\".concat(id, \"\\\"}\")); // search by name and not id... the id will be retreived.\n rqst.setOptions(\"[{\\\"Projection\\\":{\\\"_id\\\":1, \\\"email\\\":1, \\\"name\\\":1, \\\"groups\\\":1, \\\"organizations\\\":1, \\\"roles\\\":1, \\\"domain\\\":1}}]\");\n if (globule.resourceService == null) {\n errorCallback(\"Resource service not found\");\n return;\n }\n var stream = globule.resourceService.getAccounts(rqst, { domain: domain, token: token });\n var data;\n stream.on(\"data\", function (rsp) {\n if (rsp.getAccountsList().length == 0) {\n errorCallback(\"no account found with id \" + accountId);\n return;\n }\n data = rsp.getAccountsList()[0];\n });\n stream.on(\"status\", function (status) {\n if (status.code == 0) {\n // Initialyse the data...\n if (!data) {\n errorCallback(\"no account found with id \" + accountId);\n return;\n }\n AccountController.__accounts__[accountId] = data;\n AccountController.initSession(data, function () {\n AccountController.initData(data, function (account) {\n var user_id = localStorage.getItem(\"user_id\");\n if (user_id == account.getId()) {\n AccountController.__account__ = account;\n var globule_1 = backend_1.Backend.getGlobule(account.getDomain());\n globule_1.eventHub.publish(\"login_success_\", account, true);\n }\n successCallback(account);\n }, errorCallback);\n }, errorCallback);\n }\n else {\n errorCallback(status.details);\n }\n });\n }, function (err) { return (0, backend_1.displayMessage)(err, 3000); });\n };\n /**\n * Must be called once when the session open.\n * @param account\n */\n AccountController.initData = function (account, callback, errorCallback) {\n var globule = backend_1.Backend.getGlobule(account.getDomain());\n if (globule == null) {\n errorCallback(\"Globule not found\");\n return;\n }\n // Retreive user data... \n AccountController.readOneUserData(\"{\\\"_id\\\":\\\"\".concat(account.getId(), \"\\\"}\"), // The query is made on the user database and not local_ressource Accounts here so name is name_ here\n account.getName(), // The database to search into \n globule.domain, function (data) {\n if (data == null) {\n errorCallback(\"no data found for the user\");\n return;\n }\n // Set the data in the account object.\n for (var key in data) {\n account[key] = data[key];\n }\n callback(account);\n }, errorCallback);\n };\n /**\n * Read user data one result at time.\n */\n AccountController.readOneUserData = function (query, userName, userDomain, successCallback, errorCallback) {\n var rqst = new persistence_pb_1.FindOneRqst();\n // remove unwanted characters\n var id = userName.split(\"@\").join(\"_\").split(\".\").join(\"_\");\n var db = id + \"_db\";\n // set the connection id.\n rqst.setId(id);\n rqst.setDatabase(db);\n var collection = \"user_data\";\n rqst.setCollection(collection);\n rqst.setQuery(query);\n rqst.setOptions(\"\");\n var globule = backend_1.Backend.getGlobule(userDomain);\n (0, backend_1.generatePeerToken)(globule, function (token) {\n if (globule.persistenceService == null) {\n errorCallback(\"Persistence service not found\");\n return;\n }\n // call persist data\n globule.persistenceService\n .findOne(rqst, {\n token: token,\n domain: globule.domain // the domain at the origin of the request.\n })\n .then(function (rsp) {\n var data = rsp.getResult().toJavaScript();\n successCallback(data);\n })\n .catch(function (err) {\n if (err.code == 13) {\n if (AccountController.account == null) {\n (0, backend_1.displayMessage)(\"no connections found on the server you need to login\", 3000);\n setTimeout(function () {\n localStorage.removeItem(\"remember_me\");\n localStorage.removeItem(\"user_token\");\n localStorage.removeItem(\"user_id\");\n localStorage.removeItem(\"user_name\");\n localStorage.removeItem(\"user_email\");\n localStorage.removeItem(\"token_expired\");\n location.reload();\n return;\n }, 3000);\n }\n if (AccountController.account.getId() == id) {\n if (err.message.indexOf(\"no documents in result\") != -1) {\n successCallback({});\n }\n else {\n (0, backend_1.displayError)(\"no connection found on the server you need to login\", 3000);\n setTimeout(function () {\n localStorage.removeItem(\"remember_me\");\n localStorage.removeItem(\"user_token\");\n localStorage.removeItem(\"user_id\");\n localStorage.removeItem(\"user_name\");\n localStorage.removeItem(\"user_email\");\n localStorage.removeItem(\"token_expired\");\n location.reload();\n return;\n }, 3000);\n }\n }\n else {\n successCallback({});\n }\n }\n else {\n errorCallback(err);\n }\n });\n }, function (err) { return (0, backend_1.displayError)(err, 3000); });\n };\n /**\n * Close the current session explicitelty.\n */\n AccountController.logout = function () {\n // Send local event.\n if (AccountController.account != undefined) {\n // So here I will set the account session state to onlise.\n AccountController.account.session.setState(resource_pb_1.SessionState.OFFLINE);\n AccountController.saveSession(function () {\n var name = AccountController.account.getName();\n if (AccountController.account.getFirstname() != \"\" && AccountController.account.getLastname() != \"\") {\n name = AccountController.account.getFirstname() + \" \" + AccountController.account.getLastname();\n }\n var html = \"\\n <div style=\\\"display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: white; padding: 20px; border-radius: 10px;\\\">\\n \\n <h4>Bye Bye</h4>\\n <div style=\\\"font-size: 1.1rem; font-wegith: 400;\\\"> \".concat(name, \"!</div>\\n <img src=\\\"\").concat(AccountController.account.getProfilepicture(), \"\\\" style=\\\"width: 100px; height: auto; border-radius: 50%;\\\"/>\\n <p>See you soon...</p>\\n \\n </div>\\n \");\n (0, backend_1.displayMessage)(html, 3000);\n backend_1.Backend.getGlobule(AccountController.account.getDomain()).eventHub.publish(\"session_state_\".concat(AccountController.account.session.getAccountid(), \"_change_event\"), AccountController.account.session.serializeBinary(), false);\n }, function (err) { return console.log(err); });\n }\n // remove token informations\n localStorage.removeItem(\"remember_me\");\n localStorage.removeItem(\"user_token\");\n localStorage.removeItem(\"user_id\");\n localStorage.removeItem(\"user_name\");\n localStorage.removeItem(\"user_email\");\n localStorage.removeItem(\"token_expired\");\n setTimeout(function () {\n window.location.href = window.location.origin + window.location.pathname.split('/').slice(0, -1).join('/');\n }, 3000);\n };\n // Authenticate the 'sa' user on the globule...\n AccountController.authenticate = function (globule, user, password, callback, errorCallback) {\n var rqst = new authentication_pb_1.AuthenticateRqst();\n rqst.setName(user);\n rqst.setIssuer(globule.config.Mac);\n rqst.setPassword(password);\n // Check if the authentication service is available\n if (!globule.authenticationService) {\n errorCallback(\"The authentication service is not available.\");\n return;\n }\n globule.authenticationService.authenticate(rqst, {}).then(function (response) {\n // Set the token\n var token = response.getToken();\n // save the token in the local storage\n //localStorage.setItem(\"user_token\", token);\n // Here I will set the token in the localstorage.\n var decoded = (0, jwt_decode_1.default)(token);\n var userName = decoded.username;\n var email = decoded.email;\n var id = decoded.id;\n var address = decoded.address;\n var userDomain = decoded.user_domain;\n // here I will save the user token and user_name in the local storage.\n localStorage.setItem(\"user_token\", token);\n localStorage.setItem(\"token_expired\", decoded.exp);\n localStorage.setItem(\"user_email\", email);\n localStorage.setItem(\"user_name\", userName);\n localStorage.setItem(\"user_id\", id);\n localStorage.setItem(\"user_domain\", userDomain);\n var rqst = new persistence_pb_1.CreateConnectionRqst;\n var connectionId = userName.split(\"@\").join(\"_\").split(\".\").join(\"_\");\n // So here i will open the use database connection.\n var connection = new persistence_pb_1.Connection;\n connection.setId(connectionId);\n connection.setUser(connectionId);\n connection.setPassword(password);\n connection.setStore(globule.config.BackendStore);\n connection.setName(id + \"_db\");\n connection.setPort(globule.config.BackendPort);\n connection.setTimeout(60);\n connection.setHost(address);\n rqst.setConnection(connection);\n if (globule.persistenceService == null) {\n errorCallback(\"Persistence service not found\");\n return;\n }\n globule.persistenceService.createConnection(rqst, {\n token: token,\n domain: globule.domain,\n address: address\n }).then(function () {\n AccountController.getAccount(id, function (account) {\n AccountController.__account__ = account;\n // set the session state to connected\n AccountController.account.session.setState(resource_pb_1.SessionState.ONLINE);\n AccountController.account.session.setLastStateTime(Math.round(new Date().getTime() / 1000));\n AccountController.saveSession(function () {\n (0, backend_1.displayMessage)(\"Welcome \" + userName, 3000);\n backend_1.Backend.getGlobule(userDomain).eventHub.publish(\"session_state_\".concat(AccountController.account.session.getAccountid(), \"_change_event\"), AccountController.account.session.serializeBinary(), false);\n }, errorCallback);\n callback(token);\n }, errorCallback);\n });\n }).catch(function (err) {\n errorCallback(err);\n });\n };\n /**\n * Register a new account with the application.\n * @param name The account name\n * @param email The account email\n * @param password The account password\n */\n AccountController.register = function (name, email, password, confirmPassord, domain, onRegister, onError, globule, firstName, lastName, profilePicture) {\n if (globule === void 0) { globule = backend_1.Backend.globular; }\n if (firstName === void 0) { firstName = \"\"; }\n if (lastName === void 0) { lastName = \"\"; }\n if (profilePicture === void 0) { profilePicture = \"\"; }\n if (confirmPassord.length == 0) {\n onError(\"Please confirm your password\");\n return;\n }\n // Create the register request.\n var rqst = new resource_pb_1.RegisterAccountRqst();\n rqst.setConfirmPassword(confirmPassord);\n var account = new resource_pb_1.Account();\n account.setEmail(email);\n account.setName(name);\n account.setId(name);\n account.setDomain(domain);\n // Set the user refresh token.\n if (password.length == 0) {\n account.setRefreshtoken(confirmPassord); // Confirm password is the refresh token in that case.\n }\n else {\n account.setPassword(password);\n }\n if (firstName != \"\") {\n account.setFirstname(firstName);\n }\n if (lastName != \"\") {\n account.setLastname(lastName);\n }\n if (profilePicture != \"\") {\n account.setProfilepicture(profilePicture);\n }\n rqst.setAccount(account);\n if (globule.resourceService == null) {\n onError(\"Resource service not found\");\n return;\n }\n // Register a new account.\n globule.resourceService\n .registerAccount(rqst)\n .then(function (rsp) {\n // Here I will set the token in the localstorage.\n var token = rsp.getResult();\n var decoded = (0, jwt_decode_1.default)(token);\n // here I will save the user token and user_name in the local storage.\n localStorage.setItem(\"user_token\", token);\n localStorage.setItem(\"user_id\", decoded.id);\n localStorage.setItem(\"user_name\", decoded.username);\n localStorage.setItem(\"token_expired\", decoded.exp);\n localStorage.setItem(\"user_email\", decoded.email);\n localStorage.setItem(\"user_domain\", decoded.user_domain);\n var rqst = new persistence_pb_1.CreateConnectionRqst;\n var connectionId = name.split(\"@\").join(\"_\").split(\".\").join(\"_\");\n var address = decoded.address;\n var domain = decoded.domain;\n // So here i will open the use database connection.\n var connection = new persistence_pb_1.Connection;\n connection.setId(connectionId);\n connection.setUser(connectionId);\n connection.setPassword(password); // in case of no password set the refresh token as password.\n connection.setStore(globule.config.BackendStore);\n connection.setName(name + \"_db\");\n connection.setPort(globule.config.BackendPort);\n connection.setTimeout(60);\n connection.setHost(address);\n rqst.setConnection(connection);\n if (globule.persistenceService == null) {\n onError(\"Persistence service not found\");\n return;\n }\n globule.persistenceService.createConnection(rqst, {\n token: token,\n domain: domain,\n address: address\n }).then(function () {\n // Callback on login.\n AccountController.__account__ = account;\n AccountController.initSession(account, function () {\n AccountController.initData(account, function (account) {\n onRegister(account);\n backend_1.Backend.eventHub.publish(\"login_success_\", AccountController.account, true);\n }, function (err) {\n onRegister(account);\n backend_1.Backend.eventHub.publish(\"login_success_\", AccountController.account, true);\n onError(err);\n });\n }, onError);\n }).catch(function (err) {\n onError(err);\n });\n })\n .catch(function (err) {\n onError(err);\n });\n };\n ///////////////////////////////////////////////////////////////////\n // Contacts.\n ///////////////////////////////////////////////////////////////////\n AccountController.getContacts = function (account, query, callback, errorCallback) {\n // Insert the notification in the db.\n var rqst = new persistence_pb_1.FindRqst();\n // set connection infos.\n var id = account.getName().split(\"@\").join(\"_\").split(\".\").join(\"_\");\n var db = id + \"_db\";\n rqst.setId(id);\n rqst.setDatabase(db);\n rqst.setCollection(\"Contacts\");\n rqst.setQuery(query);\n var globule = backend_1.Backend.getGlobule(account.getDomain());\n (0, backend_1.generatePeerToken)(globule, function (token) {\n if (globule.persistenceService == null) {\n errorCallback(\"Persistence service not found\");\n return;\n }\n var stream = globule.persistenceService.find(rqst, {\n token: token,\n domain: globule.domain\n });\n var data;\n data = [];\n stream.on(\"data\", function (rsp) {\n data = (0, Utility_1.mergeTypedArrays)(data, rsp.getData());\n });\n stream.on(\"status\", function (status) {\n if (status.code == 0) {\n (0, Utility_1.uint8arrayToStringMethod)(data, function (str) {\n var contacts = JSON.parse(str);\n callback(contacts);\n });\n }\n else {\n console.log(\"fail to retreive contacts with error: \", status.details);\n // In case of error I will return an empty array\n callback([]);\n }\n });\n }, errorCallback);\n };\n AccountController.setContact = function (from, status_from, to, status_to, successCallback, errorCallback) {\n // So here I will save the contact invitation into pending contact invitation collection...\n var rqst = new resource_pb_1.SetAccountContactRqst;\n rqst.setAccountid(from.getId() + \"@\" + from.getDomain());\n var contact = new resource_pb_1.Contact;\n contact.setId(to.getId() + \"@\" + to.getDomain());\n contact.setStatus(status_from);\n contact.setInvitationtime(Math.round(Date.now() / 1000));\n // Test if the ringtone is set for the contact.\n var ringtone = to.ringtone;\n // Set optional values...\n if (ringtone)\n contact.setRingtone(ringtone);\n if (to.getProfilepicture())\n contact.setProfilepicture(to.getProfilepicture());\n rqst.setContact(contact);\n var globule = backend_1.Backend.getGlobule(from.getDomain());\n (0, backend_1.generatePeerToken)(globule, function (token) {\n if (globule.resourceService == null) {\n errorCallback(\"Resource service not found\");\n return;\n }\n globule.resourceService.setAccountContact(rqst, {\n token: token,\n domain: globule.domain\n })\n .then(function (rsp) {\n var sentInvitation = \"{\\\"_id\\\":\\\"\".concat(to.getId() + \"@\" + to.getDomain(), \"\\\", \\\"invitationTime\\\":\").concat(Math.floor(Date.now() / 1000), \", \\\"status\\\":\\\"\").concat(status_from, \"\\\"}\");\n backend_1.Backend.getGlobule(from.getDomain()).eventHub.publish(status_from + \"_\" + from.getId() + \"@\" + from.getDomain() + \"_evt\", sentInvitation, false);\n if (from.getDomain() != to.getDomain()) {\n backend_1.Backend.getGlobule(to.getDomain()).eventHub.publish(status_from + \"_\" + from.getId() + \"@\" + from.getDomain() + \"_evt\", sentInvitation, false);\n }\n // Here I will return the value with it\n var rqst = new resource_pb_1.SetAccountContactRqst;\n rqst.setAccountid(to.getId() + \"@\" + to.getDomain());\n var contact = new resource_pb_1.Contact;\n contact.setId(from.getId() + \"@\" + from.getDomain());\n