From 484f59f9c954fdced635c24c5ab49840c3022d93 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 30 Apr 2019 19:49:27 +0800 Subject: Add avatar upload function. --- Timeline/Services/UserService.cs | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'Timeline/Services/UserService.cs') diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 4a47ca0f..9ebf2668 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; +using System; using System.Linq; using System.Threading.Tasks; using Timeline.Entities; @@ -65,6 +66,18 @@ namespace Timeline.Services BadOldPassword } + public enum PutAvatarResult + { + /// + /// Success to upload avatar. + /// + Success, + /// + /// The user does not exists. + /// + UserNotExists + } + public interface IUserService { /// @@ -141,7 +154,14 @@ namespace Timeline.Services /// if old password is wrong. Task ChangePassword(string username, string oldPassword, string newPassword); + /// + /// Get the true avatar url of a user. + /// + /// The name of user. + /// The url if user exists. Null if user does not exist. Task GetAvatarUrl(string username); + + Task PutAvatar(string username, byte[] data, string mimeType); } public class UserService : IUserService @@ -301,11 +321,33 @@ namespace Timeline.Services public async Task GetAvatarUrl(string username) { + if (username == null) + throw new ArgumentNullException(nameof(username)); + + if ((await GetUser(username)) == null) + return null; + var exists = await _cosService.IsObjectExists("avatar", username); if (exists) return _cosService.GenerateObjectGetUrl("avatar", username); else return _cosService.GenerateObjectGetUrl("avatar", "__default"); } + + public async Task PutAvatar(string username, byte[] data, string mimeType) + { + if (username == null) + throw new ArgumentNullException(nameof(username)); + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mimeType == null) + throw new ArgumentNullException(nameof(mimeType)); + + if ((await GetUser(username)) == null) + return PutAvatarResult.UserNotExists; + + await _cosService.PutObject("avatar", username, data, mimeType); + return PutAvatarResult.Success; + } } } -- cgit v1.2.3