Skip to content

Instantly share code, notes, and snippets.

@KevinJump
Created September 25, 2019 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinJump/06010031797b93a4b22d696b8fb4271c to your computer and use it in GitHub Desktop.
Save KevinJump/06010031797b93a4b22d696b8fb4271c to your computer and use it in GitHub Desktop.
uSync Delete Protect - Save Media before it goes from the recycle bin.
using Jumoo.uSync.Core;
using Jumoo.uSync.Core.Interfaces;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
namespace DeleteProtect
{
public class DeleteProtect : ApplicationEventHandler
{
private string path;
private string filePath;
private ISyncSerializerWithParent<IMedia> mediaSerializer;
private string mediaFolder;
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
MediaService.Deleting += MediaService_Deleting;
mediaFolder = "/media/";
var root = IOHelper.MapPath("~/uSync/Deletions/");
path = Path.Combine(root, "Media");
filePath = Path.Combine(root, "Files");
Directory.CreateDirectory(path);
Directory.CreateDirectory(filePath);
mediaSerializer = uSyncCoreContext.Instance.MediaSerializer;
}
private void MediaService_Deleting(IMediaService sender, Umbraco.Core.Events.DeleteEventArgs<Umbraco.Core.Models.IMedia> e)
{
foreach (var item in e.DeletedEntities)
{
if (item.Trashed && mediaSerializer != null)
{
var attempt = mediaSerializer.Serialize(item);
if (attempt.Success)
{
BackupMediaFile(item, filePath);
attempt.Item.Save(Path.Combine(path, item.Key + ".config"));
}
}
}
}
private void BackupMediaFile(IMedia item, string folder)
{
foreach (var fileProperty in item.Properties.Where(p => p.Alias == "umbracoFile"))
{
if (fileProperty == null || fileProperty.Value == null)
continue;
var umbracoFile = fileProperty.Value.ToString();
var filePath = umbracoFile;
if (umbracoFile.DetectIsJson())
{
filePath = JsonConvert.DeserializeObject<dynamic>(umbracoFile).src;
}
string uSyncFile = Path.Combine(folder, filePath.Substring(mediaFolder.Length));
string sourceFile = IOHelper.MapPath(string.Format("~{0}", filePath));
if (System.IO.File.Exists(sourceFile))
{
Directory.CreateDirectory(Path.GetDirectoryName(uSyncFile));
System.IO.File.Copy(sourceFile, uSyncFile, true);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment