Skip to content

Commit

Permalink
Merge pull request #345 from SaintAngeLs/organizations_service
Browse files Browse the repository at this point in the history
#342 #343 mediafile service, organization serivce events handlers update
  • Loading branch information
SaintAngeLs authored Aug 3, 2024
2 parents b9098b6 + a95f1ac commit 44d37ee
Show file tree
Hide file tree
Showing 47 changed files with 1,158 additions and 116 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Convey.CQRS.Commands;
Expand Down Expand Up @@ -27,30 +28,45 @@ public DeleteMediaFileHandler(IFileSourceInfoRepository fileSourceInfoRepository

public async Task HandleAsync(DeleteMediaFile command, CancellationToken cancellationToken)
{
// Serialize the command to JSON and write to the console
var commandJson = JsonSerializer.Serialize(command, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine("Received DeleteMediaFile command: " + commandJson);

// Decode the URL before using it
var decodedUrl = Uri.UnescapeDataString(command.MediaFileUrl);

Console.WriteLine($"DeleteMediaFileHandler: {decodedUrl}");

// Retrieve the file source information
var fileSourceInfo = await _fileSourceInfoRepository.GetAsync(decodedUrl);
if (fileSourceInfo is null)
{
throw new MediaFileNotFoundException(decodedUrl);
}

// Log the fileSourceInfo details to ensure it contains the correct data
var fileSourceInfoJson = JsonSerializer.Serialize(fileSourceInfo, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine("Retrieved FileSourceInfo: " + fileSourceInfoJson);

// Check for unauthorized access
var identity = _appContext.Identity;
if (identity.IsAuthenticated && identity.Id != fileSourceInfo.UploaderId)
if (identity.IsAuthenticated && identity.Id != fileSourceInfo.UploaderId &&
!fileSourceInfo.OrganizationId.HasValue)
{
throw new UnauthorizedMediaFileAccessException(fileSourceInfo.Id, identity.Id, fileSourceInfo.UploaderId);
}

// Delete the files from S3
await _s3Service.DeleteFileAsync(fileSourceInfo.OriginalFileUrl);
await _s3Service.DeleteFileAsync(fileSourceInfo.FileUrl);
await _fileSourceInfoRepository.DeleteAsync(decodedUrl);

// Publish the MediaFileDeleted event
await _messageBroker.PublishAsync(new MediaFileDeleted(
decodedUrl,
fileSourceInfo.SourceId,
fileSourceInfo.SourceType.ToString(),
fileSourceInfo.UploaderId));
fileSourceInfo.UploaderId,
fileSourceInfo.OrganizationId));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@ public class UploadMediaFile : ICommand
public Guid MediaFileId { get; set; }
public Guid SourceId { get; set; }
public string SourceType { get; set; }
public Guid? OrganizationId { get; set; }
public Guid UploaderId { get; set; }
public string FileName { get; set; }
public string FileContentType { get; set; }
public byte[] FileData { get; set; }
public byte[] FileData { get; set; }

public UploadMediaFile(Guid mediaFileId, Guid sourceId, string sourceType, Guid uploaderId,
string fileName, string fileContentType, byte[] fileData)
public UploadMediaFile(Guid mediaFileId, Guid sourceId, string sourceType, Guid? organizationId,
Guid uploaderId, string fileName, string fileContentType, byte[] fileData)
{
MediaFileId = mediaFileId == Guid.Empty ? Guid.NewGuid() : mediaFileId;
SourceId = sourceId;
SourceType = sourceType;
OrganizationId = organizationId;
UploaderId = uploaderId;
FileName = fileName;
FileContentType = fileContentType;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Convey.CQRS.Events;
using System;

namespace MiniSpace.Services.MediaFiles.Application.Events
{
Expand All @@ -8,13 +9,16 @@ public class MediaFileDeleted : IEvent
public Guid SourceId { get; }
public string Source { get; }
public Guid UploaderId { get; }
public Guid? OrganizationId { get; }

public MediaFileDeleted(string mediaFileUrl, Guid sourceId, string source, Guid uploaderId)
public MediaFileDeleted(string mediaFileUrl, Guid sourceId, string source,
Guid uploaderId, Guid? organizationId)
{
MediaFileUrl = mediaFileUrl;
SourceId = sourceId;
Source = source;
UploaderId = uploaderId;
OrganizationId = organizationId;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<PackageReference Include="Convey.CQRS.Queries" Version="1.1.448" />
<PackageReference Include="Convey.MessageBrokers" Version="1.1.448" />
<PackageReference Include="MongoDB.Bson" Version="2.25.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.4" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ public class FileSourceInfo : AggregateRoot
public string OriginalFileContentType { get; set; }
public string FileUrl { get; set; }
public string FileName { get; set; }

public Guid? OrganizationId { get; set; }

public FileSourceInfo(Guid id, Guid sourceId, ContextType sourceType, Guid uploaderId, State state,
DateTime createdAt, string originalFileUrl, string originalFileContentType, string fileUrl, string fileName)
DateTime createdAt, string originalFileUrl, string originalFileContentType, string fileUrl, string fileName,
Guid? organizationId = null)
{
Id = id;
SourceId = sourceId;
Expand All @@ -27,13 +29,15 @@ public FileSourceInfo(Guid id, Guid sourceId, ContextType sourceType, Guid uploa
OriginalFileContentType = originalFileContentType;
FileUrl = fileUrl;
FileName = fileName;
OrganizationId = organizationId;
}



public void Associate()
{
State = State.Associated;
}

public void Unassociate()
{
State = State.Unassociated;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ public interface IFileSourceInfoRepository
Task<IEnumerable<FileSourceInfo>> FindByUploaderIdAndSourceTypeAsync(Guid uploaderId, ContextType sourceType);
Task<IEnumerable<FileSourceInfo>> GetAllAsync(string url);
Task DeleteAllAsync(string url);
Task<IEnumerable<FileSourceInfo>> FindByOrganizationIdAsync(Guid organizationId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public static FileSourceInfo AsEntity(this FileSourceInfoDocument document)
document.OriginalFileUrl,
document.OriginalFileContentType,
document.FileUrl,
document.FileName
document.FileName,
document.OrganizationId
);

public static FileSourceInfoDocument AsDocument(this FileSourceInfo entity)
Expand All @@ -32,7 +33,9 @@ public static FileSourceInfoDocument AsDocument(this FileSourceInfo entity)
OriginalFileUrl = entity.OriginalFileUrl,
OriginalFileContentType = entity.OriginalFileContentType,
FileUrl = entity.FileUrl,
FileName = entity.FileName
FileName = entity.FileName,
OrganizationId = entity.OrganizationId
};

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ public class FileSourceInfoDocument : IIdentifiable<Guid>
public string OriginalFileContentType { get; set; }
public string FileUrl { get; set; }
public string FileName { get; set; }
public Guid? OrganizationId { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,5 +77,12 @@ public async Task<IEnumerable<FileSourceInfo>> FindByUploaderIdAndSourceTypeAsyn
var fileSourceInfos = await _repository.FindAsync(s => s.UploaderId == uploaderId && s.SourceType == sourceType);
return fileSourceInfos?.Select(s => s.AsEntity());
}

// Optional: Implement method to find files by OrganizationId
public async Task<IEnumerable<FileSourceInfo>> FindByOrganizationIdAsync(Guid organizationId)
{
var fileSourceInfos = await _repository.FindAsync(s => s.OrganizationId == organizationId);
return fileSourceInfos?.Select(s => s.AsEntity());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace MiniSpace.Services.MediaFiles.Infrastructure.Services
Expand Down Expand Up @@ -41,6 +42,21 @@ public MediaFilesService(IFileSourceInfoRepository fileSourceInfoRepository, IFi

public async Task<FileUploadResponseDto> UploadAsync(UploadMediaFile command)
{
var commandWithoutFileData = new UploadMediaFile(
command.MediaFileId,
command.SourceId,
command.SourceType,
command.OrganizationId,
command.UploaderId,
command.FileName,
command.FileContentType,
null // Exclude the FileData
);

// Serialize the modified command to JSON and write to the console
var commandJson = JsonSerializer.Serialize(commandWithoutFileData, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine("Received UploadMediaFile command (excluding FileData): " + commandJson);

var identity = _appContext.Identity;
if (identity.IsAuthenticated && identity.Id != command.UploaderId)
{
Expand All @@ -52,6 +68,7 @@ public async Task<FileUploadResponseDto> UploadAsync(UploadMediaFile command)
throw new InvalidContextTypeException(command.SourceType);
}

// Handle previous files if necessary
if (sourceType == ContextType.StudentProfileImage ||
sourceType == ContextType.StudentBannerImage ||
sourceType == ContextType.OrganizationProfileImage ||
Expand Down Expand Up @@ -102,28 +119,25 @@ public async Task<FileUploadResponseDto> UploadAsync(UploadMediaFile command)
var uploadDate = _dateTimeProvider.Now;
var fileSourceInfo = new FileSourceInfo(command.MediaFileId, command.SourceId, sourceType,
command.UploaderId, State.Associated, uploadDate, originalUrl,
command.FileContentType, processedUrl, originalFileName);
command.FileContentType, processedUrl, originalFileName, command.OrganizationId);

await _fileSourceInfoRepository.AddAsync(fileSourceInfo);
await _messageBroker.PublishAsync(new MediaFileUploaded(command.MediaFileId, originalFileName));

// Handle specific events based on the source type
if (sourceType == ContextType.StudentProfileImage ||
sourceType == ContextType.StudentBannerImage ||
sourceType == ContextType.StudentGalleryImage)
// Handle specific events based on the source type and organization
if (command.OrganizationId.HasValue)
{
var imageType = sourceType.ToString();
var studentImageUploadedEvent = new StudentImageUploaded(command.UploaderId, processedUrl, imageType, uploadDate);
await _messageBroker.PublishAsync(studentImageUploadedEvent);
var organizationImageUploadedEvent = new OrganizationImageUploaded(command.OrganizationId.Value, processedUrl, imageType, uploadDate);
await _messageBroker.PublishAsync(organizationImageUploadedEvent);
}

if (sourceType == ContextType.OrganizationProfileImage ||
sourceType == ContextType.OrganizationBannerImage ||
sourceType == ContextType.OrganizationGalleryImage)
else if (sourceType == ContextType.StudentProfileImage ||
sourceType == ContextType.StudentBannerImage ||
sourceType == ContextType.StudentGalleryImage)
{
var imageType = sourceType.ToString();
var organizationImageUploadedEvent = new OrganizationImageUploaded(command.UploaderId, processedUrl, imageType, uploadDate);
await _messageBroker.PublishAsync(organizationImageUploadedEvent);
var studentImageUploadedEvent = new StudentImageUploaded(command.UploaderId, processedUrl, imageType, uploadDate);
await _messageBroker.PublishAsync(studentImageUploadedEvent);
}

return new FileUploadResponseDto(fileSourceInfo.Id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public async Task HandleAsync(AssignRoleToMember command, CancellationToken canc
throw new MemberNotFoundException(command.MemberId);
}

// Fetch the role by its name
var existingRole = await _organizationRolesRepository.GetRoleByNameAsync(command.Role);
// Fetch the role by its name using the correct method signature
var existingRole = await _organizationRolesRepository.GetRoleByNameAsync(command.OrganizationId, command.Role);
if (existingRole == null)
{
throw new RoleNotFoundException(command.Role);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using MiniSpace.Services.Organizations.Core.Entities;
using MiniSpace.Services.Organizations.Core.Repositories;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -13,12 +14,24 @@ namespace MiniSpace.Services.Organizations.Application.Commands.Handlers
public class CreateOrganizationHandler : ICommandHandler<CreateOrganization>
{
private readonly IOrganizationRepository _organizationRepository;
private readonly IOrganizationMembersRepository _organizationMembersRepository;
private readonly IOrganizationGalleryRepository _organizationGalleryRepository;
private readonly IOrganizationRolesRepository _organizationRolesRepository;
private readonly IAppContext _appContext;
private readonly IMessageBroker _messageBroker;

public CreateOrganizationHandler(IOrganizationRepository organizationRepository, IAppContext appContext, IMessageBroker messageBroker)
public CreateOrganizationHandler(
IOrganizationRepository organizationRepository,
IOrganizationMembersRepository organizationMembersRepository,
IOrganizationGalleryRepository organizationGalleryRepository,
IOrganizationRolesRepository organizationRolesRepository,
IAppContext appContext,
IMessageBroker messageBroker)
{
_organizationRepository = organizationRepository;
_organizationMembersRepository = organizationMembersRepository;
_organizationGalleryRepository = organizationGalleryRepository;
_organizationRolesRepository = organizationRolesRepository;
_appContext = appContext;
_messageBroker = messageBroker;
}
Expand Down Expand Up @@ -48,14 +61,6 @@ public async Task HandleAsync(CreateOrganization command, CancellationToken canc
);

await _organizationRepository.AddAsync(organization);
await _messageBroker.PublishAsync(new OrganizationCreated(
organization.Id,
organization.Name,
organization.Description,
organization.Id, // Root ID is the organization's own ID
null, // No parent ID
command.OwnerId,
DateTime.UtcNow));
}
else
{
Expand Down Expand Up @@ -85,15 +90,35 @@ await _messageBroker.PublishAsync(new OrganizationCreated(

parent.AddSubOrganization(organization);
await _organizationRepository.UpdateAsync(root);
await _messageBroker.PublishAsync(new OrganizationCreated(
organization.Id,
organization.Name,
organization.Description,
command.RootId.Value,
command.ParentId.Value,
command.OwnerId,
DateTime.UtcNow));
}

var defaultRoles = organization.Roles.ToList();
foreach (var role in defaultRoles)
{
await _organizationRolesRepository.AddRoleAsync(organization.Id, role);
}

// Initialize an empty gallery for the organization
await _organizationGalleryRepository.AddImageAsync(organization.Id, new GalleryImage(Guid.NewGuid(), "Default Image URL", DateTime.UtcNow));

// Add the creator as a member with the "Creator" role
var creatorRole = defaultRoles.SingleOrDefault(r => r.Name == "Creator");
if (creatorRole == null)
{
throw new RoleNotFoundException("Creator");
}

var creatorMember = new User(identity.Id, creatorRole);
await _organizationMembersRepository.AddMemberAsync(organization.Id, creatorMember);

await _messageBroker.PublishAsync(new OrganizationCreated(
organization.Id,
organization.Name,
organization.Description,
command.RootId ?? organization.Id, // Root ID is the organization's own ID or the provided root ID
command.ParentId,
command.OwnerId,
DateTime.UtcNow));
}
}
}
Loading

0 comments on commit 44d37ee

Please sign in to comment.