/** * @format * @flow */ import { Alert } from "react-native"; import AsyncStorage from "@react-native-community/async-storage"; import Matomo from "@valleyelectronics/react-native-matomo"; //import firebase from '@react-native-firebase/app'; //import analytics from '@react-native-firebase/analytics'; import uuid from "react-native-uuid"; import RNFetchBlob from "rn-fetch-blob"; import axios, { AxiosResponse } from "axios"; import { StratagemData, NavParams, AuthTypes } from "../Enums"; import { InvalidUserCredentialsError } from "../Errors"; import KeycloakClient from "./KeycloakClient"; import strings from "res/strings"; // TODO remove this import { storeData, savePracticeSetDataGameWise, saveFolderDataGameWise, saveAPICallTime, /* deleteFolderDataGameWise, deletePracticeSetDataGameWise, saveLeaderBoardDataGameWise, saveReviewDataGameWise, saveInfoDocDataGameWise, */ } from "../asyncStorageHelper"; import { changeIntoGameIdData } from "../utils/CommonMethod"; import { FILEPATH_KEY_PREFIX, CURRENT_DATASOURCE, CURRENT_LEADERBOARD, CURRENT_INFODOC, DASHBOARD_ID, // MATCH_GAME_ID, // WORD_GAME_ID, } from "../../constants"; import { API_TIME_OUT } from "../ConfigEnum"; const { dirs } = RNFetchBlob.fs; function createStratagemRequestOptions(apiKey: string) { return { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: apiKey, }, }; } /** * Returns all data starting from given page * * @param {string} accessToken * @param {string} url the url without the page query parameter appended * @param {string} dataKey the key for the data in the response. ex) 'PracticeSets' * @param {number} page */ async function fetchAllData( accessToken: string, url: string, dataKey: string, page: number ): Promise> { // We can test pagination with small datasets by including limit. If it's already included, // we add 'page' to the url with '&'. If not included we add 'page' with '?' because it's the // first query parameter. For now, the case where limit exists is only for testing, so it should // always be '?' with real data. const paginatedURL = url.includes("limit") ? `${url}&page=${page}` : `${url}?page=${page}`; // console.log("paginatedURL ==> " + paginatedURL); // const requestOptions = createStratagemRequestOptions(accessToken); const options = { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, url: paginatedURL, }; const response = await axios(options); // const response = await fetch(paginatedURL, requestOptions); if (response.status === 200) { const responseJson = response.data; const { pagination: { page: currentPage, pages: totalPages }, } = responseJson; const dataArray = responseJson[dataKey]; if (currentPage === totalPages) { return dataArray; } // this recursive function will get the data from the rest of the pages const nextPageData = await fetchAllData( accessToken, url, dataKey, page + 1 ); return dataArray.concat(nextPageData); } console.log("error in pagination case"); return []; } async function downloadTableData( accessToken: string, baseStratagemURL: string, tableID: string, keycloakClient?: KeycloakClient, isleaderBoardCall = false // by default false value for other api ): Promise { try { // const tableURL = `${baseStratagemURL}tables/${tableID}`; // ?limit=2`; // limit is just for testing // const requestOptions = createStratagemRequestOptions(accessToken); const tableURL = `${baseStratagemURL}tables/${tableID}`; const options = { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, url: tableURL, }; console.log("tableURL ==>" + JSON.stringify(tableURL)); const tableResponse = await axios(options); // const tableResponse = await fetch(tableURL, requestOptions); if (tableResponse.status === 200) { const tableResponseJson = tableResponse.data; // records try { const { id, name, pagination: { total: totalRecords, pages: totalPages }, } = tableResponseJson; let fetchedRecords = tableResponseJson.records; // if there's more than one page, fetch data from every page if (totalPages > 1) { fetchedRecords = await fetchAllData( accessToken, tableURL, "records", 1 ); // something went wrong when getting data from all pages, so return false if (fetchedRecords.length !== totalRecords) { return null; } } const tableData = { id, name, records: fetchedRecords }; // await AsyncStorage.setItem(tableID, JSON.stringify(tableData)); return tableData; } catch (error) { console.log(`data error in table record ==> ${error}`); return null; } } return null; } catch (error) { if (error.response) { if (error.response.status === 401 && keycloakClient) { // token expire issue client_auth case const token = await keycloakClient.refreshToken(); if (token) { return downloadTableData(token, baseStratagemURL, tableID); } } else { // 500 and other status code return null; } } else { // request and other error return null; } } } export async function downloadLeaderboard( authType: string, gameId: string, tableID: string, folderId: string ): Promise { let baseStratagemURL: string; let keycloakClient: KeycloakClient; const accessToken = await keycloakClient.getSavedToken(); // const leaderboardUrl = `${this.baseStratagemURL}tables/${folderId}/${tableID}`; const tableData = await downloadTableData( accessToken, baseStratagemURL, tableID, this.keycloakClient ); // // console.log(`tableData ==> ${JSON.stringify(tableData)}`); storeData(tableID, JSON.stringify(tableData)); // for offline storeData(CURRENT_LEADERBOARD, JSON.stringify(tableData)); // saveLeaderBoardDataGameWise(gameId, authType, tableData); return tableData; } export default class StratagemClient { baseStratagemURL: string; keycloakClient: KeycloakClient; constructor(baseStratagemURL: string, keycloakClient: KeycloakClient) { this.baseStratagemURL = baseStratagemURL; this.keycloakClient = keycloakClient; } /** * Fetches and saves practice sets and folders associated with user */ async retrieveUserData(gameID: string): Promise { const baseURL = `${this.baseStratagemURL}games/${gameID}/`; const token = await this.keycloakClient.getSavedToken(); if (token) { return this.retrieveStratagemData(token, baseURL, gameID); } return false; } async retriveUserAuthData(gameID: string, orgID: string): Promise { const baseURL = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/`; const token = await this.keycloakClient.getSavedToken(); if (token) { return this.retrieveStratagemData(token, baseURL, gameID); } return false; } /** * Fetches and saves practice sets and folders associated with client */ async retrieveClientData(gameID: string, orgID: string): Promise { const baseURL = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/`; const clientToken = await this.keycloakClient.getSavedToken(); if (clientToken) { return this.retrieveStratagemData(clientToken, baseURL, gameID); } return false; } /** * Downloads practice sets and folders and saves them to AsyncStorage. * Returns true if successful, false if not. * @param {string} accessToken * @param {string} baseURL */ async retrieveStratagemData( accessToken: string, baseURL: string, gameID: string ): Promise { try { // fetch and save practice sets first const practiceSetsURL = `${baseURL}practicesets`; // ?limit=2`; // limit is for testing // const baseURL = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/`; const options = { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, url: practiceSetsURL, }; const practiceSetsResponse = await axios(options); if (practiceSetsResponse.status === 200) { // delete existing practice set data from the Db for current game // deletePracticeSetDataGameWise(gameID); const practiceSetsJson = practiceSetsResponse.data; const { pagination: { total: totalPracticeSets, pages: practiceSetPages }, } = practiceSetsJson; let allPracticeSets = practiceSetsJson.PracticeSets; // if there's more than one page, fetch all practice sets from every page if (practiceSetPages > 1) { allPracticeSets = await fetchAllData( accessToken, practiceSetsURL, "PracticeSets", 1 ); // something went wrong when getting data from all pages, so return false if (allPracticeSets.length !== totalPracticeSets) { return false; } } // now fetch and save folders return this.getFolderDataOnly( accessToken, baseURL, gameID, allPracticeSets ); } return false; } catch (error) { // console.log('test error practice set ==> '+error); if (error.response) { if (error.response.status === 401) { const token = await this.keycloakClient.refreshToken(); if (token) { return this.retrieveStratagemData(token, baseURL, gameID); } else { return false; // token expire issue client_auth case } } else { return false; // not getting any response } } else { return false; // request and setting error } } } async getFolderDataOnly( accessToken, baseURL, gameID, allPracticeSets ): Promise { try { const foldersURL = `${baseURL}folders`; // ?limit=2`; const folderOptions = { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, url: foldersURL, }; // console.log(`folder url for org_outh => ${foldersURL}`); const foldersResponse = await axios(folderOptions); if (foldersResponse.status === 200) { // delete existing folder data from the Db for current game // deleteFolderDataGameWise(gameID); const foldersJson = foldersResponse.data; const { pagination: { total: totalFolders, pages: folderPages }, } = foldersJson; let allFolders = foldersJson.Folders; // if there's more than one page, fetch all folders from every page if (folderPages > 1) { allFolders = await fetchAllData( accessToken, foldersURL, "Folders", 1 ); // something went wrong when getting data from all pages, so return false if (allFolders.length !== totalFolders) { return false; } } // save practice sets and folders at roughly the same time to minimize possibility of // one set of data being updated but not the other // according to game change folder data save logic saveAPICallTime(gameID, (new Date().valueOf() / 1000).toString()); saveFolderDataGameWise(gameID, JSON.stringify(allFolders)); savePracticeSetDataGameWise(gameID, JSON.stringify(allPracticeSets)); /* await saveFolderDataGameWise(gameID, JSON.stringify(allFolders)); const isPracticeSetSaved = await savePracticeSetDataGameWise( gameID, JSON.stringify(allPracticeSets) ); return isPracticeSetSaved; */ return true; } return false; } catch (error) { console.log("test error folders ==> " + JSON.stringify(error)); if (error.response) { if (error.response.status === 401) { const token = await this.keycloakClient.refreshToken(); if (token) { return this.getFolderDataOnly( token, baseURL, gameID, allPracticeSets ); } else { return false; // token expire issue } } else { return false; // not getting any response } } else { return false; // request or setting related issue } } } async retrieveOrganizations(): Promise { try { const url = `${this.baseStratagemURL}organizations`; const token = await this.keycloakClient.getSavedToken(); if (token) { const options = { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: token, }, url: url, }; /* console.log(`retrieveOrganizations url ==> ${url} token ==> ${token}`); const requestOptions = createStratagemRequestOptions(token); const organizationsResponse = await fetch(url, requestOptions); */ const organizationsResponse = await axios(options); if (organizationsResponse.status === 200) { const organizationsJson = organizationsResponse.data; // console.log( // `organizationsResponse ==> ${JSON.stringify(organizationsJson)}` // ); return organizationsJson; } } return []; } catch (error) { // console.log('retrieve Organizations ==> '+error); return []; } } async getGameFolders(orgID: string, gameID: string): Promise { try { const baseURL = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/`; const clientToken = await this.keycloakClient.getSavedToken(); const requestOptions = createStratagemRequestOptions(clientToken); const foldersURL = `${baseURL}folders`; // ?limit=2`; // limit is for testing // console.log(`Base url for folder ==> ${foldersURL}`); const options = { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: clientToken, }, url: foldersURL, }; const foldersResponse = await axios(options); // const foldersResponse = await fetch(foldersURL, requestOptions); // console.log('foldersResponse -->', foldersResponse); if (foldersResponse.status === 200) { // delete existing folder data from the Db for current game // deleteFolderDataGameWise(gameID); // const foldersJson = await foldersResponse.json(); const foldersJson = foldersResponse.data; const { pagination: { total: totalFolders, pages: folderPages }, } = foldersJson; let allFolders = foldersJson.Folders; // if there's more than one page, fetch all folders from every page if (folderPages > 1) { allFolders = await fetchAllData( clientToken, foldersURL, "Folders", 1 ); // something went wrong when getting data from all pages, so return false if (allFolders.length !== totalFolders) { // console.log("all folder 0 ==> " + allFolders.length); return ""; } } // Over game switching load game specfic data in offline mode case // save data in realm DB /* const isFolderSaved = await saveFolderDataGameWise( gameID, JSON.stringify(allFolders) ); return isFolderSaved; */ saveFolderDataGameWise(gameID, JSON.stringify(allFolders)); saveAPICallTime(gameID, (new Date().valueOf() / 1000).toString()); return "true"; } return ""; } catch (error) { if (error.response) { /* * The request was made and the server responded with a * status code that falls out of the range of 2xx * // console.log("error code ==>"error.response.status); */ if (error.response.status === 401) { return "false"; // token expire issue client_auth case } else if (error.response.status === 500) { return ""; // not getting any response } } else if (error.request) { /* * The request was made but no response was received, `error.request` * is an instance of XMLHttpRequest in the browser and an instance * of http.ClientRequest in Node.js * // console.log(error.request); */ return ""; } else { // Something happened in setting up the request and triggered an Error // // console.log('Error', error.message); return ""; } } } async getGamePracticeSets(orgID: string, gameID: string): Promise { try { const baseURL = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/`; const clientToken = await this.keycloakClient.getSavedToken(); const practiceSetsURL = `${baseURL}practicesets`; // ?limit=2`; // limit is for testing // console.log(`Base url practice set ==> ${practiceSetsURL}`); const options = { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: clientToken, }, url: practiceSetsURL, }; const practiceSetsResponse = await axios(options); /* const requestOptions = createStratagemRequestOptions(clientToken); const practiceSetsResponse = await fetch(practiceSetsURL, requestOptions); console.log(`getGamePracticeSets status ${practiceSetsResponse.status}`);*/ if (practiceSetsResponse.status === 200) { // delete existing practice set data from the Db for current game // deletePracticeSetDataGameWise(gameID); const practiceSetsJson = practiceSetsResponse.data; const { pagination: { total: totalPracticeSets, pages: practiceSetPages }, } = practiceSetsJson; let allPracticeSets = practiceSetsJson.PracticeSets; if (practiceSetPages > 1) { allPracticeSets = await fetchAllData( clientToken, practiceSetsURL, "PracticeSets", 1 ); } // console.log( // "check point final " + // allPracticeSets.length + // " total Practice Sets " + // totalPracticeSets // ); // something went wrong when getting data from all pages, so return false if (allPracticeSets.length !== totalPracticeSets) { return "false"; } /* const isPracticeSetSaved = await savePracticeSetDataGameWise( gameID, JSON.stringify(allPracticeSets) ); return isPracticeSetSaved; */ savePracticeSetDataGameWise(gameID, JSON.stringify(allPracticeSets)); return "true"; } return "false"; } catch (error) { return "false"; } } async downloadLeaderboard( authType: string, gameId: string, tableID: string, folderId: string ): Promise { const accessToken = await this.keycloakClient.getSavedToken(); // const leaderboardUrl = `${this.baseStratagemURL}tables/${folderId}/${tableID}`; const tableData = await downloadTableData( accessToken, this.baseStratagemURL, tableID, this.keycloakClient ); // // console.log(`tableData ==> ${JSON.stringify(tableData)}`); storeData(tableID, JSON.stringify(tableData)); // for offline storeData(CURRENT_LEADERBOARD, JSON.stringify(tableData)); // saveLeaderBoardDataGameWise(gameId, authType, tableData); return tableData; } createNewPractiseSet = async ( orgID, gameID, practiseSetName, folderID, accessToken, color, createdTime, cb ) => { try { const baseURL = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/`; const practiseSetUrl = `${baseURL}practicesets`; if (folderID === "") { folderID = null; } const bodyJSON = { name: practiseSetName, folderID, color, createdTime, }; const options = { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, data: bodyJSON, url: practiseSetUrl, }; const response = await axios(options); if (response.status === 200) { cb(response); } /* const requestOptions = createStratagemRequestPutPost( accessToken, "POST", bodyJSON ); fetch(practiseSetUrl, requestOptions) .then((response) => response) .catch((error) => { if (error instanceof InvalidUserCredentialsError) { // let InvalidUserCredentialsError bubble up to be handled later on throw error; } }) .then(cb); */ } catch (error) { if (error.response) { if (error.response.status === 401) { // token expire issue client_auth case await this.keycloakClient .refreshToken() .then(async (token) => { let failedRequest = error.config; failedRequest.headers["Authorization"] = token; // retry failed request axios .request(failedRequest) .then((resendResponse) => resendResponse) .catch((reError) => { throw reError; }) .then(cb); }) .catch((tokenError) => { throw tokenError; }); } else { throw error; // not getting any response all other error } } else if (error.request) { /* // console.log(error.request); */ throw error; } else { // setting related issue throw error; } } }; // create new folder API call createNewFolderApiCall = async ( orgID, gameID, folderName, parentfolderid, accessToken, cb ) => { try { const baseURL = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/`; const createFolderUrl = `${baseURL}folders`; const bodyJSON = { name: folderName }; // is optional pass parent ID when nested folder need if (parentfolderid !== null) { bodyJSON.parentFolder = parentfolderid; } const options = { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, data: bodyJSON, url: createFolderUrl, }; const response = await axios(options); if (response.status === 200) { cb(response); } /* const requestOptions = createStratagemRequestPutPost( accessToken, "POST", bodyJSON ); fetch(createFolderUrl, requestOptions) .then((response) => response) .catch((error) => { if (error instanceof InvalidUserCredentialsError) { // let InvalidUserCredentialsError bubble up to be handled later on throw error; } }) .then(cb); */ } catch (error) { if (error.response) { if (error.response.status === 401) { await this.keycloakClient .refreshToken() .then(async (token) => { let failedRequest = error.config; failedRequest.headers["Authorization"] = token; // retry failed request axios .request(failedRequest) .then((resendResponse) => resendResponse) .catch((reError) => { throw reError; }) .then(cb); }) .catch((tokenError) => { throw tokenError; }); } else { throw error; // not getting any response all other error } } else if (error.request) { /* // console.log(error.request); */ throw error; } else { throw error; } } }; // Update Practice Set property (color,title,folder,tags) updatePracticeSet = async ( orgID, gameID, practiceSetId, practiseSetName, folderID, accessToken, color, oldFolderID, tags, cb ) => { try { const practiseSetUrl = `${this.baseStratagemURL}organizations/${orgID}/games/${gameID}/practicesets/${practiceSetId}`; const bodyJSON = { name: practiseSetName, color: Array.isArray(color) ? color[0] : color, folderID, }; if (tags && tags !== undefined && tags !== null && tags.length) { // seprate on the basis of white space and create string array bodyJSON["tags"] = tags.split(" "); // console.log(" total ==> " + tags.split(" ").length); } // console.log(`body ==> ${JSON.stringify(bodyJSON)}`); const options = { method: "PUT", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, data: bodyJSON, url: practiseSetUrl, }; const response = await axios(options); if (response.status === 200) { cb(response); } /* const requestOptions = createStratagemRequestPutPost( accessToken, "PUT", bodyJSON ); fetch(practiseSetUrl, requestOptions) .then((response) => response) .catch((error) => { if (error instanceof InvalidUserCredentialsError) { // let InvalidUserCredentialsError bubble up to be handled later on throw error; } }) .then(cb); */ } catch (error) { if (error.response) { if (error.response.status === 401) { // token expire issue client_auth case await this.keycloakClient .refreshToken() .then(async (token) => { let failedRequest = error.config; failedRequest.headers["Authorization"] = token; // retry failed request axios .request(failedRequest) .then((resendResponse) => resendResponse) .catch((reError) => { throw reError; }) .then(cb); }) .catch((tokenError) => { throw tokenError; }); } else { throw error; // not getting any response all other error } } else if (error.request) { /* // console.log(error.request); */ throw error; } else { throw error; } } }; updatePracticeSetData = async (practiceSetID, records, accessToken, cb) => { try { const baseURL = `${this.baseStratagemURL}tables/${practiceSetID}/`; const updateRecordUrl = `${baseURL}records`; const options = { method: "PUT", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, data: records, url: updateRecordUrl, }; const response = await axios(options); if (response.status === 200) { cb(response); } /* const requestOptions = createStratagemRequestPutPost( accessToken, "PUT", records ); fetch(updateRecordUrl, requestOptions) .then((response) => response) .catch((error) => { if (error instanceof InvalidUserCredentialsError) { throw error; } }) .then(cb); */ } catch (error) { if (error.response) { if (error.response.status === 401) { // token expire issue client_auth case await this.keycloakClient .refreshToken() .then(async (token) => { let failedRequest = error.config; failedRequest.headers["Authorization"] = token; // retry failed request axios .request(failedRequest) .then((resendResponse) => resendResponse) .catch((reError) => { throw reError; }) .then(cb); }) .catch((tokenError) => { throw tokenError; }); } else { throw error; // not getting any response all other error } } else if (error.request) { /* // console.log(error.request); */ throw error; } else { // Something happened in setting up the request and triggered an Error throw error; // // console.log('Error', error.message); } } }; getGameEnableList = async (organizationsId, accessToken, cb) => { try { const gameEnableURL = `${this.baseStratagemURL}organizations/${organizationsId}/games`; const options = { timeout: API_TIME_OUT, method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, url: gameEnableURL, }; const response = await axios(options); if (response.status === 200) { cb(response); } } catch (error) { if (error.response) { if (error.response.status === 401) { await this.keycloakClient .refreshToken() .then(async (token) => { let failedRequest = error.config; failedRequest.headers["Authorization"] = token; // retry failed request axios .request(failedRequest) .then((resendResponse) => resendResponse) .catch((reError) => { throw reError; }) .then(cb); }) .catch((tokenError) => { throw tokenError; }); } else { throw error; // not getting any response all other error } } else { // for request, setting related other issue throw error; } } }; getOrgId = async (token: string, url: string) => { try { const options = { method: "GET", timeout: API_TIME_OUT, headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: token, }, url: `${url}organizations`, }; const response = await axios(options); if (response.status === 200) { const res = await response.data; // console.log('response org id ==> '+JSON.stringify(res)); if (res[0] && res[0].id) { this.keycloakClient.orgID = res[0].id; await AsyncStorage.setItem( "ORGID_USER_AUTH_OrgData", JSON.stringify(res[0]) ); return res[0]; } this.keycloakClient.orgID = ""; return ""; } else { Alert.alert(strings.offlineErrorMsg.netIssueForGetGame); } } catch (error) { if (error.response) { // console.log("error response. org id ==>", error.response); if (error.response.status === 401) { const token = await this.keycloakClient.refreshToken(); if (token) { // token expire issue client_auth case // fix cycle issue TODO: return await this.getOrgId(token, url); } else { this.keycloakClient.orgID = ""; return ""; } } else { this.keycloakClient.orgID = ""; return ""; } } else { // console.log("error org id ==>", error); this.keycloakClient.orgID = ""; return ""; } } }; registerUserIntoTheMatomo = async (emailId, navigation) => { let userID; const analyticsUrl = navigation.getParam(NavParams.ANALYTICS_URL); const analyticsID = navigation.getParam(NavParams.ANALYTICS_ID); if (this.keycloakClient.authType === AuthTypes.CLIENT_AUTH) { // for Client_Auth case Use UUID as a UserId userID = uuid.v4(); await AsyncStorage.setItem(StratagemData.IS_UUID_FOR_MATOMO, userID); } else { // for other auth_type use email_ID userID = emailId; } // console.log('all analytics data ==> '+this.keycloakClient.authType, userID, analyticsUrl, analyticsID); Matomo.initTracker(analyticsUrl, Number(analyticsID)); Matomo.setUserId(userID); try { // await analytics().setUserId(userID); // await firebase.analytics().setUserProperty('crm_id', userID); // console.log('check client userID ===> '+userID); } catch (error) { console.log("error getting ==> " + JSON.stringify(error)); } }; getUserInfoForMatomo = async (emailId, navigation) => { const token = await this.keycloakClient.getSavedToken(); const userInfoUrl = `${this.baseStratagemURL}userInfo`; try { const options = { method: "GET", timeout: API_TIME_OUT, headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: token, }, url: userInfoUrl, }; const response = await axios(options); if (response.status === 200) { const userDict = await response.data; if (userDict && userDict.userName && userDict.userName.length > 0) { storeData("actual_User_Name", userDict.userName); } if (userDict && userDict.email && userDict.email.length > 0) { return await this.registerUserIntoTheMatomo( userDict.email, navigation ); } else { return await this.registerUserIntoTheMatomo(emailId, navigation); } } else { return await this.registerUserIntoTheMatomo(emailId, navigation); } } catch (error) { // console.log('user info matomo ==> '+JSON.stringify(error)); if (error.response) { if (error.response.status === 401) { const token = await this.keycloakClient.refreshToken(); if (token) { return await this.getUserInfoForMatomo(emailId, navigation); } else { return await this.registerUserIntoTheMatomo(emailId, navigation); } } else { return await this.registerUserIntoTheMatomo(emailId, navigation); } } else { return await this.registerUserIntoTheMatomo(emailId, navigation); } } }; setUrlForOrgIDUesrAuthCase = async (field: Object) => { if (field.APIUrl !== undefined) { this.baseStratagemURL = field.APIUrl; } if (field.AuthURL !== undefined) { this.keycloakClient.authURL = field.AuthURL; } // set baseUrl and AuthURL into async for drawer view case await AsyncStorage.setItem("ORGID_USER_AUTH_BaseUrl", field.APIUrl); await AsyncStorage.setItem("ORGID_USER_AUTH_AuthUrl", field.AuthURL); }; /* GET Sessions related */ async getRecentCreatedSession( gameId: string, practiceSetId: string ): Promise { try { const accessToken = await this.keycloakClient.getSavedToken(); const getSessionUrl = `${this.baseStratagemURL}organizations/${this.keycloakClient.orgID}/games/${gameId}/practicesets/${practiceSetId}/sessions?lastCreated=true&gameSubType=multigame`; console.log("getSessionUrl ==> " + getSessionUrl); const options = { method: "GET", timeout: API_TIME_OUT, headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, url: getSessionUrl, }; const response = await axios(options); // const response = await fetch(getSessionUrl, requestOptions); if (response.status === 200) { const resJson = response.data; return resJson; } } catch (error) { if (error.response) { if (error.response.status === 401) { const token = await this.keycloakClient.refreshToken(); if (token) { // token expire issue client_auth case return await this.getRecentCreatedSession(gameId, practiceSetId); } else { return []; // token not getting case } } else { // not getting any response and for other status code return []; } } else { return []; // for request and other error } } } getLiveSessionDataByPinNo = async ( pinNumber: string, accessToken: string, cb ) => { try { const liveSessionURL = `${this.baseStratagemURL}livesessions?pin=${pinNumber}`; const options = { timeout: API_TIME_OUT, method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: accessToken, }, url: liveSessionURL, }; const response = await axios(options); if (response.status === 200) { cb(response); } /* const requestOptions = createStratagemRequestOptions(accessToken); fetch(liveSessionURL, requestOptions) .then((response) => response) .catch((error) => { if (error instanceof InvalidUserCredentialsError) { throw error; } }) .then(cb); */ } catch (error) { if (error.response) { if (error.response.status === 401) { await this.keycloakClient .refreshToken() .then(async (token) => { let failedRequest = error.config; failedRequest.headers["Authorization"] = token; // retry failed request axios .request(failedRequest) .then((resendResponse) => resendResponse) .catch((reError) => { throw reError; }) .then(cb); }) .catch((tokenError) => { throw tokenError; }); } else { throw error; // not getting any response all other error } } else if (error.request) { throw error; } else { throw error; // // console.log('Error', error.message); } } }; /* GET Dashboard data related */ getDashboardData = async (navigation, cb) => { try { const getDashboardDataURL = `${this.baseStratagemURL}dashboard`; const clientToken = await this.keycloakClient.getSavedToken(); const options = { method: "GET", timeout: API_TIME_OUT, headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: clientToken, }, url: getDashboardDataURL, }; const response = await axios(options); if (response.status === 200) { let resDashboard = response.data; // change real gameID into the constant game IDs //resDashboard = await changeIntoGameIdData(resDashboard, navigation); saveAPICallTime(DASHBOARD_ID, (new Date().valueOf() / 1000).toString()); await saveFolderDataGameWise( DASHBOARD_ID, JSON.stringify(resDashboard) ); cb(response); } } catch (error) { if (error.response) { if (error.response.status === 401) { await this.keycloakClient .refreshToken() .then(async (token) => { let failedRequest = error.config; failedRequest.headers["Authorization"] = token; // retry failed request axios .request(failedRequest) .then((resendResponse) => resendResponse) .catch((reError) => { throw reError; }) .then(cb); }) .catch((tokenError) => { throw tokenError; }); } else { throw error; // not getting any response all other error } } else if (error.request) { throw error; } else { throw error; // // console.log('Error', error.message); } } }; /* Download TableData for (Data_Source/Reference) */ getTableData = async (authType, gameId, tableID) => { // delete all documents associated with the practice set, in case they are not needed anymore const allKeys = await AsyncStorage.getAllKeys(); const practiceSetKeys = allKeys.filter((key) => key.startsWith(`${FILEPATH_KEY_PREFIX}_${tableID}`) ); const allFilePaths = await AsyncStorage.multiGet(practiceSetKeys); if (allFilePaths !== null && allFilePaths.length > 0) { allFilePaths.forEach((keyValuePair) => { const path = keyValuePair[1]; // path is the value, which is index 1 RNFetchBlob.fs.unlink(path); // this deletes the file }); } // remove the saved paths if (practiceSetKeys && practiceSetKeys.length > 0) { await AsyncStorage.multiRemove(practiceSetKeys); } const accessToken = await this.keycloakClient.getSavedToken(); const tableData = await downloadTableData( accessToken, this.baseStratagemURL, tableID, this.keycloakClient ); return tableData; }; downloadAudioVedioData = async (record, tableID) => { const RecordData = Object.values(record); const responseRecordData = await RecordData.map(async (fieldValue) => { // if the value for the field is an array, that means it's a picture/video if (Array.isArray(fieldValue)) { // the array should have one element with the metadata for the picture/video const mediaData: Object = fieldValue[0]; const { id: fileID, filename, url } = mediaData; await new Promise((resolve, reject) => { RNFetchBlob.config({ path: `${dirs.DocumentDir}/${fileID}_${filename}`, }) .fetch("GET", url) .then((response) => { // Save the path using the tableID and url as the key. This will allow us to find // all the associated files with the table and delete them when refreshing later. if ( response && response.respInfo && response.respInfo.status === 200 ) { const keyToPath = `${FILEPATH_KEY_PREFIX}_${tableID}_${url}`; // // console.log("keyToPath ==> " + JSON.stringify(response.path())); AsyncStorage.setItem(keyToPath, response.path(), () => { resolve(keyToPath); }); } else { reject(strings.practiceSetRelatedError.dataDownloadIssue); } }) .catch((error) => { reject(error); }); }); // // console.log('responseData', responseData); } }); await Promise.all(responseRecordData).then(() => { // // console.log('test', res); return true; }); }; setDataMiddle = async (authType: string, gameId: string, tableID: string) => { return new Promise((resolve, reject) => { this.getTableData(authType, gameId, tableID) .then(async (tableData) => { if (tableData.records) { const tableValues = tableData.records; const response = await tableValues.map((record) => { // // console.log('inside promise'); // use RNFetchBlob to save the picture/video to the specified path return new Promise((resolve, reject) => { this.downloadAudioVedioData(record.fields, tableID) .then(() => { // // console.log("get Table Data Promise==> ", tableData); resolve(tableData); }) .catch((error) => { reject(error); }); }); }); await Promise.all(response) .then(() => { // // console.log('tableData process TableDataAsync', tableValues); resolve(tableData); }) .catch((error) => { // console.log("get data issue 4 ==> " + error); reject(error); }); } else { // console.log("error ==> " + JSON.stringify(tableData)); // eslint-disable-next-line prefer-promise-reject-errors reject(strings.practiceSetRelatedError.dataUnexpectedError); } }) .catch((error) => { // console.log("catch issue in 7 ==> " + error); reject(error); }); }); }; getDownloadDataSet = async ( authType: string, gameId: string, tableID: string ) => { const dataSet = await this.setDataMiddle(authType, gameId, tableID); if (dataSet !== null) { // save data in realm DB // saveReviewDataGameWise(gameId, authType, dataSet); // // console.log("get data " + JSON.stringify(dataSet)); storeData(tableID, JSON.stringify(dataSet)); // for offline storeData(CURRENT_DATASOURCE, JSON.stringify(dataSet)); } // // console.log("data set " + JSON.stringify(dataSet)); return dataSet; }; downloadDocFileReferenceData = async (record, tableID: string) => { if (record.fields && record.fields.Doc && record.fields.Doc !== null) { // the array should have one element with the metadata for the DOC/PDF // TODO: may be handle multiple array case const mediaData: Object = record.fields.Doc[0]; const { id: fileID, filename, url } = mediaData; await new Promise((resolve, reject) => { // use RNFetchBlob to save the DOC/PDF to the specified path RNFetchBlob.config({ path: `${dirs.DocumentDir}/${fileID}_${filename}`, }) .fetch("GET", url) .then((response) => { // Save the path using the tableID and url as the key. This will allow us to find // all the associated files with the table and delete them when refreshing later. if ( response && response.respInfo && response.respInfo.status === 200 ) { const keyToPath = `${FILEPATH_KEY_PREFIX}_${tableID}_${url}`; AsyncStorage.setItem(keyToPath, response.path(), () => { resolve(keyToPath); }); } else { reject(strings.practiceSetRelatedError.dataDownloadIssue); } }) .catch((error) => { reject(error); }); }); } }; downloadReferenceData = async ( authType: string, gameId: string, tableID: string ) => { return new Promise((resolve, reject) => { this.getTableData(authType, gameId, tableID).then(async (tableData) => { // // console.log("reference Data ===" + JSON.stringify(tableData)); if (tableData.records) { const tableValues = tableData.records; const response = await tableValues.map((record) => { // use RNFetchBlob to save the picture/video/doc to the specified path return new Promise((resolve, reject) => { this.downloadDocFileReferenceData(record, tableID).then(() => { // console.log("get ref Data ==> ", tableData); resolve(tableData); }); }); }); await Promise.all(response).then(() => { // // console.log('tableData process TableDataAsync', tableValues); resolve(tableData); }); } else { // console.log("reference error ==> " + JSON.stringify(tableData)); reject(strings.practiceSetRelatedError.dataUnexpectedError); } }); }); }; // TODO download info doc downloadReference = async ( authType: string, gameId: string, tableID: string ) => { const referenceData = await this.downloadReferenceData( authType, gameId, tableID ); if (referenceData !== null) { // Save infoDoc data in Realm DB // saveInfoDocDataGameWise(gameId, authType, referenceData); storeData(tableID, JSON.stringify(referenceData)); // for offline storeData(CURRENT_INFODOC, JSON.stringify(referenceData)); } // console.log("reference set " + JSON.stringify(referenceData)); return referenceData; }; }