From 34bc4e143cbc297b2c5f93840371888752325a5b Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Wed, 15 Jun 2022 12:01:07 +0300 Subject: [PATCH 01/30] Push: helper, dao --- common/ASC.Core.Common/ASC.Core.Common.csproj | 1 + .../EF/Context/FirebaseDbContext.cs | 66 +++++++++ common/ASC.Core.Common/EF/FireBaseUser.cs | 136 ++++++++++++++++++ .../Notify/Push/Dao/FirebaseDao.cs | 106 ++++++++++++++ .../Notify/Push/FirebaseHelper.cs | 102 +++++++++++++ 5 files changed, 411 insertions(+) create mode 100644 common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs create mode 100644 common/ASC.Core.Common/EF/FireBaseUser.cs create mode 100644 common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs create mode 100644 common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs diff --git a/common/ASC.Core.Common/ASC.Core.Common.csproj b/common/ASC.Core.Common/ASC.Core.Common.csproj index c76bbb1194..ae9a94f4a1 100644 --- a/common/ASC.Core.Common/ASC.Core.Common.csproj +++ b/common/ASC.Core.Common/ASC.Core.Common.csproj @@ -50,6 +50,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs b/common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs new file mode 100644 index 0000000000..f5e1eae6fb --- /dev/null +++ b/common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs @@ -0,0 +1,66 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +namespace ASC.Core.Common.EF.Context; +public class MySqlFirebaseDbContext : FirebaseDbContext { } +public class PostgreSqlFirebaseDbContext : FirebaseDbContext { } +public class FirebaseDbContext : BaseDbContext +{ + public DbSet Users { get; set; } + + public FirebaseDbContext() { } + public FirebaseDbContext(DbContextOptions options) + : base(options) + { + } + + protected override Dictionary> ProviderContext + { + get + { + return new Dictionary>() + { + { Provider.MySql, () => new MySqlFirebaseDbContext() } , + { Provider.PostgreSql, () => new PostgreSqlFirebaseDbContext() } , + }; + } + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + ModelBuilderWrapper + .From(modelBuilder, _provider) + .AddFireBaseUsers(); + } +} + +public static class FirebaseDbContextExtension +{ + public static DIHelper AddFirebaseDbContextService(this DIHelper services) + { + return services.AddDbContextManagerService(); + } +} diff --git a/common/ASC.Core.Common/EF/FireBaseUser.cs b/common/ASC.Core.Common/EF/FireBaseUser.cs new file mode 100644 index 0000000000..4ce05ae354 --- /dev/null +++ b/common/ASC.Core.Common/EF/FireBaseUser.cs @@ -0,0 +1,136 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ASC.Core.Common.EF; + +public class FireBaseUser : BaseEntity +{ + public int Id { get; set; } + public Guid UserId { get; set; } + public int TenantId { get; set; } + public string FirebaseDeviceToken { get; set; } + public string Application { get; set; } + public bool? IsSubscribed { get; set; } + + public override object[] GetKeys() + { + return new object[] { Id }; + } +} + +public static class FireBaseUserExtension +{ + public static ModelBuilderWrapper AddFireBaseUsers(this ModelBuilderWrapper modelBuilder) + { + modelBuilder + .Add(MySqlAddFireBaseUsers, Provider.MySql) + .Add(PgSqlAddFireBaseUsers, Provider.PostgreSql); + + return modelBuilder; + } + + public static void MySqlAddFireBaseUsers(this ModelBuilder modelBuilder) + { + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.Id }) + .HasName("PRIMARY"); + + entity.ToTable("firebase_users"); + + entity.HasIndex(e => e.UserId) + .HasDatabaseName("user_id"); + entity.HasIndex(e => e.TenantId) + .HasDatabaseName("tenant_id"); + entity.HasIndex(e => e.FirebaseDeviceToken) + .HasDatabaseName("firebase_device_token"); + + entity.Property(e => e.Id).HasColumnName("id"); + entity.Property(e => e.TenantId).HasColumnName("tenant_id"); + entity.Property(e => e.IsSubscribed).HasColumnName("is_subscribed"); + + entity.Property(e => e.UserId) + .HasColumnName("user_id") + .HasColumnType("varchar(38)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.FirebaseDeviceToken) + .HasColumnName("firebase_device_token") + .HasColumnType("varchar(255)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Application) + .HasColumnName("application") + .HasColumnType("varchar(20)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + }); + } + + public static void PgSqlAddFireBaseUsers(this ModelBuilder modelBuilder) + { + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id) + .HasName("firebase_users_pkey"); + + entity.ToTable("firebase_users", "onlyoffice"); + + entity.HasIndex(e => e.UserId) + .HasDatabaseName("user_id"); + entity.HasIndex(e => e.TenantId) + .HasDatabaseName("tenant_id"); + entity.HasIndex(e => e.FirebaseDeviceToken) + .HasDatabaseName("firebase_device_token"); + + entity.Property(e => e.Id).HasColumnName("id"); + entity.Property(e => e.TenantId).HasColumnName("tenant_id"); + entity.Property(e => e.IsSubscribed).HasColumnName("is_subscribed"); + + entity.Property(e => e.UserId) + .HasColumnName("user_id") + .HasMaxLength(38); + + entity.Property(e => e.FirebaseDeviceToken) + .HasColumnName("firebase_device_token") + .HasMaxLength(255); + + entity.Property(e => e.Application) + .HasColumnName("application") + .HasMaxLength(20); + }); + } + +} diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs new file mode 100644 index 0000000000..60877dbb8d --- /dev/null +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -0,0 +1,106 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ASC.Core.Common.Notify.Push.Dao; + + +[Scope] +public class FirebaseDao +{ + public FirebaseDbContext FirebaseDbContext { get; set; } + public FirebaseDao() { } + + public FirebaseDao(DbContextManager dbContextManager) + { + FirebaseDbContext = dbContextManager.Value; + } + + public FireBaseUser RegisterUserDevice(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) + { + + var count = FirebaseDbContext.Users + .AsNoTracking() + .Where(r => r.UserId == userId) + .Where(r => r.TenantId == tenantId) + .Where(r => r.Application == application) + .Where(r => r.FirebaseDeviceToken == fbDeviceToken) + .Count(); + + var user = new FireBaseUser + { + UserId = userId, + TenantId = tenantId, + FirebaseDeviceToken = fbDeviceToken, + IsSubscribed = isSubscribed, + Application = application + }; + + if (count == 0) + { + FirebaseDbContext.AddOrUpdate(r => r.Users, user); + FirebaseDbContext.SaveChanges(); + } + + return user; + } + + public List GetUserDeviceTokens(Guid userId, int tenantId, string application) + { + return FirebaseDbContext.Users + .AsNoTracking() + .Where(r => r.UserId == userId) + .Where(r => r.TenantId == tenantId) + .Where(r => r.Application == application) + .ToList(); + } + + public FireBaseUser UpdateUser(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) + { + + var user = new FireBaseUser + { + UserId = userId, + TenantId = tenantId, + FirebaseDeviceToken = fbDeviceToken, + IsSubscribed = isSubscribed, + Application = application + }; + + FirebaseDbContext.Update(user); + FirebaseDbContext.SaveChanges(); + + + return user; + } + + +} diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs new file mode 100644 index 0000000000..116ecd9356 --- /dev/null +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -0,0 +1,102 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using FirebaseAdmin; + +using Google.Apis.Auth.OAuth2; + +namespace ASC.Core.Common.Notify.Push; + +[Scope] +public class FirebaseHelper +{ + protected readonly UserManager _userManager; + private readonly ILogger _logger; + + public FirebaseHelper( + UserManager userManager, + ILogger logger) + { + _userManager = userManager; + _logger = logger; + } + + private FirebaseHelper() + { + FirebaseApp.Create(new AppOptions() + { + //Credential = GoogleCredential.FromJson(JsonConvert.SerializeObject(new FirebaseApiKey()).Replace("\\\\", "\\")) + Credential = GoogleCredential.FromJson(JsonConvert.SerializeObject("")) + }); + } + public void SendMessage(NotifyMessage msg) + { + var data = new Dictionary(); + var user = _userManager.GetUserByUserName(msg.ReplyTo); + var fbDao = new FirebaseDao(); + + Guid productID; + + if (!Guid.TryParse(msg.ProductID, out productID)) return; + + var fireBaseUser = new List(); + + if (productID == new Guid("{E67BE73D-F9AE-4ce1-8FEC-1880CB518CB4}")) //documents product + { + fireBaseUser = fbDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushDocAppName); + } + + if (productID == new Guid("{1e044602-43b5-4d79-82f3-fd6208a11960}")) //projects product + { + fireBaseUser = fbDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushProjAppName); + } + + foreach (var fb in fireBaseUser) + { + if ((bool)fb.IsSubscribed) + { + var m = new Message() + { + Data = new Dictionary{ + { "data", msg.Data } + }, + Token = fb.FirebaseDeviceToken, + Notification = new Notification() + { + Body = msg.Content + } + }; + FirebaseMessaging.DefaultInstance.SendAsync(m); + } + } + } +} From 1e47bf9bf320283c24fa819c276f012bb838559e Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Wed, 15 Jun 2022 17:25:23 +0300 Subject: [PATCH 02/30] Push: configuration --- .../ASC.Core.Common/Notify/FirebaseApiKey.cs | 119 ++++++++++++++++++ .../Notify/Messages/NotifyMessage.cs | 9 ++ .../Notify/Push/FirebaseHelper.cs | 11 +- .../Notify/Push/PushConstants.cs | 3 + config/appsettings.json | 7 +- 5 files changed, 145 insertions(+), 4 deletions(-) create mode 100644 common/ASC.Core.Common/Notify/FirebaseApiKey.cs diff --git a/common/ASC.Core.Common/Notify/FirebaseApiKey.cs b/common/ASC.Core.Common/Notify/FirebaseApiKey.cs new file mode 100644 index 0000000000..c83f0c6e93 --- /dev/null +++ b/common/ASC.Core.Common/Notify/FirebaseApiKey.cs @@ -0,0 +1,119 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +namespace ASC.Core.Common.Notify; +[Serializable] +class FirebaseApiKey +{ + private readonly IConfiguration _configuration; + + public FirebaseApiKey(IConfiguration configuration) + { + _configuration = configuration; + } + + [JsonProperty("type")] + public string Type + { + get + { + return "service_account"; + } + } + + [JsonProperty("project_id")] + public string ProjectId + { + get + { + return _configuration["firebase:projectId"] ?? ""; + } + } + [JsonProperty("private_key_id")] + public string PrivateKeyId + { + get + { + return _configuration["firebase:privateKeyId"] ?? ""; + } + } + [JsonProperty("private_key")] + public string PrivateKey + { + get + { + return _configuration["firebase:privateKey"] ?? ""; + } + } + [JsonProperty("client_email")] + public string ClientEmail + { + get + { + return _configuration["firebase:clientEmail"] ?? ""; + } + } + [JsonProperty("client_id")] + public string ClientId + { + get + { + return _configuration["firebase:clientId"] ?? ""; + } + } + [JsonProperty("auth_uri")] + public string AuthUri + { + get + { + return "https://accounts.google.com/o/oauth2/auth"; + } + } + [JsonProperty("token_uri")] + public string TokenUri + { + get + { + return "https://oauth2.googleapis.com/token"; + } + } + [JsonProperty("auth_provider_x509_cert_url")] + public string AuthProviderX509CertUrl + { + get + { + return "https://www.googleapis.com/oauth2/v1/certs"; + } + } + [JsonProperty("client_x509_cert_url")] + public string ClientX509CertUrl + { + get + { + return _configuration["firebase:x509CertUrl"] ?? ""; + } + } +} diff --git a/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs b/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs index 7dad14c333..07a1529446 100644 --- a/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs +++ b/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs @@ -65,6 +65,15 @@ public class NotifyMessage : IMapFrom [ProtoMember(12)] public int TenantId { get; set; } + [ProtoMember(13)] + public string ProductID { get; set; } + + [ProtoMember(14)] + public string ObjectID { get; set; } + + [ProtoMember(15)] + public string Data { get; set; } + public void Mapping(Profile profile) { profile.CreateMap() diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 116ecd9356..b537b13f64 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -30,7 +30,10 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using ASC.Core.Common.Notify.Push.Dao; + using FirebaseAdmin; +using FirebaseAdmin.Messaging; using Google.Apis.Auth.OAuth2; @@ -41,12 +44,15 @@ public class FirebaseHelper { protected readonly UserManager _userManager; private readonly ILogger _logger; + private readonly IConfiguration _configuration; public FirebaseHelper( UserManager userManager, + IConfiguration configuration, ILogger logger) { _userManager = userManager; + _configuration = configuration; _logger = logger; } @@ -54,8 +60,7 @@ public class FirebaseHelper { FirebaseApp.Create(new AppOptions() { - //Credential = GoogleCredential.FromJson(JsonConvert.SerializeObject(new FirebaseApiKey()).Replace("\\\\", "\\")) - Credential = GoogleCredential.FromJson(JsonConvert.SerializeObject("")) + Credential = GoogleCredential.FromJson(JsonConvert.SerializeObject(new FirebaseApiKey(_configuration)).Replace("\\\\", "\\")) }); } public void SendMessage(NotifyMessage msg) @@ -84,7 +89,7 @@ public class FirebaseHelper { if ((bool)fb.IsSubscribed) { - var m = new Message() + var m = new FirebaseAdmin.Messaging.Message() { Data = new Dictionary{ { "data", msg.Data } diff --git a/common/ASC.Core.Common/Notify/Push/PushConstants.cs b/common/ASC.Core.Common/Notify/Push/PushConstants.cs index 97e5443a4f..5c7be980ef 100644 --- a/common/ASC.Core.Common/Notify/Push/PushConstants.cs +++ b/common/ASC.Core.Common/Notify/Push/PushConstants.cs @@ -32,4 +32,7 @@ public static class PushConstants public const string PushParentItemTagName = "PushParentItem"; public const string PushModuleTagName = "PushModule"; public const string PushActionTagName = "PushAction"; + + public const string PushDocAppName = "doc"; + public const string PushProjAppName = "proj"; } diff --git a/config/appsettings.json b/config/appsettings.json index 0eb4241bcd..2c19855c0b 100644 --- a/config/appsettings.json +++ b/config/appsettings.json @@ -152,9 +152,14 @@ } }, "firebase": { + "projectId": "", + "privateKeyId": "", + "privateKey": "", + "clientEmail": "", + "clientId": "", + "x509CertUrl": "", "apiKey": "", "authDomain": "", - "projectId": "", "storageBucket": "", "messagingSenderId": "", "appId": "", From f59460405fe931ca4acf339eb931fcb5eab4d8fa Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Thu, 16 Jun 2022 16:07:49 +0300 Subject: [PATCH 03/30] Push: push sender --- common/ASC.Core.Common/Context/WorkContext.cs | 8 +- .../Notify/Push/Dao/NotifyData.cs | 50 +++++++++ .../Notify/Push/Dao/NotifyFileData.cs | 41 +++++++ .../Notify/Push/Dao/NotifyFolderData.cs | 39 +++++++ .../ASC.Core.Common/Notify/PushSenderSink.cs | 102 ++++++++++++------ .../Notify/Senders/PushSender.cs | 64 +++++++++++ 6 files changed, 273 insertions(+), 31 deletions(-) create mode 100644 common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs create mode 100644 common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs create mode 100644 common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs create mode 100644 common/ASC.Core.Common/Notify/Senders/PushSender.cs diff --git a/common/ASC.Core.Common/Context/WorkContext.cs b/common/ASC.Core.Common/Context/WorkContext.cs index 8f0c6024db..65d35eb0ae 100644 --- a/common/ASC.Core.Common/Context/WorkContext.cs +++ b/common/ASC.Core.Common/Context/WorkContext.cs @@ -41,6 +41,7 @@ public class WorkContext private readonly SmtpSender _smtpSender; private readonly NotifyServiceSender _notifyServiceSender; private readonly TelegramSender _telegramSender; + private readonly PushSender _pushSender; private static bool _notifyStarted; private static bool? _isMono; private static string _monoVersion; @@ -87,7 +88,8 @@ public class WorkContext AWSSender awsSender, SmtpSender smtpSender, NotifyServiceSender notifyServiceSender, - TelegramSender telegramSender + TelegramSender telegramSender, + PushSender pushSender ) { _serviceProvider = serviceProvider; @@ -100,6 +102,7 @@ public class WorkContext _smtpSender = smtpSender; _notifyServiceSender = notifyServiceSender; _telegramSender = telegramSender; + _pushSender = pushSender; } public void NotifyStartUp() @@ -119,6 +122,8 @@ public class WorkContext INotifySender jabberSender = _notifyServiceSender; INotifySender emailSender = _notifyServiceSender; INotifySender telegramSender = _telegramSender; + INotifySender pushSender = _pushSender; + var postman = _configuration["core:notify:postman"]; @@ -148,6 +153,7 @@ public class WorkContext NotifyContext.RegisterSender(_dispatchEngine, Constants.NotifyEMailSenderSysName, new EmailSenderSink(emailSender, _serviceProvider)); NotifyContext.RegisterSender(_dispatchEngine, Constants.NotifyMessengerSenderSysName, new JabberSenderSink(jabberSender, _serviceProvider)); NotifyContext.RegisterSender(_dispatchEngine, Constants.NotifyTelegramSenderSysName, new TelegramSenderSink(telegramSender, _serviceProvider)); + NotifyContext.RegisterSender(_dispatchEngine, Constants.NotifyPushSenderSysName, new PushSenderSink(pushSender, _serviceProvider)); NotifyEngine.AddAction(); diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs new file mode 100644 index 0000000000..260717e1b7 --- /dev/null +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs @@ -0,0 +1,50 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +namespace ASC.Core.Common.Notify.Push.Dao; +[Serializable] +public class NotifyData +{ + [JsonProperty("portal")] + [DataMember(Name = "portal")] + public string Portal { get; set; } + + [JsonProperty("email")] + [DataMember(Name = "email")] + public string Email { get; set; } + + [JsonProperty("file")] + [DataMember(Name = "file")] + public NotifyFileData File { get; set; } + + [JsonProperty("folder")] + [DataMember(Name = "folder")] + public NotifyFolderData Folder { get; set; } + + [JsonProperty("originalUrl")] + [DataMember(Name = "originalUrl")] + public string OriginalUrl { get; set; } +} diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs new file mode 100644 index 0000000000..76aead5fa0 --- /dev/null +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs @@ -0,0 +1,41 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +namespace ASC.Core.Common.Notify.Push.Dao; +[Serializable] +public class NotifyFileData +{ + [JsonProperty("id")] + [DataMember(Name = "id")] + public string Id { get; set; } + [JsonProperty("title")] + [DataMember(Name = "title")] + public string Title { get; set; } + [JsonProperty("extension")] + [DataMember(Name = "extension")] + public string Extension { get; set; } + +} diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs new file mode 100644 index 0000000000..b8deddb206 --- /dev/null +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs @@ -0,0 +1,39 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +namespace ASC.Core.Common.Notify.Push.Dao; +public class NotifyFolderData +{ + [JsonProperty("id")] + [DataMember(Name = "id")] + public string Id { get; set; } + [JsonProperty("parentId")] + [DataMember(Name = "parentId")] + public string ParentId { get; set; } + [JsonProperty("rootFolderType")] + [DataMember(Name = "rootFolderType")] + public int RootFolderType { get; set; } +} diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index a148958343..eb03c39cef 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -24,19 +24,22 @@ // content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode +using ASC.Core.Common.Notify.Push.Dao; + using Constants = ASC.Core.Configuration.Constants; namespace ASC.Core.Common.Notify; class PushSenderSink : Sink { - private readonly ILogger _logger; + private static readonly string _senderName = Constants.NotifyPushSenderSysName; + private readonly INotifySender _sender; private bool _configured = true; - public PushSenderSink(IServiceProvider serviceProvider, ILogger logger) + public PushSenderSink(INotifySender sender, IServiceProvider serviceProvider) { + _sender = sender ?? throw new ArgumentNullException(nameof(sender)); _serviceProvider = serviceProvider; - _logger = logger; } private readonly IServiceProvider _serviceProvider; @@ -45,42 +48,81 @@ class PushSenderSink : Sink { try { + using var scope = _serviceProvider.CreateScope(); + + var result = SendResult.OK; var tenantManager = scope.ServiceProvider.GetService(); + var userManager = scope.ServiceProvider.GetService(); + var user = userManager.GetUsers(new Guid(message.Recipient.ID)); + var username = user.UserName; - var notification = new PushNotification + if (string.IsNullOrEmpty(username)) { - Module = GetTagValue(message, PushConstants.PushModuleTagName), - Action = GetTagValue(message, PushConstants.PushActionTagName), - Item = GetTagValue(message, PushConstants.PushItemTagName), - ParentItem = GetTagValue(message, PushConstants.PushParentItemTagName), - Message = message.Body, - ShortMessage = message.Subject - }; - - if (_configured) - { - try - { - using var pushClient = new PushServiceClient(); - pushClient.EnqueueNotification( - tenantManager.GetCurrentTenant().Id, - message.Recipient.ID, - notification, - new List()); - } - catch (InvalidOperationException) - { - _configured = false; - _logger.DebugPushSender(); - } + result = SendResult.IncorrectRecipient; } else { - _logger.DebugPushSender(); + var fromTag = message.Arguments.FirstOrDefault(x => x.Tag.Equals("MessageFrom")); + var productID = message.Arguments.FirstOrDefault(x => x.Tag.Equals("__ProductID")); + var originalUrl = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentURL")); + + var folderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderId")); + var rootFolderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderParentId")); + var rootFolderType = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderRootFolderType")); + + + var notifyData = new NotifyData() + { + Email = user.Email, + Portal = tenantManager.GetCurrentTenant().TrustedDomains.FirstOrDefault(), + OriginalUrl = originalUrl != null && originalUrl.Value != null ? originalUrl.Value.ToString() : "", + Folder = new NotifyFolderData + { + Id = folderId != null && folderId.Value != null ? folderId.Value.ToString() : "", + ParentId = rootFolderId != null && rootFolderId.Value != null ? rootFolderId.Value.ToString() : "", + RootFolderType = rootFolderType != null && rootFolderType.Value != null ? (int)rootFolderType.Value : 0 + }, + }; + + var msg = (NoticeMessage)message; + + if (msg.ObjectID.StartsWith("file_")) + { + var documentTitle = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentTitle")); + var documentExtension = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentExtension")); + + notifyData.File = new NotifyFileData() + { + Id = msg.ObjectID.Substring(5), + Title = documentTitle != null && documentTitle.Value != null ? documentTitle.Value.ToString() : "", + Extension = documentExtension != null && documentExtension.Value != null ? documentExtension.Value.ToString() : "" + + }; + } + + var jsonNotifyData = JsonConvert.SerializeObject(notifyData); + var tenant = tenantManager.GetCurrentTenant(false); + + var m = new NotifyMessage + { + // To = username, + Subject = fromTag != null && fromTag.Value != null ? fromTag.Value.ToString() : message.Subject, + ContentType = message.ContentType, + Content = message.Body, + Sender = Constants.NotifyPushSenderSysName, + CreationDate = DateTime.UtcNow, + ProductID = fromTag != null && fromTag.Value != null ? productID.Value.ToString() : null, + ObjectID = msg.ObjectID, + // Tenant = tenant == null ? Tenant.DefaultTenant : tenant.Id, + Data = jsonNotifyData + }; + + _sender.Send(m); + } - return new SendResponse(message, Constants.NotifyPushSenderSysName, SendResult.OK); + return new SendResponse(message, Constants.NotifyPushSenderSysName, result); } catch (Exception error) { diff --git a/common/ASC.Core.Common/Notify/Senders/PushSender.cs b/common/ASC.Core.Common/Notify/Senders/PushSender.cs new file mode 100644 index 0000000000..f2a99816eb --- /dev/null +++ b/common/ASC.Core.Common/Notify/Senders/PushSender.cs @@ -0,0 +1,64 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +namespace ASC.Core.Notify.Senders; + +[Singletone] +public class PushSender : INotifySender +{ + private readonly ILogger _logger; + private readonly IServiceProvider _serviceProvider; + + public PushSender(ILoggerProvider options, IServiceProvider serviceProvider) + { + _logger = options.CreateLogger("ASC"); + _serviceProvider = serviceProvider; + } + + + public void Init(IDictionary properties) { } + + public NoticeSendResult Send(NotifyMessage m) + { + if (!string.IsNullOrEmpty(m.Content)) + { + m.Content = m.Content.Replace("\r\n", "\n").Trim('\n', '\r', ' '); + m.Content = Regex.Replace(m.Content, "\n{3,}", "\n\n"); + } + try + { + using var scope = _serviceProvider.CreateScope(); + var TelegramHelper = scope.ServiceProvider.GetService(); + TelegramHelper.SendMessage(m); + } + catch (Exception e) + { + _logger.ErrorUnexpected(e); + } + + return NoticeSendResult.OK; + } +} From 14404198c2c8d6f94302a04c041aa756167b63b3 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Mon, 27 Jun 2022 13:36:38 +0300 Subject: [PATCH 04/30] Push: fixed a sender sink --- common/ASC.Core.Common/Context/WorkContext.cs | 1 + .../ASC.Core.Common/Notify/PushSenderSink.cs | 149 ++++++++++-------- .../Notify/Senders/PushSender.cs | 4 +- .../Services/NotifyService/NotifyClient.cs | 6 +- .../Core/Services/NotifyService/patterns.xml | 5 + 5 files changed, 98 insertions(+), 67 deletions(-) diff --git a/common/ASC.Core.Common/Context/WorkContext.cs b/common/ASC.Core.Common/Context/WorkContext.cs index 65d35eb0ae..f54d5d77a8 100644 --- a/common/ASC.Core.Common/Context/WorkContext.cs +++ b/common/ASC.Core.Common/Context/WorkContext.cs @@ -205,6 +205,7 @@ public static class WorkContextExtension dIHelper.TryAdd(); dIHelper.TryAdd(); dIHelper.TryAdd(); + dIHelper.TryAdd(); dIHelper.TryAdd(); } } diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index eb03c39cef..5f7ce5362a 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -48,78 +48,18 @@ class PushSenderSink : Sink { try { - - using var scope = _serviceProvider.CreateScope(); var result = SendResult.OK; - var tenantManager = scope.ServiceProvider.GetService(); - var userManager = scope.ServiceProvider.GetService(); - var user = userManager.GetUsers(new Guid(message.Recipient.ID)); - var username = user.UserName; + using var scope = _serviceProvider.CreateScope(); - if (string.IsNullOrEmpty(username)) + var m = scope.ServiceProvider.GetRequiredService().CreateNotifyMessage(message, _senderName); + if (string.IsNullOrEmpty(m.Reciever)) { result = SendResult.IncorrectRecipient; } else { - var fromTag = message.Arguments.FirstOrDefault(x => x.Tag.Equals("MessageFrom")); - var productID = message.Arguments.FirstOrDefault(x => x.Tag.Equals("__ProductID")); - var originalUrl = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentURL")); - - var folderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderId")); - var rootFolderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderParentId")); - var rootFolderType = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderRootFolderType")); - - - var notifyData = new NotifyData() - { - Email = user.Email, - Portal = tenantManager.GetCurrentTenant().TrustedDomains.FirstOrDefault(), - OriginalUrl = originalUrl != null && originalUrl.Value != null ? originalUrl.Value.ToString() : "", - Folder = new NotifyFolderData - { - Id = folderId != null && folderId.Value != null ? folderId.Value.ToString() : "", - ParentId = rootFolderId != null && rootFolderId.Value != null ? rootFolderId.Value.ToString() : "", - RootFolderType = rootFolderType != null && rootFolderType.Value != null ? (int)rootFolderType.Value : 0 - }, - }; - - var msg = (NoticeMessage)message; - - if (msg.ObjectID.StartsWith("file_")) - { - var documentTitle = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentTitle")); - var documentExtension = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentExtension")); - - notifyData.File = new NotifyFileData() - { - Id = msg.ObjectID.Substring(5), - Title = documentTitle != null && documentTitle.Value != null ? documentTitle.Value.ToString() : "", - Extension = documentExtension != null && documentExtension.Value != null ? documentExtension.Value.ToString() : "" - - }; - } - - var jsonNotifyData = JsonConvert.SerializeObject(notifyData); - var tenant = tenantManager.GetCurrentTenant(false); - - var m = new NotifyMessage - { - // To = username, - Subject = fromTag != null && fromTag.Value != null ? fromTag.Value.ToString() : message.Subject, - ContentType = message.ContentType, - Content = message.Body, - Sender = Constants.NotifyPushSenderSysName, - CreationDate = DateTime.UtcNow, - ProductID = fromTag != null && fromTag.Value != null ? productID.Value.ToString() : null, - ObjectID = msg.ObjectID, - // Tenant = tenant == null ? Tenant.DefaultTenant : tenant.Id, - Data = jsonNotifyData - }; - _sender.Send(m); - } return new SendResponse(message, Constants.NotifyPushSenderSysName, result); @@ -137,3 +77,86 @@ class PushSenderSink : Sink return tag != null ? (T)tag.Value : default; } } + +[Scope] +public class PushSenderSinkMessageCreator : SinkMessageCreator +{ + private readonly UserManager _userManager; + private readonly TenantManager _tenantManager; + + public PushSenderSinkMessageCreator(UserManager userManager, TenantManager tenantManager) + { + _tenantManager = tenantManager; + _userManager = userManager; + } + + public override NotifyMessage CreateNotifyMessage(INoticeMessage message, string senderName) + { + var tenant = _tenantManager.GetCurrentTenant(false); + if (tenant == null) + { + _tenantManager.SetCurrentTenant(Tenant.DefaultTenant); + tenant = _tenantManager.GetCurrentTenant(false); + } + + var user = _userManager.GetUsers(new Guid(message.Recipient.ID)); + var username = user.UserName; + + var fromTag = message.Arguments.FirstOrDefault(x => x.Tag.Equals("MessageFrom")); + var productID = message.Arguments.FirstOrDefault(x => x.Tag.Equals("__ProductID")); + var originalUrl = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentURL")); + + var folderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderId")); + var rootFolderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderParentId")); + var rootFolderType = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderRootFolderType")); + + + var notifyData = new NotifyData() + { + Email = user.Email, + Portal = _tenantManager.GetCurrentTenant().TrustedDomains.FirstOrDefault(), + OriginalUrl = originalUrl != null && originalUrl.Value != null ? originalUrl.Value.ToString() : "", + Folder = new NotifyFolderData + { + Id = folderId != null && folderId.Value != null ? folderId.Value.ToString() : "", + ParentId = rootFolderId != null && rootFolderId.Value != null ? rootFolderId.Value.ToString() : "", + RootFolderType = rootFolderType != null && rootFolderType.Value != null ? (int)rootFolderType.Value : 0 + }, + }; + + var msg = (NoticeMessage)message; + + if (msg.ObjectID.StartsWith("file_")) + { + var documentTitle = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentTitle")); + var documentExtension = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentExtension")); + + notifyData.File = new NotifyFileData() + { + Id = msg.ObjectID.Substring(5), + Title = documentTitle != null && documentTitle.Value != null ? documentTitle.Value.ToString() : "", + Extension = documentExtension != null && documentExtension.Value != null ? documentExtension.Value.ToString() : "" + + }; + } + + var jsonNotifyData = JsonConvert.SerializeObject(notifyData); + + var m = new NotifyMessage + { + Reciever = username, + Subject = fromTag != null && fromTag.Value != null ? fromTag.Value.ToString() : message.Subject, + ContentType = message.ContentType, + Content = message.Body, + Sender = Constants.NotifyPushSenderSysName, + CreationDate = DateTime.UtcNow, + ProductID = fromTag != null && fromTag.Value != null ? productID.Value.ToString() : null, + ObjectID = msg.ObjectID, + //Tenant = tenant == null ? Tenant.DefaultTenant : tenant.Id, + Data = jsonNotifyData + }; + + + return m; + } +} diff --git a/common/ASC.Core.Common/Notify/Senders/PushSender.cs b/common/ASC.Core.Common/Notify/Senders/PushSender.cs index f2a99816eb..ff32607bc7 100644 --- a/common/ASC.Core.Common/Notify/Senders/PushSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/PushSender.cs @@ -51,8 +51,8 @@ public class PushSender : INotifySender try { using var scope = _serviceProvider.CreateScope(); - var TelegramHelper = scope.ServiceProvider.GetService(); - TelegramHelper.SendMessage(m); + var FirebaseHelper = scope.ServiceProvider.GetService(); + FirebaseHelper.SendMessage(m); } catch (Exception e) { diff --git a/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs b/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs index 8769fc2586..05284e6bcd 100644 --- a/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs +++ b/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs @@ -172,7 +172,8 @@ public class NotifyClient new TagValue(NotifyConstants.TagDocumentUrl, _baseCommonLinkUtility.GetFullAbsolutePath(url)), new TagValue(NotifyConstants.TagAccessRights, aceString), new TagValue(NotifyConstants.TagMessage, message.HtmlEncode()), - TagValues.Image(_studioNotifyHelper, 0, "privacy.png") + TagValues.Image(_studioNotifyHelper, 0, "privacy.png"), + new AdditionalSenderTag("push.sender") ); } } @@ -201,7 +202,8 @@ public class NotifyClient true, new TagValue(NotifyConstants.TagDocumentTitle, file.Title), new TagValue(NotifyConstants.TagDocumentUrl, _baseCommonLinkUtility.GetFullAbsolutePath(documentUrl)), - new TagValue(NotifyConstants.TagMessage, message.HtmlEncode()) + new TagValue(NotifyConstants.TagMessage, message.HtmlEncode()), + new AdditionalSenderTag("push.sender") ); } } diff --git a/products/ASC.Files/Core/Services/NotifyService/patterns.xml b/products/ASC.Files/Core/Services/NotifyService/patterns.xml index ae89ef63d4..81e1f7929e 100644 --- a/products/ASC.Files/Core/Services/NotifyService/patterns.xml +++ b/products/ASC.Files/Core/Services/NotifyService/patterns.xml @@ -51,6 +51,10 @@ $Message + + + + $__AuthorName @@ -77,6 +81,7 @@ $DocumentURL + $__AuthorName From 273854bf845dd026872b972c80d24407a6df6390 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 5 Jul 2022 15:55:46 +0300 Subject: [PATCH 05/30] Push: fix FirebaseHelper --- .../Notify/Push/Dao/FirebaseDao.cs | 2 +- .../Notify/Push/FirebaseHelper.cs | 50 +++++++++++-------- .../ASC.Core.Common/Notify/PushSenderSink.cs | 2 +- .../Notify/Senders/PushSender.cs | 9 +++- .../FilesPatternResource.Designer.cs | 21 +++++--- .../NotifyService/FilesPatternResource.resx | 3 ++ .../Core/Services/NotifyService/patterns.xml | 4 +- 7 files changed, 60 insertions(+), 31 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs index 60877dbb8d..b4371cdfa9 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -30,7 +30,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ASC.Core.Common.Notify.Push.Dao; +namespace ASC.Core.Common.Notify.Push; [Scope] diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index b537b13f64..e5db437f50 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -24,12 +24,6 @@ // content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - using ASC.Core.Common.Notify.Push.Dao; using FirebaseAdmin; @@ -43,31 +37,47 @@ namespace ASC.Core.Common.Notify.Push; public class FirebaseHelper { protected readonly UserManager _userManager; - private readonly ILogger _logger; + private readonly TenantManager _tenantManager; + private readonly ILogger _logger; private readonly IConfiguration _configuration; + private readonly FirebaseDao _firebaseDao; public FirebaseHelper( UserManager userManager, + TenantManager tenantManager, IConfiguration configuration, - ILogger logger) + ILogger logger, + FirebaseDao firebaseDao) { _userManager = userManager; + _tenantManager = tenantManager; _configuration = configuration; _logger = logger; + _firebaseDao = firebaseDao; + + var credentials = JsonConvert.SerializeObject(new FirebaseApiKey(_configuration)).Replace("\\\\", "\\"); + var defaultInstance = FirebaseApp.DefaultInstance; + if (defaultInstance == null) + { + FirebaseApp.Create(new AppOptions() + { + Credential = GoogleCredential.FromJson(credentials) + }); + } + _firebaseDao = firebaseDao; } - private FirebaseHelper() - { - FirebaseApp.Create(new AppOptions() - { - Credential = GoogleCredential.FromJson(JsonConvert.SerializeObject(new FirebaseApiKey(_configuration)).Replace("\\\\", "\\")) - }); - } public void SendMessage(NotifyMessage msg) { var data = new Dictionary(); - var user = _userManager.GetUserByUserName(msg.ReplyTo); - var fbDao = new FirebaseDao(); + + var tenant = _tenantManager.GetCurrentTenant(false); + + if (tenant == null) + { + _tenantManager.SetCurrentTenant(1); + } + var user = _userManager.GetUserByUserName(msg.Reciever); Guid productID; @@ -77,12 +87,12 @@ public class FirebaseHelper if (productID == new Guid("{E67BE73D-F9AE-4ce1-8FEC-1880CB518CB4}")) //documents product { - fireBaseUser = fbDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushDocAppName); + fireBaseUser = _firebaseDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushDocAppName); } if (productID == new Guid("{1e044602-43b5-4d79-82f3-fd6208a11960}")) //projects product { - fireBaseUser = fbDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushProjAppName); + fireBaseUser = _firebaseDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushProjAppName); } foreach (var fb in fireBaseUser) @@ -100,7 +110,7 @@ public class FirebaseHelper Body = msg.Content } }; - FirebaseMessaging.DefaultInstance.SendAsync(m); + var result = FirebaseMessaging.DefaultInstance.SendAsync(m).Result; } } } diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index 5f7ce5362a..e32e82df12 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -144,6 +144,7 @@ public class PushSenderSinkMessageCreator : SinkMessageCreator var m = new NotifyMessage { + TenantId = tenant.Id, Reciever = username, Subject = fromTag != null && fromTag.Value != null ? fromTag.Value.ToString() : message.Subject, ContentType = message.ContentType, @@ -152,7 +153,6 @@ public class PushSenderSinkMessageCreator : SinkMessageCreator CreationDate = DateTime.UtcNow, ProductID = fromTag != null && fromTag.Value != null ? productID.Value.ToString() : null, ObjectID = msg.ObjectID, - //Tenant = tenant == null ? Tenant.DefaultTenant : tenant.Id, Data = jsonNotifyData }; diff --git a/common/ASC.Core.Common/Notify/Senders/PushSender.cs b/common/ASC.Core.Common/Notify/Senders/PushSender.cs index ff32607bc7..9d2c3aa31a 100644 --- a/common/ASC.Core.Common/Notify/Senders/PushSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/PushSender.cs @@ -26,7 +26,7 @@ namespace ASC.Core.Notify.Senders; -[Singletone] +[Singletone(Additional = typeof(FirebaseSenderExtension))] public class PushSender : INotifySender { private readonly ILogger _logger; @@ -62,3 +62,10 @@ public class PushSender : INotifySender return NoticeSendResult.OK; } } +public static class FirebaseSenderExtension +{ + public static void Register(DIHelper services) + { + services.TryAdd(); + } +} diff --git a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs index d526ceb4a4..95a541d810 100644 --- a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs +++ b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs @@ -61,7 +61,7 @@ namespace ASC.Files.Core.Services.NotifyService { } /// - /// Looks up a localized string similar to h1. All signers completed $DocumentTitle + /// Looks up a localized string similar to h1. All signers completed $DocumentTitle /// ///This is an email notification to inform you that all signers completed "$DocumentTitle":"$DocumentURL". /// @@ -74,7 +74,7 @@ namespace ASC.Files.Core.Services.NotifyService { } /// - /// Looks up a localized string similar to h1. $Message: $DocumentTitle + /// Looks up a localized string similar to h1. $Message: $DocumentTitle /// ///Sign in to your DocuSign account for more information. /// @@ -87,7 +87,7 @@ namespace ASC.Files.Core.Services.NotifyService { } /// - /// Looks up a localized string similar to h1. "$__AuthorName":"$__AuthorUrl" mentioned you in the document comment + /// Looks up a localized string similar to h1. "$__AuthorName":"$__AuthorUrl" mentioned you in the document comment /// ///This is a mail message to notify that you have been mentioned by "$__AuthorName":"$__AuthorUrl" in the comment to the "$DocumentTitle":"$DocumentURL" document: /// @@ -102,7 +102,7 @@ namespace ASC.Files.Core.Services.NotifyService { } /// - /// Looks up a localized string similar to h1. Mailing completed + /// Looks up a localized string similar to h1. Mailing completed /// ///This is an email notification to inform you that you have requested the mailing of $MailsCount messages and the process is now complete. $Message /// @@ -117,7 +117,7 @@ namespace ASC.Files.Core.Services.NotifyService { } /// - /// Looks up a localized string similar to h1. Access granted to document: "$DocumentTitle":"$DocumentURL" + /// Looks up a localized string similar to h1. Access granted to document: "$DocumentTitle":"$DocumentURL" /// ///$__DateTime "$__AuthorName":"$__AuthorUrl" granted you the access to the "$DocumentTitle":"$DocumentURL" document with the following access rights: "$AccessRights". /// @@ -130,7 +130,7 @@ namespace ASC.Files.Core.Services.NotifyService { } /// - /// Looks up a localized string similar to h1. Access granted to folder: "$DocumentTitle":"$DocumentURL" + /// Looks up a localized string similar to h1. Access granted to folder: "$DocumentTitle":"$DocumentURL" /// ///$__DateTime "$__AuthorName":"$__AuthorUrl" granted you the access to the "$DocumentTitle":"$DocumentURL" folder with the following access rights: "$AccessRights". /// @@ -212,6 +212,15 @@ namespace ASC.Files.Core.Services.NotifyService { } } + /// + /// Looks up a localized string similar to Documents. Access granted to document: [$DocumentTitle]($DocumentURL). + /// + public static string subject_ShareDocument_push { + get { + return ResourceManager.GetString("subject_ShareDocument_push", resourceCulture); + } + } + /// /// Looks up a localized string similar to Documents. Access granted to document: [$DocumentTitle]($DocumentURL). /// diff --git a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx index eeb3b47377..364db2fc8c 100644 --- a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx +++ b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx @@ -135,4 +135,7 @@ $Message patterns.xml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Access granted to document: $DocumentTitle + \ No newline at end of file diff --git a/products/ASC.Files/Core/Services/NotifyService/patterns.xml b/products/ASC.Files/Core/Services/NotifyService/patterns.xml index 81e1f7929e..83881bfc6e 100644 --- a/products/ASC.Files/Core/Services/NotifyService/patterns.xml +++ b/products/ASC.Files/Core/Services/NotifyService/patterns.xml @@ -52,8 +52,8 @@ $Message - - + + From 393282ea92f87bc6e18ed17d5a0f7d2d10bcfef0 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 5 Jul 2022 16:40:16 +0300 Subject: [PATCH 06/30] Push: resources --- .../FilesPatternResource.Designer.cs | 54 +++++++++++++++++++ .../NotifyService/FilesPatternResource.resx | 18 +++++++ 2 files changed, 72 insertions(+) diff --git a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs index 95a541d810..d0b4d96892 100644 --- a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs +++ b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.Designer.cs @@ -167,6 +167,15 @@ namespace ASC.Files.Core.Services.NotifyService { } } + /// + /// Looks up a localized string similar to All signers completed $DocumentTitle. + /// + public static string subject_DocuSignComplete_push { + get { + return ResourceManager.GetString("subject_DocuSignComplete_push", resourceCulture); + } + } + /// /// Looks up a localized string similar to Documents. All signers completed [$DocumentTitle]($DocumentURL). /// @@ -185,6 +194,15 @@ namespace ASC.Files.Core.Services.NotifyService { } } + /// + /// Looks up a localized string similar to Sign status changed. + /// + public static string subject_DocuSignStatus_push { + get { + return ResourceManager.GetString("subject_DocuSignStatus_push", resourceCulture); + } + } + /// /// Looks up a localized string similar to Documents. Mentioned in document. /// @@ -194,6 +212,15 @@ namespace ASC.Files.Core.Services.NotifyService { } } + /// + /// Looks up a localized string similar to Mentioned in document. + /// + public static string subject_EditorMentions_push { + get { + return ResourceManager.GetString("subject_EditorMentions_push", resourceCulture); + } + } + /// /// Looks up a localized string similar to Documents. Mailing is complete.. /// @@ -203,6 +230,15 @@ namespace ASC.Files.Core.Services.NotifyService { } } + /// + /// Looks up a localized string similar to Mailing is complete.. + /// + public static string subject_MailMergeEnd_push { + get { + return ResourceManager.GetString("subject_MailMergeEnd_push", resourceCulture); + } + } + /// /// Looks up a localized string similar to Documents. Access granted to document: $DocumentTitle. /// @@ -230,6 +266,15 @@ namespace ASC.Files.Core.Services.NotifyService { } } + /// + /// Looks up a localized string similar to Access granted to the encrypted document: $DocumentTitle. + /// + public static string subject_ShareEncryptedDocument_push { + get { + return ResourceManager.GetString("subject_ShareEncryptedDocument_push", resourceCulture); + } + } + /// /// Looks up a localized string similar to Documents. Access granted to folder: $DocumentTitle. /// @@ -239,6 +284,15 @@ namespace ASC.Files.Core.Services.NotifyService { } } + /// + /// Looks up a localized string similar to Access granted to folder: $DocumentTitle. + /// + public static string subject_ShareFolder_push { + get { + return ResourceManager.GetString("subject_ShareFolder_push", resourceCulture); + } + } + /// /// Looks up a localized string similar to Documents. Access granted to folder: [$DocumentTitle]($DocumentURL). /// diff --git a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx index 364db2fc8c..9a7484cfc7 100644 --- a/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx +++ b/products/ASC.Files/Core/Services/NotifyService/FilesPatternResource.resx @@ -138,4 +138,22 @@ $Message Access granted to document: $DocumentTitle + + All signers completed $DocumentTitle + + + Sign status changed + + + Mentioned in document + + + Mailing is complete. + + + Access granted to the encrypted document: $DocumentTitle + + + Access granted to folder: $DocumentTitle + \ No newline at end of file From cac16ace79c4ca773de11db893609a85a0bb2529 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Thu, 7 Jul 2022 14:46:35 +0300 Subject: [PATCH 07/30] Push: api --- .../Notify/Push/Dao/FirebaseDao.cs | 3 -- .../Notify/Push/FirebaseHelper.cs | 12 ++++++- .../Api/Settings/SettingsController.cs | 29 +++++++++++++++- .../RequestsDto/FirebaseRequestsDto.cs | 33 +++++++++++++++++++ 4 files changed, 72 insertions(+), 5 deletions(-) create mode 100644 web/ASC.Web.Api/ApiModels/RequestsDto/FirebaseRequestsDto.cs diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs index b4371cdfa9..6c73664da0 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -85,7 +85,6 @@ public class FirebaseDao public FireBaseUser UpdateUser(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) { - var user = new FireBaseUser { UserId = userId, @@ -98,9 +97,7 @@ public class FirebaseDao FirebaseDbContext.Update(user); FirebaseDbContext.SaveChanges(); - return user; } - } diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index e5db437f50..1399481604 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -55,6 +55,7 @@ public class FirebaseHelper _logger = logger; _firebaseDao = firebaseDao; + var credentials = JsonConvert.SerializeObject(new FirebaseApiKey(_configuration)).Replace("\\\\", "\\"); var defaultInstance = FirebaseApp.DefaultInstance; if (defaultInstance == null) @@ -64,7 +65,6 @@ public class FirebaseHelper Credential = GoogleCredential.FromJson(credentials) }); } - _firebaseDao = firebaseDao; } public void SendMessage(NotifyMessage msg) @@ -114,4 +114,14 @@ public class FirebaseHelper } } } + + public FireBaseUser RegisterUserDevice(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) + { + return _firebaseDao.RegisterUserDevice(userId, tenantId, fbDeviceToken, isSubscribed, application); + } + + public FireBaseUser UpdateUser(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) + { + return _firebaseDao.UpdateUser(userId, tenantId, fbDeviceToken, isSubscribed, application); + } } diff --git a/web/ASC.Web.Api/Api/Settings/SettingsController.cs b/web/ASC.Web.Api/Api/Settings/SettingsController.cs index 65f50b3273..94a1d9af80 100644 --- a/web/ASC.Web.Api/Api/Settings/SettingsController.cs +++ b/web/ASC.Web.Api/Api/Settings/SettingsController.cs @@ -25,6 +25,7 @@ // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode using Constants = ASC.Core.Users.Constants; +using FireBaseUser = ASC.Core.Common.EF.FireBaseUser; namespace ASC.Web.Api.Controllers.Settings; public class SettingsController : BaseSettingsController @@ -58,6 +59,7 @@ public class SettingsController : BaseSettingsController private readonly PasswordHasher _passwordHasher; private readonly ILogger _log; private readonly TelegramHelper _telegramHelper; + private readonly FirebaseHelper _firebaseHelper; private readonly Constants _constants; private readonly DnsSettings _dnsSettings; @@ -90,6 +92,7 @@ public class SettingsController : BaseSettingsController ProviderManager providerManager, FirstTimeTenantSettings firstTimeTenantSettings, TelegramHelper telegramHelper, + FirebaseHelper firebaseHelper, UrlShortener urlShortener, PasswordHasher passwordHasher, Constants constants, @@ -124,6 +127,7 @@ public class SettingsController : BaseSettingsController _passwordHasher = passwordHasher; _urlShortener = urlShortener; _telegramHelper = telegramHelper; + _firebaseHelper = firebaseHelper; _constants = constants; _dnsSettings = dnsSettings; } @@ -688,6 +692,29 @@ public class SettingsController : BaseSettingsController public void TelegramDisconnect() { _telegramHelper.Disconnect(_authContext.CurrentAccount.ID, Tenant.Id); - } + } + + [HttpPost("push/docregisterdevice")] + public FireBaseUser DocRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) + { + return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); + } + + [HttpPost("push/projregisterdevice")] + public FireBaseUser ProjRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) + { + return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); + } + + [HttpPut("push/docsubscribe")] + public FireBaseUser SubscribeDocumentsPushNotification(FirebaseRequestsDto inDto) + { + return _firebaseHelper.UpdateUser(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); + } + [HttpPut("push/projsubscribe")] + public FireBaseUser SubscribeProjectsPushNotification(FirebaseRequestsDto inDto) + { + return _firebaseHelper.UpdateUser(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushProjAppName); + } } \ No newline at end of file diff --git a/web/ASC.Web.Api/ApiModels/RequestsDto/FirebaseRequestsDto.cs b/web/ASC.Web.Api/ApiModels/RequestsDto/FirebaseRequestsDto.cs new file mode 100644 index 0000000000..f2ab6f5e77 --- /dev/null +++ b/web/ASC.Web.Api/ApiModels/RequestsDto/FirebaseRequestsDto.cs @@ -0,0 +1,33 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +namespace ASC.Web.Api.ApiModels.RequestsDto; + +public class FirebaseRequestsDto +{ + public string FirebaseDeviceToken { get; set; } + public bool IsSubscribed { get; set; } +} From 47371fc82dc7a9ae8914c5f14db2fb457d7c2d24 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Thu, 7 Jul 2022 16:58:59 +0300 Subject: [PATCH 08/30] Push: api --- .../Api/Settings/SettingsController.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/web/ASC.Web.Api/Api/Settings/SettingsController.cs b/web/ASC.Web.Api/Api/Settings/SettingsController.cs index 94a1d9af80..ded1c9769a 100644 --- a/web/ASC.Web.Api/Api/Settings/SettingsController.cs +++ b/web/ASC.Web.Api/Api/Settings/SettingsController.cs @@ -694,24 +694,39 @@ public class SettingsController : BaseSettingsController _telegramHelper.Disconnect(_authContext.CurrentAccount.ID, Tenant.Id); } + /// + /// Saves a documents firebase device token specified in the request. + /// + /// FireBase user [HttpPost("push/docregisterdevice")] public FireBaseUser DocRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) { return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); } + /// + /// Saves a projects firebase device token specified in the request. + /// + /// FireBase user [HttpPost("push/projregisterdevice")] public FireBaseUser ProjRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) { return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); } + /// + /// Subscribe to documents push notification. + /// + /// FireBase user [HttpPut("push/docsubscribe")] public FireBaseUser SubscribeDocumentsPushNotification(FirebaseRequestsDto inDto) { return _firebaseHelper.UpdateUser(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); } - + /// + /// Subscribe to projects push notification. + /// + /// FireBase user [HttpPut("push/projsubscribe")] public FireBaseUser SubscribeProjectsPushNotification(FirebaseRequestsDto inDto) { From 46caff0b0c005b4eb650bf6aefd49fc2e016371c Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Mon, 15 Aug 2022 01:00:11 +0300 Subject: [PATCH 09/30] Push: post merge fixes --- common/ASC.Api.Core/Core/BaseStartup.cs | 1 + common/ASC.Core.Common/ASC.Core.Common.csproj | 2 +- .../EF/Context/FirebaseDbContext.cs | 30 +++---------------- .../Notify/Push/Dao/FirebaseDao.cs | 23 +++++++------- .../Notify/Push/FirebaseHelper.cs | 13 ++++++-- .../ASC.Core.Common/Notify/PushSenderSink.cs | 2 +- common/Tools/ASC.Migration.Runner/Program.cs | 1 + 7 files changed, 30 insertions(+), 42 deletions(-) diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 3e2a8be3dc..b51413d22a 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -65,6 +65,7 @@ public abstract class BaseStartup services.AddBaseDbContextPool(); services.AddBaseDbContextPool(); services.AddBaseDbContextPool(); + services.AddBaseDbContextPool(); services.AddBaseDbContextPool(); services.AddBaseDbContextPool(); services.AddBaseDbContextPool(); diff --git a/common/ASC.Core.Common/ASC.Core.Common.csproj b/common/ASC.Core.Common/ASC.Core.Common.csproj index 7206d4af46..ff6a6ca53f 100644 --- a/common/ASC.Core.Common/ASC.Core.Common.csproj +++ b/common/ASC.Core.Common/ASC.Core.Common.csproj @@ -50,8 +50,8 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs b/common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs index f5e1eae6fb..d4f0af1281 100644 --- a/common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/FirebaseDbContext.cs @@ -25,42 +25,20 @@ // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode namespace ASC.Core.Common.EF.Context; -public class MySqlFirebaseDbContext : FirebaseDbContext { } -public class PostgreSqlFirebaseDbContext : FirebaseDbContext { } -public class FirebaseDbContext : BaseDbContext +public class FirebaseDbContext : DbContext { + public DbSet Users { get; set; } - public FirebaseDbContext() { } - public FirebaseDbContext(DbContextOptions options) - : base(options) + public FirebaseDbContext(DbContextOptions options) : base(options) { - } - protected override Dictionary> ProviderContext - { - get - { - return new Dictionary>() - { - { Provider.MySql, () => new MySqlFirebaseDbContext() } , - { Provider.PostgreSql, () => new PostgreSqlFirebaseDbContext() } , - }; - } } protected override void OnModelCreating(ModelBuilder modelBuilder) { ModelBuilderWrapper - .From(modelBuilder, _provider) + .From(modelBuilder, Database) .AddFireBaseUsers(); } } - -public static class FirebaseDbContextExtension -{ - public static DIHelper AddFirebaseDbContextService(this DIHelper services) - { - return services.AddDbContextManagerService(); - } -} diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs index 6c73664da0..c750bdac2e 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -36,18 +36,17 @@ namespace ASC.Core.Common.Notify.Push; [Scope] public class FirebaseDao { - public FirebaseDbContext FirebaseDbContext { get; set; } - public FirebaseDao() { } + private readonly IDbContextFactory _dbContextFactory; - public FirebaseDao(DbContextManager dbContextManager) + public FirebaseDao(IDbContextFactory dbContextFactory) { - FirebaseDbContext = dbContextManager.Value; + _dbContextFactory = dbContextFactory; } public FireBaseUser RegisterUserDevice(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) { - - var count = FirebaseDbContext.Users + using var dbContext = _dbContextFactory.CreateDbContext(); + var count = dbContext.Users .AsNoTracking() .Where(r => r.UserId == userId) .Where(r => r.TenantId == tenantId) @@ -66,8 +65,8 @@ public class FirebaseDao if (count == 0) { - FirebaseDbContext.AddOrUpdate(r => r.Users, user); - FirebaseDbContext.SaveChanges(); + dbContext.AddOrUpdate(r => r.Users, user); + dbContext.SaveChanges(); } return user; @@ -75,7 +74,8 @@ public class FirebaseDao public List GetUserDeviceTokens(Guid userId, int tenantId, string application) { - return FirebaseDbContext.Users + using var dbContext = _dbContextFactory.CreateDbContext(); + return dbContext.Users .AsNoTracking() .Where(r => r.UserId == userId) .Where(r => r.TenantId == tenantId) @@ -85,6 +85,7 @@ public class FirebaseDao public FireBaseUser UpdateUser(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) { + using var dbContext = _dbContextFactory.CreateDbContext(); var user = new FireBaseUser { UserId = userId, @@ -94,8 +95,8 @@ public class FirebaseDao Application = application }; - FirebaseDbContext.Update(user); - FirebaseDbContext.SaveChanges(); + dbContext.Update(user); + dbContext.SaveChanges(); return user; } diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 1399481604..f091894196 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -60,10 +60,17 @@ public class FirebaseHelper var defaultInstance = FirebaseApp.DefaultInstance; if (defaultInstance == null) { - FirebaseApp.Create(new AppOptions() + try { - Credential = GoogleCredential.FromJson(credentials) - }); + FirebaseApp.Create(new AppOptions() + { + Credential = GoogleCredential.FromJson(credentials) + }); + } + catch (Exception e) + { + _logger.ErrorUnexpected(e); + } } } diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index e32e82df12..0dd1b3585a 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -95,7 +95,7 @@ public class PushSenderSinkMessageCreator : SinkMessageCreator var tenant = _tenantManager.GetCurrentTenant(false); if (tenant == null) { - _tenantManager.SetCurrentTenant(Tenant.DefaultTenant); + tenantManager.SetCurrentTenant(Tenant.DefaultTenant); tenant = _tenantManager.GetCurrentTenant(false); } diff --git a/common/Tools/ASC.Migration.Runner/Program.cs b/common/Tools/ASC.Migration.Runner/Program.cs index a31f647aa0..debe36b179 100644 --- a/common/Tools/ASC.Migration.Runner/Program.cs +++ b/common/Tools/ASC.Migration.Runner/Program.cs @@ -45,6 +45,7 @@ builder.WebHost.ConfigureServices((hostContext, services) => services.AddBaseDbContext(); services.AddBaseDbContext(); services.AddBaseDbContext(); + services.AddBaseDbContext(); services.AddBaseDbContext(); services.AddBaseDbContext(); services.AddBaseDbContext(); From ce5009d0c6224933c4048f5c86d055bea5e00864 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Mon, 15 Aug 2022 14:27:54 +0300 Subject: [PATCH 10/30] Push: fixes --- common/ASC.Core.Common/EF/FireBaseUser.cs | 6 ------ .../Notify/Push/Dao/FirebaseDao.cs | 6 ------ .../Notify/Push/FirebaseHelper.cs | 9 +++++---- .../ASC.Core.Common/Notify/PushSenderSink.cs | 2 +- .../Notify/Senders/PushSender.cs | 2 +- .../Services/NotifyService/NotifyClient.cs | 20 +++++++++++++++++++ .../Services/NotifyService/NotifyConstants.cs | 3 +++ .../Core/Services/NotifyService/patterns.xml | 11 ++++++++++ 8 files changed, 41 insertions(+), 18 deletions(-) diff --git a/common/ASC.Core.Common/EF/FireBaseUser.cs b/common/ASC.Core.Common/EF/FireBaseUser.cs index 4ce05ae354..9c3e2b6512 100644 --- a/common/ASC.Core.Common/EF/FireBaseUser.cs +++ b/common/ASC.Core.Common/EF/FireBaseUser.cs @@ -24,12 +24,6 @@ // content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace ASC.Core.Common.EF; public class FireBaseUser : BaseEntity diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs index c750bdac2e..ad6bc0ab9e 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -24,12 +24,6 @@ // content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace ASC.Core.Common.Notify.Push; diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index f091894196..23e0ff8432 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -76,8 +76,6 @@ public class FirebaseHelper public void SendMessage(NotifyMessage msg) { - var data = new Dictionary(); - var tenant = _tenantManager.GetCurrentTenant(false); if (tenant == null) @@ -88,7 +86,10 @@ public class FirebaseHelper Guid productID; - if (!Guid.TryParse(msg.ProductID, out productID)) return; + if (!Guid.TryParse(msg.ProductID, out productID)) + { + return; + } var fireBaseUser = new List(); @@ -117,7 +118,7 @@ public class FirebaseHelper Body = msg.Content } }; - var result = FirebaseMessaging.DefaultInstance.SendAsync(m).Result; + FirebaseMessaging.DefaultInstance.SendAsync(m); } } } diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index 0dd1b3585a..2c6e5fea4f 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -106,7 +106,7 @@ public class PushSenderSinkMessageCreator : SinkMessageCreator var productID = message.Arguments.FirstOrDefault(x => x.Tag.Equals("__ProductID")); var originalUrl = message.Arguments.FirstOrDefault(x => x.Tag.Equals("DocumentURL")); - var folderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderId")); + var folderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderID")); var rootFolderId = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderParentId")); var rootFolderType = message.Arguments.FirstOrDefault(x => x.Tag.Equals("FolderRootFolderType")); diff --git a/common/ASC.Core.Common/Notify/Senders/PushSender.cs b/common/ASC.Core.Common/Notify/Senders/PushSender.cs index 9d2c3aa31a..427abc673a 100644 --- a/common/ASC.Core.Common/Notify/Senders/PushSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/PushSender.cs @@ -34,7 +34,7 @@ public class PushSender : INotifySender public PushSender(ILoggerProvider options, IServiceProvider serviceProvider) { - _logger = options.CreateLogger("ASC"); + _logger = options.CreateLogger("ASC.Notify"); _serviceProvider = serviceProvider; } diff --git a/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs b/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs index 05284e6bcd..ef6d6300ae 100644 --- a/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs +++ b/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs @@ -143,6 +143,21 @@ public class NotifyClient var url = fileEntry.FileEntryType == FileEntryType.File ? _filesLinkUtility.GetFileWebPreviewUrl(_fileUtility, fileEntry.Title, fileEntry.Id) : await _pathProvider.GetFolderUrlAsync((Folder)fileEntry); + + Folder folder; + + var fileExtension = ""; + + if (fileEntry.FileEntryType == FileEntryType.File) + { + var file = (File)fileEntry; + fileExtension = file.ConvertedExtension; + folder = await folderDao.GetFolderAsync(file.ParentId); + } + else + { + folder = (Folder)fileEntry; + } var recipientsProvider = _notifySource.GetRecipientsProvider(); @@ -170,8 +185,12 @@ public class NotifyClient true, new TagValue(NotifyConstants.TagDocumentTitle, fileEntry.Title), new TagValue(NotifyConstants.TagDocumentUrl, _baseCommonLinkUtility.GetFullAbsolutePath(url)), + new TagValue(NotifyConstants.TagDocumentExtension, fileExtension), new TagValue(NotifyConstants.TagAccessRights, aceString), new TagValue(NotifyConstants.TagMessage, message.HtmlEncode()), + new TagValue(NotifyConstants.TagFolderID, folder.Id), + new TagValue(NotifyConstants.TagFolderParentId, folder.RootId), + new TagValue(NotifyConstants.TagFolderRootFolderType, folder.RootFolderType), TagValues.Image(_studioNotifyHelper, 0, "privacy.png"), new AdditionalSenderTag("push.sender") ); @@ -203,6 +222,7 @@ public class NotifyClient new TagValue(NotifyConstants.TagDocumentTitle, file.Title), new TagValue(NotifyConstants.TagDocumentUrl, _baseCommonLinkUtility.GetFullAbsolutePath(documentUrl)), new TagValue(NotifyConstants.TagMessage, message.HtmlEncode()), + new TagValue(NotifyConstants.TagFolderID, ((File)file).ParentId), new AdditionalSenderTag("push.sender") ); } diff --git a/products/ASC.Files/Core/Services/NotifyService/NotifyConstants.cs b/products/ASC.Files/Core/Services/NotifyService/NotifyConstants.cs index 0e715c63f0..81df1d90f2 100644 --- a/products/ASC.Files/Core/Services/NotifyService/NotifyConstants.cs +++ b/products/ASC.Files/Core/Services/NotifyService/NotifyConstants.cs @@ -43,8 +43,11 @@ public static class NotifyConstants #region Tags public static readonly string TagFolderID = "FolderID"; + public static readonly string TagFolderParentId = "FolderParentId"; + public static readonly string TagFolderRootFolderType = "FolderRootFolderType"; public static readonly string TagDocumentTitle = "DocumentTitle"; public static readonly string TagDocumentUrl = "DocumentURL"; + public static readonly string TagDocumentExtension = "DocumentExtension"; public static readonly string TagAccessRights = "AccessRights"; public static readonly string TagMessage = "Message"; public static readonly string TagMailsCount = "MailsCount"; diff --git a/products/ASC.Files/Core/Services/NotifyService/patterns.xml b/products/ASC.Files/Core/Services/NotifyService/patterns.xml index f81ad25612..fab5a6172d 100644 --- a/products/ASC.Files/Core/Services/NotifyService/patterns.xml +++ b/products/ASC.Files/Core/Services/NotifyService/patterns.xml @@ -82,6 +82,11 @@ $DocumentURL + + + + + $__AuthorName @@ -107,6 +112,12 @@ $Message + + + + + + $__AuthorName From 1c7d7fee77e4b38140422deec30b7fda1663218e Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 23 Aug 2022 10:42:49 +0300 Subject: [PATCH 11/30] Push: fix --- common/ASC.Core.Common/Notify/PushSenderSink.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index 2c6e5fea4f..1ce461e145 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -95,7 +95,7 @@ public class PushSenderSinkMessageCreator : SinkMessageCreator var tenant = _tenantManager.GetCurrentTenant(false); if (tenant == null) { - tenantManager.SetCurrentTenant(Tenant.DefaultTenant); + _tenantManager.SetCurrentTenant(Tenant.DefaultTenant); tenant = _tenantManager.GetCurrentTenant(false); } From c8e4ea7cecc86293a197611136da70726fe1d342 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 23 Aug 2022 12:05:09 +0300 Subject: [PATCH 12/30] Push: Newtonsoft.Json -> System.Text.Json --- common/ASC.Core.Common/Notify/PushSenderSink.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index 1ce461e145..721ff10d49 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -27,6 +27,7 @@ using ASC.Core.Common.Notify.Push.Dao; using Constants = ASC.Core.Configuration.Constants; +using JsonSerializer = System.Text.Json.JsonSerializer; namespace ASC.Core.Common.Notify; @@ -77,7 +78,11 @@ class PushSenderSink : Sink return tag != null ? (T)tag.Value : default; } } - +public class LowerCaseNamingPolicy : JsonNamingPolicy +{ + public override string ConvertName(string name) => + name.ToLower(); +} [Scope] public class PushSenderSinkMessageCreator : SinkMessageCreator { @@ -140,7 +145,13 @@ public class PushSenderSinkMessageCreator : SinkMessageCreator }; } - var jsonNotifyData = JsonConvert.SerializeObject(notifyData); + var serializeOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = new LowerCaseNamingPolicy(), + WriteIndented = true + }; + + var jsonNotifyData = JsonSerializer.Serialize(notifyData, serializeOptions); var m = new NotifyMessage { From 7f38657ce674c6f24b0b6c2cc317039742fbf70c Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 23 Aug 2022 13:10:37 +0300 Subject: [PATCH 13/30] Push: global usings --- common/ASC.Core.Common/GlobalUsings.cs | 7 ++++++- .../ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs | 1 - .../ASC.Core.Common/Notify/Push/Dao/NotifyData.cs | 1 + .../Notify/Push/Dao/NotifyFileData.cs | 1 + .../Notify/Push/Dao/NotifyFolderData.cs | 1 + .../ASC.Core.Common/Notify/Push/FirebaseHelper.cs | 13 +++---------- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/common/ASC.Core.Common/GlobalUsings.cs b/common/ASC.Core.Common/GlobalUsings.cs index dd807f9244..9f683002af 100644 --- a/common/ASC.Core.Common/GlobalUsings.cs +++ b/common/ASC.Core.Common/GlobalUsings.cs @@ -126,6 +126,8 @@ global using Autofac; global using AutoMapper; global using AutoMapper.QueryableExtensions; +global using Google.Apis.Auth.OAuth2; + global using MailKit.Security; global using Microsoft.AspNetCore.Http; @@ -161,4 +163,7 @@ global using Telegram.Bot; global using static ASC.Security.Cryptography.EmailValidationKeyProvider; -global using JsonIgnoreAttribute = System.Text.Json.Serialization.JsonIgnoreAttribute; \ No newline at end of file +global using JsonIgnoreAttribute = System.Text.Json.Serialization.JsonIgnoreAttribute; +global using FirebaseAdminMessaging = FirebaseAdmin.Messaging; +global using FirebaseApp = FirebaseAdmin.FirebaseApp; +global using AppOptions = FirebaseAdmin.AppOptions; diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs index ad6bc0ab9e..f808611e79 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -26,7 +26,6 @@ namespace ASC.Core.Common.Notify.Push; - [Scope] public class FirebaseDao { diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs index 260717e1b7..12d5b486be 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs @@ -25,6 +25,7 @@ // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode namespace ASC.Core.Common.Notify.Push.Dao; + [Serializable] public class NotifyData { diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs index 76aead5fa0..2d2dc05341 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs @@ -25,6 +25,7 @@ // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode namespace ASC.Core.Common.Notify.Push.Dao; + [Serializable] public class NotifyFileData { diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs index b8deddb206..53a0c7a001 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs @@ -25,6 +25,7 @@ // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode namespace ASC.Core.Common.Notify.Push.Dao; + public class NotifyFolderData { [JsonProperty("id")] diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 23e0ff8432..426a85d7d8 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -24,13 +24,6 @@ // content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode -using ASC.Core.Common.Notify.Push.Dao; - -using FirebaseAdmin; -using FirebaseAdmin.Messaging; - -using Google.Apis.Auth.OAuth2; - namespace ASC.Core.Common.Notify.Push; [Scope] @@ -107,18 +100,18 @@ public class FirebaseHelper { if ((bool)fb.IsSubscribed) { - var m = new FirebaseAdmin.Messaging.Message() + var m = new FirebaseAdminMessaging.Message() { Data = new Dictionary{ { "data", msg.Data } }, Token = fb.FirebaseDeviceToken, - Notification = new Notification() + Notification = new FirebaseAdminMessaging.Notification() { Body = msg.Content } }; - FirebaseMessaging.DefaultInstance.SendAsync(m); + FirebaseAdminMessaging.FirebaseMessaging.DefaultInstance.SendAsync(m); } } } From 971d4960c1501bb94bfbee3899a3acdb77cab90b Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 23 Aug 2022 13:23:00 +0300 Subject: [PATCH 14/30] Push: fix --- common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 426a85d7d8..0923f8648d 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -73,7 +73,7 @@ public class FirebaseHelper if (tenant == null) { - _tenantManager.SetCurrentTenant(1); + _tenantManager.SetCurrentTenant(Tenant.DefaultTenant); } var user = _userManager.GetUserByUserName(msg.Reciever); From 26d493f49850d3cd8e88097648c0b117a4567199 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 23 Aug 2022 14:28:42 +0300 Subject: [PATCH 15/30] Push: fix --- common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs | 3 --- common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs | 5 ----- common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs | 3 --- common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs | 3 --- common/ASC.Core.Common/Notify/PushSenderSink.cs | 2 -- 5 files changed, 16 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs b/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs index 07a1529446..ea92e48bf5 100644 --- a/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs +++ b/common/ASC.Core.Common/Notify/Messages/NotifyMessage.cs @@ -69,9 +69,6 @@ public class NotifyMessage : IMapFrom public string ProductID { get; set; } [ProtoMember(14)] - public string ObjectID { get; set; } - - [ProtoMember(15)] public string Data { get; set; } public void Mapping(Profile profile) diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs index 12d5b486be..8f6c1f64cd 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyData.cs @@ -30,22 +30,17 @@ namespace ASC.Core.Common.Notify.Push.Dao; public class NotifyData { [JsonProperty("portal")] - [DataMember(Name = "portal")] public string Portal { get; set; } [JsonProperty("email")] - [DataMember(Name = "email")] public string Email { get; set; } [JsonProperty("file")] - [DataMember(Name = "file")] public NotifyFileData File { get; set; } [JsonProperty("folder")] - [DataMember(Name = "folder")] public NotifyFolderData Folder { get; set; } [JsonProperty("originalUrl")] - [DataMember(Name = "originalUrl")] public string OriginalUrl { get; set; } } diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs index 2d2dc05341..85b3237e66 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFileData.cs @@ -30,13 +30,10 @@ namespace ASC.Core.Common.Notify.Push.Dao; public class NotifyFileData { [JsonProperty("id")] - [DataMember(Name = "id")] public string Id { get; set; } [JsonProperty("title")] - [DataMember(Name = "title")] public string Title { get; set; } [JsonProperty("extension")] - [DataMember(Name = "extension")] public string Extension { get; set; } } diff --git a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs index 53a0c7a001..f15bf22b9c 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/NotifyFolderData.cs @@ -29,12 +29,9 @@ namespace ASC.Core.Common.Notify.Push.Dao; public class NotifyFolderData { [JsonProperty("id")] - [DataMember(Name = "id")] public string Id { get; set; } [JsonProperty("parentId")] - [DataMember(Name = "parentId")] public string ParentId { get; set; } [JsonProperty("rootFolderType")] - [DataMember(Name = "rootFolderType")] public int RootFolderType { get; set; } } diff --git a/common/ASC.Core.Common/Notify/PushSenderSink.cs b/common/ASC.Core.Common/Notify/PushSenderSink.cs index 721ff10d49..43e2228b48 100644 --- a/common/ASC.Core.Common/Notify/PushSenderSink.cs +++ b/common/ASC.Core.Common/Notify/PushSenderSink.cs @@ -35,7 +35,6 @@ class PushSenderSink : Sink { private static readonly string _senderName = Constants.NotifyPushSenderSysName; private readonly INotifySender _sender; - private bool _configured = true; public PushSenderSink(INotifySender sender, IServiceProvider serviceProvider) { @@ -163,7 +162,6 @@ public class PushSenderSinkMessageCreator : SinkMessageCreator Sender = Constants.NotifyPushSenderSysName, CreationDate = DateTime.UtcNow, ProductID = fromTag != null && fromTag.Value != null ? productID.Value.ToString() : null, - ObjectID = msg.ObjectID, Data = jsonNotifyData }; From b633dcb4e679a5f042a2b02564ffb40ce89b94ce Mon Sep 17 00:00:00 2001 From: pavelbannov Date: Tue, 23 Aug 2022 17:19:21 +0300 Subject: [PATCH 16/30] update DocStore --- products/ASC.Files/Server/DocStore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Files/Server/DocStore b/products/ASC.Files/Server/DocStore index b9a3b81a25..776d5631ee 160000 --- a/products/ASC.Files/Server/DocStore +++ b/products/ASC.Files/Server/DocStore @@ -1 +1 @@ -Subproject commit b9a3b81a255ccaa6f174e7ad2dd3bf4d4911aa8f +Subproject commit 776d5631ee3e26f9f20d24415a5b7ad85d40b64d From 58b48df3ab97644849399c63b2a8c8725095d570 Mon Sep 17 00:00:00 2001 From: MaksimChegulov Date: Tue, 23 Aug 2022 17:22:50 +0300 Subject: [PATCH 17/30] Files: added folders only filter for rooms --- .../RequestDto/CreateRoomRequestDto.cs | 10 ++++++++++ .../Core/Core/Dao/TeamlabDao/FolderDao.cs | 4 ++-- .../Core/Core/Security/FileSecurity.cs | 6 +++--- .../Core/Thirdparty/IThirdPartyProviderDao.cs | 2 +- .../Server/Api/VirtualRoomsController.cs | 17 +++++++++-------- 5 files changed, 25 insertions(+), 14 deletions(-) diff --git a/products/ASC.Files/Core/ApiModels/RequestDto/CreateRoomRequestDto.cs b/products/ASC.Files/Core/ApiModels/RequestDto/CreateRoomRequestDto.cs index e104ed3d27..de9d2099c7 100644 --- a/products/ASC.Files/Core/ApiModels/RequestDto/CreateRoomRequestDto.cs +++ b/products/ASC.Files/Core/ApiModels/RequestDto/CreateRoomRequestDto.cs @@ -35,6 +35,16 @@ public enum RoomType CustomRoom = 5 } +public enum RoomFilterType +{ + FillingFormsRoomOnly = 1, + EditingRoomOnly = 2, + ReviewRoomOnly = 3, + ReadOnlyRoomOnly = 4, + CustomRoomOnly = 5, + FoldersOnly = 6, +} + public class CreateRoomRequestDto { public string Title { get; set; } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index b02ef9b8d0..20e4ca543d 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -176,7 +176,7 @@ internal class FolderDao : AbstractDao, IFolderDao var filter = GetRoomTypeFilter(filterType); var searchByTags = tags != null && tags.Any() && !withoutTags; - var searchByTypes = filterType != FilterType.None; + var searchByTypes = filterType != FilterType.None && filterType != FilterType.FoldersOnly; var filesDbContext = _dbContextFactory.CreateDbContext(); var q = GetFolderQuery(filesDbContext, r => r.ParentId == parentId).AsNoTracking(); @@ -206,7 +206,7 @@ internal class FolderDao : AbstractDao, IFolderDao var filter = GetRoomTypeFilter(filterType); var searchByTags = tags != null && tags.Any() && !withoutTags; - var searchByTypes = filterType != FilterType.None; + var searchByTypes = filterType != FilterType.None && filterType != FilterType.FoldersOnly; var filesDbContext = _dbContextFactory.CreateDbContext(); var q = GetFolderQuery(filesDbContext, f => roomsIds.Contains(f.Id)).AsNoTracking(); diff --git a/products/ASC.Files/Core/Core/Security/FileSecurity.cs b/products/ASC.Files/Core/Core/Security/FileSecurity.cs index 06d2d6978e..cab5df9948 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -948,7 +948,7 @@ public class FileSecurity : IFileSecurity foldersInt.AddRange(roomsEntries); foldersString.AddRange(thirdPartyRoomsEntries); - if (withSubfolders) + if (withSubfolders && filterType != FilterType.FoldersOnly) { List> files; List> thirdPartyFiles; @@ -980,7 +980,7 @@ public class FileSecurity : IFileSecurity foldersInt.AddRange(roomsEntries); foldersString.AddRange(thirdPartyRoomsEntries); - if (withSubfolders) + if (withSubfolders && filterType != FilterType.FoldersOnly) { List> files; List> thirdPartyFiles; @@ -1063,7 +1063,7 @@ public class FileSecurity : IFileSecurity entries.AddRange(fileEntries); - if (withSubfolders) + if (withSubfolders && filterType != FilterType.FoldersOnly) { List> files; diff --git a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs index 8578f24f97..571482b454 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -428,7 +428,7 @@ internal abstract class ThirdPartyProviderDao : ThirdPartyProviderDao, IDispo protected IAsyncEnumerable> FilterByRoomType(IAsyncEnumerable> rooms, FilterType filterType) { - if (filterType == FilterType.None) + if (filterType == FilterType.None || filterType == FilterType.FoldersOnly) { return rooms; } diff --git a/products/ASC.Files/Server/Api/VirtualRoomsController.cs b/products/ASC.Files/Server/Api/VirtualRoomsController.cs index 1bbf1f481d..69914a9af1 100644 --- a/products/ASC.Files/Server/Api/VirtualRoomsController.cs +++ b/products/ASC.Files/Server/Api/VirtualRoomsController.cs @@ -669,20 +669,21 @@ public class VirtualRoomsCommonController : ApiControllerBase /// Virtual Rooms content /// [HttpGet("rooms")] - public async Task> GetRoomsFolderAsync(RoomType? type, string subjectId, bool? searchInContent, bool? withSubfolders, SearchArea? searchArea, bool? withoutTags, string tags, bool? withoutMe) + public async Task> GetRoomsFolderAsync(RoomFilterType? type, string subjectId, bool? searchInContent, bool? withSubfolders, SearchArea? searchArea, bool? withoutTags, string tags, bool? withoutMe) { ErrorIfNotDocSpace(); var parentId = searchArea != SearchArea.Archive ? await _globalFolderHelper.GetFolderVirtualRooms() : await _globalFolderHelper.GetFolderArchive(); - var filterType = type switch + var filter = type switch { - RoomType.FillingFormsRoom => FilterType.FillingFormsRooms, - RoomType.ReadOnlyRoom => FilterType.ReadOnlyRooms, - RoomType.EditingRoom => FilterType.EditingRooms, - RoomType.ReviewRoom => FilterType.ReviewRooms, - RoomType.CustomRoom => FilterType.CustomRooms, + RoomFilterType.FillingFormsRoomOnly => FilterType.FillingFormsRooms, + RoomFilterType.ReadOnlyRoomOnly => FilterType.ReadOnlyRooms, + RoomFilterType.EditingRoomOnly => FilterType.EditingRooms, + RoomFilterType.ReviewRoomOnly => FilterType.ReviewRooms, + RoomFilterType.CustomRoomOnly => FilterType.CustomRooms, + RoomFilterType.FoldersOnly => FilterType.FoldersOnly, _ => FilterType.None }; @@ -698,7 +699,7 @@ public class VirtualRoomsCommonController : ApiControllerBase var count = Convert.ToInt32(_apiContext.Count); var filterValue = _apiContext.FilterValue; - var content = await _fileStorageService.GetFolderItemsAsync(parentId, startIndex, count, filterType, false, subjectId, filterValue, + var content = await _fileStorageService.GetFolderItemsAsync(parentId, startIndex, count, filter, false, subjectId, filterValue, searchInContent ?? false, withSubfolders ?? false, orderBy, searchArea ?? SearchArea.Active, withoutTags ?? false, tagNames, withoutMe ?? false); var dto = await _folderContentDtoHelper.GetAsync(content, startIndex); From 1ae7d3b11db319b82ca97db5eeb377069bf0edf3 Mon Sep 17 00:00:00 2001 From: pavelbannov Date: Tue, 23 Aug 2022 18:03:00 +0300 Subject: [PATCH 18/30] Api: push controller. Removed projects --- .../Notify/Push/FirebaseHelper.cs | 5 -- .../Notify/Push/PushConstants.cs | 1 - .../Api/Settings/PushController.cs | 71 +++++++++++++++++++ .../Api/Settings/SettingsController.cs | 40 ----------- 4 files changed, 71 insertions(+), 46 deletions(-) create mode 100644 web/ASC.Web.Api/Api/Settings/PushController.cs diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 0923f8648d..bde18bc860 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -91,11 +91,6 @@ public class FirebaseHelper fireBaseUser = _firebaseDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushDocAppName); } - if (productID == new Guid("{1e044602-43b5-4d79-82f3-fd6208a11960}")) //projects product - { - fireBaseUser = _firebaseDao.GetUserDeviceTokens(user.Id, msg.TenantId, PushConstants.PushProjAppName); - } - foreach (var fb in fireBaseUser) { if ((bool)fb.IsSubscribed) diff --git a/common/ASC.Core.Common/Notify/Push/PushConstants.cs b/common/ASC.Core.Common/Notify/Push/PushConstants.cs index 5c7be980ef..09868069d1 100644 --- a/common/ASC.Core.Common/Notify/Push/PushConstants.cs +++ b/common/ASC.Core.Common/Notify/Push/PushConstants.cs @@ -34,5 +34,4 @@ public static class PushConstants public const string PushActionTagName = "PushAction"; public const string PushDocAppName = "doc"; - public const string PushProjAppName = "proj"; } diff --git a/web/ASC.Web.Api/Api/Settings/PushController.cs b/web/ASC.Web.Api/Api/Settings/PushController.cs new file mode 100644 index 0000000000..3de3da5cf6 --- /dev/null +++ b/web/ASC.Web.Api/Api/Settings/PushController.cs @@ -0,0 +1,71 @@ +// (c) Copyright Ascensio System SIA 2010-2022 +// +// This program is a free software product. +// You can redistribute it and/or modify it under the terms +// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software +// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended +// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of +// any third-party rights. +// +// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see +// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html +// +// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021. +// +// The interactive user interfaces in modified source and object code versions of the Program must +// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3. +// +// Pursuant to Section 7(b) of the License you must retain the original Product logo when +// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under +// trademark law for use of our trademarks. +// +// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing +// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 +// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + +using ASC.Web.Api.Controllers.Settings; + +namespace ASC.Web.Api.Api.Settings; + +public class PushController : BaseSettingsController +{ + private Tenant Tenant { get { return ApiContext.Tenant; } } + + private readonly AuthContext _authContext; + private readonly FirebaseHelper _firebaseHelper; + + public PushController( + ApiContext apiContext, + AuthContext authContext, + WebItemManager webItemManager, + IMemoryCache memoryCache, + FirebaseHelper firebaseHelper, + IHttpContextAccessor httpContextAccessor + ) : base(apiContext, memoryCache, webItemManager, httpContextAccessor) + { + _authContext = authContext; + _firebaseHelper = firebaseHelper; + } + + /// + /// Saves a documents firebase device token specified in the request. + /// + /// FireBase user + [HttpPost("push/docregisterdevice")] + public FireBaseUser DocRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) + { + return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); + } + + /// + /// Subscribe to documents push notification. + /// + /// FireBase user + [HttpPut("push/docsubscribe")] + public FireBaseUser SubscribeDocumentsPushNotification(FirebaseRequestsDto inDto) + { + return _firebaseHelper.UpdateUser(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); + + } +} \ No newline at end of file diff --git a/web/ASC.Web.Api/Api/Settings/SettingsController.cs b/web/ASC.Web.Api/Api/Settings/SettingsController.cs index 48c46f89e6..b5dfc3a1cc 100644 --- a/web/ASC.Web.Api/Api/Settings/SettingsController.cs +++ b/web/ASC.Web.Api/Api/Settings/SettingsController.cs @@ -25,7 +25,6 @@ // International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode using Constants = ASC.Core.Users.Constants; -using FireBaseUser = ASC.Core.Common.EF.FireBaseUser; namespace ASC.Web.Api.Controllers.Settings; public class SettingsController : BaseSettingsController @@ -708,44 +707,5 @@ public class SettingsController : BaseSettingsController public void TelegramDisconnect() { _telegramHelper.Disconnect(_authContext.CurrentAccount.ID, Tenant.Id); - } - - /// - /// Saves a documents firebase device token specified in the request. - /// - /// FireBase user - [HttpPost("push/docregisterdevice")] - public FireBaseUser DocRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) - { - return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); - } - - /// - /// Saves a projects firebase device token specified in the request. - /// - /// FireBase user - [HttpPost("push/projregisterdevice")] - public FireBaseUser ProjRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) - { - return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); - } - - /// - /// Subscribe to documents push notification. - /// - /// FireBase user - [HttpPut("push/docsubscribe")] - public FireBaseUser SubscribeDocumentsPushNotification(FirebaseRequestsDto inDto) - { - return _firebaseHelper.UpdateUser(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); - } - /// - /// Subscribe to projects push notification. - /// - /// FireBase user - [HttpPut("push/projsubscribe")] - public FireBaseUser SubscribeProjectsPushNotification(FirebaseRequestsDto inDto) - { - return _firebaseHelper.UpdateUser(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushProjAppName); } } \ No newline at end of file From 632d7fbc41d53687cba08867351eb606f2c379ce Mon Sep 17 00:00:00 2001 From: pavelbannov Date: Tue, 23 Aug 2022 20:03:02 +0300 Subject: [PATCH 19/30] Firebase: model --- common/ASC.Core.Common/EF/FireBaseUser.cs | 26 +++---- .../Notify/Push/Dao/FirebaseDao.cs | 4 +- common/Tools/ASC.Migration.Creator/Program.cs | 1 + ...65923_FirebaseDbContextMigrate.Designer.cs | 69 +++++++++++++++++++ ...20220823165923_FirebaseDbContextMigrate.cs | 48 +++++++++++++ .../FirebaseDbContextModelSnapshot.cs | 67 ++++++++++++++++++ ...65923_FirebaseDbContextMigrate.Designer.cs | 68 ++++++++++++++++++ ...20220823165923_FirebaseDbContextMigrate.cs | 48 +++++++++++++ .../FirebaseDbContextModelSnapshot.cs | 66 ++++++++++++++++++ 9 files changed, 378 insertions(+), 19 deletions(-) create mode 100644 migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs create mode 100644 migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs create mode 100644 migrations/mysql/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs create mode 100644 migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs create mode 100644 migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs create mode 100644 migrations/postgre/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs diff --git a/common/ASC.Core.Common/EF/FireBaseUser.cs b/common/ASC.Core.Common/EF/FireBaseUser.cs index 9c3e2b6512..a60220bcdd 100644 --- a/common/ASC.Core.Common/EF/FireBaseUser.cs +++ b/common/ASC.Core.Common/EF/FireBaseUser.cs @@ -61,12 +61,8 @@ public static class FireBaseUserExtension entity.ToTable("firebase_users"); - entity.HasIndex(e => e.UserId) + entity.HasIndex(e => new { e.TenantId, e.UserId }) .HasDatabaseName("user_id"); - entity.HasIndex(e => e.TenantId) - .HasDatabaseName("tenant_id"); - entity.HasIndex(e => e.FirebaseDeviceToken) - .HasDatabaseName("firebase_device_token"); entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.TenantId).HasColumnName("tenant_id"); @@ -74,16 +70,16 @@ public static class FireBaseUserExtension entity.Property(e => e.UserId) .HasColumnName("user_id") - .HasColumnType("varchar(38)") + .HasColumnType("varchar(36)") .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - + .UseCollation("utf8_general_ci"); + entity.Property(e => e.FirebaseDeviceToken) .HasColumnName("firebase_device_token") .HasColumnType("varchar(255)") .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - + .UseCollation("utf8_general_ci"); + entity.Property(e => e.Application) .HasColumnName("application") .HasColumnType("varchar(20)") @@ -100,14 +96,10 @@ public static class FireBaseUserExtension entity.HasKey(e => e.Id) .HasName("firebase_users_pkey"); - entity.ToTable("firebase_users", "onlyoffice"); + entity.ToTable("firebase_users", "onlyoffice"); - entity.HasIndex(e => e.UserId) + entity.HasIndex(e => new { e.TenantId, e.UserId }) .HasDatabaseName("user_id"); - entity.HasIndex(e => e.TenantId) - .HasDatabaseName("tenant_id"); - entity.HasIndex(e => e.FirebaseDeviceToken) - .HasDatabaseName("firebase_device_token"); entity.Property(e => e.Id).HasColumnName("id"); entity.Property(e => e.TenantId).HasColumnName("tenant_id"); @@ -115,7 +107,7 @@ public static class FireBaseUserExtension entity.Property(e => e.UserId) .HasColumnName("user_id") - .HasMaxLength(38); + .HasMaxLength(36); entity.Property(e => e.FirebaseDeviceToken) .HasColumnName("firebase_device_token") diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs index f808611e79..5216255d9e 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -89,8 +89,8 @@ public class FirebaseDao }; dbContext.Update(user); - dbContext.SaveChanges(); - + dbContext.SaveChanges(); + return user; } diff --git a/common/Tools/ASC.Migration.Creator/Program.cs b/common/Tools/ASC.Migration.Creator/Program.cs index cd1c5a4415..ec66e57bec 100644 --- a/common/Tools/ASC.Migration.Creator/Program.cs +++ b/common/Tools/ASC.Migration.Creator/Program.cs @@ -58,6 +58,7 @@ builder.WebHost.ConfigureServices((hostContext, services) => services.AddBaseDbContext(); services.AddBaseDbContext(); services.AddBaseDbContext(); + services.AddBaseDbContext(); }); var app = builder.Build(); diff --git a/migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs b/migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs new file mode 100644 index 0000000000..b0fece1905 --- /dev/null +++ b/migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs @@ -0,0 +1,69 @@ +// +using System; +using ASC.Core.Common.EF.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace ASC.Migrations.MySql.Migrations.FirebaseDb +{ + [DbContext(typeof(FirebaseDbContext))] + [Migration("20220823165923_FirebaseDbContextMigrate")] + partial class FirebaseDbContextMigrate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("ASC.Core.Common.EF.FireBaseUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasColumnName("id"); + + b.Property("Application") + .HasColumnType("varchar(20)") + .HasColumnName("application") + .UseCollation("utf8_general_ci") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("FirebaseDeviceToken") + .HasColumnType("varchar(255)") + .HasColumnName("firebase_device_token") + .UseCollation("utf8_general_ci") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("IsSubscribed") + .HasColumnType("tinyint(1)") + .HasColumnName("is_subscribed"); + + b.Property("TenantId") + .HasColumnType("int") + .HasColumnName("tenant_id"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(36)") + .HasColumnName("user_id") + .UseCollation("utf8_general_ci") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.HasKey("Id") + .HasName("PRIMARY"); + + b.HasIndex("TenantId", "UserId") + .HasDatabaseName("user_id"); + + b.ToTable("firebase_users", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs b/migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs new file mode 100644 index 0000000000..1fcdf490fb --- /dev/null +++ b/migrations/mysql/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ASC.Migrations.MySql.Migrations.FirebaseDb +{ + public partial class FirebaseDbContextMigrate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "firebase_users", + columns: table => new + { + id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + user_id = table.Column(type: "varchar(36)", nullable: false, collation: "utf8_general_ci") + .Annotation("MySql:CharSet", "utf8"), + tenant_id = table.Column(type: "int", nullable: false), + firebase_device_token = table.Column(type: "varchar(255)", nullable: true, collation: "utf8_general_ci") + .Annotation("MySql:CharSet", "utf8"), + application = table.Column(type: "varchar(20)", nullable: true, collation: "utf8_general_ci") + .Annotation("MySql:CharSet", "utf8"), + is_subscribed = table.Column(type: "tinyint(1)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PRIMARY", x => x.id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "user_id", + table: "firebase_users", + columns: new[] { "tenant_id", "user_id" }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "firebase_users"); + } + } +} diff --git a/migrations/mysql/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs b/migrations/mysql/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs new file mode 100644 index 0000000000..4e26247259 --- /dev/null +++ b/migrations/mysql/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs @@ -0,0 +1,67 @@ +// +using System; +using ASC.Core.Common.EF.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace ASC.Migrations.MySql.Migrations.FirebaseDb +{ + [DbContext(typeof(FirebaseDbContext))] + partial class FirebaseDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("ASC.Core.Common.EF.FireBaseUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasColumnName("id"); + + b.Property("Application") + .HasColumnType("varchar(20)") + .HasColumnName("application") + .UseCollation("utf8_general_ci") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("FirebaseDeviceToken") + .HasColumnType("varchar(255)") + .HasColumnName("firebase_device_token") + .UseCollation("utf8_general_ci") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.Property("IsSubscribed") + .HasColumnType("tinyint(1)") + .HasColumnName("is_subscribed"); + + b.Property("TenantId") + .HasColumnType("int") + .HasColumnName("tenant_id"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(36)") + .HasColumnName("user_id") + .UseCollation("utf8_general_ci") + .HasAnnotation("MySql:CharSet", "utf8"); + + b.HasKey("Id") + .HasName("PRIMARY"); + + b.HasIndex("TenantId", "UserId") + .HasDatabaseName("user_id"); + + b.ToTable("firebase_users", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs b/migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs new file mode 100644 index 0000000000..7ea3f064f2 --- /dev/null +++ b/migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.Designer.cs @@ -0,0 +1,68 @@ +// +using System; +using ASC.Core.Common.EF.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace ASC.Migrations.PostgreSql.Migrations.FirebaseDb +{ + [DbContext(typeof(FirebaseDbContext))] + [Migration("20220823165923_FirebaseDbContextMigrate")] + partial class FirebaseDbContextMigrate + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) + .HasAnnotation("ProductVersion", "6.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + modelBuilder.Entity("ASC.Core.Common.EF.FireBaseUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + b.Property("Application") + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("application"); + + b.Property("FirebaseDeviceToken") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("firebase_device_token"); + + b.Property("IsSubscribed") + .HasColumnType("boolean") + .HasColumnName("is_subscribed"); + + b.Property("TenantId") + .HasColumnType("integer") + .HasColumnName("tenant_id"); + + b.Property("UserId") + .HasMaxLength(36) + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("firebase_users_pkey"); + + b.HasIndex("TenantId", "UserId") + .HasDatabaseName("user_id"); + + b.ToTable("firebase_users", "onlyoffice"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs b/migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs new file mode 100644 index 0000000000..75aec99be6 --- /dev/null +++ b/migrations/postgre/FirebaseDbContext/20220823165923_FirebaseDbContextMigrate.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace ASC.Migrations.PostgreSql.Migrations.FirebaseDb +{ + public partial class FirebaseDbContextMigrate : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.EnsureSchema( + name: "onlyoffice"); + + migrationBuilder.CreateTable( + name: "firebase_users", + schema: "onlyoffice", + columns: table => new + { + id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + user_id = table.Column(type: "uuid", maxLength: 36, nullable: false), + tenant_id = table.Column(type: "integer", nullable: false), + firebase_device_token = table.Column(type: "character varying(255)", maxLength: 255, nullable: true), + application = table.Column(type: "character varying(20)", maxLength: 20, nullable: true), + is_subscribed = table.Column(type: "boolean", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("firebase_users_pkey", x => x.id); + }); + + migrationBuilder.CreateIndex( + name: "user_id", + schema: "onlyoffice", + table: "firebase_users", + columns: new[] { "tenant_id", "user_id" }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "firebase_users", + schema: "onlyoffice"); + } + } +} diff --git a/migrations/postgre/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs b/migrations/postgre/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs new file mode 100644 index 0000000000..5ba91d1723 --- /dev/null +++ b/migrations/postgre/FirebaseDbContext/FirebaseDbContextModelSnapshot.cs @@ -0,0 +1,66 @@ +// +using System; +using ASC.Core.Common.EF.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace ASC.Migrations.PostgreSql.Migrations.FirebaseDb +{ + [DbContext(typeof(FirebaseDbContext))] + partial class FirebaseDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) + .HasAnnotation("ProductVersion", "6.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + modelBuilder.Entity("ASC.Core.Common.EF.FireBaseUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); + + b.Property("Application") + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("application"); + + b.Property("FirebaseDeviceToken") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("firebase_device_token"); + + b.Property("IsSubscribed") + .HasColumnType("boolean") + .HasColumnName("is_subscribed"); + + b.Property("TenantId") + .HasColumnType("integer") + .HasColumnName("tenant_id"); + + b.Property("UserId") + .HasMaxLength(36) + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("firebase_users_pkey"); + + b.HasIndex("TenantId", "UserId") + .HasDatabaseName("user_id"); + + b.ToTable("firebase_users", "onlyoffice"); + }); +#pragma warning restore 612, 618 + } + } +} From 8f248f6ac27feb47c7fad2e6d927955d2ae99672 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Tue, 23 Aug 2022 23:35:26 +0300 Subject: [PATCH 20/30] Push: fix --- common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 0923f8648d..3f52294786 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -69,12 +69,8 @@ public class FirebaseHelper public void SendMessage(NotifyMessage msg) { - var tenant = _tenantManager.GetCurrentTenant(false); + _tenantManager.SetCurrentTenant(msg.TenantId); - if (tenant == null) - { - _tenantManager.SetCurrentTenant(Tenant.DefaultTenant); - } var user = _userManager.GetUserByUserName(msg.Reciever); Guid productID; From d282aa74f73ff374bb3f85ede08469e0bc33ea6e Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Wed, 24 Aug 2022 00:10:37 +0300 Subject: [PATCH 21/30] Push: fixed message sending function --- common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 3f52294786..ff5bb70e58 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -94,7 +94,7 @@ public class FirebaseHelper foreach (var fb in fireBaseUser) { - if ((bool)fb.IsSubscribed) + if(fb.IsSubscribed.HasValue && fb.IsSubscribed.Value == true) { var m = new FirebaseAdminMessaging.Message() { From ed41675476f59c3132c634f3fe822c381dd11b79 Mon Sep 17 00:00:00 2001 From: pavelbannov Date: Wed, 24 Aug 2022 12:34:30 +0300 Subject: [PATCH 22/30] Firebase: optimization --- .../Notify/Push/FirebaseHelper.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 3be168bcd7..56c4303e4a 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -46,15 +46,17 @@ public class FirebaseHelper _tenantManager = tenantManager; _configuration = configuration; _logger = logger; - _firebaseDao = firebaseDao; + _firebaseDao = firebaseDao; + } - - var credentials = JsonConvert.SerializeObject(new FirebaseApiKey(_configuration)).Replace("\\\\", "\\"); + public void SendMessage(NotifyMessage msg) + { var defaultInstance = FirebaseApp.DefaultInstance; if (defaultInstance == null) { try - { + { + var credentials = JsonConvert.SerializeObject(new FirebaseApiKey(_configuration)).Replace("\\\\", "\\"); FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromJson(credentials) @@ -64,11 +66,8 @@ public class FirebaseHelper { _logger.ErrorUnexpected(e); } - } - } + } - public void SendMessage(NotifyMessage msg) - { _tenantManager.SetCurrentTenant(msg.TenantId); var user = _userManager.GetUserByUserName(msg.Reciever); @@ -89,7 +88,7 @@ public class FirebaseHelper foreach (var fb in fireBaseUser) { - if(fb.IsSubscribed.HasValue && fb.IsSubscribed.Value == true) + if (fb.IsSubscribed.HasValue && fb.IsSubscribed.Value == true) { var m = new FirebaseAdminMessaging.Message() { From ae49029f91ad3e228420057f1e03260ffecbc3cf Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Wed, 24 Aug 2022 13:21:18 +0300 Subject: [PATCH 23/30] Push: fix api --- .../Notify/Push/Dao/FirebaseDao.cs | 36 ++++++++++--------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs index 5216255d9e..cae0eddc10 100644 --- a/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs +++ b/common/ASC.Core.Common/Notify/Push/Dao/FirebaseDao.cs @@ -39,29 +39,31 @@ public class FirebaseDao public FireBaseUser RegisterUserDevice(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) { using var dbContext = _dbContextFactory.CreateDbContext(); - var count = dbContext.Users + var user = dbContext.Users .AsNoTracking() .Where(r => r.UserId == userId) .Where(r => r.TenantId == tenantId) .Where(r => r.Application == application) .Where(r => r.FirebaseDeviceToken == fbDeviceToken) - .Count(); - - var user = new FireBaseUser - { - UserId = userId, - TenantId = tenantId, - FirebaseDeviceToken = fbDeviceToken, - IsSubscribed = isSubscribed, - Application = application - }; - - if (count == 0) - { - dbContext.AddOrUpdate(r => r.Users, user); - dbContext.SaveChanges(); + .FirstOrDefault(); + + + if (user == null) + { + var newUser = new FireBaseUser + { + UserId = userId, + TenantId = tenantId, + FirebaseDeviceToken = fbDeviceToken, + IsSubscribed = isSubscribed, + Application = application + }; + dbContext.Add(newUser); + dbContext.SaveChanges(); + + return newUser; } - + return user; } From b8efdefbcda9da2d775fa5ce2b98b196527619fa Mon Sep 17 00:00:00 2001 From: Artem Tarasov Date: Wed, 24 Aug 2022 13:35:57 +0300 Subject: [PATCH 24/30] Web: Doceditor: fixed variable name for getting path to logs from environment --- packages/editor/src/server/lib/logger.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/packages/editor/src/server/lib/logger.js b/packages/editor/src/server/lib/logger.js index 062d11f2eb..4aabab024e 100644 --- a/packages/editor/src/server/lib/logger.js +++ b/packages/editor/src/server/lib/logger.js @@ -3,18 +3,16 @@ import "winston-daily-rotate-file"; import path from "path"; import fs from "fs"; -let logpath = process.env.logpath || null; +let logPath = process.env.logPath || null; -if (logpath != null) { - if (!path.isAbsolute(logpath)) { - logpath = path.join(__dirname, "..", logpath); +if (logPath != null) { + if (!path.isAbsolute(logPath)) { + logPath = path.join(__dirname, "..", logPath); } } -const fileName = IS_DEVELOPMENT - ? path.join(__dirname, "..", "..", "..", "Logs", "editor.%DATE%.log") - : logpath - ? path.join(logpath, "editor.%DATE%.log") +const fileName = logPath + ? path.join(logPath, "editor.%DATE%.log") : path.join(__dirname, "..", "..", "..", "Logs", "editor.%DATE%.log"); const dirName = path.dirname(fileName); From 9523560b16b6de2f7d8ce5eec8764d2f76289147 Mon Sep 17 00:00:00 2001 From: Nikolay Rechkin Date: Wed, 24 Aug 2022 14:26:45 +0300 Subject: [PATCH 25/30] Push: fix api --- .../Notify/Push/FirebaseHelper.cs | 21 +++++++++++++------ .../Api/Settings/PushController.cs | 9 ++------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs index 56c4303e4a..cb6d6bae44 100644 --- a/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs +++ b/common/ASC.Core.Common/Notify/Push/FirebaseHelper.cs @@ -30,18 +30,21 @@ namespace ASC.Core.Common.Notify.Push; public class FirebaseHelper { protected readonly UserManager _userManager; + private readonly AuthContext _authContext; private readonly TenantManager _tenantManager; private readonly ILogger _logger; private readonly IConfiguration _configuration; private readonly FirebaseDao _firebaseDao; - public FirebaseHelper( + public FirebaseHelper( + AuthContext authContext, UserManager userManager, TenantManager tenantManager, IConfiguration configuration, ILogger logger, FirebaseDao firebaseDao) - { + { + _authContext = authContext; _userManager = userManager; _tenantManager = tenantManager; _configuration = configuration; @@ -106,13 +109,19 @@ public class FirebaseHelper } } - public FireBaseUser RegisterUserDevice(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) - { + public FireBaseUser RegisterUserDevice(string fbDeviceToken, bool isSubscribed, string application) + { + var userId = _authContext.CurrentAccount.ID; + var tenantId = _tenantManager.GetCurrentTenant().Id; + return _firebaseDao.RegisterUserDevice(userId, tenantId, fbDeviceToken, isSubscribed, application); } - public FireBaseUser UpdateUser(Guid userId, int tenantId, string fbDeviceToken, bool isSubscribed, string application) - { + public FireBaseUser UpdateUser(string fbDeviceToken, bool isSubscribed, string application) + { + var userId = _authContext.CurrentAccount.ID; + var tenantId = _tenantManager.GetCurrentTenant().Id; + return _firebaseDao.UpdateUser(userId, tenantId, fbDeviceToken, isSubscribed, application); } } diff --git a/web/ASC.Web.Api/Api/Settings/PushController.cs b/web/ASC.Web.Api/Api/Settings/PushController.cs index 3de3da5cf6..210947829a 100644 --- a/web/ASC.Web.Api/Api/Settings/PushController.cs +++ b/web/ASC.Web.Api/Api/Settings/PushController.cs @@ -30,21 +30,16 @@ namespace ASC.Web.Api.Api.Settings; public class PushController : BaseSettingsController { - private Tenant Tenant { get { return ApiContext.Tenant; } } - - private readonly AuthContext _authContext; private readonly FirebaseHelper _firebaseHelper; public PushController( ApiContext apiContext, - AuthContext authContext, WebItemManager webItemManager, IMemoryCache memoryCache, FirebaseHelper firebaseHelper, IHttpContextAccessor httpContextAccessor ) : base(apiContext, memoryCache, webItemManager, httpContextAccessor) { - _authContext = authContext; _firebaseHelper = firebaseHelper; } @@ -55,7 +50,7 @@ public class PushController : BaseSettingsController [HttpPost("push/docregisterdevice")] public FireBaseUser DocRegisterPusnNotificationDevice(FirebaseRequestsDto inDto) { - return _firebaseHelper.RegisterUserDevice(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); + return _firebaseHelper.RegisterUserDevice(inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); } /// @@ -65,7 +60,7 @@ public class PushController : BaseSettingsController [HttpPut("push/docsubscribe")] public FireBaseUser SubscribeDocumentsPushNotification(FirebaseRequestsDto inDto) { - return _firebaseHelper.UpdateUser(_authContext.CurrentAccount.ID, Tenant.Id, inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); + return _firebaseHelper.UpdateUser(inDto.FirebaseDeviceToken, inDto.IsSubscribed, PushConstants.PushDocAppName); } } \ No newline at end of file From ee757db2a8b73d44f57c16f2414d6605699ab9c5 Mon Sep 17 00:00:00 2001 From: Artem Tarasov Date: Wed, 24 Aug 2022 16:28:10 +0300 Subject: [PATCH 26/30] Web: Doceditor: added nconf --- packages/editor/package.json | 1 + yarn.lock | 31 +++++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/packages/editor/package.json b/packages/editor/package.json index edd3e3ca72..c1f5206146 100644 --- a/packages/editor/package.json +++ b/packages/editor/package.json @@ -66,6 +66,7 @@ "i18next-express-middleware": "^2.0.0", "i18next-fs-backend": "^1.1.4", "morgan": "^1.10.0", + "nconf": "^0.12.0", "utf-8-validate": "^5.0.9", "winston": "^3.8.1", "winston-daily-rotate-file": "^4.7.1" diff --git a/yarn.lock b/yarn.lock index a0090dbf12..2f5db25ae9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2194,6 +2194,7 @@ __metadata: i18next-fs-backend: ^1.1.4 json-loader: ^0.5.7 morgan: ^1.10.0 + nconf: ^0.12.0 nodemon: ^2.0.7 npm-run-all: ^4.1.5 sass: ^1.53.0 @@ -7238,7 +7239,7 @@ __metadata: languageName: node linkType: hard -"async@npm:^3.2.3": +"async@npm:^3.0.0, async@npm:^3.2.3": version: 3.2.4 resolution: "async@npm:3.2.4" checksum: 43d07459a4e1d09b84a20772414aa684ff4de085cbcaec6eea3c7a8f8150e8c62aa6cd4e699fe8ee93c3a5b324e777d34642531875a0817a35697522c1b02e89 @@ -14087,6 +14088,13 @@ __metadata: languageName: node linkType: hard +"ini@npm:^2.0.0": + version: 2.0.0 + resolution: "ini@npm:2.0.0" + checksum: e7aadc5fb2e4aefc666d74ee2160c073995a4061556b1b5b4241ecb19ad609243b9cceafe91bae49c219519394bbd31512516cb22a3b1ca6e66d869e0447e84e + languageName: node + linkType: hard + "inline-style-parser@npm:0.1.1": version: 0.1.1 resolution: "inline-style-parser@npm:0.1.1" @@ -17717,6 +17725,18 @@ __metadata: languageName: node linkType: hard +"nconf@npm:^0.12.0": + version: 0.12.0 + resolution: "nconf@npm:0.12.0" + dependencies: + async: ^3.0.0 + ini: ^2.0.0 + secure-keys: ^1.0.0 + yargs: ^16.1.1 + checksum: 70c1ce82d91149940dbe57555372c99282a9625a961915b302093b34e04ab308d978d1885224b9738a0873c064a0aa48914a7260e67ba312441fc4917221dbd8 + languageName: node + linkType: hard + "nearley@npm:^2.7.10": version: 2.20.1 resolution: "nearley@npm:2.20.1" @@ -21810,6 +21830,13 @@ __metadata: languageName: node linkType: hard +"secure-keys@npm:^1.0.0": + version: 1.0.0 + resolution: "secure-keys@npm:1.0.0" + checksum: 3dd4e64e6717fe6e2dc4c70e172982fcbad87b853e96566ab1cfaec540587f737bac106853ae469cb32d4a6413cfe80a28176cfe7dfcf7ddd35c9f92e58dffed + languageName: node + linkType: hard + "select-hose@npm:^2.0.0": version: 2.0.0 resolution: "select-hose@npm:2.0.0" @@ -25697,7 +25724,7 @@ __metadata: languageName: node linkType: hard -"yargs@npm:16.2.0, yargs@npm:^16.2.0": +"yargs@npm:16.2.0, yargs@npm:^16.1.1, yargs@npm:^16.2.0": version: 16.2.0 resolution: "yargs@npm:16.2.0" dependencies: From 2b915db42544826244527eb9e0f6a60f21fc324f Mon Sep 17 00:00:00 2001 From: Artem Tarasov Date: Wed, 24 Aug 2022 16:30:37 +0300 Subject: [PATCH 27/30] Web: Doceditor: applied nconf, logPath is now taken from appsettings.services.json --- packages/editor/src/server/config/config.json | 5 ++- packages/editor/src/server/config/index.js | 35 +++++++++++++++++++ packages/editor/src/server/lib/logger.js | 3 +- 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 packages/editor/src/server/config/index.js diff --git a/packages/editor/src/server/config/config.json b/packages/editor/src/server/config/config.json index ac8606aef8..b21f871e26 100644 --- a/packages/editor/src/server/config/config.json +++ b/packages/editor/src/server/config/config.json @@ -1,3 +1,6 @@ { - "PORT": "5013" + "PORT": "5013", + "app": { + "appsettings": "../../../config" + } } \ No newline at end of file diff --git a/packages/editor/src/server/config/index.js b/packages/editor/src/server/config/index.js new file mode 100644 index 0000000000..b24e028b28 --- /dev/null +++ b/packages/editor/src/server/config/index.js @@ -0,0 +1,35 @@ +import nconf from "nconf"; +import path from "path"; +import fs from "fs"; + +nconf.argv().env().file("config", path.join(__dirname, "config.json")); + +getAndSaveAppsettings(); + +function getAndSaveAppsettings() { + let appsettings = nconf.get("app").appsettings; + + if (!path.isAbsolute(appsettings)) { + appsettings = path.join(__dirname, appsettings); + } + + const env = nconf.get("app").environment; + const valueEnv = nconf.get(env); + const fileWithEnv = path.join( + appsettings, + "appsettings." + valueEnv + ".json" + ); + + if (fs.existsSync(fileWithEnv)) { + nconf.file("appsettings", fileWithEnv); + } else { + nconf.file("appsettings", path.join(appsettings, "appsettings.json")); + } + + nconf.file( + "appsettingsServices", + path.join(appsettings, "appsettings.services.json") + ); +} + +export default nconf; diff --git a/packages/editor/src/server/lib/logger.js b/packages/editor/src/server/lib/logger.js index 4aabab024e..36660b34f9 100644 --- a/packages/editor/src/server/lib/logger.js +++ b/packages/editor/src/server/lib/logger.js @@ -2,8 +2,9 @@ import winston from "winston"; import "winston-daily-rotate-file"; import path from "path"; import fs from "fs"; +import config from "../config"; -let logPath = process.env.logPath || null; +let logPath = config.get("logPath"); if (logPath != null) { if (!path.isAbsolute(logPath)) { From e2472b392edece23bf6d7c22399014653e166f68 Mon Sep 17 00:00:00 2001 From: pavelbannov Date: Wed, 24 Aug 2022 20:27:20 +0300 Subject: [PATCH 28/30] Files: fix doceditor link --- products/ASC.Files/Core/Helpers/FilesLinkUtility.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/products/ASC.Files/Core/Helpers/FilesLinkUtility.cs b/products/ASC.Files/Core/Helpers/FilesLinkUtility.cs index c916a553bb..d419452988 100644 --- a/products/ASC.Files/Core/Helpers/FilesLinkUtility.cs +++ b/products/ASC.Files/Core/Helpers/FilesLinkUtility.cs @@ -273,7 +273,7 @@ public class FilesLinkUtility public string FileWebViewerUrlString { - get { return FileWebEditorUrlString + "&" + Action + "=view"; } + get { return $"{FileWebEditorUrlString}&{Action}=view"; } } public string GetFileWebViewerUrlForMobile(object fileId, int fileVersion) @@ -296,10 +296,10 @@ public class FilesLinkUtility public string FileWebEditorUrlString { - get { return FilesBaseAbsolutePath + EditorPage + "?" + FileId + "={0}"; } + get { return $"/{EditorPage}?{FileId}={{0}}"; } } - public string GetFileWebEditorUrl(object fileId, int fileVersion = 0) + public string GetFileWebEditorUrl(T fileId, int fileVersion = 0) { return string.Format(FileWebEditorUrlString, HttpUtility.UrlEncode(fileId.ToString())) + (fileVersion > 0 ? "&" + Version + "=" + fileVersion : string.Empty); From 4dcd9be0411851c3cb410e3e61de8a51b3c35f91 Mon Sep 17 00:00:00 2001 From: MaksimChegulov Date: Thu, 25 Aug 2022 13:29:08 +0300 Subject: [PATCH 29/30] fix: removed IOptionsSnapshot --- .../LoginProviders/EncryptionLoginProvider.cs | 12 +++++------- .../ASC.Files/Core/ThirdPartyApp/BoxApp.cs | 13 ++++++------- .../Core/ThirdPartyApp/GoogleDriveApp.cs | 19 +++++++++---------- .../Server/Api/ThirdpartyController.cs | 17 ++++++----------- .../Api/AuthenticationController.cs | 9 ++++----- 5 files changed, 30 insertions(+), 40 deletions(-) diff --git a/common/ASC.FederatedLogin/LoginProviders/EncryptionLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/EncryptionLoginProvider.cs index 4ab6aec3fe..a2e1d63568 100644 --- a/common/ASC.FederatedLogin/LoginProviders/EncryptionLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/EncryptionLoginProvider.cs @@ -33,20 +33,20 @@ public class EncryptionLoginProvider private readonly SecurityContext _securityContext; private readonly Signature _signature; private readonly InstanceCrypto _instanceCrypto; - private readonly IOptionsSnapshot _snapshot; + private readonly AccountLinker _accountLinker; public EncryptionLoginProvider( ILogger logger, SecurityContext securityContext, Signature signature, InstanceCrypto instanceCrypto, - IOptionsSnapshot snapshot) + AccountLinker accountLinker) { _logger = logger; _securityContext = securityContext; _signature = signature; _instanceCrypto = instanceCrypto; - _snapshot = snapshot; + _accountLinker = accountLinker; } @@ -63,8 +63,7 @@ public class EncryptionLoginProvider Name = _instanceCrypto.Encrypt(keys) }; - var linker = _snapshot.Get("webstudio"); - linker.AddLink(userId.ToString(), loginProfile); + _accountLinker.AddLink(userId.ToString(), loginProfile); } public string GetKeys() @@ -74,8 +73,7 @@ public class EncryptionLoginProvider public string GetKeys(Guid userId) { - var linker = _snapshot.Get("webstudio"); - var profile = linker.GetLinkedProfiles(userId.ToString(), ProviderConstants.Encryption).FirstOrDefault(); + var profile = _accountLinker.GetLinkedProfiles(userId.ToString(), ProviderConstants.Encryption).FirstOrDefault(); if (profile == null) { return null; diff --git a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs index 761cb5e43b..d715c07e03 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -57,7 +57,7 @@ public class BoxApp : Consumer, IThirdPartyApp, IOAuthProvider private readonly SettingsManager _settingsManager; private readonly PersonalSettingsHelper _personalSettingsHelper; private readonly BaseCommonLinkUtility _baseCommonLinkUtility; - private readonly IOptionsSnapshot _snapshot; + private readonly AccountLinker _accountLinker; private readonly SetupInfo _setupInfo; private readonly TokenHelper _tokenHelper; private readonly DocumentServiceConnector _documentServiceConnector; @@ -85,7 +85,7 @@ public class BoxApp : Consumer, IThirdPartyApp, IOAuthProvider SettingsManager settingsManager, PersonalSettingsHelper personalSettingsHelper, BaseCommonLinkUtility baseCommonLinkUtility, - IOptionsSnapshot snapshot, + AccountLinker accountLinker, SetupInfo setupInfo, TokenHelper tokenHelper, DocumentServiceConnector documentServiceConnector, @@ -117,7 +117,7 @@ public class BoxApp : Consumer, IThirdPartyApp, IOAuthProvider _settingsManager = settingsManager; _personalSettingsHelper = personalSettingsHelper; _baseCommonLinkUtility = baseCommonLinkUtility; - _snapshot = snapshot; + _accountLinker = accountLinker; _setupInfo = setupInfo; _tokenHelper = tokenHelper; _documentServiceConnector = documentServiceConnector; @@ -465,8 +465,7 @@ public class BoxApp : Consumer, IThirdPartyApp, IOAuthProvider private bool CurrentUser(string boxUserId) { - var linkedProfiles = _snapshot.Get("webstudio") - .GetLinkedObjectsByHashId(HashHelper.MD5($"{ProviderConstants.Box}/{boxUserId}")); + var linkedProfiles = _accountLinker.GetLinkedObjectsByHashId(HashHelper.MD5($"{ProviderConstants.Box}/{boxUserId}")); return linkedProfiles.Any(profileId => Guid.TryParse(profileId, out var tmp) && tmp == _authContext.CurrentAccount.ID); } @@ -474,8 +473,8 @@ public class BoxApp : Consumer, IThirdPartyApp, IOAuthProvider private void AddLinker(string boxUserId) { _logger.DebugBoxAppAddLinker(boxUserId); - var linker = _snapshot.Get("webstudio"); - linker.AddLink(_authContext.CurrentAccount.ID.ToString(), boxUserId, ProviderConstants.Box); + + _accountLinker.AddLink(_authContext.CurrentAccount.ID.ToString(), boxUserId, ProviderConstants.Box); } private UserInfo GetUserInfo(Token token, out bool isNew) diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index a32a92d334..f658b74091 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -63,7 +63,7 @@ public class GoogleDriveApp : Consumer, IThirdPartyApp, IOAuthProvider private readonly BaseCommonLinkUtility _baseCommonLinkUtility; private readonly FileUtility _fileUtility; private readonly FilesSettingsHelper _filesSettingsHelper; - private readonly IOptionsSnapshot _snapshot; + private readonly AccountLinker _accountLinker; private readonly SetupInfo _setupInfo; private readonly GoogleLoginProvider _googleLoginProvider; private readonly TokenHelper _tokenHelper; @@ -97,7 +97,7 @@ public class GoogleDriveApp : Consumer, IThirdPartyApp, IOAuthProvider ILogger logger, FileUtility fileUtility, FilesSettingsHelper filesSettingsHelper, - IOptionsSnapshot snapshot, + AccountLinker accountLinker, SetupInfo setupInfo, GoogleLoginProvider googleLoginProvider, TokenHelper tokenHelper, @@ -111,9 +111,9 @@ public class GoogleDriveApp : Consumer, IThirdPartyApp, IOAuthProvider ICacheNotify cache, ConsumerFactory consumerFactory, IHttpClientFactory clientFactory, - OAuth20TokenHelper oAuth20TokenHelper, - RequestHelper requestHelper, - ThirdPartySelector thirdPartySelector, + OAuth20TokenHelper oAuth20TokenHelper, + RequestHelper requestHelper, + ThirdPartySelector thirdPartySelector, string name, int order, Dictionary additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) { @@ -135,7 +135,7 @@ public class GoogleDriveApp : Consumer, IThirdPartyApp, IOAuthProvider _baseCommonLinkUtility = baseCommonLinkUtility; _fileUtility = fileUtility; _filesSettingsHelper = filesSettingsHelper; - _snapshot = snapshot; + _accountLinker = accountLinker; _setupInfo = setupInfo; _googleLoginProvider = googleLoginProvider; _tokenHelper = tokenHelper; @@ -618,8 +618,7 @@ public class GoogleDriveApp : Consumer, IThirdPartyApp, IOAuthProvider private bool CurrentUser(string googleId) { - var linker = _snapshot.Get("webstudio"); - var linkedProfiles = linker.GetLinkedObjectsByHashId(HashHelper.MD5($"{ProviderConstants.Google}/{googleId}")); + var linkedProfiles = _accountLinker.GetLinkedObjectsByHashId(HashHelper.MD5($"{ProviderConstants.Google}/{googleId}")); return linkedProfiles.Any(profileId => Guid.TryParse(profileId, out var tmp) && tmp == _authContext.CurrentAccount.ID); } @@ -627,8 +626,8 @@ public class GoogleDriveApp : Consumer, IThirdPartyApp, IOAuthProvider private void AddLinker(string googleUserId) { _logger.DebugGoogleDriveApAddLinker(googleUserId); - var linker = _snapshot.Get("webstudio"); - linker.AddLink(_authContext.CurrentAccount.ID.ToString(), googleUserId, ProviderConstants.Google); + + _accountLinker.AddLink(_authContext.CurrentAccount.ID.ToString(), googleUserId, ProviderConstants.Google); } private UserInfo GetUserInfo(Token token, out bool isNew) diff --git a/products/ASC.People/Server/Api/ThirdpartyController.cs b/products/ASC.People/Server/Api/ThirdpartyController.cs index 099d5d005d..be876c1c25 100644 --- a/products/ASC.People/Server/Api/ThirdpartyController.cs +++ b/products/ASC.People/Server/Api/ThirdpartyController.cs @@ -30,7 +30,7 @@ namespace ASC.People.Api; public class ThirdpartyController : ApiControllerBase { - private readonly IOptionsSnapshot _accountLinker; + private readonly AccountLinker _accountLinker; private readonly CookiesManager _cookiesManager; private readonly CoreBaseSettings _coreBaseSettings; private readonly DisplayUserSettingsHelper _displayUserSettingsHelper; @@ -52,7 +52,7 @@ public class ThirdpartyController : ApiControllerBase private readonly StudioNotifyService _studioNotifyService; public ThirdpartyController( - IOptionsSnapshot accountLinker, + AccountLinker accountLinker, CookiesManager cookiesManager, CoreBaseSettings coreBaseSettings, DisplayUserSettingsHelper displayUserSettingsHelper, @@ -104,7 +104,7 @@ public class ThirdpartyController : ApiControllerBase if (_authContext.IsAuthenticated) { - linkedAccounts = _accountLinker.Get("webstudio").GetLinkedProfiles(_authContext.CurrentAccount.ID.ToString()); + linkedAccounts = _accountLinker.GetLinkedProfiles(_authContext.CurrentAccount.ID.ToString()); } fromOnly = string.IsNullOrWhiteSpace(fromOnly) ? string.Empty : fromOnly.ToLower(); @@ -148,7 +148,7 @@ public class ThirdpartyController : ApiControllerBase if (string.IsNullOrEmpty(profile.AuthorizationError)) { - GetLinker().AddLink(_securityContext.CurrentAccount.ID.ToString(), profile); + _accountLinker.AddLink(_securityContext.CurrentAccount.ID.ToString(), profile); _messageService.Send(MessageAction.UserLinkedSocialAccount, GetMeaningfulProviderName(profile.Provider)); } else @@ -204,7 +204,7 @@ public class ThirdpartyController : ApiControllerBase SaveContactImage(userID, thirdPartyProfile.Avatar); } - GetLinker().AddLink(userID.ToString(), thirdPartyProfile); + _accountLinker.AddLink(userID.ToString(), thirdPartyProfile); } finally { @@ -232,7 +232,7 @@ public class ThirdpartyController : ApiControllerBase [HttpDelete("thirdparty/unlinkaccount")] public void UnlinkAccount(string provider) { - GetLinker().RemoveProvider(_securityContext.CurrentAccount.ID.ToString(), provider); + _accountLinker.RemoveProvider(_securityContext.CurrentAccount.ID.ToString(), provider); _messageService.Send(MessageAction.UserUnlinkedSocialAccount, GetMeaningfulProviderName(provider)); } @@ -262,11 +262,6 @@ public class ThirdpartyController : ApiControllerBase return _userManagerWrapper.AddUser(userInfo, passwordHash, true, true, isVisitor, fromInviteLink); } - private AccountLinker GetLinker() - { - return _accountLinker.Get("webstudio"); - } - private void SaveContactImage(Guid userID, string url) { using (var memstream = new MemoryStream()) diff --git a/web/ASC.Web.Api/Api/AuthenticationController.cs b/web/ASC.Web.Api/Api/AuthenticationController.cs index e9de9d48ea..8c197fa9e4 100644 --- a/web/ASC.Web.Api/Api/AuthenticationController.cs +++ b/web/ASC.Web.Api/Api/AuthenticationController.cs @@ -46,7 +46,7 @@ public class AuthenticationController : ControllerBase private readonly SetupInfo _setupInfo; private readonly MessageService _messageService; private readonly ProviderManager _providerManager; - private readonly IOptionsSnapshot _accountLinker; + private readonly AccountLinker _accountLinker; private readonly CoreBaseSettings _coreBaseSettings; private readonly PersonalSettingsHelper _personalSettingsHelper; private readonly StudioNotifyService _studioNotifyService; @@ -80,7 +80,7 @@ public class AuthenticationController : ControllerBase SetupInfo setupInfo, MessageService messageService, ProviderManager providerManager, - IOptionsSnapshot accountLinker, + AccountLinker accountLinker, CoreBaseSettings coreBaseSettings, PersonalSettingsHelper personalSettingsHelper, StudioNotifyService studioNotifyService, @@ -534,8 +534,7 @@ public class AuthenticationController : ControllerBase } } - var linker = _accountLinker.Get("webstudio"); - linker.AddLink(userInfo.Id.ToString(), loginProfile); + _accountLinker.AddLink(userInfo.Id.ToString(), loginProfile); return userInfo; } @@ -581,7 +580,7 @@ public class AuthenticationController : ControllerBase return false; } - var linkedProfiles = _accountLinker.Get("webstudio").GetLinkedObjectsByHashId(hashId); + var linkedProfiles = _accountLinker.GetLinkedObjectsByHashId(hashId); var tmp = Guid.Empty; if (linkedProfiles.Any(profileId => Guid.TryParse(profileId, out tmp) && _userManager.UserExists(tmp))) { From ff8e3c38e9b161acadb89f459a42c087407a8d2b Mon Sep 17 00:00:00 2001 From: MaksimChegulov Date: Thu, 25 Aug 2022 13:54:11 +0300 Subject: [PATCH 30/30] removed unnecessary --- .../Caching/CachedUserService.cs | 36 ------------------- .../Context/Impl/CoreConfiguration.cs | 33 +---------------- common/ASC.Core.Common/Tenants/TenantUtil.cs | 28 --------------- 3 files changed, 1 insertion(+), 96 deletions(-) diff --git a/common/ASC.Core.Common/Caching/CachedUserService.cs b/common/ASC.Core.Common/Caching/CachedUserService.cs index 17d433a1a5..b8e8f7a0c5 100644 --- a/common/ASC.Core.Common/Caching/CachedUserService.cs +++ b/common/ASC.Core.Common/Caching/CachedUserService.cs @@ -134,42 +134,6 @@ public class UserServiceCache } } -[Scope] -class ConfigureCachedUserService : IConfigureNamedOptions -{ - internal readonly IOptionsSnapshot Service; - internal readonly UserServiceCache UserServiceCache; - internal readonly CoreBaseSettings CoreBaseSettings; - - public ConfigureCachedUserService( - IOptionsSnapshot service, - UserServiceCache userServiceCache, - CoreBaseSettings coreBaseSettings) - { - Service = service; - UserServiceCache = userServiceCache; - CoreBaseSettings = coreBaseSettings; - } - - public void Configure(string name, CachedUserService options) - { - Configure(options); - options.Service = Service.Get(name); - } - - public void Configure(CachedUserService options) - { - options.Service = Service.Value; - options.CoreBaseSettings = CoreBaseSettings; - options.UserServiceCache = UserServiceCache; - options.Cache = UserServiceCache.Cache; - options.CacheUserInfoItem = UserServiceCache.CacheUserInfoItem; - options.CacheUserPhotoItem = UserServiceCache.CacheUserPhotoItem; - options.CacheGroupCacheItem = UserServiceCache.CacheGroupCacheItem; - options.CacheUserGroupRefItem = UserServiceCache.CacheUserGroupRefItem; - } -} - [Scope] public class CachedUserService : IUserService, ICachedService { diff --git a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs index 77f6f291cb..010ce6e141 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -66,38 +66,7 @@ public class CoreBaseSettings public bool DisableDocSpace => _disableDocSpace ?? (bool)(_disableDocSpace = string.Equals(Configuration["core:disableDocspace"], "true", StringComparison.OrdinalIgnoreCase)); } -class ConfigureCoreSettings : IConfigureNamedOptions -{ - private readonly IOptionsSnapshot _tenantService; - private readonly CoreBaseSettings _coreBaseSettings; - private readonly IConfiguration _configuration; - - public ConfigureCoreSettings( - IOptionsSnapshot tenantService, - CoreBaseSettings coreBaseSettings, - IConfiguration configuration - ) - { - _tenantService = tenantService; - _coreBaseSettings = coreBaseSettings; - _configuration = configuration; - } - - public void Configure(string name, CoreSettings options) - { - Configure(options); - options.TenantService = _tenantService.Get(name); - } - - public void Configure(CoreSettings options) - { - options.Configuration = _configuration; - options.CoreBaseSettings = _coreBaseSettings; - options.TenantService = _tenantService.Value; - } -} - -[Scope(typeof(ConfigureCoreSettings))] +[Scope] public class CoreSettings { public string BaseDomain diff --git a/common/ASC.Core.Common/Tenants/TenantUtil.cs b/common/ASC.Core.Common/Tenants/TenantUtil.cs index 30c77bb27f..fea42b4294 100644 --- a/common/ASC.Core.Common/Tenants/TenantUtil.cs +++ b/common/ASC.Core.Common/Tenants/TenantUtil.cs @@ -27,34 +27,6 @@ namespace ASC.Core.Tenants; [Scope] -class ConfigureTenantUtil : IConfigureNamedOptions -{ - private readonly IOptionsSnapshot _tenantManager; - private readonly TimeZoneConverter _timeZoneConverter; - - public ConfigureTenantUtil( - IOptionsSnapshot tenantManager, - TimeZoneConverter timeZoneConverter - ) - { - _tenantManager = tenantManager; - _timeZoneConverter = timeZoneConverter; - } - - public void Configure(string name, TenantUtil options) - { - Configure(options); - options._tenantManager = _tenantManager.Get(name); - } - - public void Configure(TenantUtil options) - { - options._timeZoneConverter = _timeZoneConverter; - options._tenantManager = _tenantManager.Value; - } -} - -[Scope(typeof(ConfigureTenantUtil))] public class TenantUtil { internal TenantManager _tenantManager;