aboutsummaryrefslogtreecommitdiff
path: root/Timeline
diff options
context:
space:
mode:
author杨宇千 <crupest@outlook.com>2019-10-25 23:03:36 +0800
committer杨宇千 <crupest@outlook.com>2019-10-25 23:03:36 +0800
commit181b53e270ff7c0558edec75b8b255d487e796c3 (patch)
tree5315d3339e3fcb43c22b0e39c761ab46d45f9b9c /Timeline
parenta175f8328d7a6c36464676d54fc50d03e64be0af (diff)
downloadtimeline-181b53e270ff7c0558edec75b8b255d487e796c3.tar.gz
timeline-181b53e270ff7c0558edec75b8b255d487e796c3.tar.bz2
timeline-181b53e270ff7c0558edec75b8b255d487e796c3.zip
Add user detail service.
Diffstat (limited to 'Timeline')
-rw-r--r--Timeline/Entities/DatabaseContext.cs1
-rw-r--r--Timeline/Entities/User.cs2
-rw-r--r--Timeline/Entities/UserDetail.cs21
-rw-r--r--Timeline/Resources/Services/UserDetailService.Designer.cs99
-rw-r--r--Timeline/Resources/Services/UserDetailService.resx132
-rw-r--r--Timeline/Services/DatabaseExtensions.cs6
-rw-r--r--Timeline/Services/UserAvatarService.cs9
-rw-r--r--Timeline/Services/UserDetailService.cs102
-rw-r--r--Timeline/Timeline.csproj9
9 files changed, 373 insertions, 8 deletions
diff --git a/Timeline/Entities/DatabaseContext.cs b/Timeline/Entities/DatabaseContext.cs
index e1b98e7d..6c005b30 100644
--- a/Timeline/Entities/DatabaseContext.cs
+++ b/Timeline/Entities/DatabaseContext.cs
@@ -19,5 +19,6 @@ namespace Timeline.Entities
public DbSet<User> Users { get; set; } = default!;
public DbSet<UserAvatar> UserAvatars { get; set; } = default!;
+ public DbSet<UserDetail> UserDetails { get; set; } = default!;
}
}
diff --git a/Timeline/Entities/User.cs b/Timeline/Entities/User.cs
index 6e8e4967..02352b03 100644
--- a/Timeline/Entities/User.cs
+++ b/Timeline/Entities/User.cs
@@ -28,5 +28,7 @@ namespace Timeline.Entities
public long Version { get; set; }
public UserAvatar? Avatar { get; set; }
+
+ public UserDetail? Detail { get; set; }
}
}
diff --git a/Timeline/Entities/UserDetail.cs b/Timeline/Entities/UserDetail.cs
new file mode 100644
index 00000000..45f87e2b
--- /dev/null
+++ b/Timeline/Entities/UserDetail.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace Timeline.Entities
+{
+ [Table("user_details")]
+ public class UserDetail
+ {
+ [Column("id"), Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public long Id { get; set; }
+
+ [Column("nickname"), MaxLength(26)]
+ public string? Nickname { get; set; }
+
+ public long UserId { get; set; }
+ }
+}
diff --git a/Timeline/Resources/Services/UserDetailService.Designer.cs b/Timeline/Resources/Services/UserDetailService.Designer.cs
new file mode 100644
index 00000000..2f586b36
--- /dev/null
+++ b/Timeline/Resources/Services/UserDetailService.Designer.cs
@@ -0,0 +1,99 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Timeline.Resources.Services {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class UserDetailService {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal UserDetailService() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Resources.Services.UserDetailService", typeof(UserDetailService).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Length of nickname can&apos;t be bigger than 10..
+ /// </summary>
+ internal static string ExceptionNicknameTooLong {
+ get {
+ return ResourceManager.GetString("ExceptionNicknameTooLong", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A user_details entity has been created. User id is {0}. Nickname is {1}..
+ /// </summary>
+ internal static string LogEntityNicknameCreate {
+ get {
+ return ResourceManager.GetString("LogEntityNicknameCreate", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Nickname of a user_details entity has been updated to a new value. User id is {0}. New value is {1}..
+ /// </summary>
+ internal static string LogEntityNicknameSetNotNull {
+ get {
+ return ResourceManager.GetString("LogEntityNicknameSetNotNull", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Nickname of a user_details entity has been updated to null. User id is {0}..
+ /// </summary>
+ internal static string LogEntityNicknameSetToNull {
+ get {
+ return ResourceManager.GetString("LogEntityNicknameSetToNull", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/Timeline/Resources/Services/UserDetailService.resx b/Timeline/Resources/Services/UserDetailService.resx
new file mode 100644
index 00000000..ea32aeda
--- /dev/null
+++ b/Timeline/Resources/Services/UserDetailService.resx
@@ -0,0 +1,132 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="ExceptionNicknameTooLong" xml:space="preserve">
+ <value>Length of nickname can't be bigger than 10.</value>
+ </data>
+ <data name="LogEntityNicknameCreate" xml:space="preserve">
+ <value>A user_details entity has been created. User id is {0}. Nickname is {1}.</value>
+ </data>
+ <data name="LogEntityNicknameSetNotNull" xml:space="preserve">
+ <value>Nickname of a user_details entity has been updated to a new value. User id is {0}. New value is {1}.</value>
+ </data>
+ <data name="LogEntityNicknameSetToNull" xml:space="preserve">
+ <value>Nickname of a user_details entity has been updated to null. User id is {0}.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/Timeline/Services/DatabaseExtensions.cs b/Timeline/Services/DatabaseExtensions.cs
index 8cbc8fef..140c3146 100644
--- a/Timeline/Services/DatabaseExtensions.cs
+++ b/Timeline/Services/DatabaseExtensions.cs
@@ -9,6 +9,8 @@ namespace Timeline.Services
{
internal static class DatabaseExtensions
{
+ private static readonly UsernameValidator usernameValidator = new UsernameValidator();
+
/// <summary>
/// Check the existence and get the id of the user.
/// </summary>
@@ -17,11 +19,11 @@ namespace Timeline.Services
/// <exception cref="ArgumentNullException">Thrown if <paramref name="username"/> is null.</exception>
/// <exception cref="UsernameBadFormatException">Thrown if <paramref name="username"/> is of bad format.</exception>
/// <exception cref="UserNotExistException">Thrown if user does not exist.</exception>
- internal static async Task<long> CheckAndGetUser(DbSet<User> userDbSet, UsernameValidator validator, string username)
+ internal static async Task<long> CheckAndGetUser(DbSet<User> userDbSet, string? username)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
- var (result, message) = validator.Validate(username);
+ var (result, message) = usernameValidator.Validate(username);
if (!result)
throw new UsernameBadFormatException(username, message);
diff --git a/Timeline/Services/UserAvatarService.cs b/Timeline/Services/UserAvatarService.cs
index 2afe9093..01201864 100644
--- a/Timeline/Services/UserAvatarService.cs
+++ b/Timeline/Services/UserAvatarService.cs
@@ -177,8 +177,6 @@ namespace Timeline.Services
private readonly IETagGenerator _eTagGenerator;
- private readonly UsernameValidator _usernameValidator;
-
private readonly IClock _clock;
public UserAvatarService(
@@ -194,13 +192,12 @@ namespace Timeline.Services
_defaultUserAvatarProvider = defaultUserAvatarProvider;
_avatarValidator = avatarValidator;
_eTagGenerator = eTagGenerator;
- _usernameValidator = new UsernameValidator();
_clock = clock;
}
public async Task<string> GetAvatarETag(string username)
{
- var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, _usernameValidator, username);
+ var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, username);
var eTag = (await _database.UserAvatars.Where(a => a.UserId == userId).Select(a => new { a.ETag }).SingleOrDefaultAsync())?.ETag;
if (eTag == null)
@@ -211,7 +208,7 @@ namespace Timeline.Services
public async Task<AvatarInfo> GetAvatar(string username)
{
- var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, _usernameValidator, username);
+ var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, username);
var avatarEntity = await _database.UserAvatars.Where(a => a.UserId == userId).Select(a => new { a.Type, a.Data, a.LastModified }).SingleOrDefaultAsync();
@@ -253,7 +250,7 @@ namespace Timeline.Services
throw new ArgumentException(Resources.Services.UserAvatarService.ExceptionAvatarTypeNullOrEmpty, nameof(avatar));
}
- var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, _usernameValidator, username);
+ var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, username);
var avatarEntity = await _database.UserAvatars.Where(a => a.UserId == userId).SingleOrDefaultAsync();
if (avatar == null)
diff --git a/Timeline/Services/UserDetailService.cs b/Timeline/Services/UserDetailService.cs
new file mode 100644
index 00000000..0b24e4e2
--- /dev/null
+++ b/Timeline/Services/UserDetailService.cs
@@ -0,0 +1,102 @@
+using Microsoft.Extensions.Logging;
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using Timeline.Entities;
+using static Timeline.Resources.Services.UserDetailService;
+
+namespace Timeline.Services
+{
+ public interface IUserDetailService
+ {
+ /// <summary>
+ /// Get the nickname of the user with given username.
+ /// If the user does not set a nickname, the username is returned as the nickname.
+ /// </summary>
+ /// <param name="username">The username of the user to get nickname of.</param>
+ /// <returns>The nickname of the user.</returns>
+ /// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> is null.</exception>
+ /// <exception cref="UsernameBadFormatException">Thrown when <paramref name="username"/> is of bad format.</exception>
+ /// <exception cref="UserNotExistException">Thrown when the user does not exist.</exception>
+ Task<string> GetNickname(string username);
+
+ /// <summary>
+ /// Set the nickname of the user with given username.
+ /// </summary>
+ /// <param name="username">The username of the user to set nickname of.</param>
+ /// <param name="nickname">The nickname. Pass null to unset.</param>
+ /// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> is null.</exception>
+ /// <exception cref="ArgumentException">Thrown when <paramref name="nickname"/> is not null but its length is bigger than 10.</exception>
+ /// <exception cref="UsernameBadFormatException">Thrown when <paramref name="username"/> is of bad format.</exception>
+ /// <exception cref="UserNotExistException">Thrown when the user does not exist.</exception>
+ Task SetNickname(string username, string? nickname);
+ }
+
+ public class UserDetailService : IUserDetailService
+ {
+ private readonly DatabaseContext _database;
+
+ private readonly ILogger<UserDetailService> _logger;
+
+ public UserDetailService(DatabaseContext database, ILogger<UserDetailService> logger)
+ {
+ _database = database;
+ _logger = logger;
+ }
+
+ public async Task<string> GetNickname(string username)
+ {
+ var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, username);
+ var nickname = _database.UserDetails.Where(d => d.UserId == userId).Select(d => new { d.Nickname }).SingleOrDefault()?.Nickname;
+ return nickname ?? username;
+ }
+
+ public async Task SetNickname(string username, string? nickname)
+ {
+ if (nickname != null && nickname.Length > 10)
+ {
+ throw new ArgumentException(ExceptionNicknameTooLong, nameof(nickname));
+ }
+ var userId = await DatabaseExtensions.CheckAndGetUser(_database.Users, username);
+ var userDetail = _database.UserDetails.Where(d => d.UserId == userId).SingleOrDefault();
+ if (nickname == null)
+ {
+ if (userDetail == null || userDetail.Nickname == null)
+ {
+ return;
+ }
+ else
+ {
+ userDetail.Nickname = null;
+ await _database.SaveChangesAsync();
+ _logger.LogInformation(LogEntityNicknameSetToNull, userId);
+ }
+ }
+ else
+ {
+ var create = userDetail == null;
+ if (create)
+ {
+ userDetail = new UserDetail
+ {
+ UserId = userId
+ };
+ }
+ userDetail!.Nickname = nickname;
+ if (create)
+ {
+ _database.UserDetails.Add(userDetail);
+ }
+ await _database.SaveChangesAsync();
+ if (create)
+ {
+ _logger.LogInformation(LogEntityNicknameCreate, userId, nickname);
+ }
+ else
+ {
+ _logger.LogInformation(LogEntityNicknameSetNotNull, userId, nickname);
+ }
+ }
+ }
+ }
+}
diff --git a/Timeline/Timeline.csproj b/Timeline/Timeline.csproj
index b989cd3b..0260d725 100644
--- a/Timeline/Timeline.csproj
+++ b/Timeline/Timeline.csproj
@@ -89,6 +89,11 @@
<AutoGen>True</AutoGen>
<DependentUpon>UserAvatarService.resx</DependentUpon>
</Compile>
+ <Compile Update="Resources\Services\UserDetailService.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>UserDetailService.resx</DependentUpon>
+ </Compile>
<Compile Update="Resources\Services\UserService.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
@@ -146,6 +151,10 @@
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>UserAvatarService.Designer.cs</LastGenOutput>
</EmbeddedResource>
+ <EmbeddedResource Update="Resources\Services\UserDetailService.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>UserDetailService.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Update="Resources\Services\UserService.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>UserService.Designer.cs</LastGenOutput>