Backup_FME_personal/force-app/main/default/classes/ServerApiCalloutUtility.cls

969 lines
39 KiB
OpenEdge ABL

public class ServerApiCalloutUtility {
private static String SERVER_URL = System.Label.Ngrok;
// ATTENTION !
// externalStorage is hardcoded for Google Drive/googleDrive. Won't work for others
// until a value is passed in as externalStorage in parameter from LWC.
// For now, lets use a static variable value for Google Drive (or googleDrive)
// static String externalStorage = 'GoogleDrive';
static String orgId = UserInfo.getOrganizationId();
public class AuthConfig {
@AuraEnabled public String clientId;
@AuraEnabled public String redirectUri;
@AuraEnabled public String orgId;
@AuraEnabled public Boolean sandbox;
}
public class ConnectionResponse {
@AuraEnabled public Boolean isConnected;
@AuraEnabled public String username;
}
// @AuraEnabled(cacheable=false)
// public static Map<String, Object> getFileFromNgrok(String queryBase64) {
// Map<String, Object> result = new Map<String, Object>();
// Http http = new Http();
// HttpRequest req = new HttpRequest();
// req.setEndpoint('https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/external?query=' + EncodingUtil.urlEncode(queryBase64, 'UTF-8'));
// req.setMethod('GET');
// req.setTimeout(60000);
// System.debug('Endpoint: '+ req.getEndpoint());
// System.debug('Request: ' + req);
// HttpResponse res = http.send(req);
// if (res.getStatusCode() == 200) {
// result.put('contentType', res.getHeader('Content-Type'));
// result.put('base64Data', EncodingUtil.base64Encode(res.getBodyAsBlob()));
// System.debug('Result: ' + result);
// return result;
// }
// else if(res.getStatusCode() == 404) {
// result.put('success', false);
// result.put('message', 'Internal Server Error');
// return result;
// }
// else {
// throw new AuraHandledException(
// 'Failed to fetch file: ' + res.getStatusCode() + ' - ' + res.getBody()
// );
// }
// }
@AuraEnabled(cacheable=false)
public static Map<String, Object> getFileFromNgrok(String queryBase64) {
Map<String, Object> result = new Map<String, Object>();
try {
Http http = new Http();
HttpRequest req = new HttpRequest();
// req.setEndpoint(
// 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/external?query='
// + EncodingUtil.urlEncode(queryBase64, 'UTF-8')
// );
String endpoint = SERVER_URL + '/api/v1/file/external?query=' + EncodingUtil.urlEncode(queryBase64, 'UTF-8');
req.setEndpoint(endpoint);
req.setMethod('GET');
req.setTimeout(60000);
System.debug('Endpoint: ' + req.getEndpoint());
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
result.put('contentType', res.getHeader('Content-Type'));
result.put('base64Data', EncodingUtil.base64Encode(res.getBodyAsBlob()));
return result;
} else if (res.getStatusCode() == 404) {
result.put('success', false);
result.put('message', 'File not found on Ngrok server');
FME_Logger.error('File not found (404) for queryBase64', 'ServerApiCalloutUtility', 'getFileFromNgrok');
return result;
} else {
throw new AuraHandledException(
'Failed to fetch file: ' + res.getStatusCode() + ' - ' + res.getBody()
);
}
} catch (Exception e) {
FME_Logger.error(e.getMessage(),'ServerApiCalloutUtility','getFileFromNgrok Line: ' + e.getLineNumber());
throw new AuraHandledException('Unexpected error while fetching file.');
} finally {
FME_Logger.saveLog();
}
}
// @AuraEnabled
// public static Map<String,String> getCreatedPublicUrl(Boolean isServiceMode, String userId, String fileId, Map<String,Object> body){
// try {
// Map<String,String> result = new Map<String, String>();
// Map<String,String> accessTokenMap=new Map<String, String> ();
// accessTokenMap = CloudStorageUtlilty.getAccessToken(isServiceMode, userId);
// System.debug('accTK2:-- '+accessTokenMap);
// String ACCESS_TOKEN = (String) accessTokenMap.get('ACCESS_TOKEN');
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/publicUrl';
// System.debug('Endpoint: '+ endpoint);
// Map<String, Object> tmp = new Map<String, Object>();
// System.debug('accTK:-- '+ accessTokenMap);
// tmp.put('accessToken', ACCESS_TOKEN);
// body.put('googlePayload', tmp);
// Map<String,String> headers = new Map<String,String>();
// headers.put('Content-Type', 'application/json');
// System.debug('Request Body=) '+ body);
// HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
// if(res.getStatusCode() != 200){
// System.debug('Something went wrong ');
// System.debug('Result: '+ res.getBody());
// // return '--Problem occured/in/call/to/server--';
// return null;
// }
// result = (Map<String,String>) JSON.deserialize(res.getBody(), Map<String,String>.class);
// System.debug(result);
// // return result;
// // String responseBody = res.getBody();
// String url = result.get('publicUrl');
// url = url.substringAfter('/api/');
// url = 'https://hopelessly-upright-platypus.ngrok-free.app' + '/api/' + url;
// result.put('publicUrl', url);
// // System.debug('URL: '+ url);
// return result;
// } catch (Exception e) {
// throw new AuraHandledException(e.getMessage());
// }
// }
@AuraEnabled
public static Map<String,Object> getCreatedPublicUrl(String externalStorage, Boolean isServiceMode, String userId, String fileId, Map<String,Object> body){
System.debug('getCreatedPublicUrl');
System.debug('isServiceMode' + isServiceMode);
System.debug('userId'+userId);
System.debug('fileId'+fileId);
System.debug('bodyinpublicurl'+json.serializePretty(body));
System.debug('externalStorage' +externalStorage);
Map<String,Object> result = new Map<String, Object>();
try {
Map<String,Object> accessTokenMap=new Map<String, Object> ();
accessTokenMap = (Map<String, Object>) CloudStorageUtlilty.getAccessToken(isServiceMode, userId, externalStorage);
System.debug('accTK2:-- '+ JSON.serializePretty(accessTokenMap));
String ACCESS_TOKEN = (String) accessTokenMap.get('ACCESS_TOKEN');
Map<String, Object> payload = (Map<String, Object>) accessTokenMap.get('payload');
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/publicUrl';
String endpoint = SERVER_URL + '/api/v1/file/publicUrl';
System.debug('Endpoint: '+ endpoint);
System.debug('accTK:-- '+ accessTokenMap);
System.debug('Token present: ' + accessTokenMap.containsKey('ACCESS_TOKEN'));
Map<String, Object> tmp = new Map<String, Object>();
tmp.put('accessToken', ACCESS_TOKEN);
if(externalStorage.equalsIgnoreCase('googledrive')){
body.put('googlePayload', tmp);
}
else if(externalStorage.equalsIgnoreCase('dropbox')){
body.put('dropBox', tmp);
}
else if(externalStorage.equalsIgnoreCase('sharepoint')){
System.debug('line189');
Object rawSp = body.get('sharepoint');
System.debug('rawSp' + rawSp);
Map<String,Object> sp;
if(rawSp != null){
sp = (Map<String,Object>) JSON.deserializeUntyped(JSON.serialize(rawSp));
} else {
sp = new Map<String,Object>();
}
System.debug('SharePoint keys: ' + sp.keySet());
System.debug('driveId: ' + sp.get('driveId'));
System.debug('itemId: ' + sp.get('itemId'));
sp.put('accessToken', ACCESS_TOKEN);
body.put('sharepoint', sp);
}
else if(externalStorage.equalsIgnoreCase('onedrive')){
// tmp.put('fileId', fileId);
body.put('oneDrive', tmp);
}
else if(externalStorage.equalsIgnoreCase('box')){
body.put('box', tmp);
}
else if(externalStorage.equalsIgnoreCase('awss3')){
Map<Object, Object> fileDetails = (Map<Object, Object>) body.get('fileDetails');
fileDetails.put('objectKey', fileId);
body.put('fileDetails', fileDetails);
body.put('awsPayload', payload);
}
else if(externalStorage.equalsIgnoreCase('sftp')){
Map<Object, Object> fileDetails = (Map<Object, Object>) body.get('fileDetails');
fileDetails.put('objectKey', fileId);
body.put('fileDetails', fileDetails);
body.put('sftp', payload);
}
Map<String,String> headers = new Map<String,String>();
headers.put('Content-Type', 'application/json');
System.debug('Request Body=) '+ body);
HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
System.debug('StatusCode: '+ res.getStatusCode());
System.debug('ResponseBody: '+ res.getBody());
result = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
System.debug(result);
if(res.getStatusCode() != 200){
System.debug('Something went wrong ');
System.debug('Result: '+ res.getBody());
// return '--Problem occured/in/call/to/server--';
return result;
}
// return result;
// String responseBody = res.getBody();
String url = (String) result.get('publicUrl');
url = url.substringAfter('/api/');
url = SERVER_URL + '/api/' + url;
// result.put('publicUrl', url);
Boolean success = res.getStatusCode() == 200;
result.put('success', success);
FME_Logger.info('Public URL created successfully: ' + url, 'ServerApiCalloutUtility', 'getCreatedPublicUrl');
// System.debug('URL: '+ url);
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'getCreatedPublicUrl');
throw new AuraHandledException(e.getMessage());
} finally {
FME_Logger.saveLog();
}
return result;
}
// @AuraEnabled
// public static Map<String,String> updatePublicUrl(Boolean isServiceMode, String userId, Map<String,Object> body){
// try {
// Map<String, String> result = new Map<String, String>();
// Map<String,String> accessTokenMap=new Map<String, String> ();
// accessTokenMap = CloudStorageUtlilty.getAccessToken(isServiceMode, userId);
// String ACCESS_TOKEN = (String) accessTokenMap.get('ACCESS_TOKEN');
// Map<String, Object> tmp = new Map<String, Object>();
// tmp.put('accessToken', ACCESS_TOKEN);
// body.put('googlePayload', tmp);
// // Set Endpoint
// String endpoint;
// endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/publicUrl';
// // Set Header
// Map<String,String> headers = new Map<String,String>();
// headers.put('Content-Type', 'application/json');
// HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
// if(res.getStatusCode() != 200 && res.getStatusCode() != 201){
// System.debug('Something went wrong ');
// System.debug('Result: '+ res.getBody());
// return result;
// }
// result = (Map<String,String>) JSON.deserialize(res.getBody(), Map<String,String>.class);
// String url = result.get('publicUrl');
// url = url.substringAfter('/api/');
// url = 'https://hopelessly-upright-platypus.ngrok-free.app' + '/api/' + url;
// result.put('publicUrl', url);
// return result;
// } catch (Exception e) {
// throw new AuraHandledException(e.getMessage());
// }
// }
@AuraEnabled
public static Map<String,String> updatePublicUrl(String externalStorage, Boolean isServiceMode, String userId, Map<String,Object> body){
Map<String, String> result = new Map<String, String>();
try {
Map<String,Object> accessTokenMap=new Map<String, Object> ();
accessTokenMap = (Map<String, Object>) CloudStorageUtlilty.getAccessToken(isServiceMode, userId, externalStorage);
String ACCESS_TOKEN = (String) accessTokenMap.get('ACCESS_TOKEN');
Map<String, Object> tmp = new Map<String, Object>();
tmp.put('accessToken', ACCESS_TOKEN);
body.put('googlePayload', tmp);
// Set Endpoint
String endpoint;
// endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/publicUrl';
endpoint = SERVER_URL + '/api/v1/file/publicUrl';
// Set Header
Map<String,String> headers = new Map<String,String>();
headers.put('Content-Type', 'application/json');
HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
if(res.getStatusCode() != 200 && res.getStatusCode() != 201){
System.debug('Something went wrong ');
System.debug('Result: '+ res.getBody());
return result;
}
result = (Map<String,String>) JSON.deserialize(res.getBody(), Map<String,String>.class);
String url = result.get('publicUrl');
url = url.substringAfter('/api/');
url = SERVER_URL + '/api/' + url;
result.put('publicUrl', url);
FME_Logger.info('public URL updated: ' + url, 'ServerApiCalloutUtility', 'updatePublicUrl');
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'updatePublicUrl');
throw new AuraHandledException(e.getMessage());
} finally {
FME_Logger.saveLog();
}
return result;
}
// @AuraEnabled
// public static Map<String,String> queryFileInServer(String orgId, String fileId, String uuid, String externalStorageProvider){
// try {
// Map<String,String> result = new Map<String,String>();
// Map<String,String> headers = new Map<String,String>();
// headers.put('Content-Type', 'application/json');
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/check';
// Map<String,String> body = new Map<string,String>();
// body.put('orgId', orgId);
// body.put('fileId', fileId);
// body.put('uuid', uuid);
// body.put('externalStorageProvider', externalStorageProvider);
// System.debug('Request body:-> '+ body);
// HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
// if(res.getStatusCode() != 200){
// System.debug('Something went wrong ');
// System.debug('Result: '+ res.getBody());
// return result;
// }
// result = (Map<String,String>) JSON.deserialize(res.getBody(), Map<String,String>.class);
// System.debug('Result: '+ res.getBody());
// return result;
// } catch (Exception e) {
// throw new AuraHandledException(e.getMessage());
// }
// }
@AuraEnabled
public static Map<String,Object> queryFileInServer( String fileId, String uuid, String externalStorageProvider){
System.debug('queryFileInServer called with fileId=' + fileId + ', uuid=' + uuid + ', externalStorageProvider=' + externalStorageProvider );
Map<String,Object> result = new Map<String,Object>();
try {
Map<String,String> headers = new Map<String,String>();
headers.put('Content-Type', 'application/json');
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/check';
String endpoint = SERVER_URL + '/api/v1/file/check';
Map<String,String> body = new Map<string,String>();
body.put('orgId', orgId);
body.put('fileId', fileId);
body.put('uuid', uuid);
body.put('externalStorageProvider', externalStorageProvider);
System.debug('Request body:-> '+ body);
HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
if(res.getStatusCode() != 200){
System.debug('Something went wrong ');
System.debug('Result: '+ res.getBody());
return result;
}
result = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
Boolean success = res.getStatusCode() == 200;
result.put('success', success);
System.debug('Result: '+ res.getBody());
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'queryFileInServer');
result = new Map<String,Object>();
// throw new AuraHandledException(e.getMessage());
} finally {
FME_Logger.saveLog();
}
return result;
}
// @AuraEnabled
// public static List<Map<String,String>> getAllPublicUrls(String orgId){
// try {
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/publicUrlDetails';
// endpoint += '?orgId=' + orgId;
// Map<String,String> headers = new Map<String,String>();
// headers.put('Content-Type', 'application/json');
// Map<String,String> body = new Map<string,String>();
// // body.put('orgId', orgId);
// List<Map<String,String>> result = new List<Map<String,String>>();
// HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
// if(res.getStatusCode() != 200){
// System.debug('Something went wrong ');
// System.debug('Result: '+ res.getBody());
// return result;
// }
// System.debug('Result: '+ JSON.serialize(res.getBody()));
// result = (List<Map<String,String>>) JSON.deserialize(res.getBody(), List<Map<String,String>>.class);
// // System.debug('Result: '+ res.getBody());
// // return JSON.serialize(result);
// return result;
// } catch (Exception e) {
// throw new AuraHandledException(e.getMessage());
// }
// }
//added the logger
@AuraEnabled
public static List<Map<String,String>> getAllPublicUrls(){
List<Map<String,String>> result = new List<Map<String,String>>();
try {
String orgId = UserInfo.getOrganizationId(); // backend se fetch
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/publicUrlDetails';
String endpoint = SERVER_URL + '/api/v1/file/publicUrlDetails';
endpoint += '?orgId=' + orgId;
Map<String,String> headers = new Map<String,String>();
headers.put('Content-Type', 'application/json');
Map<String,String> body = new Map<string,String>();
// body.put('orgId', orgId);
HttpResponse res = CloudStorageUtlilty.makeCallout(JSON.serialize(body), endpoint, headers, 'POST');
if(res.getStatusCode() != 200){
System.debug('Something went wrong ');
System.debug('Result: '+ res.getBody());
return result;
}
System.debug('Result: '+ JSON.serialize(res.getBody()));
result = (List<Map<String,String>>) JSON.deserialize(res.getBody(), List<Map<String,String>>.class);
// System.debug('Result: '+ res.getBody());
// return JSON.serialize(result);
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'getAllPublicUrls');
result = new List<Map<String,String>>();
// throw new AuraHandledException(e.getMessage());
} finally{
FME_Logger.saveLog();
}
return result;
}
// @AuraEnabled
// public static void deletePublicUrl(String uuid, String orgId){
// try {
// // Map<String,String> result = new Map<String,String>();
// Map<String,String> headers = new Map<String,String>();
// headers.put('Content-Type', 'application/json');
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/';
// endpoint += (uuid +'?orgId='+ orgId);
// HttpResponse res = CloudStorageUtlilty.makeCallout(null, endpoint, headers, 'DELETE');
// if(res.getStatusCode() != 200 && res.getStatusCode() != 204){
// System.debug('Something went wrong ');
// System.debug('Result: '+ res.getBody());
// // return result;
// return;
// }
// // result = (Map<String,String>) JSON.deserialize(res.getBody(), Map<String,String>.class);
// System.debug('Result: '+ res.getBody());
// // return result;
// } catch (Exception e) {
// throw new AuraHandledException(e.getMessage());
// }
// }
@AuraEnabled
public static void deletePublicUrl(String uuid){
try {
// System.debug('deletePublicUrl called with uuid=' + uuid + ', orgId=' + orgId);
// Map<String,String> result = new Map<String,String>();
Map<String,String> headers = new Map<String,String>();
headers.put('Content-Type', 'application/json');
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/';
String endpoint = SERVER_URL + '/api/v1/file/';
String orgId = UserInfo.getOrganizationId();
endpoint += (uuid +'?orgId='+ orgId);
HttpResponse res = CloudStorageUtlilty.makeCallout(null, endpoint, headers, 'DELETE');
FME_Logger.info('deletePublicUrl called with uuid=' + uuid + ', orgId=' + orgId,
'ServerApiCalloutUtility', 'deletePublicUrl');
if(res.getStatusCode() != 200 && res.getStatusCode() != 204){
System.debug('Something went wrong ');
System.debug('Result: '+ res.getBody());
// return result;
return;
}
// result = (Map<String,String>) JSON.deserialize(res.getBody(), Map<String,String>.class);
System.debug('Result: '+ res.getBody());
// return result;
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'deletePublicUrl');
// throw new AuraHandledException(e.getMessage());
} finally{
FME_Logger.saveLog();
}
}
// @AuraEnabled(cacheable=true)
// public static AuthConfig getConnectionSettings() {
// HIC_FilesME__Storage_Provider_Config__mdt config = [
// SELECT HIC_FilesME__Client_ID__c, HIC_FilesME__Redirect_Uri__c
// FROM HIC_FilesME__Storage_Provider_Config__mdt
// WHERE DeveloperName = 'Files_Server_Creds'
// LIMIT 1
// ];
// Organization orgInfo = [SELECT Id, IsSandbox FROM Organization LIMIT 1];
// System.debug('filescrd>>>> ' + config);
// AuthConfig auth = new AuthConfig();
// auth.clientId = config.HIC_FilesME__Client_ID__c;
// auth.redirectUri = config.HIC_FilesME__Redirect_Uri__c;
// auth.sandbox = orgInfo.IsSandbox;
// auth.orgId = UserInfo.getOrganizationId();
// System.debug('orgId: ' + auth.orgId);
// System.debug('sandbox: ' + auth.sandbox);
// System.debug('auth: ' + auth);
// return auth;
// }
@AuraEnabled(cacheable=true)
public static AuthConfig getConnectionSettings() {
AuthConfig auth = new AuthConfig();
try{
HIC_FilesME__Storage_Provider_Config__mdt config = [
SELECT HIC_FilesME__Client_ID__c, HIC_FilesME__Redirect_Uri__c
FROM HIC_FilesME__Storage_Provider_Config__mdt
WHERE DeveloperName = 'Files_Server_Creds'
LIMIT 1
];
Organization orgInfo = [SELECT Id, IsSandbox FROM Organization LIMIT 1];
System.debug('filescrd>>>> ' + config);
auth.clientId = config.HIC_FilesME__Client_ID__c;
auth.redirectUri = config.HIC_FilesME__Redirect_Uri__c;
auth.sandbox = orgInfo.IsSandbox;
auth.orgId = UserInfo.getOrganizationId();
System.debug('orgId: ' + auth.orgId);
System.debug('sandbox: ' + auth.sandbox);
System.debug('auth: ' + auth);
} catch(Exception e){
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'getConnectionSettings');
} finally {
FME_Logger.saveLog();
}
return auth;
}
// @AuraEnabled
// public static ConnectionResponse checkConnectionStatus(String orgId) {
// User currentUser = [
// SELECT Username FROM User WHERE Id = :UserInfo.getUserId()
// ];
// String username = currentUser.Username;
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/oauth/salesforce/authenticated'
// + '?orgId=' + orgId
// + '&username=' + username;
// System.debug('endpoint: ' + endpoint);
// Map<String, String> headers = new Map<String, String>{
// 'Content-Type' => 'application/json'
// };
// HttpResponse res = CloudStorageUtlilty.makeCallout('', endpoint, headers, 'GET');
// if (res.getStatusCode() == 200) {
// Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
// Boolean exists = (Boolean)data.get('exists');
// Boolean active = (Boolean)data.get('active');
// ConnectionResponse response = new ConnectionResponse();
// response.isConnected = exists && active;
// response.username = username;
// System.debug('response (checkConnectionStatus): ' + response);
// //No saveAuthConfig call here
// return response;
// } else {
// throw new AuraHandledException('Connection check failed: ' + res.getStatus());
// }
// }
// This method checks the status of server connection. Returns true if already connected
@AuraEnabled
public static ConnectionResponse checkConnectionStatus() {
String orgId = UserInfo.getOrganizationId();
ConnectionResponse response = new ConnectionResponse();
try {
User currentUser = [
SELECT Username FROM User WHERE Id = :UserInfo.getUserId()
];
String username = currentUser.Username;
// Always build endpoint early
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/oauth/salesforce/authenticated'
String endpoint = SERVER_URL + '/api/v1/oauth/salesforce/authenticated' + '?orgId=' + orgId + '&username=' + username;
System.debug('endpoint: ' + endpoint);
Map<String, String> headers = new Map<String, String>{
'Content-Type' => 'application/json'
};
HttpResponse res = CloudStorageUtlilty.makeCallout('', endpoint, headers, 'GET');
if (res.getStatusCode() == 200) {
Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
Boolean exists = (Boolean)data.get('exists');
Boolean active = (Boolean)data.get('active');
response.isConnected = exists && active;
response.username = username;
} else {
response.isConnected = false;
throw new AuraHandledException('Connection check failed: ' + res.getStatus());
}
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility:' + e.getLineNumber(), 'checkConnectionStatus');
} finally {
FME_Logger.saveLog();
}
return response;
}
// Check connection status and save config if connected
// @AuraEnabled
// public static ConnectionResponse isConnectionActive(String orgId) {
// User currentUser = [
// SELECT Username FROM User WHERE Id = :UserInfo.getUserId()
// ];
// String username = currentUser.Username;
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/oauth/salesforce/authenticated'
// + '?orgId=' + orgId
// + '&username=' + username;
// System.debug('endpoint: ' + endpoint);
// Map<String, String> headers = new Map<String, String>{
// 'Content-Type' => 'application/json'
// };
// HttpResponse res = CloudStorageUtlilty.makeCallout('', endpoint, headers, 'GET');
// if (res.getStatusCode() == 200) {
// Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
// Boolean exists = (Boolean)data.get('exists');
// Boolean active = (Boolean)data.get('active');
// ConnectionResponse response = new ConnectionResponse();
// response.isConnected = exists && active;
// response.username = username;
// System.debug('response: ' + response);
// if (response.isConnected) {
// saveAuthConfig(true);
// }
// return response;
// } else {
// throw new AuraHandledException('Connection check: ' + res.getStatus());
// }
// }
@AuraEnabled
public static ConnectionResponse isConnectionActive(String orgId) {
ConnectionResponse response = new ConnectionResponse();
try {
User currentUser = [SELECT Username FROM User WHERE Id = :UserInfo.getUserId()];
String username = currentUser.Username;
String endpoint = SERVER_URL + '/api/v1/oauth/salesforce/authenticated'
+ '?orgId=' + orgId
+ '&username=' + username;
Map<String, String> headers = new Map<String, String>{
'Content-Type' => 'application/json'
};
HttpResponse res = CloudStorageUtlilty.makeCallout('', endpoint, headers, 'GET');
if (res.getStatusCode() == 200) {
Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
Boolean exists = (Boolean) data.get('exists');
Boolean active = (Boolean) data.get('active');
response.isConnected = exists && active;
response.username = username;
if (response.isConnected) {
saveAuthConfig(true);
}
} else {
throw new AuraHandledException('Connection check: ' + res.getStatus());
}
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'isConnectionActive');
// throw new AuraHandledException(e.getMessage());
} finally {
FME_Logger.saveLog();
}
return response;
}
// private static void saveAuthConfig(Boolean isActive) {
// // Id userId = UserInfo.getUserId();
// // String userId = UserInfo.getOrganizationId();
// // System.debug('userId' + userId);
// HIC_FilesME__FilesMadeasyConfigurationSettings__c cs = HIC_FilesME__FilesMadeasyConfigurationSettings__c.getInstance('FilesMadeEasy UI Config');
// if (cs == null) {
// cs = new HIC_FilesME__FilesMadeasyConfigurationSettings__c(Name = 'FilesMadeEasy UI Config');
// }
// System.debug('cs: ' + cs);
// cs.HIC_FilesME__IsConnected__c = isActive;
// cs.HIC_FilesME__OrgId__c = UserInfo.getOrganizationId();
// upsert cs;
// }
private static void saveAuthConfig(Boolean isActive) {
// Id userId = UserInfo.getUserId();
// String userId = UserInfo.getOrganizationId();
// System.debug('userId' + userId);
try{
HIC_FilesME__FilesMadeasyConfigurationSettings__c cs = HIC_FilesME__FilesMadeasyConfigurationSettings__c.getInstance('FilesMadeEasy UI Config');
if (cs == null) {
cs = new HIC_FilesME__FilesMadeasyConfigurationSettings__c(Name = 'FilesMadeEasy UI Config');
}
System.debug('cs: ' + cs);
cs.HIC_FilesME__IsConnected__c = isActive;
cs.HIC_FilesME__OrgId__c = UserInfo.getOrganizationId();
upsert cs;
} catch (Exception e){
FME_Logger.error(e.getMessage(), '' + e.getLineNumber(), 'saveAuthConfig');
}
}
//saved to hide connect page if active
// @AuraEnabled
// public static Boolean getIsActiveFlag() {
// HIC_FilesME__FilesMadeasyConfigurationSettings__c cs = HIC_FilesME__FilesMadeasyConfigurationSettings__c.getInstance('FilesMadeEasy UI Config');
// System.debug('cs: ' + cs);
// return cs != null && cs.HIC_FilesME__IsConnected__c == true;
// }
@AuraEnabled
public static Boolean getIsActiveFlag() {
Boolean isActive = false;
try {
HIC_FilesME__FilesMadeasyConfigurationSettings__c cs = HIC_FilesME__FilesMadeasyConfigurationSettings__c.getInstance('FilesMadeEasy UI Config');
System.debug('cs: ' + cs);
isActive = (cs != null && cs.HIC_FilesME__IsConnected__c == true);
} catch (Exception e) {
FME_Logger.error(e, 'ServerApiCalloutUtility', 'getIsActiveFlag');
// isActive = false;
} finally {
FME_Logger.saveLog();
}
return isActive;
}
//to disconnect connection with server
// @AuraEnabled
// public static Boolean disconnect() {
// String orgId = UserInfo.getOrganizationId();
// System.debug('orgId: ' + orgId);
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/oauth/salesforce'
// + '?orgId=' + orgId;
// System.debug('endpoint: ' + endpoint);
// Map<String, String> headers = new Map<String, String>{
// 'Content-Type' => 'application/json'
// };
// HttpResponse res = CloudStorageUtlilty.makeCallout('', endpoint, headers, 'DELETE');
// System.debug('res: ' + res);
// if (res.getStatusCode() == 200 || res.getStatusCode() == 204) {
// return true;
// } else {
// return false;
// }
// }
@AuraEnabled
public static Boolean disconnect() {
Boolean success = false;
try {
String orgId = UserInfo.getOrganizationId();
String endpoint = SERVER_URL + '/api/v1/oauth/salesforce'
+ '?orgId=' + orgId;
Map<String, String> headers = new Map<String, String>{
'Content-Type' => 'application/json'
};
HttpResponse res = CloudStorageUtlilty.makeCallout('', endpoint, headers, 'DELETE');
success = (res.getStatusCode() == 200 || res.getStatusCode() == 204);
} catch (Exception e) {
FME_Logger.error(e, 'ServerApiCalloutUtility', 'disconnect');
// success = false;
} finally {
FME_Logger.saveLog();
}
return success;
}
@AuraEnabled
public static String getAnalytics(String uuid){
// Map<String,Object> result = new Map<String,Object>();
String result;
try {
// String uuid = '5e548ccd-b05a-426b-8e3c-392a2bc8d8f9';
// String endpoint = 'https://hopelessly-upright-platypus.ngrok-free.app/api/v1/file/analytics/'+ uuid;
String endpoint = SERVER_URL + '/api/v1/file/analytics/'+ uuid;
System.debug('endpoint: ' + endpoint);
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
req.setTimeout(60000);
HttpResponse res = http.send(req);
System.debug('result--> '+ res.getBody());
if(res.getStatusCode() != 200){
System.debug('Something went wrong ');
System.debug('Result: '+ res.getBody());
result = '';
return result;
}
// result = (Map<String,String>) JSON.deserializeUntyped(res.getBody());
result = res.getBody();
System.debug('Result + : '+ result);
return result;
} catch (Exception e) {
FME_Logger.error(e.getMessage(), 'ServerApiCalloutUtility' + e.getLineNumber(), 'getAnalytics');
// return new Map<String,Object>();
return '';
// throw new AuraHandledException(e.getMessage());
} finally {
FME_Logger.saveLog();
}
// return result;
}
}