import AsyncStorage from "@react-native-community/async-storage"; import axios from "axios"; import { BASE_URL, AUTH_KEY, TABLE_URL, APP_DATA_PROPS, ERROR, } from "../constants"; import * as KeychainHelper from "../common/utils/KeychainHelper"; import KeycloakClient from "./networking/KeycloakClient"; import { AuthTypes } from "./Enums"; import { InvalidUserCredentialsError } from "./Errors"; import { API_TIME_OUT } from "./ConfigEnum"; import { ROUTES } from "./routes/RouteConst"; import { storeData } from "./asyncStorageHelper"; const base64 = require("base-64"); /** * @format * @flow */ export const getGameContents = async () => { try { const URL = `${BASE_URL}/gamecontents`; const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: AUTH_KEY, }, URL, }; const response = await axios(options); const responseJson = response.data; return responseJson; } catch (error) { return error; } }; export const getTablesBasedOnBaseId = async (baseId: string) => { try { const URL = `${BASE_URL}/bases/${baseId}`; const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: AUTH_KEY, }, URL, }; const response = await axios(options); const responseJson = response.data; return responseJson; } catch (error) { return error; } }; export const getTablesBasedOnTableId = async (tableId: string) => { try { const URL = `${TABLE_URL}/${tableId}`; const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: AUTH_KEY, }, URL, }; const response = await axios(options); const responseJson = response.data; return responseJson; } catch (error) { return error; } }; export async function getAppPropsData() { try { const temp = await AsyncStorage.getItem(APP_DATA_PROPS); // const temp1 = await AsyncStorage.getAllKeys(); let data = JSON.parse(temp); return data; } catch (e) { throw e; } } export const getAssignmentHistoryData = async (refreshToken: any) => { let accessToken = ""; let suffix: string = `assignmentHistory?assignRole=myAssignment`; const temp = await AsyncStorage.getItem(APP_DATA_PROPS); let data = JSON.parse(temp); const baseURL = data.stratagemClient.baseStratagemURL; if (refreshToken) { accessToken = refreshToken; } else { // accessToken = await KeychainHelper.getSavedToken(data.authType); accessToken = await ReturnAccessToken(); } try { let url = baseURL + suffix; try { const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: accessToken, }, url, }; const historyData = await axios(options); if (historyData?.status == 200) { return historyData; } else return "ERROR_NOT_200"; } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case const token = await ReturnrefreshToken(data.authType); if (token.length > 0) { getAssignmentHistoryData(token); } else { return; } } else { // 500 and other status code return error; } } } catch (e) { console.log("e1", e); throw e; } }; export async function fetchExtraDataforNestedItemsViaFolderId( folderId: string, refreshToken: any ) { let accessToken: string = ""; const temp = await AsyncStorage.getItem(APP_DATA_PROPS); let data = JSON.parse(temp); if (refreshToken) { accessToken = refreshToken; } else { accessToken = await ReturnAccessToken(); // accessToken = await KeychainHelper.getSavedToken(data.authType); } try { const baseURL = data.stratagemClient.baseStratagemURL; let suffix = `folders/${folderId}`; let url = baseURL + suffix; const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: accessToken, }, url, }; const response = await axios(options); if (response.status == 200) { return response.data; } else { return "ERROR_NOT_200"; } } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case console.log("err 401", error); const newtoken = await ReturnrefreshToken(data.authType); console.log("newtoken", newtoken); fetchExtraDataforNestedItemsViaFolderId(folderId, newtoken); } else { // 500 and other status code return error; } } } async function ReturnAccessToken(): Promise { let accessToken: string = ""; try { const temp = await AsyncStorage.getItem(APP_DATA_PROPS); let data = JSON.parse(temp); accessToken = await KeychainHelper.getSavedToken(data.authType); return accessToken; } catch (e) { console.log(e); throw e; } } async function ReturnrefreshToken(authType: string): Promise { try { if ( authType === AuthTypes.USER_AUTH || authType === AuthTypes.ORGID_USER_AUTH || authType === AuthTypes.USER_ORG_AUTH ) { const credentials = await KeychainHelper.getUserCredentials(authType); if (credentials) { return loginWithUserCredentials( credentials.username, credentials.password ); } } if (authType === AuthTypes.CLIENT_AUTH) { return loginWithClientID(credentials.username, credentials.password); } return ""; } catch (error) { console.log("ReturnrefreshToken", error); if (error instanceof InvalidUserCredentialsError) { // let InvalidUserCredentialsError bubble up to be handled later on throw error; } else { return ""; } } } async function loginWithClientID( clientID: string, clientPassword: string ): Promise { try { const encodedAuthorization = base64.encode(`${clientID}:${clientPassword}`); const options = { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: `Basic ${encodedAuthorization}`, }, data: "grant_type=client_credentials", url: this.authURL, }; const response = await axios(options); const responseJSON = response.data; if (response.status === 200) { const accessToken = `Bearer ${responseJSON.access_token}`; await KeychainHelper.saveClientToken(this.clientID, accessToken); return accessToken; } return ""; } catch (error) { console.log("getting error ==> " + JSON.stringify(error)); return ""; } } async function loginWithUserCredentials( username: string, password: string ): Promise { try { const data = await getAppPropsData(); const authURL: string = data.stratagemClient.keycloakClient.authURL; const bodyJSON = { username, password, grant_type: "password", client_id: "Stratagem-Application", }; // convert body parameters to query string. ex) username=john&password=doe&key=value const bodyString = Object.keys(bodyJSON) .map((key) => `${key}=${bodyJSON[key]}`) .join("&"); const options = { method: "POST", timeout: API_TIME_OUT, headers: { "Content-Type": "application/x-www-form-urlencoded", // Authorization: `Basic ${encodedAuthorization}`, }, data: bodyString, url: authURL, }; const response = await axios(options); const responseJSON = response.data; if (response.status === 200) { const accessToken = `Bearer ${responseJSON.access_token}`; // save credentials if login was successful await KeychainHelper.saveUserCredentials( username, password, data.authType, accessToken ); return accessToken; } // if login failed for another reason, send empty string to indicate failure return ""; } catch (error) { if (error.response) { if (error.response.status === 401) { return ""; // not a Valid User credentials } else { // 500 and other status code return ""; // not getting any response } } else { // Something happened in setting up the request and triggered an Error return ""; } } } //adding for assignment export const getAssignmentComponentData = async (token: string) => { let suffix: string = `assignments`; const temp = await AsyncStorage.getItem(APP_DATA_PROPS); let data = JSON.parse(temp); const baseURL = data.stratagemClient.baseStratagemURL; const baseURL2 = baseURL.substring(0, 58); const v2_baseURL = baseURL2.concat("/v2/" + suffix); if (token) { try { let url = baseURL + suffix; try { const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: token, }, url, }; const assignmentComponentData = await axios(options); if (assignmentComponentData?.status == 200) { await storeData( ROUTES.ASSIGNMENTS, JSON.stringify(assignmentComponentData.data) ); return assignmentComponentData.data; } else if (assignmentComponentData?.status == 401) { const token = await ReturnrefreshToken(data.authType); getAssignmentComponentData(token); } } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case console.log("err", error); const token = await ReturnrefreshToken(data.authType); getAssignmentComponentData(token); } else { // 500 and other status code return error; } } } catch (e) { throw e; } } else { let new_token: string = await ReturnrefreshToken(data.authType); return getAssignmentComponentData(new_token); } }; //addinf for assignmentscreendata export const getAssignedComponentData = async ( refreshToken: any, assignmentId: String ) => { let accessToken = ""; let suffix: string = `assignments/` + assignmentId; const temp = await AsyncStorage.getItem(APP_DATA_PROPS); let data = JSON.parse(temp); const baseURL = data.stratagemClient.baseStratagemURL; if (refreshToken) { accessToken = refreshToken; } else { accessToken = await ReturnAccessToken(); } try { let url = baseURL + suffix; try { const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: accessToken, }, url, }; const assignmentComponentData = await axios(options); if (assignmentComponentData?.status == 200) { await AsyncStorage.setItem( ROUTES.ASSIGNMENTS, JSON.stringify(assignmentComponentData.data) ); return assignmentComponentData; } else return "ERROR_NOT_200"; } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case console.log("err1=>", error); const token = await ReturnrefreshToken(data.authType); getAssignedComponentData(token, assignmentId); } else { // 500 and other status code return error; } } } catch (e) { throw e; } }; // adding for session data export const getSessionDatafromAPI = async ( token: string, gameId: string, practiceSetId: string ) => { const data = await getAppPropsData(); const orgID = data.keycloakClient.orgID; const baseURL = data.stratagemClient.baseStratagemURL; const url = `${baseURL}organizations/${orgID}/games/${gameId}/practicesets/${practiceSetId}/sessions?lastCreated=true&gameSubType=multigame`; if (token) { try { try { const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: token, }, url, }; const response = await axios(options); if (response.status == 200) { const resJson = response.data; return resJson; } else if (response.status == 401) { const token = await ReturnrefreshToken(data.authType); getSessionDatafromAPI(token, gameId, practiceSetId); } } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case console.log("err", error); const token = await ReturnrefreshToken(data.authType); getSessionDatafromAPI(token, gameId, practiceSetId); } else { // 500 and other status code return error; } } } catch (e) { console.log("e", e); } } else { let new_token: string = await ReturnrefreshToken(data.authType); console.log(`new_token`, new_token); return getSessionDatafromAPI(new_token, gameId, practiceSetId); } }; //adding for leaderboard export const getLeaderBoardData = async ( refreshToken: any, leaderboardId: String ) => { let accessToken = ""; let suffix: string = `tables/` + leaderboardId; const temp = await AsyncStorage.getItem(APP_DATA_PROPS); let data = JSON.parse(temp); const baseURL = data.stratagemClient.baseStratagemURL; if (refreshToken) { accessToken = refreshToken; } else { accessToken = await ReturnAccessToken(); } try { let url = baseURL + suffix; try { const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: accessToken, }, url, }; const leaderboardData = await axios(options); if (leaderboardData?.status == 200) { await AsyncStorage.setItem( ROUTES.ASSIGNMENTS, JSON.stringify(leaderboardData.data) ); return leaderboardData; } else return "ERROR_NOT_200"; } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case console.log("err", error); const token = await ReturnrefreshToken(data.authType); // getAssignmentComponentData(token); } else { // 500 and other status code return error; } } } catch (e) { throw e; } }; //adding for recently played data export const getRecentlyPlayedData = async (token: string) => { let suffix: string = `recentlyPlayedPracticeSets`; const temp = await AsyncStorage.getItem(APP_DATA_PROPS); let data = JSON.parse(temp); const baseURL = data.stratagemClient.baseStratagemURL; const baseURL2 = baseURL.substring(0, 58); const v2_baseURL = baseURL2.concat("/v2/"); if (token) { try { let url = v2_baseURL + suffix; console.log("getRecentlyPlayedData", url); try { const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: token, }, url, }; const recentlyPlayedData = await axios(options); if (recentlyPlayedData?.status == 200) { return recentlyPlayedData.data; } else if (recentlyPlayedData?.status == 401) { const token = await ReturnrefreshToken(data.authType); getRecentlyPlayedData(token); } } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case console.log("err", error); const token = await ReturnrefreshToken(data.authType); getRecentlyPlayedData(token); } else { // 500 and other status code return error; } } } catch (e) { throw e; } } else { let new_token: string = await ReturnrefreshToken(data.authType); return getRecentlyPlayedData(new_token); } }; // Quiz history section export const getQuizResultsHistory = async ( token: string, assignmentId: string, practiceSetId: string ) => { const data = await getAppPropsData(); const orgID = data.keycloakClient.orgID; const baseURL = data.stratagemClient.baseStratagemURL; const url = `${baseURL}/result/${assignmentId}/${practiceSetId}`; if (token) { try { try { const options = { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: token, }, url, }; const response = await axios(options); if (response.status == 200) { const resJson = response.data; return resJson; } else if (response.status == 401) { const token = await ReturnrefreshToken(data.authType); getQuizResultsHistory(token, assignmentId, practiceSetId); } } catch (error) { if (error && error.response.status === 401) { // token expire issue client_auth case console.log("err", error); const token = await ReturnrefreshToken(data.authType); getQuizResultsHistory(token, assignmentId, practiceSetId); } else { // 500 and other status code return error; } } } catch (e) { console.log("e", e); } } else { let new_token: string = await ReturnrefreshToken(data.authType); return getQuizResultsHistory(new_token, assignmentId, practiceSetId); } };