Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

package info #507

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions uSync.BackOffice/Models/uSyncImportOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ public class uSyncImportOptions
/// should we pause the uSync export events during the import ?
/// </summary>
public bool PauseDuringImport { get; set; } = true;

/// <summary>
/// the user doing the import.
/// </summary>
public int UserId { get; set; } = -1;
}

/// <summary>
Expand Down
5 changes: 3 additions & 2 deletions uSync.BackOffice/Services/uSyncService_Single.cs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,8 @@ public IEnumerable<uSyncAction> ImportPostCleanFiles(IEnumerable<uSyncAction> ac
{
using (var pause = _mutexService.ImportPause(options.PauseDuringImport))
{
SyncHandlerOptions syncHandlerOptions = new SyncHandlerOptions(options.HandlerSet);
SyncHandlerOptions syncHandlerOptions = new SyncHandlerOptions(
options.HandlerSet, options.UserId);

var cleans = actions
.Where(x => x.Change == ChangeType.Clean && !string.IsNullOrWhiteSpace(x.FileName))
Expand Down Expand Up @@ -274,7 +275,7 @@ public IEnumerable<uSyncAction> ImportPostCleanFiles(IEnumerable<uSyncAction> ac
}

private SyncHandlerOptions HandlerOptionsFromPaged(uSyncPagedImportOptions options)
=> new SyncHandlerOptions(options.HandlerSet)
=> new SyncHandlerOptions(options.HandlerSet, options.UserId)
{
IncludeDisabled = options.IncludeDisabledHandlers
};
Expand Down
21 changes: 19 additions & 2 deletions uSync.BackOffice/SyncHandlers/Models/SyncHandlerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,12 @@
/// <summary>
/// include handlers that are by default disabled
/// </summary>
public bool IncludeDisabled { get; set; } = false;
public bool IncludeDisabled { get; set; } = false;

/// <summary>
/// the user id doing all the work.
/// </summary>
public int UserId { get; set; } = -1;

/// <summary>
/// Default constructor
Expand All @@ -44,15 +49,27 @@
this.Set = setName;
}

public SyncHandlerOptions(string setName, int userId)

Check warning on line 52 in uSync.BackOffice/SyncHandlers/Models/SyncHandlerOptions.cs

View workflow job for this annotation

GitHub Actions / build

Missing XML comment for publicly visible type or member 'SyncHandlerOptions.SyncHandlerOptions(string, int)'

Check warning on line 52 in uSync.BackOffice/SyncHandlers/Models/SyncHandlerOptions.cs

View workflow job for this annotation

GitHub Actions / build

Missing XML comment for publicly visible type or member 'SyncHandlerOptions.SyncHandlerOptions(string, int)'
:this(setName)
{
this.UserId = userId;
}

/// <summary>
/// Construct options with set and handler action set.
/// </summary>
public SyncHandlerOptions(string setName, HandlerActions action)
: this()
: this(setName)
{
this.Set = setName;
this.Action = action;
}

public SyncHandlerOptions(string setName, HandlerActions action, int userId)

Check warning on line 68 in uSync.BackOffice/SyncHandlers/Models/SyncHandlerOptions.cs

View workflow job for this annotation

GitHub Actions / build

Missing XML comment for publicly visible type or member 'SyncHandlerOptions.SyncHandlerOptions(string, HandlerActions, int)'

Check warning on line 68 in uSync.BackOffice/SyncHandlers/Models/SyncHandlerOptions.cs

View workflow job for this annotation

GitHub Actions / build

Missing XML comment for publicly visible type or member 'SyncHandlerOptions.SyncHandlerOptions(string, HandlerActions, int)'
: this(setName, action)
{
this.UserId = userId;
}
}


Expand Down
6 changes: 3 additions & 3 deletions uSync.BackOffice/SyncHandlers/SyncHandlerRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ virtual public IEnumerable<uSyncAction> ImportElement(XElement node, string file
try
{
// merge the options from the handler and any import options into our serializer options.
var serializerOptions = new SyncSerializerOptions(options.Flags, settings.Settings);
var serializerOptions = new SyncSerializerOptions(options.Flags, settings.Settings, options.UserId);
serializerOptions.MergeSettings(options.Settings);

// get the item.
Expand Down Expand Up @@ -522,7 +522,7 @@ virtual public IEnumerable<uSyncAction> ImportSecondPass(uSyncAction action, Han
if (item == null) return Enumerable.Empty<uSyncAction>();

// merge the options from the handler and any import options into our serializer options.
var serializerOptions = new SyncSerializerOptions(options?.Flags ?? SerializerFlags.None, settings.Settings);
var serializerOptions = new SyncSerializerOptions(options?.Flags ?? SerializerFlags.None, settings.Settings, options?.UserId ?? -1);
serializerOptions.MergeSettings(options?.Settings);

// do the second pass on this item
Expand Down Expand Up @@ -1078,7 +1078,7 @@ public IEnumerable<uSyncAction> ReportElement(XElement node, string filename, Ha
var actions = new List<uSyncAction>();

// get the serializer options
var serializerOptions = new SyncSerializerOptions(options.Flags, settings.Settings);
var serializerOptions = new SyncSerializerOptions(options.Flags, settings.Settings, options.UserId);
serializerOptions.MergeSettings(options.Settings);

// check if this item is current (the provided XML and exported XML match)
Expand Down
22 changes: 21 additions & 1 deletion uSync.Core/CompatibilitySuppressions.xml
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- https://learn.microsoft.com/en-us/dotnet/fundamentals/package-validation/diagnostic-ids -->
<Suppressions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!-- DI Constructor for ImagePathMapper now included GlobalSettings-->
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:uSync.Core.Mapping.ImagePathMapper.#ctor(Microsoft.Extensions.Configuration.IConfiguration,Umbraco.Cms.Core.Services.IEntityService,Microsoft.Extensions.Logging.ILogger{uSync.Core.Mapping.ImagePathMapper})</Target>
<Left>lib/net7.0/uSync.Core.dll</Left>
<Right>lib/net7.0/uSync.Core.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:uSync.Core.Serialization.Serializers.ContentSerializer.#ctor(Umbraco.Cms.Core.Services.IEntityService,Umbraco.Cms.Core.Services.ILocalizationService,Umbraco.Cms.Core.Services.IRelationService,Umbraco.Cms.Core.Strings.IShortStringHelper,Microsoft.Extensions.Logging.ILogger{uSync.Core.Serialization.Serializers.ContentSerializer},Umbraco.Cms.Core.Services.IContentService,Umbraco.Cms.Core.Services.IFileService,uSync.Core.Mapping.SyncValueMapperCollection)</Target>
<Left>lib/net7.0/uSync.Core.dll</Left>
<Right>lib/net7.0/uSync.Core.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:uSync.Core.Serialization.Serializers.ContentSerializer.PublishItem(Umbraco.Cms.Core.Models.IContent)</Target>
<Left>lib/net7.0/uSync.Core.dll</Left>
<Right>lib/net7.0/uSync.Core.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:uSync.Core.Serialization.Serializers.ContentTemplateSerializer.#ctor(Umbraco.Cms.Core.Services.IEntityService,Umbraco.Cms.Core.Services.ILocalizationService,Umbraco.Cms.Core.Services.IRelationService,Umbraco.Cms.Core.Strings.IShortStringHelper,Microsoft.Extensions.Logging.ILogger{uSync.Core.Serialization.Serializers.ContentTemplateSerializer},Umbraco.Cms.Core.Services.IContentService,Umbraco.Cms.Core.Services.IFileService,Umbraco.Cms.Core.Services.IContentTypeService,uSync.Core.Mapping.SyncValueMapperCollection)</Target>
<Left>lib/net7.0/uSync.Core.dll</Left>
<Right>lib/net7.0/uSync.Core.dll</Right>
<IsBaselineSuppression>true</IsBaselineSuppression>
</Suppression>
</Suppressions>
38 changes: 38 additions & 0 deletions uSync.Core/Extensions/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;

using Umbraco.Cms.Core.Models.Membership;

namespace uSync.Core.Extensions;
internal static class DictionaryExtensions
{
/// <summary>
/// get the username
/// </summary>
/// <param name="usernames"></param>
/// <param name="id"></param>
/// <param name="findMethod"></param>
/// <returns></returns>

public static string GetUsername(this Dictionary<int, string> usernames, int? id, Func<int, IUser> findMethod)
{
if (usernames == null || id == null) return "unknown";

usernames[id.Value] = usernames.ContainsKey(id.Value)
? usernames[id.Value]
: findMethod(id.Value)?.Email ?? "unknown";

return usernames[id.Value];
}

public static int GetEmails(this Dictionary<string, int> emails, string email, Func<string, IUser> findMethod)
{
if (emails == null || string.IsNullOrEmpty(email)) return -1;

emails[email] = emails.ContainsKey(email)
? emails[email]
: findMethod(email)?.Id ?? -1;

return emails[email];
}
}
70 changes: 59 additions & 11 deletions uSync.Core/Serialization/Serializers/ContentSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Umbraco.Cms.Core.Strings;
using Umbraco.Extensions;

using uSync.Core.Extensions;
using uSync.Core.Mapping;
using uSync.Core.Models;

Expand All @@ -23,6 +24,7 @@ public class ContentSerializer : ContentSerializerBase<IContent>, ISyncSerialize
{
protected readonly IContentService contentService;
protected readonly IFileService fileService;
protected readonly IUserService userService;

public ContentSerializer(
IEntityService entityService,
Expand All @@ -32,13 +34,15 @@ public class ContentSerializer : ContentSerializerBase<IContent>, ISyncSerialize
ILogger<ContentSerializer> logger,
IContentService contentService,
IFileService fileService,
SyncValueMapperCollection syncMappers)
SyncValueMapperCollection syncMappers,
IUserService userService)
: base(entityService, localizationService, relationService, shortStringHelper, logger, UmbracoObjectTypes.Document, syncMappers)
{
this.contentService = contentService;
this.fileService = fileService;

this.relationAlias = Constants.Conventions.RelationTypes.RelateParentDocumentOnDeleteAlias;
this.userService = userService;
}

#region Serialization
Expand All @@ -65,6 +69,11 @@ protected override XElement SerializeInfo(IContent item, SyncSerializerOptions o
info.Add(SerializeSchedule(item, options));
info.Add(SerializeTemplate(item, options));

if (options.GetSetting<bool>("IncludeUserInfo", false))
{
info.Add(SerializerWriterInfo(item, options));
}

return info;
}

Expand Down Expand Up @@ -133,6 +142,19 @@ protected virtual XElement SerializeSchedule(IContent item, SyncSerializerOption
return node;
}


private XElement SerializerWriterInfo(IContent item, SyncSerializerOptions options)
{
var userInfoNode = new XElement("UserInfo");
var usernames = new Dictionary<int, string>();

userInfoNode.Add(new XElement("Writer", usernames.GetUsername(item.WriterId, userService.GetUserById)));
userInfoNode.Add(new XElement("Creator", usernames.GetUsername(item.CreatorId, userService.GetUserById)));
userInfoNode.Add(new XElement("Publisher", usernames.GetUsername(item.PublisherId, userService.GetUserById)));

return userInfoNode;
}

#endregion

#region De-serialization
Expand Down Expand Up @@ -178,6 +200,15 @@ protected override SyncAttempt<IContent> DeserializeCore(XElement node, SyncSeri
new Exception("Import failed because of warnings, and fail on warnings is true"));
}

// read user ids from the xml,
var userId = DeserializeWriterInfo(item, node, options);

// if the userId hasn't been set in the options , we use the one from the xml.
if (options.UserId == -1)
{
options.UserId = userId;
}

// published status
// this does the last save and publish
var saveAttempt = DoSaveOrPublish(item, node, options);
Expand Down Expand Up @@ -240,6 +271,20 @@ protected virtual uSyncChange DeserializeTemplate(IContent item, XElement node)
return null;
}

public int DeserializeWriterInfo(IContent item, XElement node, SyncSerializerOptions options)
{
var writerNode = node.Element("Info")?.Element("UserInfo");
if (writerNode == null) return -1;

var emails = new Dictionary<string, int>();

item.CreatorId = emails.GetEmails(writerNode.Element("Creator").ValueOrDefault(string.Empty), userService.GetByEmail);
item.WriterId = emails.GetEmails(writerNode.Element("Writer").ValueOrDefault(string.Empty), userService.GetByEmail);
item.PublisherId = emails.GetEmails(writerNode.Element("Publisher").ValueOrDefault(string.Empty), userService.GetByEmail);

return item.WriterId;
}

/// <summary>
/// Second pass.
/// </summary>
Expand Down Expand Up @@ -420,7 +465,7 @@ protected virtual Attempt<string> DoSaveOrPublish(IContent item, XElement node,

if (cultureStatuses.Count > 0)
{
return PublishItem(item, cultureStatuses, unpublishMissingCultures);
return PublishItem(item, cultureStatuses, unpublishMissingCultures, options.UserId);
}
}
else
Expand All @@ -433,7 +478,7 @@ protected virtual Attempt<string> DoSaveOrPublish(IContent item, XElement node,

if (state == uSyncContentState.Published)
{
return PublishItem(item);
return PublishItem(item, options.UserId);
}
else if (state == uSyncContentState.Unpublished && item.Published == true)
{
Expand All @@ -442,7 +487,7 @@ protected virtual Attempt<string> DoSaveOrPublish(IContent item, XElement node,
}
}

this.SaveItem(item);
this.SaveItem(item, options.UserId);
return Attempt.Succeed("Saved");
}

Expand All @@ -463,11 +508,11 @@ private IList<ContentSchedule> GetSchedules(XElement schedulesNode)
return schedules;
}

public Attempt<string> PublishItem(IContent item)
public Attempt<string> PublishItem(IContent item, int userId)
{
try
{
var result = contentService.SaveAndPublish(item);
var result = contentService.SaveAndPublish(item, userId: userId);
if (!result.Success)
{
var messages = result.EventMessages.FormatMessages(",");
Expand Down Expand Up @@ -496,9 +541,9 @@ public Attempt<string> PublishItem(IContent item)
/// <param name="cultures"></param>
/// <param name="unpublishMissing"></param>
/// <returns></returns>
private Attempt<string> PublishItem(IContent item, IDictionary<string, uSyncContentState> cultures, bool unpublishMissing)
private Attempt<string> PublishItem(IContent item, IDictionary<string, uSyncContentState> cultures, bool unpublishMissing, int userId)
{
if (cultures == null) return PublishItem(item);
if (cultures == null) return PublishItem(item, userId);

try
{
Expand All @@ -511,7 +556,7 @@ private Attempt<string> PublishItem(IContent item, IDictionary<string, uSyncCont

if (publishedCultures.Length > 0)
{
var result = contentService.SaveAndPublish(item, publishedCultures);
var result = contentService.SaveAndPublish(item, publishedCultures, userId);

// if this fails, we return the result
if (!result.Success)
Expand Down Expand Up @@ -542,7 +587,7 @@ private Attempt<string> PublishItem(IContent item, IDictionary<string, uSyncCont
{
// unpublish if the culture is currently published.
if (item.PublishedCultures.InvariantContains(culture))
contentService.Unpublish(item, culture);
contentService.Unpublish(item, culture, userId);
}
}

Expand Down Expand Up @@ -631,10 +676,13 @@ public override void Save(IEnumerable<IContent> items)
=> contentService.Save(items);

public override void SaveItem(IContent item)
=> SaveItem(item, -1);

public void SaveItem(IContent item, int userId)
{
try
{
contentService.Save(item);
contentService.Save(item, userId);
}
catch (ArgumentNullException ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ public class ContentTemplateSerializer : ContentSerializer, ISyncSerializer<ICon
IContentService contentService,
IFileService fileService,
IContentTypeService contentTypeService,
SyncValueMapperCollection syncMappers)
: base(entityService, localizationService, relationService, shortStringHelper, logger, contentService, fileService, syncMappers)
SyncValueMapperCollection syncMappers,
IUserService userService)
: base(entityService, localizationService, relationService, shortStringHelper, logger, contentService, fileService, syncMappers, userService)
{
_contentTypeService = contentTypeService;
this.umbracoObjectType = UmbracoObjectTypes.DocumentBlueprint;
Expand Down Expand Up @@ -143,7 +144,7 @@ protected override Attempt<IContent> CreateItem(string alias, ITreeEntity parent

protected override Attempt<string> DoSaveOrPublish(IContent item, XElement node, SyncSerializerOptions options)
{
contentService.SaveBlueprint(item);
contentService.SaveBlueprint(item, options.UserId);
return Attempt.Succeed<string>("blueprint saved");
}

Expand Down