initial commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Features.Profile.Avatar.Cqrs;
|
||||
using Indotalent.Infrastructure.File;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Indotalent.Features.Profile.Avatar;
|
||||
|
||||
public static class AvatarEndpoint
|
||||
{
|
||||
public static void MapAvatarEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/profile-avatar").WithTags("Profile Avatar")
|
||||
.RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
|
||||
.RequireAuthenticatedUser());
|
||||
|
||||
group.MapGet("/info/{userId}", async (string userId, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetAvatarInfoQuery(userId));
|
||||
return result.ToApiResponse("Avatar info retrieved successfully");
|
||||
})
|
||||
.WithName("GetMyAvatarInfo");
|
||||
|
||||
group.MapPost("/change", async (ChangeAvatarRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new ChangeAvatarCommand(request));
|
||||
return result.IsSuccess
|
||||
? result.ToApiResponse(result.Message)
|
||||
: result.ToApiResponse(result.Message, StatusCodes.Status400BadRequest);
|
||||
})
|
||||
.WithName("ProfileChangeAvatar");
|
||||
|
||||
group.MapGet("/avatar-image/{fileName}", async (string fileName, IOptions<FileStorageSettingsModel> options, IWebHostEnvironment env) =>
|
||||
{
|
||||
var avatarSettings = options.Value.Avatar;
|
||||
var folderPath = Path.Combine(env.WebRootPath, avatarSettings.StoragePath);
|
||||
var filePath = Path.Combine(folderPath, fileName);
|
||||
|
||||
if (!System.IO.File.Exists(filePath)) return Results.NotFound();
|
||||
|
||||
var bytes = await System.IO.File.ReadAllBytesAsync(filePath);
|
||||
var extension = Path.GetExtension(fileName).ToLower();
|
||||
var contentType = extension switch
|
||||
{
|
||||
".png" => "image/png",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
_ => "application/octet-stream"
|
||||
};
|
||||
return Results.File(bytes, contentType);
|
||||
})
|
||||
.WithName("ProfileGetAvatarImage");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Common;
|
||||
using Indotalent.Features.Profile.Avatar.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
|
||||
namespace Indotalent.Features.Profile.Avatar;
|
||||
|
||||
public class AvatarService : BaseService
|
||||
{
|
||||
private readonly RestClient _client;
|
||||
|
||||
public AvatarService(IHttpClientFactory clientFactory, NavigationManager nav, ISnackbar snackbar, ICurrentUserService currentUserService, TokenProvider tokenProvider)
|
||||
: base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
|
||||
{
|
||||
_client = new RestClient(nav.BaseUri);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<GetAvatarInfoResponse>?> GetAvatarInfoAsync(string userId)
|
||||
{
|
||||
var request = new RestRequest($"api/profile-avatar/info/{userId}", Method.Get);
|
||||
return await ExecuteWithResponseAsync<GetAvatarInfoResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<ChangeAvatarResponse>?> ChangeAvatarAsync(ChangeAvatarRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/profile-avatar/change", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<ChangeAvatarResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<byte[]?> GetAvatarBlobAsync(string fileName)
|
||||
{
|
||||
var request = new RestRequest($"api/profile-avatar/avatar-image/{fileName}", Method.Get);
|
||||
|
||||
if (!string.IsNullOrEmpty(TokenProvider.Token))
|
||||
{
|
||||
request.AddHeader("Authorization", $"Bearer {TokenProvider.Token}");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(CurrentUserService.UserId))
|
||||
{
|
||||
request.AddHeader("X-UserId", CurrentUserService.UserId);
|
||||
}
|
||||
|
||||
var response = await _client.ExecuteAsync(request);
|
||||
|
||||
return response.IsSuccessful ? response.RawBytes : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
@page "/profile/avatar"
|
||||
@using System.ComponentModel.DataAnnotations
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using MudBlazor
|
||||
@using System.IO
|
||||
@using Indotalent.Features.Profile.Avatar
|
||||
@using Indotalent.Features.Profile.Avatar.Cqrs
|
||||
@using Indotalent.ConfigBackEnd.Interfaces
|
||||
@inject ISnackbar Snackbar
|
||||
@inject AvatarService AvatarService
|
||||
@inject ICurrentUserService CurrentUserService
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Profile Picture</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Update your avatar and how you appear to other members.</MudText>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">Profile</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #1a1a1a;">Avatar</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; background-color: #ffffff;">
|
||||
<MudStack Spacing="8">
|
||||
<MudGrid>
|
||||
<MudItem xs="12" md="4">
|
||||
<MudText Typo="Typo.h6" Class="fw-bold">Your Avatar</MudText>
|
||||
<MudText Typo="Typo.body2">Recommended size: 200x200px. Supported formats: JPG, JPEG, PNG. (max 2MB).</MudText>
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" md="8">
|
||||
<div style="border: 2px dashed #e2e8f0; border-radius: 8px; background-color: #f8fafc;" class="pa-10">
|
||||
<MudStack Spacing="6" AlignItems="AlignItems.Center">
|
||||
|
||||
@if (_isLoading)
|
||||
{
|
||||
<MudProgressCircular Color="Color.Primary" Indeterminate="true" Style="width: 150px; height: 150px;" />
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(_previewUrl))
|
||||
{
|
||||
<div style="width:150px; height:150px; border-radius: 50%; overflow: hidden; border: 4px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
|
||||
<img src="@_previewUrl" style="width: 100%; height: 100%; object-fit: cover;" />
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudAvatar Color="Color.Primary" Variant="Variant.Filled" Style="width:150px; height:150px; font-size: 3rem; font-weight: 800;">
|
||||
@(CurrentUserService.FullName?.Substring(0, 1).ToUpper() ?? "U")
|
||||
</MudAvatar>
|
||||
}
|
||||
|
||||
<div class="text-center">
|
||||
<MudText Typo="Typo.subtitle1" Class="fw-bold">Avatar Preview</MudText>
|
||||
<MudText Typo="Typo.body2" Class="text-muted">This is how your photo will look.</MudText>
|
||||
</div>
|
||||
|
||||
<MudFileUpload T="IBrowserFile" FilesChanged="HandleFileSelected" Accept=".jpg, .jpeg, .png" Class="w-100">
|
||||
<MudButton HtmlTag="label"
|
||||
Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
StartIcon="@Icons.Material.Filled.CloudUpload"
|
||||
Style="text-transform: none; height: 50px; font-weight: 700;">
|
||||
@(_selectedFile == null ? "Browse File" : _selectedFile.Name)
|
||||
</MudButton>
|
||||
</MudFileUpload>
|
||||
</MudStack>
|
||||
</div>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end align-center gap-4 mt-4">
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
OnClick="SubmitAvatar"
|
||||
Disabled="@(_selectedFile == null || _processing)"
|
||||
Class="px-10"
|
||||
Style="height: 45px; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Changes</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</div>
|
||||
</MudStack>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
private IBrowserFile? _selectedFile;
|
||||
private string? _previewUrl;
|
||||
private bool _processing = false;
|
||||
private bool _isLoading = false;
|
||||
private string? _fullName;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await LoadExistingAvatar();
|
||||
}
|
||||
|
||||
private async Task LoadExistingAvatar()
|
||||
{
|
||||
var userId = CurrentUserService.UserId;
|
||||
if (string.IsNullOrEmpty(userId)) return;
|
||||
|
||||
_isLoading = true;
|
||||
try
|
||||
{
|
||||
var response = await AvatarService.GetAvatarInfoAsync(userId);
|
||||
|
||||
if (response != null && response.IsSuccess && response.Value != null)
|
||||
{
|
||||
_fullName = response.Value.FullName;
|
||||
|
||||
if (!string.IsNullOrEmpty(response.Value.AvatarFile))
|
||||
{
|
||||
var bytes = await AvatarService.GetAvatarBlobAsync(response.Value.AvatarFile);
|
||||
if (bytes != null && bytes.Length > 0)
|
||||
{
|
||||
_previewUrl = $"data:image/png;base64,{Convert.ToBase64String(bytes)}";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
finally
|
||||
{
|
||||
_isLoading = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleFileSelected(IBrowserFile file)
|
||||
{
|
||||
if (file == null) return;
|
||||
if (file.Size > 2 * 1024 * 1024)
|
||||
{
|
||||
Snackbar.Add("File too large. Max 2MB allowed.", Severity.Warning);
|
||||
return;
|
||||
}
|
||||
_selectedFile = file;
|
||||
using var stream = file.OpenReadStream(2 * 1024 * 1024);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms);
|
||||
_previewUrl = $"data:{file.ContentType};base64,{Convert.ToBase64String(ms.ToArray())}";
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private async Task SubmitAvatar()
|
||||
{
|
||||
if (_selectedFile == null) return;
|
||||
var userId = CurrentUserService.UserId;
|
||||
if (string.IsNullOrEmpty(userId)) return;
|
||||
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
using var stream = _selectedFile.OpenReadStream(2 * 1024 * 1024);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms);
|
||||
|
||||
var request = new ChangeAvatarRequest
|
||||
{
|
||||
UserId = userId,
|
||||
FileData = ms.ToArray(),
|
||||
FileName = _selectedFile.Name
|
||||
};
|
||||
|
||||
var response = await AvatarService.ChangeAvatarAsync(request);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Avatar updated successfully", Severity.Success);
|
||||
_selectedFile = null;
|
||||
await LoadExistingAvatar();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Upload failed: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_processing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Infrastructure.File;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Indotalent.Features.Profile.Avatar.Cqrs;
|
||||
|
||||
public class ChangeAvatarRequest
|
||||
{
|
||||
public string UserId { get; set; } = string.Empty;
|
||||
public byte[] FileData { get; set; } = Array.Empty<byte>();
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class ChangeAvatarResponse
|
||||
{
|
||||
public bool IsSuccess { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public record ChangeAvatarCommand(ChangeAvatarRequest Data) : IRequest<ChangeAvatarResponse>;
|
||||
|
||||
public class ChangeAvatarHandler : IRequestHandler<ChangeAvatarCommand, ChangeAvatarResponse>
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly FileStorageService _fileStorage;
|
||||
|
||||
public ChangeAvatarHandler(UserManager<ApplicationUser> userManager, FileStorageService fileStorage)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_fileStorage = fileStorage;
|
||||
}
|
||||
|
||||
public async Task<ChangeAvatarResponse> Handle(ChangeAvatarCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(request.Data.UserId);
|
||||
if (user == null) return new ChangeAvatarResponse { IsSuccess = false, Message = "User not found" };
|
||||
|
||||
try
|
||||
{
|
||||
var extension = Path.GetExtension(request.Data.FileName);
|
||||
|
||||
if (!string.IsNullOrEmpty(user.AvatarFile))
|
||||
{
|
||||
_fileStorage.DeleteOldAvatar(user.AvatarFile);
|
||||
}
|
||||
|
||||
var newFileName = await _fileStorage.SaveAvatarAsync(user.Id, request.Data.FileData, extension);
|
||||
|
||||
user.AvatarFile = newFileName;
|
||||
user.UpdatedAt = DateTime.Now;
|
||||
|
||||
var result = await _userManager.UpdateAsync(user);
|
||||
|
||||
return new ChangeAvatarResponse
|
||||
{
|
||||
IsSuccess = result.Succeeded,
|
||||
Message = result.Succeeded ? "Avatar updated successfully" : "Failed to update user profile"
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ChangeAvatarResponse { IsSuccess = false, Message = ex.Message };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Indotalent.Features.Profile.Avatar.Cqrs;
|
||||
|
||||
public class GetAvatarInfoResponse
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string? FullName { get; set; }
|
||||
public string? AvatarFile { get; set; }
|
||||
}
|
||||
|
||||
public record GetAvatarInfoQuery(string UserId) : IRequest<GetAvatarInfoResponse?>;
|
||||
|
||||
public class GetAvatarInfoHandler : IRequestHandler<GetAvatarInfoQuery, GetAvatarInfoResponse?>
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
|
||||
public GetAvatarInfoHandler(UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
public async Task<GetAvatarInfoResponse?> Handle(GetAvatarInfoQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(request.UserId);
|
||||
if (user == null) return null;
|
||||
|
||||
return new GetAvatarInfoResponse
|
||||
{
|
||||
Id = user.Id,
|
||||
FullName = user.FullName,
|
||||
AvatarFile = user.AvatarFile
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user