Skip to content

Instantly share code, notes, and snippets.

@lukethacoder
Created August 11, 2020 12:39
Show Gist options
  • Save lukethacoder/818d4dba3f7fb00ea861a76fe85fc1a3 to your computer and use it in GitHub Desktop.
Save lukethacoder/818d4dba3f7fb00ea861a76fe85fc1a3 to your computer and use it in GitHub Desktop.
Check and/or Create a ContentDistribution with a ContentDownloadURL (allows for public links of 'Files' in Salesforce)
String linkedEntityId = 'a05B000000ACLmYIAX';
List<ContentDocumentLink> cdl = [
SELECT
ContentDocument.Id, ContentDocument.Title, ContentDocument.FileType, ContentDocumentId
FROM ContentDocumentLink
WHERE LinkedEntityId =: linkedEntityId
];
ContentDocumentLink cdl1 = cdl[0];
Id contentDocId = cdl1.ContentDocumentId;
ContentDistribution contentDist = [
SELECT
Id, ContentDownloadUrl
FROM ContentDistribution
WHERE ContentDocumentId =: contentDocId
];
System.debug('contentDist.Id ' + contentDist.Id);
System.debug('contentDist.ContentDownloadUrl ' + contentDist.ContentDownloadUrl);
ContentVersion cv = [SELECT Id, Title FROM ContentVersion WHERE ContentDocumentId =: contentDocId];
List<ContentDistribution> contentDistList = [
SELECT
Id, ContentDownloadUrl, ContentVersionId
FROM ContentDistribution
WHERE ContentDocumentId =: contentDocId
];
System.debug('Found ' + contentDistList.size() + ' ContentDistribution objects.');
if (contentDistList.size() == 0) {
System.debug('No ContentDistribution found for ContentDoc with Id ' + contentDocId);
// Create a new ContentDistribution
ContentDistribution cd = new ContentDistribution();
cd.Name = cv.Title;
cd.ContentVersionId = cv.Id;
cd.PreferencesAllowViewInBrowser = true;
cd.PreferencesLinkLatestVersion = true;
cd.PreferencesNotifyOnVisit = false;
cd.PreferencesPasswordRequired = false;
cd.PreferencesAllowOriginalDownload = true;
insert cd;
System.debug('cd ' + cd.Id);
// Have to re-query to get the
ContentDistribution cdAfter = [ SELECT ContentDownloadUrl FROM ContentDistribution WHERE Id =: cd.Id];
System.debug('cdAfter ' + cdAfter.ContentDownloadUrl);
} else {
System.debug('We already have a public link');
System.debug('Existing URL: ' + contentDistList[0].ContentDownloadUrl);
for (ContentDistribution cDist : contentDistList) {
System.debug('cDist ' + cDist);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment