· 6 years ago · Jul 29, 2019, 09:12 AM
1public class FileDeleteHandler {
2 public static void fileDeleteMethod(Set<Id> fileIds) {
3 List<CustomSettings__c> settings = [SELECT BucketName__c, ClientKey__c, Region__c, SecretKey__c FROM CustomSettings__c LIMIT 1];
4
5 String bucketName = '';
6 String region = '';
7 String clientKey = '';
8 String secretKey = '';
9
10 if(!settings.isEmpty()){
11 bucketName = settings[0].BucketName__c;
12 region = settings[0].Region__c;
13 clientKey = settings[0].ClientKey__c;
14 secretKey = settings[0].SecretKey__c;
15 if(String.isBlank(bucketName)||String.isBlank(region)||
16 String.isBlank(clientKey)||String.isBlank(secretKey)){
17 return;
18 }
19 }
20
21 List<Custom_Object__c> coList = [SELECT Id, Name, Path__c, File_ID__c, File_Saved__c FROM Custom_Object__c WHERE File_ID__c =: fileIds];
22
23 if (!coList.isEmpty()) {
24 if (coList[0].File_Saved__c== true) {
25 List<ContentVersion> cvs = [SELECT Title, ContentDocumentId, FileExtension, FileType, VersionData FROM ContentVersion WHERE ContentDocumentId IN :fileIds]; //This is EMPTY!
26
27 String path = coList[0].Path__c;
28
29 String formattedDateString = Datetime.now().format('EEE, dd MMM yyyy HH:mm:ss z');
30 Blob data = cvs[0].VersionData;
31
32 makeCallout(cvs[0].FileExtension, bucketName, path, formattedDateString, clientKey, secretKey, data);
33
34 } else if (coList[0].File_Saved__c== false) {
35 delete coList;
36 }
37 }
38 }
39
40 @future(callout=true)
41 private static void makeCallout(String extension, String bucketName, String path, String formattedDateString, String clientKey, String secretKey, Blob data) {
42 HttpRequest req = new HttpRequest();
43 Http http = new Http();
44
45 req.setHeader('Content-Type', extension);
46 req.setMethod('DELETE');
47 req.setHeader('Host','s3.amazonaws.com');
48 req.setEndpoint('https://s3.amazonaws.com'+'/'+bucketName+'/'+path);
49 req.setHeader('Date',formattedDateString);
50 req.setHeader('Authorization', createAuthHeader('DELETE', extension, path, formattedDateString, bucketName, clientKey, secretKey));
51 req.setBodyAsBlob(data);
52 req.setHeader('Content-Length', String.valueOf((EncodingUtil.base64Encode(data)).length()));
53
54 try{
55 HTTPResponse res = http.send(req);
56 } catch(System.CalloutException e) {
57 }
58 }
59
60 public static string createAuthHeader(String method,String contentType,String filename,String formattedDateString,String bucket,String client,String secret){
61 string auth;
62 String stringToSign = method+'\n\n'+contentType+'\n'+formattedDateString+'\n/'+bucket+'/'+filename;
63 Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof(secret));
64 String sig = EncodingUtil.base64Encode(mac);
65 auth = 'AWS' + ' ' + client + ':' + sig;
66 return auth;
67 }
68}