How to clean previous version of documents from Document and Media

If you are using liferay sync you might have run in to issue where you end up having 1000 version of the same document and for 1 MB size document your disk space utilization 1 GB.  

Reason is for every save of document opened from folder mapped using liferay sync it will try to create a version if you are connected to the network and liferay sync is active. 

You can use this Groovy script to clean up  all previous version of the document to clean up the disk space.  Run this script from Control Panel > Server Administration > Script > Select Groovy .

Note: run it carefully this script will delete all the verison of the document for a given folder and it's children in given group/site.

 

import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import java.util.List;
 
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.repository.model.FileVersion;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLFileVersionLocalServiceUtil;
import com.liferay.portlet.documentlibrary.model.DLFileVersion;
 
// Param1: Group ID
// Param2: Folder ID
listFiles(16018, 9077187);
 
def listFiles(groupId, folderId) {
    allfiles = DLAppServiceUtil.getFileEntries(groupId,folderId)
    for (FileEntry file:allfiles) {
         System.out.println("File Title: " + file.getTitle());
         System.out.println("File Version: " + file.getVersion());
        List results = file.getFileVersions(-1);
         latestversion = file.getVersion();
         for(FileVersion fv : results){
             if(fv.getVersion() != latestversion){
                  System.out.println("Deleting >>" + fv.getVersion()  );
                  DLAppServiceUtil.deleteFileVersion(file.getFileEntryId(), fv.getVersion());
             }
         }
     }
 
     allfolders = DLAppServiceUtil.getFolders(groupId,folderId);
     for (Folder folder:allfolders) {
           System.out.println("Folder Name: " + folder.getName());
           listFiles(groupId,folder.getFolderId());
     }
}

Write a blog post too!

Write a deep dive into how you use Liferay projects in your technology stack. Or let people know useful tips and tricks for a particular functionality. The Liferay community needs you!

Login or Create an account