From d828a58fe11fad37aa461bd92f483faab1208e5f Mon Sep 17 00:00:00 2001
From: SuhorukovAnton
Date: Tue, 15 Feb 2022 14:05:43 +0300
Subject: [PATCH 01/28] refactoring: update editorconfig
---
.editorconfig | 114 +++++++++++++++++++++++++++-----------------------
1 file changed, 62 insertions(+), 52 deletions(-)
diff --git a/.editorconfig b/.editorconfig
index 9a74367cef..251a5c60c1 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -29,34 +29,30 @@ dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_property = false:silent
# Language keywords vs BCL types preferences
-dotnet_style_predefined_type_for_locals_parameters_members = true:warning
-dotnet_style_predefined_type_for_member_access = true:warning
+dotnet_style_predefined_type_for_locals_parameters_members = true:silent
+dotnet_style_predefined_type_for_member_access = true:silent
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
-dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
+dotnet_style_parentheses_in_other_operators = always_for_clarity:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
# Expression-level preferences
-dotnet_style_coalesce_expression = true:warning
-dotnet_style_collection_initializer = true:warning
-dotnet_style_explicit_tuple_names = true:warning
-dotnet_style_null_propagation = true:warning
-dotnet_style_object_initializer = true:warning
-dotnet_style_operator_placement_when_wrapping = beginning_of_line
-dotnet_style_prefer_auto_properties = true:warning
-dotnet_style_prefer_compound_assignment = true:warning
+dotnet_style_object_initializer = true:suggestion
+dotnet_style_collection_initializer = true:suggestion
+dotnet_style_explicit_tuple_names = true:suggestion
+dotnet_style_null_propagation = true:suggestion
+dotnet_style_coalesce_expression = true:suggestion
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent
+dotnet_style_prefer_inferred_tuple_names = true:suggestion
+dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
+dotnet_style_prefer_auto_properties = true:silent
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
-dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning
-dotnet_style_prefer_inferred_tuple_names = true:warning
-dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
-dotnet_style_prefer_simplified_boolean_expressions = true:warning
-dotnet_style_prefer_simplified_interpolation = true:suggestion
# Field preferences
dotnet_style_readonly_field = true:warning
@@ -64,6 +60,13 @@ dotnet_style_readonly_field = true:warning
# Parameter preferences
dotnet_code_quality_unused_parameters = all:warning
+# Suppression preferences
+dotnet_remove_unnecessary_suppression_exclusions = none
+
+# New line preferences
+dotnet_style_allow_multiple_blank_lines_experimental = false
+dotnet_style_allow_statement_immediately_after_block_experimental = false
+
#### C# Coding Conventions ####
# var preferences
@@ -72,44 +75,48 @@ csharp_style_var_for_built_in_types = true:warning
csharp_style_var_when_type_is_apparent = true:warning
# Expression-bodied members
-csharp_style_expression_bodied_accessors = when_on_single_line:suggestion
+csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_constructors = false:silent
-csharp_style_expression_bodied_indexers = when_on_single_line:suggestion
-csharp_style_expression_bodied_lambdas = when_on_single_line:suggestion
-csharp_style_expression_bodied_local_functions = when_on_single_line:suggestion
-csharp_style_expression_bodied_methods = false:suggestion
csharp_style_expression_bodied_operators = false:silent
-csharp_style_expression_bodied_properties = when_on_single_line:suggestion
+csharp_style_expression_bodied_properties = true:silent
+csharp_style_expression_bodied_indexers = true:silent
+csharp_style_expression_bodied_accessors = true:silent
# Pattern matching preferences
-csharp_style_pattern_matching_over_as_with_null_check = true:warning
-csharp_style_pattern_matching_over_is_with_cast_check = true:warning
-csharp_style_prefer_switch_expression = true:suggestion
+csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
+csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
# Null-checking preferences
-csharp_style_conditional_delegate_call = true:warning
+csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
-csharp_prefer_static_local_function = true:suggestion
-csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
+csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
# Code-block preferences
-csharp_prefer_braces = true:silent
-csharp_prefer_simple_using_statement = true:suggestion
+csharp_prefer_braces = true:warning
+csharp_prefer_simple_using_statement = false:silent
+csharp_style_namespace_declarations = file_scoped:warning
# Expression-level preferences
-csharp_prefer_simple_default_expression = true:warning
-csharp_style_deconstructed_variable_declaration = true:warning
-csharp_style_inlined_variable_declaration = true:warning
-csharp_style_pattern_local_over_anonymous_function = true:warning
-csharp_style_prefer_index_operator = true:warning
-csharp_style_prefer_range_operator = true:warning
-csharp_style_throw_expression = true:warning
-csharp_style_unused_value_assignment_preference = discard_variable:suggestion
+csharp_prefer_simple_default_expression = false:silent
+csharp_style_deconstructed_variable_declaration = true:suggestion
+csharp_style_implicit_object_creation_when_type_is_apparent = false
+csharp_style_inlined_variable_declaration = true:suggestion
+csharp_style_pattern_local_over_anonymous_function = true:suggestion
+csharp_style_prefer_index_operator = false
+csharp_style_prefer_null_check_over_type_check = true
+csharp_style_prefer_range_operator = false
+csharp_style_throw_expression = true:suggestion
+csharp_style_unused_value_assignment_preference = discard_variable
csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion
# 'using' directive preferences
-csharp_using_directive_placement = outside_namespace:silent
+csharp_using_directive_placement = outside_namespace:warning
+
+# New line preferences
+csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false
+csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false
+csharp_style_allow_embedded_statements_on_same_line_experimental = true
#### C# Formatting Rules ####
@@ -126,8 +133,8 @@ csharp_new_line_between_query_expression_clauses = true
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
-csharp_indent_case_contents_when_block = false
-csharp_indent_labels = one_less_than_current
+csharp_indent_case_contents_when_block = true
+csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
@@ -162,32 +169,32 @@ csharp_preserve_single_line_statements = true
# Naming rules
+dotnet_naming_rule.private_or_internal_field_should_be_begin_with_underscore.severity = warning
+dotnet_naming_rule.private_or_internal_field_should_be_begin_with_underscore.symbols = private_or_internal_field
+dotnet_naming_rule.private_or_internal_field_should_be_begin_with_underscore.style = begin_with_underscore
+
dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
-dotnet_naming_rule.types_should_be_pascal_case.severity = warning
+dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
-dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = warning
-dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
-dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
-
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
+dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field
+dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected
+dotnet_naming_symbols.private_or_internal_field.required_modifiers =
+
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
-dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
-dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
-dotnet_naming_symbols.non_field_members.required_modifiers =
-
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
@@ -200,5 +207,8 @@ dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
-# Default severity for analyzer diagnostics with category 'Style'
-dotnet_analyzer_diagnostic.category-Style.severity = silent
\ No newline at end of file
+dotnet_naming_style.begin_with_underscore.required_prefix = _
+dotnet_naming_style.begin_with_underscore.required_suffix =
+dotnet_naming_style.begin_with_underscore.word_separator =
+dotnet_naming_style.begin_with_underscore.capitalization = camel_case
+csharp_prefer_static_local_function=false:error
From c81c9346b52e529ff9c9b475c1a2b7f7858fa41f Mon Sep 17 00:00:00 2001
From: SuhorukovAnton
Date: Tue, 15 Feb 2022 14:11:08 +0300
Subject: [PATCH 02/28] refactoring: delete waste
---
.editorconfig | 1 -
1 file changed, 1 deletion(-)
diff --git a/.editorconfig b/.editorconfig
index 251a5c60c1..47dae92c15 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -211,4 +211,3 @@ dotnet_naming_style.begin_with_underscore.required_prefix = _
dotnet_naming_style.begin_with_underscore.required_suffix =
dotnet_naming_style.begin_with_underscore.word_separator =
dotnet_naming_style.begin_with_underscore.capitalization = camel_case
-csharp_prefer_static_local_function=false:error
From e42e0aa4e564d43131098fc6f7acd44c7161f8ae Mon Sep 17 00:00:00 2001
From: SuhorukovAnton
Date: Wed, 16 Feb 2022 17:07:58 +0300
Subject: [PATCH 03/28] refactoring: voipService
---
common/ASC.VoipService/Dao/AbstractDao.cs | 19 +-
common/ASC.VoipService/Dao/CachedVoipDao.cs | 121 ++--
common/ASC.VoipService/Dao/VoIPCallFilter.cs | 147 +++--
common/ASC.VoipService/Dao/VoipDao.cs | 518 +++++++++---------
common/ASC.VoipService/IVoipProvider.cs | 31 +-
common/ASC.VoipService/Twilio/TwilioPhone.cs | 19 +-
.../ASC.VoipService/Twilio/TwilioProvider.cs | 65 ++-
.../Twilio/TwilioResponseHelper.cs | 302 +++++-----
.../Twilio/TwilioVoipSettings.cs | 89 ++-
common/ASC.VoipService/VoipCall.cs | 91 ++-
common/ASC.VoipService/VoipModel.cs | 259 +++++----
common/ASC.VoipService/VoipPhone.cs | 99 ++--
common/ASC.VoipService/VoipSettings.cs | 275 +++++-----
13 files changed, 1007 insertions(+), 1028 deletions(-)
diff --git a/common/ASC.VoipService/Dao/AbstractDao.cs b/common/ASC.VoipService/Dao/AbstractDao.cs
index fb74e26a9b..20f00495d5 100644
--- a/common/ASC.VoipService/Dao/AbstractDao.cs
+++ b/common/ASC.VoipService/Dao/AbstractDao.cs
@@ -28,23 +28,22 @@ namespace ASC.VoipService.Dao
{
public class AbstractDao
{
- private readonly string dbid = "default";
-
- private Lazy LazyVoipDbContext { get; }
- protected VoipDbContext VoipDbContext { get => LazyVoipDbContext.Value; }
-
- protected AbstractDao(DbContextManager dbOptions, TenantManager tenantManager)
- {
- LazyVoipDbContext = new Lazy(() => dbOptions.Get(dbid));
- TenantID = tenantManager.GetCurrentTenant().TenantId;
- }
+ private readonly string _dbid = "default";
+ private Lazy _lazyVoipDbContext;
+ protected VoipDbContext VoipDbContext { get => _lazyVoipDbContext.Value; }
protected int TenantID
{
get;
private set;
}
+ protected AbstractDao(DbContextManager dbOptions, TenantManager tenantManager)
+ {
+ _lazyVoipDbContext = new Lazy(() => dbOptions.Get(_dbid));
+ TenantID = tenantManager.GetCurrentTenant().TenantId;
+ }
+
protected string GetTenantColumnName(string table)
{
const string tenant = "tenant_id";
diff --git a/common/ASC.VoipService/Dao/CachedVoipDao.cs b/common/ASC.VoipService/Dao/CachedVoipDao.cs
index 3635caeefe..90647a9e48 100644
--- a/common/ASC.VoipService/Dao/CachedVoipDao.cs
+++ b/common/ASC.VoipService/Dao/CachedVoipDao.cs
@@ -23,78 +23,77 @@
*
*/
-namespace ASC.VoipService.Dao
+namespace ASC.VoipService.Dao;
+
+[Singletone]
+public class VoipDaoCache
{
- [Singletone]
- public class VoipDaoCache
+ internal readonly ICache _cache;
+ private readonly ICacheNotify _notify;
+
+ public VoipDaoCache(ICacheNotify notify, ICache cache)
{
- internal ICache Cache { get; }
- private ICacheNotify Notify { get; }
-
- public VoipDaoCache(ICacheNotify notify, ICache cache)
- {
- Cache = cache;
- Notify = notify;
- Notify.Subscribe((c) => Cache.Remove(CachedVoipDao.GetCacheKey(c.Tenant)), Common.Caching.CacheNotifyAction.Any);
- }
-
- public void ResetCache(int tenant)
- {
- Notify.Publish(new CachedVoipItem { Tenant = tenant }, Common.Caching.CacheNotifyAction.Any);
- }
+ _cache = cache;
+ _notify = notify;
+ _notify.Subscribe((c) => _cache.Remove(CachedVoipDao.GetCacheKey(c.Tenant)), Common.Caching.CacheNotifyAction.Any);
}
- [Scope]
- public class CachedVoipDao : VoipDao
+ public void ResetCache(int tenant)
{
- private readonly ICache cache;
- private static readonly TimeSpan timeout = TimeSpan.FromDays(1);
+ _notify.Publish(new CachedVoipItem { Tenant = tenant }, Common.Caching.CacheNotifyAction.Any);
+ }
+}
- private VoipDaoCache VoipDaoCache { get; }
+[Scope]
+public class CachedVoipDao : VoipDao
+{
+ private static readonly TimeSpan timeout = TimeSpan.FromDays(1);
+
+ private readonly ICache _cache;
+ private readonly VoipDaoCache _voipDaoCache;
- public CachedVoipDao(
- TenantManager tenantManager,
- DbContextManager dbOptions,
- AuthContext authContext,
- TenantUtil tenantUtil,
- SecurityContext securityContext,
- BaseCommonLinkUtility baseCommonLinkUtility,
- ConsumerFactory consumerFactory,
- VoipDaoCache voipDaoCache)
- : base(tenantManager, dbOptions, authContext, tenantUtil, securityContext, baseCommonLinkUtility, consumerFactory)
- {
- cache = voipDaoCache.Cache;
- VoipDaoCache = voipDaoCache;
- }
+ public CachedVoipDao(
+ TenantManager tenantManager,
+ DbContextManager dbOptions,
+ AuthContext authContext,
+ TenantUtil tenantUtil,
+ SecurityContext securityContext,
+ BaseCommonLinkUtility baseCommonLinkUtility,
+ ConsumerFactory consumerFactory,
+ VoipDaoCache voipDaoCache)
+ : base(tenantManager, dbOptions, authContext, tenantUtil, securityContext, baseCommonLinkUtility, consumerFactory)
+ {
+ _cache = voipDaoCache._cache;
+ _voipDaoCache = voipDaoCache;
+ }
- public override VoipPhone SaveOrUpdateNumber(VoipPhone phone)
+ public override VoipPhone SaveOrUpdateNumber(VoipPhone phone)
+ {
+ var result = base.SaveOrUpdateNumber(phone);
+ _voipDaoCache.ResetCache(TenantID);
+ return result;
+ }
+
+ public override void DeleteNumber(string phoneId = "")
+ {
+ base.DeleteNumber(phoneId);
+ _voipDaoCache.ResetCache(TenantID);
+ }
+
+ public override IEnumerable GetNumbers(params string[] ids)
+ {
+ var numbers = _cache.Get>(GetCacheKey(TenantID));
+ if (numbers == null)
{
- var result = base.SaveOrUpdateNumber(phone);
- VoipDaoCache.ResetCache(TenantID);
- return result;
+ numbers = new List(base.GetAllNumbers());
+ _cache.Insert(GetCacheKey(TenantID), numbers, DateTime.UtcNow.Add(timeout));
}
- public override void DeleteNumber(string phoneId = "")
- {
- base.DeleteNumber(phoneId);
- VoipDaoCache.ResetCache(TenantID);
- }
+ return ids.Length > 0 ? numbers.Where(r => ids.Contains(r.Id) || ids.Contains(r.Number)).ToList() : numbers;
+ }
- public override IEnumerable GetNumbers(params string[] ids)
- {
- var numbers = cache.Get>(GetCacheKey(TenantID));
- if (numbers == null)
- {
- numbers = new List(base.GetAllNumbers());
- cache.Insert(GetCacheKey(TenantID), numbers, DateTime.UtcNow.Add(timeout));
- }
-
- return ids.Length > 0 ? numbers.Where(r => ids.Contains(r.Id) || ids.Contains(r.Number)).ToList() : numbers;
- }
-
- public static string GetCacheKey(int tenant)
- {
- return "voip" + tenant.ToString(CultureInfo.InvariantCulture);
- }
+ public static string GetCacheKey(int tenant)
+ {
+ return "voip" + tenant.ToString(CultureInfo.InvariantCulture);
}
}
\ No newline at end of file
diff --git a/common/ASC.VoipService/Dao/VoIPCallFilter.cs b/common/ASC.VoipService/Dao/VoIPCallFilter.cs
index fe0fc3a896..2267d8aa41 100644
--- a/common/ASC.VoipService/Dao/VoIPCallFilter.cs
+++ b/common/ASC.VoipService/Dao/VoIPCallFilter.cs
@@ -23,92 +23,91 @@
*
*/
-namespace ASC.VoipService.Dao
+namespace ASC.VoipService.Dao;
+
+public class VoipCallFilter
{
- public class VoipCallFilter
+ public string Type { get; set; }
+
+ public DateTime? FromDate { get; set; }
+
+ public DateTime? ToDate { get; set; }
+
+ public Guid? Agent { get; set; }
+
+ public int? Client { get; set; }
+
+ public int? ContactID { get; set; }
+
+ public string Id { get; set; }
+
+ public string ParentId { get; set; }
+
+ public string SortBy { get; set; }
+
+ public bool SortOrder { get; set; }
+
+ public string SearchText { get; set; }
+
+ public long Offset { get; set; }
+
+ public long Max { get; set; }
+
+ public int? TypeStatus
{
- public string Type { get; set; }
-
- public DateTime? FromDate { get; set; }
-
- public DateTime? ToDate { get; set; }
-
- public Guid? Agent { get; set; }
-
- public int? Client { get; set; }
-
- public int? ContactID { get; set; }
-
- public string Id { get; set; }
-
- public string ParentId { get; set; }
-
- public string SortBy { get; set; }
-
- public bool SortOrder { get; set; }
-
- public string SearchText { get; set; }
-
- public long Offset { get; set; }
-
- public long Max { get; set; }
-
- public int? TypeStatus
+ get
{
- get
- {
- if (string.IsNullOrWhiteSpace(Type)) return null;
- if (TypeStatuses.TryGetValue(Type, out var status)) return status;
+ if (string.IsNullOrWhiteSpace(Type)) return null;
+ if (TypeStatuses.TryGetValue(Type, out var status)) return status;
- return null;
- }
+ return null;
}
+ }
- public string SortByColumn
+ public string SortByColumn
+ {
+ get
{
- get
- {
- if (string.IsNullOrWhiteSpace(SortBy)) return null;
- return SortColumns.ContainsKey(SortBy) ? SortColumns[SortBy] : null;
- }
+ if (string.IsNullOrWhiteSpace(SortBy)) return null;
+ return SortColumns.ContainsKey(SortBy) ? SortColumns[SortBy] : null;
}
+ }
- private static Dictionary TypeStatuses
+ private static Dictionary TypeStatuses
+ {
+ get
{
- get
- {
- return new Dictionary
+ return new Dictionary
+ {
{
- {
- "answered", (int)VoipCallStatus.Answered
- },
- {
- "missed", (int)VoipCallStatus.Missed
- },
- {
- "outgoing", (int)VoipCallStatus.Outcoming
- }
- };
- }
- }
-
- private static Dictionary SortColumns
- {
- get
- {
- return new Dictionary
+ "answered", (int)VoipCallStatus.Answered
+ },
{
- {
- "date", "dial_date"
- },
- {
- "duration", "dial_duration"
- },
- {
- "price", "price"
- },
- };
- }
+ "missed", (int)VoipCallStatus.Missed
+ },
+ {
+ "outgoing", (int)VoipCallStatus.Outcoming
+ }
+ };
+ }
+ }
+
+ private static Dictionary SortColumns
+ {
+ get
+ {
+ return new Dictionary
+ {
+ {
+ "date", "dial_date"
+ },
+ {
+ "duration", "dial_duration"
+ },
+ {
+ "price", "price"
+ },
+ };
}
}
}
\ No newline at end of file
diff --git a/common/ASC.VoipService/Dao/VoipDao.cs b/common/ASC.VoipService/Dao/VoipDao.cs
index e520fd4814..fa4638e9f3 100644
--- a/common/ASC.VoipService/Dao/VoipDao.cs
+++ b/common/ASC.VoipService/Dao/VoipDao.cs
@@ -23,342 +23,338 @@
*
*/
-namespace ASC.VoipService.Dao
+namespace ASC.VoipService.Dao;
+
+[Scope(typeof(CachedVoipDao))]
+public class VoipDao : AbstractDao
{
- [Scope(typeof(CachedVoipDao))]
- public class VoipDao : AbstractDao
+ private readonly AuthContext _authContext;
+ private readonly TenantUtil _tenantUtil;
+ private readonly SecurityContext _securityContext;
+ private readonly BaseCommonLinkUtility _baseCommonLinkUtility;
+ private readonly ConsumerFactory _consumerFactory;
+
+ public VoipDao(
+ TenantManager tenantManager,
+ DbContextManager dbOptions,
+ AuthContext authContext,
+ TenantUtil tenantUtil,
+ SecurityContext securityContext,
+ BaseCommonLinkUtility baseCommonLinkUtility,
+ ConsumerFactory consumerFactory)
+ : base(dbOptions, tenantManager)
{
- public VoipDao(
- TenantManager tenantManager,
- DbContextManager dbOptions,
- AuthContext authContext,
- TenantUtil tenantUtil,
- SecurityContext securityContext,
- BaseCommonLinkUtility baseCommonLinkUtility,
- ConsumerFactory consumerFactory)
- : base(dbOptions, tenantManager)
+ _authContext = authContext;
+ _tenantUtil = tenantUtil;
+ _securityContext = securityContext;
+ _baseCommonLinkUtility = baseCommonLinkUtility;
+ _consumerFactory = consumerFactory;
+ }
+
+ public virtual VoipPhone SaveOrUpdateNumber(VoipPhone phone)
+ {
+ if (!string.IsNullOrEmpty(phone.Number))
{
- AuthContext = authContext;
- TenantUtil = tenantUtil;
- SecurityContext = securityContext;
- BaseCommonLinkUtility = baseCommonLinkUtility;
- ConsumerFactory = consumerFactory;
+ phone.Number = phone.Number.TrimStart('+');
}
- public virtual VoipPhone SaveOrUpdateNumber(VoipPhone phone)
+ var voipNumber = new VoipNumber
{
- if (!string.IsNullOrEmpty(phone.Number))
- {
- phone.Number = phone.Number.TrimStart('+');
- }
+ Id = phone.Id,
+ Number = phone.Number,
+ Alias = phone.Alias,
+ Settings = phone.Settings.ToString(),
+ TenantId = TenantID
+ };
- var voipNumber = new VoipNumber
- {
- Id = phone.Id,
- Number = phone.Number,
- Alias = phone.Alias,
- Settings = phone.Settings.ToString(),
- TenantId = TenantID
- };
+ VoipDbContext.VoipNumbers.Add(voipNumber);
+ VoipDbContext.SaveChanges();
- VoipDbContext.VoipNumbers.Add(voipNumber);
- VoipDbContext.SaveChanges();
+ return phone;
+ }
- return phone;
+ public virtual void DeleteNumber(string phoneId = "")
+ {
+ var number = VoipDbContext.VoipNumbers.Where(r => r.Id == phoneId && r.TenantId == TenantID).FirstOrDefault();
+ VoipDbContext.VoipNumbers.Remove(number);
+ VoipDbContext.SaveChanges();
+ }
+
+ public virtual IEnumerable GetAllNumbers()
+ {
+ return VoipDbContext.VoipNumbers
+ .Where(r => r.TenantId == TenantID)
+ .ToList()
+ .ConvertAll(ToPhone);
+ }
+
+ public virtual IEnumerable GetNumbers(params string[] ids)
+ {
+ var numbers = VoipDbContext.VoipNumbers.Where(r => r.TenantId == TenantID);
+
+ if (ids.Length > 0)
+ {
+ numbers = numbers.Where(r => ids.Any(a => a == r.Number || a == r.Id));
}
- public virtual void DeleteNumber(string phoneId = "")
+ return numbers.ToList().ConvertAll(ToPhone);
+ }
+
+ public VoipPhone GetNumber(string id)
+ {
+ return GetNumbers(id.TrimStart('+')).FirstOrDefault();
+ }
+
+ public virtual VoipPhone GetCurrentNumber()
+ {
+ return GetNumbers().FirstOrDefault(r => r.Caller != null);
+ }
+
+
+ public VoipCall SaveOrUpdateCall(VoipCall call)
+ {
+ var voipCall = new DbVoipCall
{
- var number = VoipDbContext.VoipNumbers.Where(r => r.Id == phoneId && r.TenantId == TenantID).FirstOrDefault();
- VoipDbContext.VoipNumbers.Remove(number);
- VoipDbContext.SaveChanges();
+ TenantId = TenantID,
+ Id = call.Id,
+ NumberFrom = call.From,
+ NumberTo = call.To,
+ ContactId = call.ContactId
+ };
+
+ if (!string.IsNullOrEmpty(call.ParentID))
+ {
+ voipCall.ParentCallId = call.ParentID;
}
- public virtual IEnumerable GetAllNumbers()
+ if (call.Status.HasValue)
{
- return VoipDbContext.VoipNumbers
- .Where(r => r.TenantId == TenantID)
- .ToList()
- .ConvertAll(ToPhone);
+ voipCall.Status = (int)call.Status.Value;
}
- public virtual IEnumerable GetNumbers(params string[] ids)
+ if (!call.AnsweredBy.Equals(Guid.Empty))
{
- var numbers = VoipDbContext.VoipNumbers.Where(r => r.TenantId == TenantID);
-
- if (ids.Length > 0)
- {
- numbers = numbers.Where(r => ids.Any(a => a == r.Number || a == r.Id));
- }
-
- return numbers.ToList().ConvertAll(ToPhone);
+ voipCall.AnsweredBy = call.AnsweredBy;
}
- public VoipPhone GetNumber(string id)
+ if (call.DialDate == DateTime.MinValue)
{
- return GetNumbers(id.TrimStart('+')).FirstOrDefault();
+ call.DialDate = DateTime.UtcNow;
}
- public virtual VoipPhone GetCurrentNumber()
+ voipCall.DialDate = _tenantUtil.DateTimeToUtc(call.DialDate);
+
+ if (call.DialDuration > 0)
{
- return GetNumbers().FirstOrDefault(r => r.Caller != null);
+ voipCall.DialDuration = call.DialDuration;
}
-
- public VoipCall SaveOrUpdateCall(VoipCall call)
+ if (call.Price > decimal.Zero)
{
- var voipCall = new DbVoipCall
- {
- TenantId = TenantID,
- Id = call.Id,
- NumberFrom = call.From,
- NumberTo = call.To,
- ContactId = call.ContactId
- };
+ voipCall.Price = call.Price;
+ }
- if (!string.IsNullOrEmpty(call.ParentID))
+ if (call.VoipRecord != null)
+ {
+ if (!string.IsNullOrEmpty(call.VoipRecord.Id))
{
- voipCall.ParentCallId = call.ParentID;
+ voipCall.RecordSid = call.VoipRecord.Id;
}
- if (call.Status.HasValue)
+ if (!string.IsNullOrEmpty(call.VoipRecord.Uri))
{
- voipCall.Status = (int)call.Status.Value;
+ voipCall.RecordUrl = call.VoipRecord.Uri;
}
- if (!call.AnsweredBy.Equals(Guid.Empty))
+ if (call.VoipRecord.Duration != 0)
{
- voipCall.AnsweredBy = call.AnsweredBy;
+ voipCall.RecordDuration = call.VoipRecord.Duration;
}
- if (call.DialDate == DateTime.MinValue)
+ if (call.VoipRecord.Price != default)
{
- call.DialDate = DateTime.UtcNow;
+ voipCall.RecordPrice = call.VoipRecord.Price;
}
+ }
- voipCall.DialDate = TenantUtil.DateTimeToUtc(call.DialDate);
+ VoipDbContext.VoipCalls.Add(voipCall);
+ VoipDbContext.SaveChanges();
- if (call.DialDuration > 0)
- {
- voipCall.DialDuration = call.DialDuration;
- }
+ return call;
+ }
- if (call.Price > decimal.Zero)
- {
- voipCall.Price = call.Price;
- }
+ public IEnumerable GetCalls(VoipCallFilter filter)
+ {
+ var query = GetCallsQuery(filter);
- if (call.VoipRecord != null)
- {
- if (!string.IsNullOrEmpty(call.VoipRecord.Id))
- {
- voipCall.RecordSid = call.VoipRecord.Id;
- }
+ if (filter.SortByColumn != null)
+ {
+ query.OrderBy(filter.SortByColumn, filter.SortOrder);
+ }
- if (!string.IsNullOrEmpty(call.VoipRecord.Uri))
- {
- voipCall.RecordUrl = call.VoipRecord.Uri;
- }
+ query = query.Skip((int)filter.Offset);
+ query = query.Take((int)filter.Max * 3);
- if (call.VoipRecord.Duration != 0)
- {
- voipCall.RecordDuration = call.VoipRecord.Duration;
- }
-
- if (call.VoipRecord.Price != default)
- {
- voipCall.RecordPrice = call.VoipRecord.Price;
- }
- }
-
- VoipDbContext.VoipCalls.Add(voipCall);
- VoipDbContext.SaveChanges();
+ var calls = query.ToList().ConvertAll(ToCall);
+ calls = calls.GroupJoin(calls, call => call.Id, h => h.ParentID, (call, h) =>
+ {
+ call.ChildCalls.AddRange(h);
return call;
- }
+ }).Where(r => string.IsNullOrEmpty(r.ParentID)).ToList();
- public IEnumerable GetCalls(VoipCallFilter filter)
+ return calls;
+ }
+
+ public VoipCall GetCall(string id)
+ {
+ return GetCalls(new VoipCallFilter { Id = id }).FirstOrDefault();
+ }
+
+ public int GetCallsCount(VoipCallFilter filter)
+ {
+ return GetCallsQuery(filter).Where(r => r.DbVoipCall.ParentCallId == "").Count();
+ }
+
+ public IEnumerable GetMissedCalls(Guid agent, long count = 0, DateTime? from = null)
+ {
+ var query = GetCallsQuery(new VoipCallFilter { Agent = agent, SortBy = "date", SortOrder = true, Type = "missed" });
+
+ if (from.HasValue)
{
- var query = GetCallsQuery(filter);
-
- if (filter.SortByColumn != null)
- {
- query.OrderBy(filter.SortByColumn, filter.SortOrder);
- }
-
- query = query.Skip((int)filter.Offset);
- query = query.Take((int)filter.Max * 3);
-
- var calls = query.ToList().ConvertAll(ToCall);
-
- calls = calls.GroupJoin(calls, call => call.Id, h => h.ParentID, (call, h) =>
- {
- call.ChildCalls.AddRange(h);
- return call;
- }).Where(r => string.IsNullOrEmpty(r.ParentID)).ToList();
-
- return calls;
+ query = query.Where(r => r.DbVoipCall.DialDate >= _tenantUtil.DateTimeFromUtc(from.Value));
}
- public VoipCall GetCall(string id)
+ if (count != 0)
{
- return GetCalls(new VoipCallFilter { Id = id }).FirstOrDefault();
+ query = query.Take((int)count);
}
- public int GetCallsCount(VoipCallFilter filter)
+ var a = query.Select(ca => new
{
- return GetCallsQuery(filter).Where(r => r.DbVoipCall.ParentCallId == "").Count();
- }
+ dbVoipCall = ca,
+ tmpDate = VoipDbContext.VoipCalls
+ .Where(tmp => tmp.TenantId == ca.DbVoipCall.TenantId)
+ .Where(tmp => tmp.NumberFrom == ca.DbVoipCall.NumberFrom || tmp.NumberTo == ca.DbVoipCall.NumberFrom)
+ .Where(tmp => tmp.Status <= (int)VoipCallStatus.Missed)
+ .Max(tmp => tmp.DialDate)
+ }).Where(r => r.dbVoipCall.DbVoipCall.DialDate >= r.tmpDate || r.tmpDate == default);
- public IEnumerable GetMissedCalls(Guid agent, long count = 0, DateTime? from = null)
+ return a.ToList().ConvertAll(r => ToCall(r.dbVoipCall));
+ }
+
+ private IQueryable GetCallsQuery(VoipCallFilter filter)
+ {
+ var q = VoipDbContext.VoipCalls
+ .Where(r => r.TenantId == TenantID);
+
+ if (!string.IsNullOrEmpty(filter.Id))
{
- var query = GetCallsQuery(new VoipCallFilter { Agent = agent, SortBy = "date", SortOrder = true, Type = "missed" });
-
- if (from.HasValue)
- {
- query = query.Where(r => r.DbVoipCall.DialDate >= TenantUtil.DateTimeFromUtc(from.Value));
- }
-
- if (count != 0)
- {
- query = query.Take((int)count);
- }
-
- var a = query.Select(ca => new
- {
- dbVoipCall = ca,
- tmpDate = VoipDbContext.VoipCalls
- .Where(tmp => tmp.TenantId == ca.DbVoipCall.TenantId)
- .Where(tmp => tmp.NumberFrom == ca.DbVoipCall.NumberFrom || tmp.NumberTo == ca.DbVoipCall.NumberFrom)
- .Where(tmp => tmp.Status <= (int)VoipCallStatus.Missed)
- .Max(tmp => tmp.DialDate)
- }).Where(r => r.dbVoipCall.DbVoipCall.DialDate >= r.tmpDate || r.tmpDate == default);
-
- return a.ToList().ConvertAll(r => ToCall(r.dbVoipCall));
+ q = q.Where(r => r.Id == filter.Id || r.ParentCallId == filter.Id);
}
- private IQueryable GetCallsQuery(VoipCallFilter filter)
+ if (filter.ContactID.HasValue)
{
- var q = VoipDbContext.VoipCalls
- .Where(r => r.TenantId == TenantID);
-
- if (!string.IsNullOrEmpty(filter.Id))
- {
- q = q.Where(r => r.Id == filter.Id || r.ParentCallId == filter.Id);
- }
-
- if (filter.ContactID.HasValue)
- {
- q = q.Where(r => r.ContactId == filter.ContactID.Value);
- }
-
- if (!string.IsNullOrWhiteSpace(filter.SearchText))
- {
- q = q.Where(r => r.Id.StartsWith(filter.SearchText));
- }
-
- if (filter.TypeStatus.HasValue)
- {
- q = q.Where(r => r.Status == filter.TypeStatus.Value);
- }
-
- if (filter.FromDate.HasValue)
- {
- q = q.Where(r => r.DialDate >= filter.FromDate.Value);
- }
-
- if (filter.ToDate.HasValue)
- {
- q = q.Where(r => r.DialDate <= filter.ToDate.Value);
- }
-
- if (filter.Agent.HasValue)
- {
- q = q.Where(r => r.AnsweredBy == filter.Agent.Value);
- }
-
- return q
- .GroupBy(r => r.Id, r => r)
- .Join(
- VoipDbContext.CrmContact.DefaultIfEmpty(),
- r => r.FirstOrDefault().ContactId,
- c => c.Id,
- (call, contact) => new CallContact { DbVoipCall = call.FirstOrDefault(), CrmContact = contact })
- ;
+ q = q.Where(r => r.ContactId == filter.ContactID.Value);
}
- class CallContact
+ if (!string.IsNullOrWhiteSpace(filter.SearchText))
{
- public DbVoipCall DbVoipCall { get; set; }
- public CrmContact CrmContact { get; set; }
+ q = q.Where(r => r.Id.StartsWith(filter.SearchText));
}
- #region Converters
-
- private VoipPhone ToPhone(VoipNumber r)
+ if (filter.TypeStatus.HasValue)
{
- return GetProvider().GetPhone(r);
+ q = q.Where(r => r.Status == filter.TypeStatus.Value);
}
- private VoipCall ToCall(CallContact dbVoipCall)
+ if (filter.FromDate.HasValue)
{
- var call = new VoipCall
+ q = q.Where(r => r.DialDate >= filter.FromDate.Value);
+ }
+
+ if (filter.ToDate.HasValue)
+ {
+ q = q.Where(r => r.DialDate <= filter.ToDate.Value);
+ }
+
+ if (filter.Agent.HasValue)
+ {
+ q = q.Where(r => r.AnsweredBy == filter.Agent.Value);
+ }
+
+ return q
+ .GroupBy(r => r.Id, r => r)
+ .Join(
+ VoipDbContext.CrmContact.DefaultIfEmpty(),
+ r => r.FirstOrDefault().ContactId,
+ c => c.Id,
+ (call, contact) => new CallContact { DbVoipCall = call.FirstOrDefault(), CrmContact = contact })
+ ;
+ }
+
+ class CallContact
+ {
+ public DbVoipCall DbVoipCall { get; set; }
+ public CrmContact CrmContact { get; set; }
+ }
+
+
+ private VoipPhone ToPhone(VoipNumber r)
+ {
+ return GetProvider().GetPhone(r);
+ }
+
+ private VoipCall ToCall(CallContact dbVoipCall)
+ {
+ var call = new VoipCall
+ {
+ Id = dbVoipCall.DbVoipCall.Id,
+ ParentID = dbVoipCall.DbVoipCall.ParentCallId,
+ From = dbVoipCall.DbVoipCall.NumberFrom,
+ To = dbVoipCall.DbVoipCall.NumberTo,
+ AnsweredBy = dbVoipCall.DbVoipCall.AnsweredBy,
+ DialDate = _tenantUtil.DateTimeFromUtc(dbVoipCall.DbVoipCall.DialDate),
+ DialDuration = dbVoipCall.DbVoipCall.DialDuration,
+ Price = dbVoipCall.DbVoipCall.Price,
+ Status = (VoipCallStatus)dbVoipCall.DbVoipCall.Status,
+ VoipRecord = new VoipRecord
{
- Id = dbVoipCall.DbVoipCall.Id,
- ParentID = dbVoipCall.DbVoipCall.ParentCallId,
- From = dbVoipCall.DbVoipCall.NumberFrom,
- To = dbVoipCall.DbVoipCall.NumberTo,
- AnsweredBy = dbVoipCall.DbVoipCall.AnsweredBy,
- DialDate = TenantUtil.DateTimeFromUtc(dbVoipCall.DbVoipCall.DialDate),
- DialDuration = dbVoipCall.DbVoipCall.DialDuration,
- Price = dbVoipCall.DbVoipCall.Price,
- Status = (VoipCallStatus)dbVoipCall.DbVoipCall.Status,
- VoipRecord = new VoipRecord
- {
- Id = dbVoipCall.DbVoipCall.RecordSid,
- Uri = dbVoipCall.DbVoipCall.RecordUrl,
- Duration = dbVoipCall.DbVoipCall.RecordDuration,
- Price = dbVoipCall.DbVoipCall.RecordPrice
- },
- ContactId = dbVoipCall.CrmContact.Id,
- ContactIsCompany = dbVoipCall.CrmContact.IsCompany,
- };
+ Id = dbVoipCall.DbVoipCall.RecordSid,
+ Uri = dbVoipCall.DbVoipCall.RecordUrl,
+ Duration = dbVoipCall.DbVoipCall.RecordDuration,
+ Price = dbVoipCall.DbVoipCall.RecordPrice
+ },
+ ContactId = dbVoipCall.CrmContact.Id,
+ ContactIsCompany = dbVoipCall.CrmContact.IsCompany,
+ };
- if (call.ContactId != 0)
- {
- call.ContactTitle = call.ContactIsCompany
- ? dbVoipCall.CrmContact.CompanyName
- : dbVoipCall.CrmContact.FirstName == null || dbVoipCall.CrmContact.LastName == null ? null : $"{dbVoipCall.CrmContact.FirstName} {dbVoipCall.CrmContact.LastName}";
- }
-
- return call;
- }
-
- public Consumer Consumer
+ if (call.ContactId != 0)
{
- get { return ConsumerFactory.GetByKey("twilio"); }
+ call.ContactTitle = call.ContactIsCompany
+ ? dbVoipCall.CrmContact.CompanyName
+ : dbVoipCall.CrmContact.FirstName == null || dbVoipCall.CrmContact.LastName == null ? null : $"{dbVoipCall.CrmContact.FirstName} {dbVoipCall.CrmContact.LastName}";
}
- public TwilioProvider GetProvider()
+ return call;
+ }
+
+ public Consumer Consumer
+ {
+ get { return _consumerFactory.GetByKey("twilio"); }
+ }
+
+ public TwilioProvider GetProvider()
+ {
+ return new TwilioProvider(Consumer["twilioAccountSid"], Consumer["twilioAuthToken"], _authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility);
+ }
+
+ public bool ConfigSettingsExist
+ {
+ get
{
- return new TwilioProvider(Consumer["twilioAccountSid"], Consumer["twilioAuthToken"], AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility);
+ return !string.IsNullOrEmpty(Consumer["twilioAccountSid"]) &&
+ !string.IsNullOrEmpty(Consumer["twilioAuthToken"]);
}
-
- public bool ConfigSettingsExist
- {
- get
- {
- return !string.IsNullOrEmpty(Consumer["twilioAccountSid"]) &&
- !string.IsNullOrEmpty(Consumer["twilioAuthToken"]);
- }
- }
-
- private AuthContext AuthContext { get; }
- private TenantUtil TenantUtil { get; }
- private SecurityContext SecurityContext { get; }
- private BaseCommonLinkUtility BaseCommonLinkUtility { get; }
- private ConsumerFactory ConsumerFactory { get; }
-
- #endregion
}
}
\ No newline at end of file
diff --git a/common/ASC.VoipService/IVoipProvider.cs b/common/ASC.VoipService/IVoipProvider.cs
index fdd2de18ce..06f2c80cf5 100644
--- a/common/ASC.VoipService/IVoipProvider.cs
+++ b/common/ASC.VoipService/IVoipProvider.cs
@@ -23,32 +23,31 @@
*
*/
-namespace ASC.VoipService
+namespace ASC.VoipService;
+
+public interface IVoipProvider
{
- public interface IVoipProvider
- {
- IEnumerable GetExistingPhoneNumbers();
+ IEnumerable GetExistingPhoneNumbers();
- IEnumerable GetAvailablePhoneNumbers(PhoneNumberType phoneNumberType, string isoCountryCode);
+ IEnumerable GetAvailablePhoneNumbers(PhoneNumberType phoneNumberType, string isoCountryCode);
- VoipPhone BuyNumber(string phoneNumber);
+ VoipPhone BuyNumber(string phoneNumber);
- VoipPhone DeleteNumber(VoipPhone phone);
+ VoipPhone DeleteNumber(VoipPhone phone);
- VoipPhone GetPhone(VoipNumber r);
+ VoipPhone GetPhone(VoipNumber r);
- VoipPhone GetPhone(string id);
+ VoipPhone GetPhone(string id);
- VoipCall GetCall(string callId);
+ VoipCall GetCall(string callId);
- string GetToken(Agent agent, int seconds = 60 * 60 * 24);
+ string GetToken(Agent agent, int seconds = 60 * 60 * 24);
- void UpdateSettings(VoipPhone phone);
+ void UpdateSettings(VoipPhone phone);
- VoipRecord GetRecord(string callId, string recordId);
+ VoipRecord GetRecord(string callId, string recordId);
- void CreateQueue(VoipPhone newPhone);
+ void CreateQueue(VoipPhone newPhone);
- void DisablePhone(VoipPhone phone);
- }
+ void DisablePhone(VoipPhone phone);
}
diff --git a/common/ASC.VoipService/Twilio/TwilioPhone.cs b/common/ASC.VoipService/Twilio/TwilioPhone.cs
index 227da4123c..055dc62fd5 100644
--- a/common/ASC.VoipService/Twilio/TwilioPhone.cs
+++ b/common/ASC.VoipService/Twilio/TwilioPhone.cs
@@ -27,8 +27,7 @@ namespace ASC.VoipService.Twilio
{
public class TwilioPhone : VoipPhone
{
- private readonly TwilioRestClient twilio;
-
+ private readonly TwilioRestClient _twilio;
public TwilioPhone(
TwilioRestClient twilio,
AuthContext authContext,
@@ -37,7 +36,7 @@ namespace ASC.VoipService.Twilio
BaseCommonLinkUtility baseCommonLinkUtility) :
base(authContext, tenantUtil, securityContext, baseCommonLinkUtility)
{
- this.twilio = twilio;
+ _twilio = twilio;
Settings = new TwilioVoipSettings(authContext, tenantUtil, securityContext, baseCommonLinkUtility);
}
@@ -52,7 +51,7 @@ namespace ASC.VoipService.Twilio
SendDigits = number.Length > 1 ? number[1] + "#" : string.Empty,
Record = Settings.Caller.Record,
Url = new System.Uri(Settings.Connect(contactId: contactId))
- }, twilio);
+ }, _twilio);
return new VoipCall { Id = call.Sid, From = call.From, To = call.To };
}
@@ -64,7 +63,7 @@ namespace ASC.VoipService.Twilio
public override VoipCall RedirectCall(string callId, string to)
{
- var call = CallResource.Update(callId, url: new System.Uri(Settings.Redirect(to)), method: HttpMethod.Post, client: twilio);
+ var call = CallResource.Update(callId, url: new System.Uri(Settings.Redirect(to)), method: HttpMethod.Post, client: _twilio);
return new VoipCall { Id = call.Sid, To = to };
}
@@ -79,24 +78,24 @@ namespace ASC.VoipService.Twilio
public Queue CreateQueue(string name, int size, string waitUrl, int waitTime)
{
- var queues = QueueResource.Read(new ReadQueueOptions(), twilio);
+ var queues = QueueResource.Read(new ReadQueueOptions(), _twilio);
var queue = queues.FirstOrDefault(r => r.FriendlyName == name);
if (queue == null)
{
- queue = QueueResource.Create(name, client: twilio);
+ queue = QueueResource.Create(name, client: _twilio);
}
return new Queue(queue.Sid, name, size, waitUrl, waitTime);
}
public string GetQueue(string name)
{
- var queues = QueueResource.Read(new ReadQueueOptions(), twilio);
+ var queues = QueueResource.Read(new ReadQueueOptions(), _twilio);
return queues.First(r => r.FriendlyName == name).Sid;
}
public IEnumerable QueueCalls(string id)
{
- var calls = MemberResource.Read(id, client: twilio);
+ var calls = MemberResource.Read(id, client: _twilio);
return calls.Select(r => r.CallSid);
}
@@ -106,7 +105,7 @@ namespace ASC.VoipService.Twilio
if (calls.Contains(callId))
{
MemberResource.Update(queueId, callId, new System.Uri(Settings.Dequeue(reject)), HttpMethod.Post,
- client: twilio);
+ client: _twilio);
}
}
diff --git a/common/ASC.VoipService/Twilio/TwilioProvider.cs b/common/ASC.VoipService/Twilio/TwilioProvider.cs
index 2423b7ddeb..4f84fe560c 100644
--- a/common/ASC.VoipService/Twilio/TwilioProvider.cs
+++ b/common/ASC.VoipService/Twilio/TwilioProvider.cs
@@ -31,28 +31,27 @@ namespace ASC.VoipService.Twilio
{
public class TwilioProvider : IVoipProvider
{
- private readonly string accountSid;
- private readonly string authToken;
- private readonly TwilioRestClient client;
-
- private AuthContext AuthContext { get; }
- private TenantUtil TenantUtil { get; }
- private SecurityContext SecurityContext { get; }
- private BaseCommonLinkUtility BaseCommonLinkUtility { get; }
+ private readonly string _accountSid;
+ private readonly string _authToken;
+ private readonly TwilioRestClient _client;
+ private readonly AuthContext _authContext;
+ private readonly TenantUtil _tenantUtil;
+ private readonly SecurityContext _securityContext;
+ private readonly BaseCommonLinkUtility _baseCommonLinkUtility;
public TwilioProvider(string accountSid, string authToken, AuthContext authContext, TenantUtil tenantUtil, SecurityContext securityContext, BaseCommonLinkUtility baseCommonLinkUtility)
{
if (string.IsNullOrEmpty(accountSid)) throw new ArgumentNullException(nameof(accountSid));
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException(nameof(authToken));
- this.authToken = authToken;
- AuthContext = authContext;
- TenantUtil = tenantUtil;
- SecurityContext = securityContext;
- BaseCommonLinkUtility = baseCommonLinkUtility;
- this.accountSid = accountSid;
+ _authToken = authToken;
+ _authContext = authContext;
+ _tenantUtil = tenantUtil;
+ _securityContext = securityContext;
+ _baseCommonLinkUtility = baseCommonLinkUtility;
+ _accountSid = accountSid;
- client = new TwilioRestClient(accountSid, authToken);
+ _client = new TwilioRestClient(accountSid, authToken);
}
#region Call
@@ -66,7 +65,7 @@ namespace ASC.VoipService.Twilio
{
try
{
- var record = RecordingResource.Fetch(callId, recordSid, client: client);
+ var record = RecordingResource.Fetch(callId, recordSid, client: _client);
if (!record.Price.HasValue)
{
@@ -108,31 +107,31 @@ namespace ASC.VoipService.Twilio
var newNumber = IncomingPhoneNumberResource.Create(
new CreateIncomingPhoneNumberOptions
{
- PathAccountSid = accountSid,
+ PathAccountSid = _accountSid,
PhoneNumber = new PhoneNumber(phoneNumber)
- }, client);
+ }, _client);
- return new TwilioPhone(client, AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility) { Id = newNumber.Sid, Number = phoneNumber.Substring(1) };
+ return new TwilioPhone(_client, _authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility) { Id = newNumber.Sid, Number = phoneNumber.Substring(1) };
}
public VoipPhone DeleteNumber(VoipPhone phone)
{
- IncomingPhoneNumberResource.Delete(phone.Id, client: client);
+ IncomingPhoneNumberResource.Delete(phone.Id, client: _client);
return phone;
}
public IEnumerable GetExistingPhoneNumbers()
{
- var result = IncomingPhoneNumberResource.Read(client: client);
- return result.Select(r => new TwilioPhone(client, AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility) { Id = r.Sid, Number = r.PhoneNumber.ToString() });
+ var result = IncomingPhoneNumberResource.Read(client: _client);
+ return result.Select(r => new TwilioPhone(_client, _authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility) { Id = r.Sid, Number = r.PhoneNumber.ToString() });
}
public IEnumerable GetAvailablePhoneNumbers(PhoneNumberType phoneNumberType, string isoCountryCode)
{
return phoneNumberType switch
{
- PhoneNumberType.Local => LocalResource.Read(isoCountryCode, voiceEnabled: true, client: client).Select(r => new TwilioPhone(client, AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility) { Number = r.PhoneNumber.ToString() }),
- PhoneNumberType.TollFree => TollFreeResource.Read(isoCountryCode, voiceEnabled: true, client: client).Select(r => new TwilioPhone(client, AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility) { Number = r.PhoneNumber.ToString() }),
+ PhoneNumberType.Local => LocalResource.Read(isoCountryCode, voiceEnabled: true, client: _client).Select(r => new TwilioPhone(_client, _authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility) { Number = r.PhoneNumber.ToString() }),
+ PhoneNumberType.TollFree => TollFreeResource.Read(isoCountryCode, voiceEnabled: true, client: _client).Select(r => new TwilioPhone(_client, _authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility) { Number = r.PhoneNumber.ToString() }),
_ => new List(),
};
@@ -140,13 +139,13 @@ namespace ASC.VoipService.Twilio
public VoipPhone GetPhone(string phoneSid)
{
- var phone = IncomingPhoneNumberResource.Fetch(phoneSid, client: client);
+ var phone = IncomingPhoneNumberResource.Fetch(phoneSid, client: _client);
- var result = new TwilioPhone(client, AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility)
+ var result = new TwilioPhone(_client, _authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility)
{
Id = phone.Sid,
Number = phone.PhoneNumber.ToString(),
- Settings = new TwilioVoipSettings(AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility)
+ Settings = new TwilioVoipSettings(_authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility)
};
if (phone.VoiceUrl == null)
@@ -159,12 +158,12 @@ namespace ASC.VoipService.Twilio
public VoipPhone GetPhone(VoipNumber data)
{
- return new TwilioPhone(client, AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility)
+ return new TwilioPhone(_client, _authContext, _tenantUtil, _securityContext, _baseCommonLinkUtility)
{
Id = data.Id,
Number = data.Number,
Alias = data.Alias,
- Settings = new TwilioVoipSettings(data.Settings, AuthContext)
+ Settings = new TwilioVoipSettings(data.Settings, _authContext)
};
}
@@ -177,7 +176,7 @@ namespace ASC.VoipService.Twilio
{
try
{
- var call = CallResource.Fetch(result.Id, client: client);
+ var call = CallResource.Fetch(result.Id, client: _client);
if (!call.Price.HasValue || string.IsNullOrEmpty(call.Duration))
{
count--;
@@ -205,19 +204,19 @@ namespace ASC.VoipService.Twilio
{
new IncomingClientScope(agent.ClientID)
};
- var capability = new ClientCapability(accountSid, authToken, scopes: scopes);
+ var capability = new ClientCapability(_accountSid, _authToken, scopes: scopes);
return capability.ToJwt();
}
public void UpdateSettings(VoipPhone phone)
{
- IncomingPhoneNumberResource.Update(phone.Id, voiceUrl: new Uri(phone.Settings.Connect(false)), client: client);
+ IncomingPhoneNumberResource.Update(phone.Id, voiceUrl: new Uri(phone.Settings.Connect(false)), client: _client);
}
public void DisablePhone(VoipPhone phone)
{
- IncomingPhoneNumberResource.Update(phone.Id, voiceUrl: new Uri("https://demo.twilio.com/welcome/voice/"), client: client);
+ IncomingPhoneNumberResource.Update(phone.Id, voiceUrl: new Uri("https://demo.twilio.com/welcome/voice/"), client: _client);
}
#endregion
diff --git a/common/ASC.VoipService/Twilio/TwilioResponseHelper.cs b/common/ASC.VoipService/Twilio/TwilioResponseHelper.cs
index 0103b91057..a55e82bf73 100644
--- a/common/ASC.VoipService/Twilio/TwilioResponseHelper.cs
+++ b/common/ASC.VoipService/Twilio/TwilioResponseHelper.cs
@@ -23,189 +23,187 @@
*
*/
-namespace ASC.VoipService.Twilio
+namespace ASC.VoipService.Twilio;
+
+public class TwilioResponseHelper
{
- public class TwilioResponseHelper
+ private readonly VoipSettings _settings;
+ private readonly string _baseUrl;
+ private readonly AuthContext _authContext;
+ private readonly TenantUtil _tenantUtil;
+ private readonly SecurityContext _securityContext;
+
+ public TwilioResponseHelper(
+ VoipSettings settings,
+ string baseUrl,
+ AuthContext authContext,
+ TenantUtil tenantUtil,
+ SecurityContext securityContext)
{
- private readonly VoipSettings settings;
- private readonly string baseUrl;
+ _settings = settings;
+ _authContext = authContext;
+ _tenantUtil = tenantUtil;
+ _securityContext = securityContext;
+ _baseUrl = baseUrl.TrimEnd('/') + "/twilio/";
+ }
- private AuthContext AuthContext { get; }
- private TenantUtil TenantUtil { get; }
- private SecurityContext SecurityContext { get; }
+ public VoiceResponse Inbound(Tuple agentTuple)
+ {
+ var agent = agentTuple?.Item1;
+ var anyOnline = agentTuple != null && agentTuple.Item2;
+ var response = new VoiceResponse();
- public TwilioResponseHelper(
- VoipSettings settings,
- string baseUrl,
- AuthContext authContext,
- TenantUtil tenantUtil,
- SecurityContext securityContext)
+ if (_settings.WorkingHours != null && _settings.WorkingHours.Enabled)
{
- this.settings = settings;
- AuthContext = authContext;
- TenantUtil = tenantUtil;
- SecurityContext = securityContext;
- this.baseUrl = baseUrl.TrimEnd('/') + "/twilio/";
+ var now = _tenantUtil.DateTimeFromUtc(DateTime.UtcNow);
+ if (!(_settings.WorkingHours.From <= now.TimeOfDay && _settings.WorkingHours.To >= now.TimeOfDay))
+ {
+ return AddVoiceMail(response);
+ }
}
- public VoiceResponse Inbound(Tuple agentTuple)
+ if (anyOnline)
{
- var agent = agentTuple?.Item1;
- var anyOnline = agentTuple != null && agentTuple.Item2;
- var response = new VoiceResponse();
-
- if (settings.WorkingHours != null && settings.WorkingHours.Enabled)
+ if (!string.IsNullOrEmpty(_settings.GreetingAudio))
{
- var now = TenantUtil.DateTimeFromUtc(DateTime.UtcNow);
- if (!(settings.WorkingHours.From <= now.TimeOfDay && settings.WorkingHours.To >= now.TimeOfDay))
- {
- return AddVoiceMail(response);
- }
+ response.Play(Uri.EscapeDataString(_settings.GreetingAudio));
}
- if (anyOnline)
- {
- if (!string.IsNullOrEmpty(settings.GreetingAudio))
- {
- response.Play(Uri.EscapeDataString(settings.GreetingAudio));
- }
-
- response.Enqueue(settings.Queue.Name, GetEcho("Enqueue", agent != null), "POST",
- GetEcho("Wait", agent != null), "POST");
- }
-
- return AddVoiceMail(response);
+ response.Enqueue(_settings.Queue.Name, GetEcho("Enqueue", agent != null), "POST",
+ GetEcho("Wait", agent != null), "POST");
}
- public VoiceResponse Outbound()
+ return AddVoiceMail(response);
+ }
+
+ public VoiceResponse Outbound()
+ {
+ return !_settings.Caller.AllowOutgoingCalls
+ ? new VoiceResponse()
+ : AddToResponse(new VoiceResponse(), _settings.Caller);
+ }
+
+ public VoiceResponse Dial()
+ {
+ return new VoiceResponse();
+ }
+
+ public VoiceResponse Queue()
+ {
+ return new VoiceResponse();
+ }
+
+ public VoiceResponse Enqueue(string queueResult)
+ {
+ return queueResult == "leave" ? AddVoiceMail(new VoiceResponse()) : new VoiceResponse();
+ }
+
+ public VoiceResponse Dequeue()
+ {
+ return AddToResponse(new VoiceResponse(), _settings.Caller);
+ }
+
+ public VoiceResponse Leave()
+ {
+ return AddVoiceMail(new VoiceResponse());
+ }
+
+ public VoiceResponse Wait(string queueTime, string queueSize)
+ {
+ var response = new VoiceResponse();
+ var queue = _settings.Queue;
+
+ if (Convert.ToInt32(queueTime) > queue.WaitTime || Convert.ToInt32(queueSize) > queue.Size) return response.Leave();
+
+ if (!string.IsNullOrEmpty(queue.WaitUrl))
{
- return !settings.Caller.AllowOutgoingCalls
- ? new VoiceResponse()
- : AddToResponse(new VoiceResponse(), settings.Caller);
+ var gather = new Gather(method: "POST", action: GetEcho("gatherQueue"));
+ gather.Play(Uri.EscapeDataString(queue.WaitUrl));
+ response.Gather(gather);
}
-
- public VoiceResponse Dial()
+ else
{
- return new VoiceResponse();
+ response.Pause(queue.WaitTime);
}
- public VoiceResponse Queue()
+ return response;
+ }
+
+ public VoiceResponse GatherQueue(string digits, List availableOperators)
+ {
+ var response = new VoiceResponse();
+
+ if (digits == "#") return AddVoiceMail(response);
+
+ var oper = _settings.Operators.Find(r => r.PostFix == digits && availableOperators.Contains(r)) ??
+ _settings.Operators.FirstOrDefault(r => availableOperators.Contains(r));
+
+ return oper != null ? AddToResponse(response, oper) : response;
+ }
+
+ public VoiceResponse Redirect(string to)
+ {
+ if (to == "hold")
{
- return new VoiceResponse();
+ return new VoiceResponse().Play(Uri.EscapeDataString(_settings.HoldAudio), 0);
}
- public VoiceResponse Enqueue(string queueResult)
+
+ if (Guid.TryParse(to, out var newCallerId))
{
- return queueResult == "leave" ? AddVoiceMail(new VoiceResponse()) : new VoiceResponse();
+ _securityContext.AuthenticateMeWithoutCookie(newCallerId);
}
- public VoiceResponse Dequeue()
+ return new VoiceResponse().Enqueue(_settings.Queue.Name, GetEcho("enqueue"), "POST",
+ GetEcho("wait") + "&RedirectTo=" + to, "POST");
+ }
+
+ public VoiceResponse VoiceMail()
+ {
+ return new VoiceResponse();
+ }
+
+ private VoiceResponse AddToResponse(VoiceResponse response, Agent agent)
+ {
+ var dial = new Dial(method: "POST", action: GetEcho("dial"), timeout: agent.TimeOut, record: agent.Record ? "record-from-answer" : "do-not-record");
+
+ switch (agent.Answer)
{
- return AddToResponse(new VoiceResponse(), settings.Caller);
+ case AnswerType.Number:
+ response.Dial(dial.Number(agent.PhoneNumber, method: "POST", url: GetEcho("client")));
+ break;
+ case AnswerType.Client:
+ response.Dial(dial.Client(agent.ClientID, "POST", GetEcho("client")));
+ break;
+ case AnswerType.Sip:
+ response.Dial(dial.Sip(agent.ClientID, method: "POST", url: GetEcho("client")));
+ break;
}
- public VoiceResponse Leave()
+ return response;
+ }
+
+
+ private VoiceResponse AddVoiceMail(VoiceResponse response)
+ {
+ return string.IsNullOrEmpty(_settings.VoiceMail)
+ ? response.Say("")
+ : response.Play(Uri.EscapeDataString(_settings.VoiceMail)).Record(method: "POST", action: GetEcho("voiceMail"), maxLength: 30);
+ }
+
+ public string GetEcho(string action, bool user = true)
+ {
+ var result = _baseUrl.TrimEnd('/');
+
+ if (!string.IsNullOrEmpty(action))
{
- return AddVoiceMail(new VoiceResponse());
+ result += "/" + action.TrimStart('/');
}
-
- public VoiceResponse Wait(string queueTime, string queueSize)
+ if (user)
{
- var response = new VoiceResponse();
- var queue = settings.Queue;
-
- if (Convert.ToInt32(queueTime) > queue.WaitTime || Convert.ToInt32(queueSize) > queue.Size) return response.Leave();
-
- if (!string.IsNullOrEmpty(queue.WaitUrl))
- {
- var gather = new Gather(method: "POST", action: GetEcho("gatherQueue"));
- gather.Play(Uri.EscapeDataString(queue.WaitUrl));
- response.Gather(gather);
- }
- else
- {
- response.Pause(queue.WaitTime);
- }
-
- return response;
+ result += "?CallerId=" + _authContext.CurrentAccount.ID;
}
- public VoiceResponse GatherQueue(string digits, List availableOperators)
- {
- var response = new VoiceResponse();
-
- if (digits == "#") return AddVoiceMail(response);
-
- var oper = settings.Operators.Find(r => r.PostFix == digits && availableOperators.Contains(r)) ??
- settings.Operators.FirstOrDefault(r => availableOperators.Contains(r));
-
- return oper != null ? AddToResponse(response, oper) : response;
- }
-
- public VoiceResponse Redirect(string to)
- {
- if (to == "hold")
- {
- return new VoiceResponse().Play(Uri.EscapeDataString(settings.HoldAudio), 0);
- }
-
-
- if (Guid.TryParse(to, out var newCallerId))
- {
- SecurityContext.AuthenticateMeWithoutCookie(newCallerId);
- }
-
- return new VoiceResponse().Enqueue(settings.Queue.Name, GetEcho("enqueue"), "POST",
- GetEcho("wait") + "&RedirectTo=" + to, "POST");
- }
-
- public VoiceResponse VoiceMail()
- {
- return new VoiceResponse();
- }
-
- private VoiceResponse AddToResponse(VoiceResponse response, Agent agent)
- {
- var dial = new Dial(method: "POST", action: GetEcho("dial"), timeout: agent.TimeOut, record: agent.Record ? "record-from-answer" : "do-not-record");
-
- switch (agent.Answer)
- {
- case AnswerType.Number:
- response.Dial(dial.Number(agent.PhoneNumber, method: "POST", url: GetEcho("client")));
- break;
- case AnswerType.Client:
- response.Dial(dial.Client(agent.ClientID, "POST", GetEcho("client")));
- break;
- case AnswerType.Sip:
- response.Dial(dial.Sip(agent.ClientID, method: "POST", url: GetEcho("client")));
- break;
- }
-
- return response;
- }
-
-
- private VoiceResponse AddVoiceMail(VoiceResponse response)
- {
- return string.IsNullOrEmpty(settings.VoiceMail)
- ? response.Say("")
- : response.Play(Uri.EscapeDataString(settings.VoiceMail)).Record(method: "POST", action: GetEcho("voiceMail"), maxLength: 30);
- }
-
- public string GetEcho(string action, bool user = true)
- {
- var result = baseUrl.TrimEnd('/');
-
- if (!string.IsNullOrEmpty(action))
- {
- result += "/" + action.TrimStart('/');
- }
- if (user)
- {
- result += "?CallerId=" + AuthContext.CurrentAccount.ID;
- }
-
- return result;
- }
+ return result;
}
}
diff --git a/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs b/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs
index e7b930c427..98055764a6 100644
--- a/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs
+++ b/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs
@@ -26,58 +26,57 @@
using Uri = System.Uri;
-namespace ASC.VoipService.Twilio
+namespace ASC.VoipService.Twilio;
+
+public class TwilioVoipSettings : VoipSettings
{
- public class TwilioVoipSettings : VoipSettings
+ public TwilioVoipSettings(
+ AuthContext authContext,
+ TenantUtil tenantUtil,
+ SecurityContext securityContext,
+ BaseCommonLinkUtility baseCommonLinkUtility) :
+ base(authContext, tenantUtil, securityContext, baseCommonLinkUtility)
+ { }
+
+ public TwilioVoipSettings(
+ Uri voiceUrl,
+ AuthContext authContext,
+ TenantUtil tenantUtil,
+ SecurityContext securityContext,
+ BaseCommonLinkUtility baseCommonLinkUtility) :
+ this(authContext, tenantUtil, securityContext, baseCommonLinkUtility)
{
- public TwilioVoipSettings(
- AuthContext authContext,
- TenantUtil tenantUtil,
- SecurityContext securityContext,
- BaseCommonLinkUtility baseCommonLinkUtility) :
- base(authContext, tenantUtil, securityContext, baseCommonLinkUtility)
- { }
+ if (string.IsNullOrEmpty(voiceUrl.Query)) return;
- public TwilioVoipSettings(
- Uri voiceUrl,
- AuthContext authContext,
- TenantUtil tenantUtil,
- SecurityContext securityContext,
- BaseCommonLinkUtility baseCommonLinkUtility) :
- this(authContext, tenantUtil, securityContext, baseCommonLinkUtility)
+ JsonSettings = Encoding.UTF8.GetString(Convert.FromBase64String(HttpUtility.UrlDecode(HttpUtility.ParseQueryString(voiceUrl.Query)["settings"])));
+ }
+
+ public TwilioVoipSettings(string settings, AuthContext authContext) : base(settings, authContext)
+ {
+ }
+
+ public override string Connect(bool user = true, string contactId = null)
+ {
+ var result = GetEcho("", user);
+ if (!string.IsNullOrEmpty(contactId))
{
- if (string.IsNullOrEmpty(voiceUrl.Query)) return;
-
- JsonSettings = Encoding.UTF8.GetString(Convert.FromBase64String(HttpUtility.UrlDecode(HttpUtility.ParseQueryString(voiceUrl.Query)["settings"])));
+ result += "&ContactId=" + contactId;
}
+ return result;
+ }
- public TwilioVoipSettings(string settings, AuthContext authContext) : base(settings, authContext)
- {
- }
+ public override string Redirect(string to)
+ {
+ return GetEcho("redirect") + "&RedirectTo=" + to;
+ }
- public override string Connect(bool user = true, string contactId = null)
- {
- var result = GetEcho("", user);
- if (!string.IsNullOrEmpty(contactId))
- {
- result += "&ContactId=" + contactId;
- }
- return result;
- }
+ public override string Dequeue(bool reject)
+ {
+ return GetEcho("dequeue") + "&Reject=" + reject;
+ }
- public override string Redirect(string to)
- {
- return GetEcho("redirect") + "&RedirectTo=" + to;
- }
-
- public override string Dequeue(bool reject)
- {
- return GetEcho("dequeue") + "&Reject=" + reject;
- }
-
- private string GetEcho(string method, bool user = true)
- {
- return new TwilioResponseHelper(this, BaseCommonLinkUtility.GetFullAbsolutePath(""), AuthContext, TenantUtil, SecurityContext).GetEcho(method, user);
- }
+ private string GetEcho(string method, bool user = true)
+ {
+ return new TwilioResponseHelper(this, BaseCommonLinkUtility.GetFullAbsolutePath(""), AuthContext, TenantUtil, SecurityContext).GetEcho(method, user);
}
}
diff --git a/common/ASC.VoipService/VoipCall.cs b/common/ASC.VoipService/VoipCall.cs
index 322aba1c05..59d1f84bfc 100644
--- a/common/ASC.VoipService/VoipCall.cs
+++ b/common/ASC.VoipService/VoipCall.cs
@@ -23,54 +23,53 @@
*
*/
-namespace ASC.VoipService
+namespace ASC.VoipService;
+
+public class VoipCall
{
- public class VoipCall
+ public string Id { get; set; }
+
+ public string ParentID { get; set; }
+
+ public string From { get; set; }
+
+ public string To { get; set; }
+
+ public Guid AnsweredBy { get; set; }
+
+ public DateTime DialDate { get; set; }
+
+ public int DialDuration { get; set; }
+
+ public VoipCallStatus? Status { get; set; }
+
+ public decimal Price { get; set; }
+
+ public int ContactId { get; set; }
+
+ public bool ContactIsCompany { get; set; }
+
+ public string ContactTitle { get; set; }
+
+ public DateTime Date { get; set; }
+
+ public DateTime EndDialDate { get; set; }
+
+ public VoipRecord VoipRecord { get; set; }
+
+ public List ChildCalls { get; set; }
+
+ public VoipCall()
{
- public string Id { get; set; }
-
- public string ParentID { get; set; }
-
- public string From { get; set; }
-
- public string To { get; set; }
-
- public Guid AnsweredBy { get; set; }
-
- public DateTime DialDate { get; set; }
-
- public int DialDuration { get; set; }
-
- public VoipCallStatus? Status { get; set; }
-
- public decimal Price { get; set; }
-
- public int ContactId { get; set; }
-
- public bool ContactIsCompany { get; set; }
-
- public string ContactTitle { get; set; }
-
- public DateTime Date { get; set; }
-
- public DateTime EndDialDate { get; set; }
-
- public VoipRecord VoipRecord { get; set; }
-
- public List ChildCalls { get; set; }
-
- public VoipCall()
- {
- ChildCalls = new List();
- VoipRecord = new VoipRecord();
- }
+ ChildCalls = new List();
+ VoipRecord = new VoipRecord();
}
+}
- public enum VoipCallStatus
- {
- Incoming,
- Outcoming,
- Answered,
- Missed
- }
+public enum VoipCallStatus
+{
+ Incoming,
+ Outcoming,
+ Answered,
+ Missed
}
\ No newline at end of file
diff --git a/common/ASC.VoipService/VoipModel.cs b/common/ASC.VoipService/VoipModel.cs
index 72ca08eda0..5d27c214bb 100644
--- a/common/ASC.VoipService/VoipModel.cs
+++ b/common/ASC.VoipService/VoipModel.cs
@@ -23,142 +23,137 @@
*
*/
-namespace ASC.VoipService
+namespace ASC.VoipService;
+
+public class Agent
{
- public class Agent
+ public Guid Id { get; set; }
+
+ public AnswerType Answer { get; set; }
+
+ public string ClientID { get { return PhoneNumber + PostFix; } }
+
+ public bool Record { get; set; }
+
+ public int TimeOut { get; set; }
+
+ public AgentStatus Status { get; set; }
+
+ public bool AllowOutgoingCalls { get; set; }
+
+ public string PostFix { get; set; }
+
+ public string PhoneNumber { get; set; }
+
+ public string RedirectToNumber { get; set; }
+
+ public Agent()
{
- public Guid Id { get; set; }
-
- public AnswerType Answer { get; set; }
-
- public string ClientID { get { return PhoneNumber + PostFix; } }
-
- public bool Record { get; set; }
-
- public int TimeOut { get; set; }
-
- public AgentStatus Status { get; set; }
-
- public bool AllowOutgoingCalls { get; set; }
-
- public string PostFix { get; set; }
-
- public string PhoneNumber { get; set; }
-
- public string RedirectToNumber { get; set; }
-
- public Agent()
- {
- Status = AgentStatus.Offline;
- TimeOut = 30;
- AllowOutgoingCalls = true;
- Record = true;
- }
-
- public Agent(Guid id, AnswerType answer, VoipPhone phone, string postFix)
- : this()
- {
- Id = id;
- Answer = answer;
- PhoneNumber = phone.Number;
- AllowOutgoingCalls = phone.Settings.AllowOutgoingCalls;
- Record = phone.Settings.Record;
- PostFix = postFix;
- }
+ Status = AgentStatus.Offline;
+ TimeOut = 30;
+ AllowOutgoingCalls = true;
+ Record = true;
}
- public class Queue
+ public Agent(Guid id, AnswerType answer, VoipPhone phone, string postFix)
+ : this()
{
- public string Id { get; set; }
- public string Name { get; set; }
- public int Size { get; set; }
- public string WaitUrl { get; set; }
- public int WaitTime { get; set; }
-
- public Queue() { }
-
- public Queue(string id, string name, int size, string waitUrl, int waitTime)
- {
- Id = id;
- Name = name;
- WaitUrl = waitUrl;
- WaitTime = waitTime;
- Size = size;
- }
+ Id = id;
+ Answer = answer;
+ PhoneNumber = phone.Number;
+ AllowOutgoingCalls = phone.Settings.AllowOutgoingCalls;
+ Record = phone.Settings.Record;
+ PostFix = postFix;
}
-
- public sealed class WorkingHours
- {
- public bool Enabled { get; set; }
- public TimeSpan? From { get; set; }
- public TimeSpan? To { get; set; }
-
- public WorkingHours() { }
-
- public WorkingHours(TimeSpan from, TimeSpan to)
- {
- From = from;
- To = to;
- }
-
-
- private bool Equals(WorkingHours other)
- {
- return Enabled.Equals(other.Enabled) && From.Equals(other.From) && To.Equals(other.To);
- }
-
- public override bool Equals(object obj)
- {
- if (obj is null) return false;
- if (ReferenceEquals(this, obj)) return true;
- if (obj.GetType() != GetType()) return false;
- return Equals((WorkingHours)obj);
- }
-
- public override int GetHashCode()
- {
- return HashCode.Combine(Enabled, From, To);
- }
- }
-
- public class VoipUpload
- {
- public string Name { get; set; }
- public string Path { get; set; }
- public AudioType AudioType { get; set; }
- public bool IsDefault { get; set; }
- }
-
- #region Enum
-
- public enum AnswerType
- {
- Number,
- Sip,
- Client
- }
-
- public enum GreetingMessageVoice
- {
- Man,
- Woman,
- Alice
- }
-
- public enum AgentStatus
- {
- Online,
- Paused,
- Offline
- }
-
- public enum AudioType
- {
- Greeting,
- HoldUp,
- VoiceMail,
- Queue
- }
-
- #endregion
}
+
+public class Queue
+{
+ public string Id { get; set; }
+ public string Name { get; set; }
+ public int Size { get; set; }
+ public string WaitUrl { get; set; }
+ public int WaitTime { get; set; }
+
+ public Queue() { }
+
+ public Queue(string id, string name, int size, string waitUrl, int waitTime)
+ {
+ Id = id;
+ Name = name;
+ WaitUrl = waitUrl;
+ WaitTime = waitTime;
+ Size = size;
+ }
+}
+
+public sealed class WorkingHours
+{
+ public bool Enabled { get; set; }
+ public TimeSpan? From { get; set; }
+ public TimeSpan? To { get; set; }
+
+ public WorkingHours() { }
+
+ public WorkingHours(TimeSpan from, TimeSpan to)
+ {
+ From = from;
+ To = to;
+ }
+
+
+ private bool Equals(WorkingHours other)
+ {
+ return Enabled.Equals(other.Enabled) && From.Equals(other.From) && To.Equals(other.To);
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj is null) return false;
+ if (ReferenceEquals(this, obj)) return true;
+ if (obj.GetType() != GetType()) return false;
+ return Equals((WorkingHours)obj);
+ }
+
+ public override int GetHashCode()
+ {
+ return HashCode.Combine(Enabled, From, To);
+ }
+}
+
+public class VoipUpload
+{
+ public string Name { get; set; }
+ public string Path { get; set; }
+ public AudioType AudioType { get; set; }
+ public bool IsDefault { get; set; }
+}
+
+public enum AnswerType
+{
+ Number,
+ Sip,
+ Client
+}
+
+public enum GreetingMessageVoice
+{
+ Man,
+ Woman,
+ Alice
+}
+
+public enum AgentStatus
+{
+ Online,
+ Paused,
+ Offline
+}
+
+public enum AudioType
+{
+ Greeting,
+ HoldUp,
+ VoiceMail,
+ Queue
+}
\ No newline at end of file
diff --git a/common/ASC.VoipService/VoipPhone.cs b/common/ASC.VoipService/VoipPhone.cs
index 492b85c7f4..3b725d01bf 100644
--- a/common/ASC.VoipService/VoipPhone.cs
+++ b/common/ASC.VoipService/VoipPhone.cs
@@ -23,63 +23,62 @@
*
*/
-namespace ASC.VoipService
+namespace ASC.VoipService;
+
+public class VoipPhone
{
- public class VoipPhone
+ public string Id { get; set; }
+ public string Number { get; set; }
+ public string Alias { get; set; }
+ public VoipSettings Settings { get; set; }
+ public Agent Caller
{
- public string Id { get; set; }
- public string Number { get; set; }
- public string Alias { get; set; }
- public VoipSettings Settings { get; set; }
- public Agent Caller
- {
- get { return Settings.Caller; }
- }
-
- public VoipPhone(AuthContext authContext, TenantUtil tenantUtil, SecurityContext securityContext, BaseCommonLinkUtility baseCommonLinkUtility)
- {
- Settings = new VoipSettings(authContext, tenantUtil, securityContext, baseCommonLinkUtility);
- }
-
- public virtual VoipCall Call(string to, string contactId = null)
- {
- throw new NotImplementedException();
- }
-
- public virtual VoipCall LocalCall(string to)
- {
- throw new NotImplementedException();
- }
-
- public virtual VoipCall RedirectCall(string callId, string to)
- {
- throw new NotImplementedException();
- }
-
- public virtual VoipCall HoldUp(string callId)
- {
- throw new NotImplementedException();
- }
-
- public virtual void AnswerQueueCall(string callId)
- {
- throw new NotImplementedException();
- }
-
- public virtual void RejectQueueCall(string callId)
- {
- throw new NotImplementedException();
- }
+ get { return Settings.Caller; }
}
- public class VoipRecord
+ public VoipPhone(AuthContext authContext, TenantUtil tenantUtil, SecurityContext securityContext, BaseCommonLinkUtility baseCommonLinkUtility)
{
- public string Id { get; set; }
+ Settings = new VoipSettings(authContext, tenantUtil, securityContext, baseCommonLinkUtility);
+ }
- public string Uri { get; set; }
+ public virtual VoipCall Call(string to, string contactId = null)
+ {
+ throw new NotImplementedException();
+ }
- public int Duration { get; set; }
+ public virtual VoipCall LocalCall(string to)
+ {
+ throw new NotImplementedException();
+ }
- public decimal Price { get; set; }
+ public virtual VoipCall RedirectCall(string callId, string to)
+ {
+ throw new NotImplementedException();
+ }
+
+ public virtual VoipCall HoldUp(string callId)
+ {
+ throw new NotImplementedException();
+ }
+
+ public virtual void AnswerQueueCall(string callId)
+ {
+ throw new NotImplementedException();
+ }
+
+ public virtual void RejectQueueCall(string callId)
+ {
+ throw new NotImplementedException();
}
}
+
+public class VoipRecord
+{
+ public string Id { get; set; }
+
+ public string Uri { get; set; }
+
+ public int Duration { get; set; }
+
+ public decimal Price { get; set; }
+}
\ No newline at end of file
diff --git a/common/ASC.VoipService/VoipSettings.cs b/common/ASC.VoipService/VoipSettings.cs
index b688cea3bb..36ebf034b2 100644
--- a/common/ASC.VoipService/VoipSettings.cs
+++ b/common/ASC.VoipService/VoipSettings.cs
@@ -23,165 +23,164 @@
*
*/
-namespace ASC.VoipService
+namespace ASC.VoipService;
+
+public class VoipSettings
{
- public class VoipSettings
+ public string VoiceUrl { get; set; }
+
+ public string Name { get; set; }
+
+ public List Operators { get; set; }
+
+ public Queue Queue { get; set; }
+
+ public Agent Caller { get { return Operators.FirstOrDefault(r => r.Id == AuthContext.CurrentAccount.ID); } }
+
+ public WorkingHours WorkingHours { get; set; }
+
+ public string VoiceMail { get; set; }
+
+ public string GreetingAudio { get; set; }
+
+ public string HoldAudio { get; set; }
+
+ public bool AllowOutgoingCalls { get; set; }
+
+ public bool Pause { get; set; }
+
+ public bool Record { get; set; }
+
+ internal string JsonSettings
{
- public string VoiceUrl { get; set; }
-
- public string Name { get; set; }
-
- public List Operators { get; set; }
-
- public Queue Queue { get; set; }
-
- public Agent Caller { get { return Operators.FirstOrDefault(r => r.Id == AuthContext.CurrentAccount.ID); } }
-
- public WorkingHours WorkingHours { get; set; }
-
- public string VoiceMail { get; set; }
-
- public string GreetingAudio { get; set; }
-
- public string HoldAudio { get; set; }
-
- public bool AllowOutgoingCalls { get; set; }
-
- public bool Pause { get; set; }
-
- public bool Record { get; set; }
-
- internal string JsonSettings
+ get
{
- get
+ return JsonConvert.SerializeObject(
+ new
+ {
+ Operators,
+ GreetingAudio,
+ Name,
+ Queue,
+ WorkingHours,
+ VoiceMail,
+ HoldAudio,
+ AllowOutgoingCalls,
+ Pause,
+ Record
+ },
+ new JsonSerializerSettings { ContractResolver = CustomSerializeContractResolver.Instance });
+ }
+ set
+ {
+ try
{
- return JsonConvert.SerializeObject(
- new
- {
- Operators,
- GreetingAudio,
- Name,
- Queue,
- WorkingHours,
- VoiceMail,
- HoldAudio,
- AllowOutgoingCalls,
- Pause,
- Record
- },
- new JsonSerializerSettings { ContractResolver = CustomSerializeContractResolver.Instance });
+ var settings = JsonConvert.DeserializeObject(value, new JsonSerializerSettings { ContractResolver = CustomSerializeContractResolver.Instance });
+
+ Operators = settings.Operators ?? new List();
+ Name = settings.Name;
+ Queue = settings.Queue;
+ WorkingHours = settings.WorkingHours;
+ GreetingAudio = settings.GreetingAudio;
+ VoiceMail = settings.VoiceMail;
+ HoldAudio = settings.HoldAudio;
+ AllowOutgoingCalls = settings.AllowOutgoingCalls;
+ Pause = settings.Pause;
+ Record = settings.Record;
}
- set
+ catch (Exception)
{
- try
- {
- var settings = JsonConvert.DeserializeObject(value, new JsonSerializerSettings { ContractResolver = CustomSerializeContractResolver.Instance });
-
- Operators = settings.Operators ?? new List();
- Name = settings.Name;
- Queue = settings.Queue;
- WorkingHours = settings.WorkingHours;
- GreetingAudio = settings.GreetingAudio;
- VoiceMail = settings.VoiceMail;
- HoldAudio = settings.HoldAudio;
- AllowOutgoingCalls = settings.AllowOutgoingCalls;
- Pause = settings.Pause;
- Record = settings.Record;
- }
- catch (Exception)
- {
-
- }
}
- }
- protected AuthContext AuthContext { get; }
- protected TenantUtil TenantUtil { get; }
- protected SecurityContext SecurityContext { get; }
- protected BaseCommonLinkUtility BaseCommonLinkUtility { get; }
-
- public VoipSettings(AuthContext authContext, TenantUtil tenantUtil, SecurityContext securityContext, BaseCommonLinkUtility baseCommonLinkUtility)
- {
- Operators = new List();
- AuthContext = authContext;
- TenantUtil = tenantUtil;
- SecurityContext = securityContext;
- BaseCommonLinkUtility = baseCommonLinkUtility;
- }
-
- public VoipSettings(string settings, AuthContext authContext)
- {
- JsonSettings = settings;
- AuthContext = authContext;
- }
-
- public virtual string Connect(bool user = true, string contactId = null)
- {
- throw new NotImplementedException();
- }
-
- public virtual string Redirect(string to)
- {
- throw new NotImplementedException();
- }
-
- public virtual string Dequeue(bool reject)
- {
- throw new NotImplementedException();
- }
-
- public override string ToString()
- {
- return JsonSettings;
- }
-
- public VoipSettings GetSettings(string settings)
- {
- return new VoipSettings(AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility) { JsonSettings = settings };
}
}
- class CustomSerializeContractResolver : CamelCasePropertyNamesContractResolver
+ protected AuthContext AuthContext { get; }
+ protected TenantUtil TenantUtil { get; }
+ protected SecurityContext SecurityContext { get; }
+ protected BaseCommonLinkUtility BaseCommonLinkUtility { get; }
+
+ public VoipSettings(AuthContext authContext, TenantUtil tenantUtil, SecurityContext securityContext, BaseCommonLinkUtility baseCommonLinkUtility)
{
- public static readonly CustomSerializeContractResolver Instance = new CustomSerializeContractResolver();
-
- protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
- {
- var property = base.CreateProperty(member, memberSerialization);
-
- if (property.PropertyName == "voiceMail")
- {
- property.Converter = new VoiceMailConverter();
- }
-
- return property;
- }
+ Operators = new List();
+ AuthContext = authContext;
+ TenantUtil = tenantUtil;
+ SecurityContext = securityContext;
+ BaseCommonLinkUtility = baseCommonLinkUtility;
}
- class VoiceMailConverter : JsonConverter
+ public VoipSettings(string settings, AuthContext authContext)
{
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ JsonSettings = settings;
+ AuthContext = authContext;
+ }
+
+ public virtual string Connect(bool user = true, string contactId = null)
+ {
+ throw new NotImplementedException();
+ }
+
+ public virtual string Redirect(string to)
+ {
+ throw new NotImplementedException();
+ }
+
+ public virtual string Dequeue(bool reject)
+ {
+ throw new NotImplementedException();
+ }
+
+ public override string ToString()
+ {
+ return JsonSettings;
+ }
+
+ public VoipSettings GetSettings(string settings)
+ {
+ return new VoipSettings(AuthContext, TenantUtil, SecurityContext, BaseCommonLinkUtility) { JsonSettings = settings };
+ }
+}
+
+class CustomSerializeContractResolver : CamelCasePropertyNamesContractResolver
+{
+ public static readonly CustomSerializeContractResolver Instance = new CustomSerializeContractResolver();
+
+ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
+ {
+ var property = base.CreateProperty(member, memberSerialization);
+
+ if (property.PropertyName == "voiceMail")
{
- serializer.Serialize(writer, value);
+ property.Converter = new VoiceMailConverter();
}
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ return property;
+ }
+}
+
+class VoiceMailConverter : JsonConverter
+{
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ serializer.Serialize(writer, value);
+ }
+
+ public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ {
+ if (reader.ValueType != null && reader.ValueType.Name == "String")
{
- if (reader.ValueType != null && reader.ValueType.Name == "String")
- {
- return reader.Value;
- }
-
- var jObject = JObject.Load(reader);
- var url = jObject.Value("url");
-
- return !string.IsNullOrEmpty(url) ? url : "";
+ return reader.Value;
}
- public override bool CanConvert(Type objectType)
- {
- return true;
- }
+ var jObject = JObject.Load(reader);
+ var url = jObject.Value("url");
+
+ return !string.IsNullOrEmpty(url) ? url : "";
+ }
+
+ public override bool CanConvert(Type objectType)
+ {
+ return true;
}
}
\ No newline at end of file
From 0e2feb0a35d0fddc8216859eed47376d45e18104 Mon Sep 17 00:00:00 2001
From: SuhorukovAnton
Date: Thu, 17 Feb 2022 12:08:01 +0300
Subject: [PATCH 04/28] refactoring: texttile
---
common/ASC.Textile/BlockModifier.cs | 25 +-
common/ASC.Textile/BlockModifierAttribute.cs | 11 +-
.../Blocks/BlockAttributesParser.cs | 235 +++++++-------
.../Blocks/BoldPhraseBlockModifier.cs | 11 +-
.../Blocks/CapitalsBlockModifier.cs | 27 +-
.../Blocks/CitePhraseBlockModifier.cs | 11 +-
.../ASC.Textile/Blocks/CodeBlockModifier.cs | 81 +++--
.../Blocks/DeletedPhraseBlockModifier.cs | 11 +-
.../Blocks/EmphasisPhraseBlockModifier.cs | 11 +-
.../Blocks/FootNoteReferenceBlockModifier.cs | 11 +-
.../ASC.Textile/Blocks/GlyphBlockModifier.cs | 135 ++++----
.../Blocks/HyperLinkBlockModifier.cs | 73 +++--
.../ASC.Textile/Blocks/ImageBlockModifier.cs | 99 +++---
.../Blocks/InsertedPhraseBlockModifier.cs | 11 +-
.../Blocks/ItalicPhraseBlockModifier.cs | 11 +-
.../Blocks/NoTextileBlockModifier.cs | 31 +-
common/ASC.Textile/Blocks/NoTextileEncoder.cs | 131 ++++----
.../ASC.Textile/Blocks/PhraseBlockModifier.cs | 123 ++++---
common/ASC.Textile/Blocks/PreBlockModifier.cs | 43 ++-
.../Blocks/SpanPhraseBlockModifier.cs | 11 +-
.../Blocks/StrongPhraseBlockModifier.cs | 13 +-
.../Blocks/SubScriptPhraseBlockModifier.cs | 13 +-
.../Blocks/SuperScriptPhraseBlockModifier.cs | 11 +-
common/ASC.Textile/FormatterState.cs | 229 +++++++------
common/ASC.Textile/FormatterStateAttribute.cs | 31 +-
common/ASC.Textile/Globals.cs | 131 ++++----
common/ASC.Textile/IOutputter.cs | 63 ++--
.../States/BlockQuoteFormatterState.cs | 59 ++--
.../ASC.Textile/States/CodeFormatterState.cs | 149 +++++----
.../States/FootNoteFormatterState.cs | 75 +++--
.../States/HeaderFormatterState.cs | 157 +++++----
.../ASC.Textile/States/ListFormatterState.cs | 34 +-
.../States/NoTextileFormatterState.cs | 99 +++---
.../States/OrderedListFormatterState.cs | 51 ++-
.../States/ParagraphFormatterState.cs | 65 ++--
.../States/PassthroughFormatterState.cs | 59 ++--
.../States/PreCodeFormatterState.cs | 93 +++---
.../ASC.Textile/States/PreFormatterState.cs | 143 +++++----
.../States/SimpleBlockFormatterState.cs | 121 ++++---
common/ASC.Textile/States/TableCellParser.cs | 83 +++--
.../ASC.Textile/States/TableFormatterState.cs | 103 +++---
.../States/TableRowFormatterState.cs | 139 ++++----
.../States/UnorderedListFormatterState.cs | 61 ++--
.../StringBuilderTextileFormatter.cs | 69 ++--
common/ASC.Textile/StyleReader.cs | 37 ++-
common/ASC.Textile/TextileFormatter.cs | 301 +++++++++---------
common/ASC.Textile/TextileFormatterBlocks.cs | 65 ++--
.../ASC.Textile/TextileFormatterFormatting.cs | 189 ++++++-----
common/ASC.Textile/TextileFormatterStates.cs | 266 ++++++++--------
49 files changed, 1979 insertions(+), 2032 deletions(-)
diff --git a/common/ASC.Textile/BlockModifier.cs b/common/ASC.Textile/BlockModifier.cs
index 4a0d63174e..f0cb398ba1 100644
--- a/common/ASC.Textile/BlockModifier.cs
+++ b/common/ASC.Textile/BlockModifier.cs
@@ -1,19 +1,18 @@
-namespace Textile
+namespace Textile;
+
+public class BlockModifier
{
- public class BlockModifier
+ protected BlockModifier()
{
- protected BlockModifier()
- {
- }
+ }
- public virtual string ModifyLine(string line)
- {
- return line;
- }
+ public virtual string ModifyLine(string line)
+ {
+ return line;
+ }
- public virtual string Conclude(string line)
- {
- return line;
- }
+ public virtual string Conclude(string line)
+ {
+ return line;
}
}
diff --git a/common/ASC.Textile/BlockModifierAttribute.cs b/common/ASC.Textile/BlockModifierAttribute.cs
index 0d28eb6f02..f516e9b6ca 100644
--- a/common/ASC.Textile/BlockModifierAttribute.cs
+++ b/common/ASC.Textile/BlockModifierAttribute.cs
@@ -1,10 +1,9 @@
-namespace Textile
+namespace Textile;
+
+[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
+public sealed class BlockModifierAttribute : Attribute
{
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
- public sealed class BlockModifierAttribute : Attribute
+ public BlockModifierAttribute()
{
- public BlockModifierAttribute()
- {
- }
}
}
diff --git a/common/ASC.Textile/Blocks/BlockAttributesParser.cs b/common/ASC.Textile/Blocks/BlockAttributesParser.cs
index 2946471efd..8315925a23 100644
--- a/common/ASC.Textile/Blocks/BlockAttributesParser.cs
+++ b/common/ASC.Textile/Blocks/BlockAttributesParser.cs
@@ -10,142 +10,141 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.Blocks
-{
- public static class BlockAttributesParser
- {
- public static StyleReader Styler { get; set; }
+namespace Textile.Blocks;
- ///
- ///
- ///
- ///
- ///
- static public string ParseBlockAttributes(string input)
+public static class BlockAttributesParser
+{
+ public static StyleReader Styler { get; set; }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ static public string ParseBlockAttributes(string input)
+ {
+ return ParseBlockAttributes(input, "");
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ static public string ParseBlockAttributes(string input, string element)
+ {
+ var style = string.Empty;
+ var cssClass = string.Empty;
+ var lang = string.Empty;
+ var colspan = string.Empty;
+ var rowspan = string.Empty;
+ var id = string.Empty;
+
+ if (Styler != null)
{
- return ParseBlockAttributes(input, "");
+ style = GetStyle(element, style);
}
- ///
- ///
- ///
- ///
- ///
- ///
- static public string ParseBlockAttributes(string input, string element)
+ if (input.Length == 0)
+ return style.Length > 0 ? " style=\"" + style + "\"" : "";
+
+
+ Match m;
+ var matched = input;
+ if (element == "td")
{
- var style = string.Empty;
- var cssClass = string.Empty;
- var lang = string.Empty;
- var colspan = string.Empty;
- var rowspan = string.Empty;
- var id = string.Empty;
-
- if (Styler != null)
- {
- style = GetStyle(element, style);
- }
-
- if (input.Length == 0)
- return style.Length > 0 ? " style=\"" + style + "\"" : "";
-
-
- Match m;
- var matched = input;
- if (element == "td")
- {
- // column span
- m = Regex.Match(matched, @"\\(\d+)");
- if (m.Success)
- colspan = m.Groups[1].Value;
- // row span
- m = Regex.Match(matched, @"/(\d+)");
- if (m.Success)
- rowspan = m.Groups[1].Value;
- // vertical align
- m = Regex.Match(matched, @"(" + Globals.VerticalAlignPattern + @")");
- if (m.Success)
- style += "vertical-align:" + Globals.VerticalAlign[m.Captures[0].Value] + ";";
- }
-
- // First, match custom styles
- m = Regex.Match(matched, @"\{([^}]*)\}");
+ // column span
+ m = Regex.Match(matched, @"\\(\d+)");
if (m.Success)
- {
- style += m.Groups[1].Value + ";";
- matched = matched.Replace(m.ToString(), "");
- }
-
- // Then match the language
- m = Regex.Match(matched, @"\[([^()]+)\]");
+ colspan = m.Groups[1].Value;
+ // row span
+ m = Regex.Match(matched, @"/(\d+)");
if (m.Success)
- {
- lang = m.Groups[1].Value;
- matched = matched.Replace(m.ToString(), "");
- }
+ rowspan = m.Groups[1].Value;
+ // vertical align
+ m = Regex.Match(matched, @"(" + Globals.VerticalAlignPattern + @")");
+ if (m.Success)
+ style += "vertical-align:" + Globals.VerticalAlign[m.Captures[0].Value] + ";";
+ }
- // Match classes and IDs after that
- m = Regex.Match(matched, @"\(([^()]+)\)");
+ // First, match custom styles
+ m = Regex.Match(matched, @"\{([^}]*)\}");
+ if (m.Success)
+ {
+ style += m.Groups[1].Value + ";";
+ matched = matched.Replace(m.ToString(), "");
+ }
+
+ // Then match the language
+ m = Regex.Match(matched, @"\[([^()]+)\]");
+ if (m.Success)
+ {
+ lang = m.Groups[1].Value;
+ matched = matched.Replace(m.ToString(), "");
+ }
+
+ // Match classes and IDs after that
+ m = Regex.Match(matched, @"\(([^()]+)\)");
+ if (m.Success)
+ {
+ cssClass = m.Groups[1].Value;
+ matched = matched.Replace(m.ToString(), "");
+
+ // Separate the public class and the ID
+ m = Regex.Match(cssClass, @"^(.*)#(.*)$");
if (m.Success)
{
cssClass = m.Groups[1].Value;
- matched = matched.Replace(m.ToString(), "");
-
- // Separate the public class and the ID
- m = Regex.Match(cssClass, @"^(.*)#(.*)$");
- if (m.Success)
- {
- cssClass = m.Groups[1].Value;
- id = m.Groups[2].Value;
- }
- if (Styler != null && !string.IsNullOrEmpty(cssClass))
- {
- style = GetStyle("." + cssClass, style);
- }
-
+ id = m.Groups[2].Value;
}
-
- // Get the padding on the left
- m = Regex.Match(matched, @"([(]+)");
- if (m.Success)
+ if (Styler != null && !string.IsNullOrEmpty(cssClass))
{
- style += "padding-left:" + m.Groups[1].Length + "em;";
- matched = matched.Replace(m.ToString(), "");
+ style = GetStyle("." + cssClass, style);
}
- // Get the padding on the right
- m = Regex.Match(matched, @"([)]+)");
- if (m.Success)
- {
- style += "padding-right:" + m.Groups[1].Length + "em;";
- matched = matched.Replace(m.ToString(), "");
- }
-
- // Get the text alignment
- m = Regex.Match(matched, "(" + Globals.HorizontalAlignPattern + ")");
- if (m.Success)
- style += "text-align:" + Globals.HorizontalAlign[m.Groups[1].Value] + ";";
-
-
-
- return
- (style.Length > 0 ? " style=\"" + style + "\"" : "") +
- (cssClass.Length > 0 ? " class=\"" + cssClass + "\"" : "") +
- (lang.Length > 0 ? " lang=\"" + lang + "\"" : "") +
- (id.Length > 0 ? " id=\"" + id + "\"" : "") +
- (colspan.Length > 0 ? " colspan=\"" + colspan + "\"" : "") +
- (rowspan.Length > 0 ? " rowspan=\"" + rowspan + "\"" : "")
- ;
}
- private static string GetStyle(string element, string style)
+ // Get the padding on the left
+ m = Regex.Match(matched, @"([(]+)");
+ if (m.Success)
{
- var styled = Styler.GetStyle(element);
- if (!string.IsNullOrEmpty(styled))
- {
- style += styled;
- }
- return style;
+ style += "padding-left:" + m.Groups[1].Length + "em;";
+ matched = matched.Replace(m.ToString(), "");
}
+
+ // Get the padding on the right
+ m = Regex.Match(matched, @"([)]+)");
+ if (m.Success)
+ {
+ style += "padding-right:" + m.Groups[1].Length + "em;";
+ matched = matched.Replace(m.ToString(), "");
+ }
+
+ // Get the text alignment
+ m = Regex.Match(matched, "(" + Globals.HorizontalAlignPattern + ")");
+ if (m.Success)
+ style += "text-align:" + Globals.HorizontalAlign[m.Groups[1].Value] + ";";
+
+
+
+ return
+ (style.Length > 0 ? " style=\"" + style + "\"" : "") +
+ (cssClass.Length > 0 ? " class=\"" + cssClass + "\"" : "") +
+ (lang.Length > 0 ? " lang=\"" + lang + "\"" : "") +
+ (id.Length > 0 ? " id=\"" + id + "\"" : "") +
+ (colspan.Length > 0 ? " colspan=\"" + colspan + "\"" : "") +
+ (rowspan.Length > 0 ? " rowspan=\"" + rowspan + "\"" : "")
+ ;
+ }
+
+ private static string GetStyle(string element, string style)
+ {
+ var styled = Styler.GetStyle(element);
+ if (!string.IsNullOrEmpty(styled))
+ {
+ style += styled;
+ }
+ return style;
}
}
diff --git a/common/ASC.Textile/Blocks/BoldPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/BoldPhraseBlockModifier.cs
index 9d195736a2..abf1eca805 100644
--- a/common/ASC.Textile/Blocks/BoldPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/BoldPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class BoldPhraseBlockModifier : PhraseBlockModifier
{
- public class BoldPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"\*\*", "b");
- }
+ return PhraseModifierFormat(line, @"\*\*", "b");
}
}
diff --git a/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs b/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs
index 7a7963ea10..3a4d8804bb 100644
--- a/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs
@@ -1,17 +1,16 @@
-namespace Textile.Blocks
-{
- public class CapitalsBlockModifier : BlockModifier
- {
- public override string ModifyLine(string line)
- {
- var me = new MatchEvaluator(CapitalsFormatMatchEvaluator);
- line = Regex.Replace(line, @"(?<=^|\s|" + Globals.PunctuationPattern + @")(?[A-Z][A-Z0-9]+)(?=$|\s|" + Globals.PunctuationPattern + @")", me);
- return line;
- }
+namespace Textile.Blocks;
- private string CapitalsFormatMatchEvaluator(Match m)
- {
- return @"" + m.Groups["caps"].Value + @"";
- }
+public class CapitalsBlockModifier : BlockModifier
+{
+ public override string ModifyLine(string line)
+ {
+ var me = new MatchEvaluator(CapitalsFormatMatchEvaluator);
+ line = Regex.Replace(line, @"(?<=^|\s|" + Globals.PunctuationPattern + @")(?[A-Z][A-Z0-9]+)(?=$|\s|" + Globals.PunctuationPattern + @")", me);
+ return line;
+ }
+
+ private string CapitalsFormatMatchEvaluator(Match m)
+ {
+ return @"" + m.Groups["caps"].Value + @"";
}
}
diff --git a/common/ASC.Textile/Blocks/CitePhraseBlockModifier.cs b/common/ASC.Textile/Blocks/CitePhraseBlockModifier.cs
index e91b0eea4c..b39671e4fb 100644
--- a/common/ASC.Textile/Blocks/CitePhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/CitePhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class CitePhraseBlockModifier : PhraseBlockModifier
{
- public class CitePhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"\?\?", "cite");
- }
+ return PhraseModifierFormat(line, @"\?\?", "cite");
}
}
diff --git a/common/ASC.Textile/Blocks/CodeBlockModifier.cs b/common/ASC.Textile/Blocks/CodeBlockModifier.cs
index 2c825aef81..5d7b26ec35 100644
--- a/common/ASC.Textile/Blocks/CodeBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/CodeBlockModifier.cs
@@ -10,47 +10,46 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class CodeBlockModifier : BlockModifier
{
- public class CodeBlockModifier : BlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- // Replace "@...@" zones with "" tags.
- var me = new MatchEvaluator(CodeFormatMatchEvaluator);
- line = Regex.Replace(line,
- @"(?^|([\s\([{]))" + // before
- "@" +
- @"(\|(?\w+)\|)?" + // lang
- "(?[^@]+)" + // code
- "@" +
- @"(?$|([\]}])|(?=" + Globals.PunctuationPattern + @"{1,2}|\s|$))", // after
- me);
- // Encode the contents of the "" tags so that we don't
- // generate formatting out of it.
- line = NoTextileEncoder.EncodeNoTextileZones(line,
- @"(?<=(^|\s))",
- @"(?=
)");
- return line;
- }
-
- public override string Conclude(string line)
- {
- // Recode everything except "<" and ">";
- line = NoTextileEncoder.DecodeNoTextileZones(line,
- @"(?<=(^|\s))",
- @"(?=
)",
- new string[] { "<", ">" });
- return line;
- }
-
- public string CodeFormatMatchEvaluator(Match m)
- {
- var res = m.Groups["before"].Value + " 0)
- res += " language=\"" + m.Groups["lang"].Value + "\"";
- res += ">" + m.Groups["code"].Value + "
" + m.Groups["after"].Value;
- return res;
- }
+ // Replace "@...@" zones with "" tags.
+ var me = new MatchEvaluator(CodeFormatMatchEvaluator);
+ line = Regex.Replace(line,
+ @"(?^|([\s\([{]))" + // before
+ "@" +
+ @"(\|(?\w+)\|)?" + // lang
+ "(?[^@]+)" + // code
+ "@" +
+ @"(?$|([\]}])|(?=" + Globals.PunctuationPattern + @"{1,2}|\s|$))", // after
+ me);
+ // Encode the contents of the "" tags so that we don't
+ // generate formatting out of it.
+ line = NoTextileEncoder.EncodeNoTextileZones(line,
+ @"(?<=(^|\s))",
+ @"(?=
)");
+ return line;
}
-}
+
+ public override string Conclude(string line)
+ {
+ // Recode everything except "<" and ">";
+ line = NoTextileEncoder.DecodeNoTextileZones(line,
+ @"(?<=(^|\s))",
+ @"(?=
)",
+ new string[] { "<", ">" });
+ return line;
+ }
+
+ public string CodeFormatMatchEvaluator(Match m)
+ {
+ var res = m.Groups["before"].Value + " 0)
+ res += " language=\"" + m.Groups["lang"].Value + "\"";
+ res += ">" + m.Groups["code"].Value + "
" + m.Groups["after"].Value;
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/Blocks/DeletedPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/DeletedPhraseBlockModifier.cs
index a8c4ac2916..f0c7816918 100644
--- a/common/ASC.Textile/Blocks/DeletedPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/DeletedPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class DeletedPhraseBlockModifier : PhraseBlockModifier
{
- public class DeletedPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"\-", "del");
- }
+ return PhraseModifierFormat(line, @"\-", "del");
}
}
diff --git a/common/ASC.Textile/Blocks/EmphasisPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/EmphasisPhraseBlockModifier.cs
index 96ce7210f6..ee2b49d44c 100644
--- a/common/ASC.Textile/Blocks/EmphasisPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/EmphasisPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class EmphasisPhraseBlockModifier : PhraseBlockModifier
{
- public class EmphasisPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"_", "em");
- }
+ return PhraseModifierFormat(line, @"_", "em");
}
}
diff --git a/common/ASC.Textile/Blocks/FootNoteReferenceBlockModifier.cs b/common/ASC.Textile/Blocks/FootNoteReferenceBlockModifier.cs
index bafc735672..787416329a 100644
--- a/common/ASC.Textile/Blocks/FootNoteReferenceBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/FootNoteReferenceBlockModifier.cs
@@ -10,13 +10,12 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class FootNoteReferenceBlockModifier : BlockModifier
{
- public class FootNoteReferenceBlockModifier : BlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return Regex.Replace(line, @"\b\[([0-9]+)\](\W)", "$1$2");
- }
+ return Regex.Replace(line, @"\b\[([0-9]+)\](\W)", "$1$2");
}
}
diff --git a/common/ASC.Textile/Blocks/GlyphBlockModifier.cs b/common/ASC.Textile/Blocks/GlyphBlockModifier.cs
index 93b16f8855..1509d0b74d 100644
--- a/common/ASC.Textile/Blocks/GlyphBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/GlyphBlockModifier.cs
@@ -10,79 +10,78 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class GlyphBlockModifier : BlockModifier
{
- public class GlyphBlockModifier : BlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
+ line = Regex.Replace(line, "\"\\z", "\" ");
+
+ // fix: hackish
+ string[,] glyphs = {
+ { @"([^\s[{(>_*])?\'(?(1)|(\s|s\b|" + Globals.PunctuationPattern + @"))", "$1’$2" }, // single closing
+ { @"\'", "‘" }, // single opening
+ { @"([^\s[{(>_*])?""(?(1)|(\s|" + Globals.PunctuationPattern + @"))", "$1”$2" }, // double closing
+ { @"""", "“" }, // double opening
+ { @"\b( )?\.{3}", "$1…" }, // ellipsis
+ { @"\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])", "$1" }, // 3+ uppercase acronym
+ { @"(\s)?--(\s)?", "$1—$2" }, // em dash
+ { @"\s-\s", " – " }, // en dash
+ { @"(\d+)( )?x( )?(\d+)", "$1$2×$3$4" }, // dimension sign
+ { @"\b ?[([](TM|tm)[])]", "™" }, // trademark
+ { @"\b ?[([](R|r)[])]", "®" }, // registered
+ { @"\b ?[([](C|c)[])]", "©" } // copyright
+ };
+
+ var sb = new StringBuilder();
+
+ if (!Regex.IsMatch(line, "<.*>"))
{
- line = Regex.Replace(line, "\"\\z", "\" ");
-
- // fix: hackish
- string[,] glyphs = {
- { @"([^\s[{(>_*])?\'(?(1)|(\s|s\b|" + Globals.PunctuationPattern + @"))", "$1’$2" }, // single closing
- { @"\'", "‘" }, // single opening
- { @"([^\s[{(>_*])?""(?(1)|(\s|" + Globals.PunctuationPattern + @"))", "$1”$2" }, // double closing
- { @"""", "“" }, // double opening
- { @"\b( )?\.{3}", "$1…" }, // ellipsis
- { @"\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])", "$1" }, // 3+ uppercase acronym
- { @"(\s)?--(\s)?", "$1—$2" }, // em dash
- { @"\s-\s", " – " }, // en dash
- { @"(\d+)( )?x( )?(\d+)", "$1$2×$3$4" }, // dimension sign
- { @"\b ?[([](TM|tm)[])]", "™" }, // trademark
- { @"\b ?[([](R|r)[])]", "®" }, // registered
- { @"\b ?[([](C|c)[])]", "©" } // copyright
- };
-
- var sb = new StringBuilder();
-
- if (!Regex.IsMatch(line, "<.*>"))
+ // If no HTML, do a simple search & replace.
+ for (var i = 0; i < glyphs.GetLength(0); ++i)
{
- // If no HTML, do a simple search & replace.
- for (var i = 0; i < glyphs.GetLength(0); ++i)
- {
- line = Regex.Replace(line, glyphs[i, 0], glyphs[i, 1]);
- }
- sb.Append(line);
+ line = Regex.Replace(line, glyphs[i, 0], glyphs[i, 1]);
}
- else
- {
- var splits = Regex.Split(line, "(<.*?>)");
- var offtags = "code|pre|notextile";
- var codepre = false;
-
- foreach (var split in splits)
- {
- var modifiedSplit = split;
- if (modifiedSplit.Length == 0)
- continue;
-
- if (Regex.IsMatch(modifiedSplit, @"<(" + offtags + ")>"))
- codepre = true;
- if (Regex.IsMatch(modifiedSplit, @"<\/(" + offtags + ")>"))
- codepre = false;
-
- if (!Regex.IsMatch(modifiedSplit, "<.*>") && !codepre)
- {
- for (var i = 0; i < glyphs.GetLength(0); ++i)
- {
- modifiedSplit = Regex.Replace(modifiedSplit, glyphs[i, 0], glyphs[i, 1]);
- }
- }
-
- // do htmlspecial if between
- if (codepre)
- {
- //TODO: htmlspecialchars(line)
- //line = Regex.Replace(line, @"<(\/?" + offtags + ")>", "<$1>");
- //line = line.Replace("&#", "");
- }
-
- sb.Append(modifiedSplit);
- }
- }
-
- return sb.ToString();
+ sb.Append(line);
}
+ else
+ {
+ var splits = Regex.Split(line, "(<.*?>)");
+ var offtags = "code|pre|notextile";
+ var codepre = false;
+
+ foreach (var split in splits)
+ {
+ var modifiedSplit = split;
+ if (modifiedSplit.Length == 0)
+ continue;
+
+ if (Regex.IsMatch(modifiedSplit, @"<(" + offtags + ")>"))
+ codepre = true;
+ if (Regex.IsMatch(modifiedSplit, @"<\/(" + offtags + ")>"))
+ codepre = false;
+
+ if (!Regex.IsMatch(modifiedSplit, "<.*>") && !codepre)
+ {
+ for (var i = 0; i < glyphs.GetLength(0); ++i)
+ {
+ modifiedSplit = Regex.Replace(modifiedSplit, glyphs[i, 0], glyphs[i, 1]);
+ }
+ }
+
+ // do htmlspecial if between
+ if (codepre)
+ {
+ //TODO: htmlspecialchars(line)
+ //line = Regex.Replace(line, @"<(\/?" + offtags + ")>", "<$1>");
+ //line = line.Replace("&#", "");
+ }
+
+ sb.Append(modifiedSplit);
+ }
+ }
+
+ return sb.ToString();
}
}
diff --git a/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs b/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs
index c7fa26bb61..b4bdcf1408 100644
--- a/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs
@@ -11,46 +11,45 @@
#endregion
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class HyperLinkBlockModifier : BlockModifier
{
- public class HyperLinkBlockModifier : BlockModifier
+ private readonly string _rel = string.Empty;
+
+ public override string ModifyLine(string line)
{
- private readonly string m_rel = string.Empty;
+ line = Regex.Replace(line,
+ @"(?[\s[{(]|" + Globals.PunctuationPattern + @")?" + // $pre
+ "\"" + // start
+ Globals.BlockModifiersPattern + // attributes
+ "(?[\\w\\W]+?)" + // text
+ @"\s?" +
+ @"(?:\((?[^)]+)\)(?=""))?" + // title
+ "\":" +
+ @"""(?\S+[^""]+)""" + // url
+ @"(?\/)?" + // slash
+ @"(?[^\w\/;]*)" + // post
+ @"(?=\s|$)",
+ new MatchEvaluator(HyperLinksFormatMatchEvaluator));
+ return line;
+ }
- public override string ModifyLine(string line)
- {
- line = Regex.Replace(line,
- @"(?[\s[{(]|" + Globals.PunctuationPattern + @")?" + // $pre
- "\"" + // start
- Globals.BlockModifiersPattern + // attributes
- "(?[\\w\\W]+?)" + // text
- @"\s?" +
- @"(?:\((?[^)]+)\)(?=""))?" + // title
- "\":" +
- @"""(?\S+[^""]+)""" + // url
- @"(?\/)?" + // slash
- @"(?[^\w\/;]*)" + // post
- @"(?=\s|$)",
- new MatchEvaluator(HyperLinksFormatMatchEvaluator));
- return line;
- }
+ private string HyperLinksFormatMatchEvaluator(Match m)
+ {
+ //TODO: check the URL
+ var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "a");
+ if (m.Groups["title"].Length > 0)
+ atts += " title=\"" + m.Groups["title"].Value + "\"";
+ var linkText = m.Groups["text"].Value.Trim(' ');
- private string HyperLinksFormatMatchEvaluator(Match m)
- {
- //TODO: check the URL
- var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "a");
- if (m.Groups["title"].Length > 0)
- atts += " title=\"" + m.Groups["title"].Value + "\"";
- var linkText = m.Groups["text"].Value.Trim(' ');
-
- var str = m.Groups["pre"].Value + "" + linkText + "" + m.Groups["post"].Value;
- return str;
- }
+ var str = m.Groups["pre"].Value + "" + linkText + "" + m.Groups["post"].Value;
+ return str;
}
}
diff --git a/common/ASC.Textile/Blocks/ImageBlockModifier.cs b/common/ASC.Textile/Blocks/ImageBlockModifier.cs
index 73cba25946..24518fa017 100644
--- a/common/ASC.Textile/Blocks/ImageBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/ImageBlockModifier.cs
@@ -10,60 +10,59 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class ImageBlockModifier : BlockModifier
{
- public class ImageBlockModifier : BlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
+ line = Regex.Replace(line,
+ @"\!" + // opening !
+ @"(?\<|\=|\>)?" + // optional alignment atts
+ Globals.BlockModifiersPattern + // optional style, public class atts
+ @"(?:\. )?" + // optional dot-space
+ @"(?[^\s(!]+)" + // presume this is the src
+ @"\s?" + // optional space
+ @"(?:\((?([^\)]+))\))?" +// optional title
+ @"\!" + // closing
+ @"(?::(?(\S+)))?" + // optional href
+ @"(?=\s|\.|,|;|\)|\||$)", // lookahead: space or simple punctuation or end of string
+ new MatchEvaluator(ImageFormatMatchEvaluator)
+ );
+ return line;
+ }
+
+ string ImageFormatMatchEvaluator(Match m)
+ {
+ var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "img");
+ if (m.Groups["algn"].Length > 0)
+ atts += " align=\"" + Globals.ImageAlign[m.Groups["algn"].Value] + "\"";
+ if (m.Groups["title"].Length > 0)
{
- line = Regex.Replace(line,
- @"\!" + // opening !
- @"(?\<|\=|\>)?" + // optional alignment atts
- Globals.BlockModifiersPattern + // optional style, public class atts
- @"(?:\. )?" + // optional dot-space
- @"(?[^\s(!]+)" + // presume this is the src
- @"\s?" + // optional space
- @"(?:\((?([^\)]+))\))?" +// optional title
- @"\!" + // closing
- @"(?::(?(\S+)))?" + // optional href
- @"(?=\s|\.|,|;|\)|\||$)", // lookahead: space or simple punctuation or end of string
- new MatchEvaluator(ImageFormatMatchEvaluator)
- );
- return line;
+ atts += " title=\"" + m.Groups["title"].Value + "\"";
+ atts += " alt=\"" + m.Groups["title"].Value + "\"";
+ }
+ else
+ {
+ atts += " alt=\"\"";
+ }
+ // Get Image Size?
+
+ var res = "";
+
+ if (m.Groups["href"].Length > 0)
+ {
+ var href = m.Groups["href"].Value;
+ var end = string.Empty;
+ var endMatch = Regex.Match(href, @"(.*)(?\.|,|;|\))$");
+ if (m.Success && !string.IsNullOrEmpty(endMatch.Groups["end"].Value))
+ {
+ href = href[0..^1];
+ end = endMatch.Groups["end"].Value;
+ }
+ res = "" + res + "" + end;
}
- string ImageFormatMatchEvaluator(Match m)
- {
- var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "img");
- if (m.Groups["algn"].Length > 0)
- atts += " align=\"" + Globals.ImageAlign[m.Groups["algn"].Value] + "\"";
- if (m.Groups["title"].Length > 0)
- {
- atts += " title=\"" + m.Groups["title"].Value + "\"";
- atts += " alt=\"" + m.Groups["title"].Value + "\"";
- }
- else
- {
- atts += " alt=\"\"";
- }
- // Get Image Size?
-
- var res = "";
-
- if (m.Groups["href"].Length > 0)
- {
- var href = m.Groups["href"].Value;
- var end = string.Empty;
- var endMatch = Regex.Match(href, @"(.*)(?\.|,|;|\))$");
- if (m.Success && !string.IsNullOrEmpty(endMatch.Groups["end"].Value))
- {
- href = href[0..^1];
- end = endMatch.Groups["end"].Value;
- }
- res = "" + res + "" + end;
- }
-
- return res;
- }
+ return res;
}
}
diff --git a/common/ASC.Textile/Blocks/InsertedPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/InsertedPhraseBlockModifier.cs
index 2e16731d28..ba3cda8e33 100644
--- a/common/ASC.Textile/Blocks/InsertedPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/InsertedPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class InsertedPhraseBlockModifier : PhraseBlockModifier
{
- public class InsertedPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"\+", "ins");
- }
+ return PhraseModifierFormat(line, @"\+", "ins");
}
}
diff --git a/common/ASC.Textile/Blocks/ItalicPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/ItalicPhraseBlockModifier.cs
index be69e9f9ce..6aa882d39f 100644
--- a/common/ASC.Textile/Blocks/ItalicPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/ItalicPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class ItalicPhraseBlockModifier : PhraseBlockModifier
{
- public class ItalicPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"__", "i");
- }
+ return PhraseModifierFormat(line, @"__", "i");
}
}
diff --git a/common/ASC.Textile/Blocks/NoTextileBlockModifier.cs b/common/ASC.Textile/Blocks/NoTextileBlockModifier.cs
index b242d47a7e..af695396fe 100644
--- a/common/ASC.Textile/Blocks/NoTextileBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/NoTextileBlockModifier.cs
@@ -11,22 +11,21 @@
#endregion
-namespace Textile.Blocks
-{
- public class NoTextileBlockModifier : BlockModifier
- {
- public override string ModifyLine(string line)
- {
- line = NoTextileEncoder.EncodeNoTextileZones(line, @"(?<=^|\s)", @"(?=(\s|$)?)");
- line = NoTextileEncoder.EncodeNoTextileZones(line, @"==", @"==");
- return line;
- }
+namespace Textile.Blocks;
- public override string Conclude(string line)
- {
- line = NoTextileEncoder.DecodeNoTextileZones(line, @"(?<=^|\s)", @"(?=(\s|$)?)");
- line = NoTextileEncoder.DecodeNoTextileZones(line, @"==", @"==");
- return line;
- }
+public class NoTextileBlockModifier : BlockModifier
+{
+ public override string ModifyLine(string line)
+ {
+ line = NoTextileEncoder.EncodeNoTextileZones(line, @"(?<=^|\s)", @"(?=(\s|$)?)");
+ line = NoTextileEncoder.EncodeNoTextileZones(line, @"==", @"==");
+ return line;
+ }
+
+ public override string Conclude(string line)
+ {
+ line = NoTextileEncoder.DecodeNoTextileZones(line, @"(?<=^|\s)", @"(?=(\s|$)?)");
+ line = NoTextileEncoder.DecodeNoTextileZones(line, @"==", @"==");
+ return line;
}
}
diff --git a/common/ASC.Textile/Blocks/NoTextileEncoder.cs b/common/ASC.Textile/Blocks/NoTextileEncoder.cs
index 83391866d9..d6aa40e436 100644
--- a/common/ASC.Textile/Blocks/NoTextileEncoder.cs
+++ b/common/ASC.Textile/Blocks/NoTextileEncoder.cs
@@ -1,79 +1,78 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public static class NoTextileEncoder
{
- public static class NoTextileEncoder
+ private static readonly string[,] TextileModifiers = {
+ { "\"", """ },
+ { "%", "%" },
+ { "*", "*" },
+ { "+", "+" },
+ { "-", "-" },
+ { "<", "<" }, // or "<"
+ { "=", "=" },
+ { ">", ">" }, // or ">"
+ { "?", "?" },
+ { "^", "^" },
+ { "_", "_" },
+ { "~", "~" },
+ { "@", "@" },
+ { "'", "'" },
+ { "|", "|" },
+ { "!", "!" },
+ { "(", "(" },
+ { ")", ")" },
+ { ".", "." },
+ { "x", "x" }
+ };
+
+
+ public static string EncodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix)
{
- private static readonly string[,] TextileModifiers = {
- { "\"", """ },
- { "%", "%" },
- { "*", "*" },
- { "+", "+" },
- { "-", "-" },
- { "<", "<" }, // or "<"
- { "=", "=" },
- { ">", ">" }, // or ">"
- { "?", "?" },
- { "^", "^" },
- { "_", "_" },
- { "~", "~" },
- { "@", "@" },
- { "'", "'" },
- { "|", "|" },
- { "!", "!" },
- { "(", "(" },
- { ")", ")" },
- { ".", "." },
- { "x", "x" }
- };
+ return EncodeNoTextileZones(tmp, patternPrefix, patternSuffix, null);
+ }
-
- public static string EncodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix)
+ public static string EncodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix, string[] exceptions)
+ {
+ string evaluator(Match m)
{
- return EncodeNoTextileZones(tmp, patternPrefix, patternSuffix, null);
- }
-
- public static string EncodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix, string[] exceptions)
- {
- string evaluator(Match m)
+ var toEncode = m.Groups["notex"].Value;
+ if (toEncode.Length == 0)
{
- var toEncode = m.Groups["notex"].Value;
- if (toEncode.Length == 0)
- {
- return string.Empty;
- }
- for (var i = 0; i < TextileModifiers.GetLength(0); ++i)
- {
- if (exceptions == null || Array.IndexOf(exceptions, TextileModifiers[i, 0]) < 0)
- {
- toEncode = toEncode.Replace(TextileModifiers[i, 0], TextileModifiers[i, 1]);
- }
- }
- return patternPrefix + toEncode + patternSuffix;
+ return string.Empty;
}
- tmp = Regex.Replace(tmp, "("+ patternPrefix + "(?.+?)" + patternSuffix + ")*", new MatchEvaluator(evaluator));
- return tmp;
- }
-
- public static string DecodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix)
- {
- return DecodeNoTextileZones(tmp, patternPrefix, patternSuffix, null);
- }
-
- public static string DecodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix, string[] exceptions)
- {
- string evaluator(Match m)
+ for (var i = 0; i < TextileModifiers.GetLength(0); ++i)
{
- var toEncode = m.Groups["notex"].Value;
- for (var i = 0; i < TextileModifiers.GetLength(0); ++i)
+ if (exceptions == null || Array.IndexOf(exceptions, TextileModifiers[i, 0]) < 0)
{
- if (exceptions == null || Array.IndexOf(exceptions, TextileModifiers[i, 0]) < 0)
- {
- toEncode = toEncode.Replace(TextileModifiers[i, 1], TextileModifiers[i, 0]);
- }
+ toEncode = toEncode.Replace(TextileModifiers[i, 0], TextileModifiers[i, 1]);
}
- return toEncode;
}
- tmp = Regex.Replace(tmp, "(" + patternPrefix + "(?.+?)" + patternSuffix + ")*", new MatchEvaluator(evaluator));
- return tmp;
+ return patternPrefix + toEncode + patternSuffix;
}
+ tmp = Regex.Replace(tmp, "("+ patternPrefix + "(?.+?)" + patternSuffix + ")*", new MatchEvaluator(evaluator));
+ return tmp;
+ }
+
+ public static string DecodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix)
+ {
+ return DecodeNoTextileZones(tmp, patternPrefix, patternSuffix, null);
+ }
+
+ public static string DecodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix, string[] exceptions)
+ {
+ string evaluator(Match m)
+ {
+ var toEncode = m.Groups["notex"].Value;
+ for (var i = 0; i < TextileModifiers.GetLength(0); ++i)
+ {
+ if (exceptions == null || Array.IndexOf(exceptions, TextileModifiers[i, 0]) < 0)
+ {
+ toEncode = toEncode.Replace(TextileModifiers[i, 1], TextileModifiers[i, 0]);
+ }
+ }
+ return toEncode;
+ }
+ tmp = Regex.Replace(tmp, "(" + patternPrefix + "(?.+?)" + patternSuffix + ")*", new MatchEvaluator(evaluator));
+ return tmp;
}
}
diff --git a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs
index afbe0c160c..bb08630a15 100644
--- a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs
@@ -10,82 +10,81 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public abstract class PhraseBlockModifier : BlockModifier
{
- public abstract class PhraseBlockModifier : BlockModifier
+ protected PhraseBlockModifier()
{
- protected PhraseBlockModifier()
- {
- }
+ }
- protected string PhraseModifierFormat(string input, string modifier, string tag)
+ protected string PhraseModifierFormat(string input, string modifier, string tag)
+ {
+ // All phrase modifiers are one character, or a double character. Sometimes,
+ // there's an additional escape character for the regex ('\').
+ var compressedModifier = modifier;
+ if (modifier.Length == 4)
{
- // All phrase modifiers are one character, or a double character. Sometimes,
- // there's an additional escape character for the regex ('\').
- var compressedModifier = modifier;
- if (modifier.Length == 4)
- {
- compressedModifier = modifier.Substring(0, 2);
- }
- else if (modifier.Length == 2)
- {
- if (modifier[0] != '\\')
- compressedModifier = modifier[0].ToString();
- //else: compressedModifier = modifier;
- }
+ compressedModifier = modifier.Substring(0, 2);
+ }
+ else if (modifier.Length == 2)
+ {
+ if (modifier[0] != '\\')
+ compressedModifier = modifier[0].ToString();
//else: compressedModifier = modifier;
+ }
+ //else: compressedModifier = modifier;
- // We try to remove the Textile tag used for the formatting from
- // the punctuation pattern, so that we match the end of the formatted
- // zone correctly.
- var punctuationPattern = Globals.PunctuationPattern.Replace(compressedModifier, "");
+ // We try to remove the Textile tag used for the formatting from
+ // the punctuation pattern, so that we match the end of the formatted
+ // zone correctly.
+ var punctuationPattern = Globals.PunctuationPattern.Replace(compressedModifier, "");
- // Now we can do the replacement.
- var pmme = new PhraseModifierMatchEvaluator(tag);
- var res = Regex.Replace(input,
- @"(?<=\s|" + punctuationPattern + @"|[{\(\[]|^)" +
- modifier +
- Globals.BlockModifiersPattern +
- @"(:(?(\S+)))?" +
- @"(?[^" + compressedModifier + "]*)" +
- @"(?" + punctuationPattern + @"*)" +
- modifier +
- @"(?=[\]\)}]|" + punctuationPattern + @"+|\s|$)",
- new MatchEvaluator(pmme.MatchEvaluator)
- );
- return res;
+ // Now we can do the replacement.
+ var pmme = new PhraseModifierMatchEvaluator(tag);
+ var res = Regex.Replace(input,
+ @"(?<=\s|" + punctuationPattern + @"|[{\(\[]|^)" +
+ modifier +
+ Globals.BlockModifiersPattern +
+ @"(:(?(\S+)))?" +
+ @"(?[^" + compressedModifier + "]*)" +
+ @"(?" + punctuationPattern + @"*)" +
+ modifier +
+ @"(?=[\]\)}]|" + punctuationPattern + @"+|\s|$)",
+ new MatchEvaluator(pmme.MatchEvaluator)
+ );
+ return res;
+ }
+
+ private sealed class PhraseModifierMatchEvaluator
+ {
+ private readonly string _tag;
+
+ public PhraseModifierMatchEvaluator(string tag)
+ {
+ _tag = tag;
}
- private sealed class PhraseModifierMatchEvaluator
+ public string MatchEvaluator(Match m)
{
- readonly string m_tag;
-
- public PhraseModifierMatchEvaluator(string tag)
+ if (m.Groups["content"].Length == 0)
{
- m_tag = tag;
+ // It's possible that the "atts" match groups eats the contents
+ // when the user didn't want to give block attributes, but the content
+ // happens to match the syntax. For example: "*(blah)*".
+ if (m.Groups["atts"].Length == 0)
+ return m.ToString();
+ return "<" + _tag + ">" + m.Groups["atts"].Value + m.Groups["end"].Value + "" + _tag + ">";
}
- public string MatchEvaluator(Match m)
- {
- if (m.Groups["content"].Length == 0)
- {
- // It's possible that the "atts" match groups eats the contents
- // when the user didn't want to give block attributes, but the content
- // happens to match the syntax. For example: "*(blah)*".
- if (m.Groups["atts"].Length == 0)
- return m.ToString();
- return "<" + m_tag + ">" + m.Groups["atts"].Value + m.Groups["end"].Value + "" + m_tag + ">";
- }
+ var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, _tag);
+ if (m.Groups["cite"].Length > 0)
+ atts += " cite=\"" + m.Groups["cite"] + "\"";
- var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, m_tag);
- if (m.Groups["cite"].Length > 0)
- atts += " cite=\"" + m.Groups["cite"] + "\"";
-
- var res = "<" + m_tag + atts + ">" +
- m.Groups["content"].Value + m.Groups["end"].Value +
- "" + m_tag + ">";
- return res;
- }
+ var res = "<" + _tag + atts + ">" +
+ m.Groups["content"].Value + m.Groups["end"].Value +
+ "" + _tag + ">";
+ return res;
}
}
}
diff --git a/common/ASC.Textile/Blocks/PreBlockModifier.cs b/common/ASC.Textile/Blocks/PreBlockModifier.cs
index 2003e58492..63da6c16cb 100644
--- a/common/ASC.Textile/Blocks/PreBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/PreBlockModifier.cs
@@ -10,28 +10,27 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.Blocks
-{
- public class PreBlockModifier : BlockModifier
- {
- public override string ModifyLine(string line)
- {
- // Encode the contents of the "" tags so that we don't
- // generate formatting out of it.
- line = NoTextileEncoder.EncodeNoTextileZones(line,
- @"(?<=(^|\s))",
- @"(?=
)");
- return line;
- }
+namespace Textile.Blocks;
- public override string Conclude(string line)
- {
- // Recode everything.
- line = NoTextileEncoder.DecodeNoTextileZones(line,
- @"(?<=(^|\s))",
- @"(?=
)",
- new string[] { "<", ">" });
- return line;
- }
+public class PreBlockModifier : BlockModifier
+{
+ public override string ModifyLine(string line)
+ {
+ // Encode the contents of the "" tags so that we don't
+ // generate formatting out of it.
+ line = NoTextileEncoder.EncodeNoTextileZones(line,
+ @"(?<=(^|\s))",
+ @"(?=
)");
+ return line;
+ }
+
+ public override string Conclude(string line)
+ {
+ // Recode everything.
+ line = NoTextileEncoder.DecodeNoTextileZones(line,
+ @"(?<=(^|\s))",
+ @"(?=
)",
+ new string[] { "<", ">" });
+ return line;
}
}
diff --git a/common/ASC.Textile/Blocks/SpanPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/SpanPhraseBlockModifier.cs
index e3ed75850b..c6c564056f 100644
--- a/common/ASC.Textile/Blocks/SpanPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/SpanPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class SpanPhraseBlockModifier : PhraseBlockModifier
{
- public class SpanPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"%", "span");
- }
+ return PhraseModifierFormat(line, @"%", "span");
}
}
diff --git a/common/ASC.Textile/Blocks/StrongPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/StrongPhraseBlockModifier.cs
index 342402827b..9bae9abffe 100644
--- a/common/ASC.Textile/Blocks/StrongPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/StrongPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class StrongPhraseBlockModifier : PhraseBlockModifier
{
- public class StrongPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"\*", "strong");
- }
+ return PhraseModifierFormat(line, @"\*", "strong");
}
-}
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/Blocks/SubScriptPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/SubScriptPhraseBlockModifier.cs
index 3a6cb68c39..68e25faa70 100644
--- a/common/ASC.Textile/Blocks/SubScriptPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/SubScriptPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class SubScriptPhraseBlockModifier : PhraseBlockModifier
{
- public class SubScriptPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"~", "sub");
- }
+ return PhraseModifierFormat(line, @"~", "sub");
}
-}
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/Blocks/SuperScriptPhraseBlockModifier.cs b/common/ASC.Textile/Blocks/SuperScriptPhraseBlockModifier.cs
index 77c92d3cc1..08c782d5c6 100644
--- a/common/ASC.Textile/Blocks/SuperScriptPhraseBlockModifier.cs
+++ b/common/ASC.Textile/Blocks/SuperScriptPhraseBlockModifier.cs
@@ -1,10 +1,9 @@
-namespace Textile.Blocks
+namespace Textile.Blocks;
+
+public class SuperScriptPhraseBlockModifier : PhraseBlockModifier
{
- public class SuperScriptPhraseBlockModifier : PhraseBlockModifier
+ public override string ModifyLine(string line)
{
- public override string ModifyLine(string line)
- {
- return PhraseModifierFormat(line, @"\^", "sup");
- }
+ return PhraseModifierFormat(line, @"\^", "sup");
}
}
diff --git a/common/ASC.Textile/FormatterState.cs b/common/ASC.Textile/FormatterState.cs
index 769dad3e16..df4b9e2158 100644
--- a/common/ASC.Textile/FormatterState.cs
+++ b/common/ASC.Textile/FormatterState.cs
@@ -10,126 +10,125 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile
+namespace Textile;
+
+///
+/// Base class for formatter states.
+///
+/// A formatter state describes the current situation
+/// of the text being currently processed. A state can
+/// write HTML code when entered, exited, and can modify
+/// each line of text it receives.
+public abstract class FormatterState
{
///
- /// Base class for formatter states.
+ /// The formatter this state belongs to.
///
- /// A formatter state describes the current situation
- /// of the text being currently processed. A state can
- /// write HTML code when entered, exited, and can modify
- /// each line of text it receives.
- public abstract class FormatterState
+ public TextileFormatter Formatter { get; }
+
+ ///
+ /// Public constructor.
+ ///
+ /// The parent formatter.
+ protected FormatterState(TextileFormatter formatter)
{
- ///
- /// The formatter this state belongs to.
- ///
- public TextileFormatter Formatter { get; }
+ Formatter = formatter;
+ }
- ///
- /// Public constructor.
- ///
- /// The parent formatter.
- protected FormatterState(TextileFormatter formatter)
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public abstract string Consume(string input, Match m);
+
+ ///
+ /// Method called when the state is entered.
+ ///
+ public abstract void Enter();
+ ///
+ /// Method called when the state is exited.
+ ///
+ public abstract void Exit();
+ ///
+ /// Method called when a line of text should be written
+ /// to the web form.
+ ///
+ /// The line of text.
+ public abstract void FormatLine(string input);
+
+ ///
+ /// Returns whether this state can last for more than one line.
+ ///
+ /// A boolean value stating whether this state is only for one line.
+ /// This method should return true only if this state is genuinely
+ /// multi-line. For example, a header text is only one line long. You can
+ /// have several consecutive lines of header texts, but they are not the same
+ /// header - just several headers one after the other.
+ /// Bulleted and numbered lists are good examples of multi-line states.
+ //abstract public bool IsOneLineOnly();
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public abstract bool ShouldExit(string input);
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public virtual bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
+
+ ///
+ /// Returns whether block formatting (quick phrase modifiers, etc.) should be
+ /// applied to this line.
+ ///
+ /// The line of text
+ /// Whether the line should be formatted for blocks
+ public virtual bool ShouldFormatBlocks(string input)
+ {
+ return true;
+ }
+
+ ///
+ /// Returns whether the current state accepts being superceded by another one
+ /// we would possibly find by parsing the input line of text.
+ ///
+ ///
+ ///
+ public virtual bool ShouldParseForNewFormatterState(string input)
+ {
+ return true;
+ }
+
+ ///
+ /// Gets the formatting state we should fallback to if we don't find anything
+ /// relevant in a line of text.
+ ///
+ public virtual Type FallbackFormattingState
+ {
+ get
{
- Formatter = formatter;
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public abstract string Consume(string input, Match m);
-
- ///
- /// Method called when the state is entered.
- ///
- public abstract void Enter();
- ///
- /// Method called when the state is exited.
- ///
- public abstract void Exit();
- ///
- /// Method called when a line of text should be written
- /// to the web form.
- ///
- /// The line of text.
- public abstract void FormatLine(string input);
-
- ///
- /// Returns whether this state can last for more than one line.
- ///
- /// A boolean value stating whether this state is only for one line.
- /// This method should return true only if this state is genuinely
- /// multi-line. For example, a header text is only one line long. You can
- /// have several consecutive lines of header texts, but they are not the same
- /// header - just several headers one after the other.
- /// Bulleted and numbered lists are good examples of multi-line states.
- //abstract public bool IsOneLineOnly();
-
- ///
- ///
- ///
- ///
- ///
- public abstract bool ShouldExit(string input);
-
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public virtual bool ShouldNestState(FormatterState other)
- {
- return false;
- }
-
- ///
- /// Returns whether block formatting (quick phrase modifiers, etc.) should be
- /// applied to this line.
- ///
- /// The line of text
- /// Whether the line should be formatted for blocks
- public virtual bool ShouldFormatBlocks(string input)
- {
- return true;
- }
-
- ///
- /// Returns whether the current state accepts being superceded by another one
- /// we would possibly find by parsing the input line of text.
- ///
- ///
- ///
- public virtual bool ShouldParseForNewFormatterState(string input)
- {
- return true;
- }
-
- ///
- /// Gets the formatting state we should fallback to if we don't find anything
- /// relevant in a line of text.
- ///
- public virtual Type FallbackFormattingState
- {
- get
- {
- return typeof(States.ParagraphFormatterState);
- }
- }
-
- protected FormatterState CurrentFormatterState
- {
- get { return this.Formatter.CurrentState; }
- }
-
- protected void ChangeFormatterState(FormatterState formatterState)
- {
- this.Formatter.ChangeState(formatterState);
+ return typeof(States.ParagraphFormatterState);
}
}
-}
+
+ protected FormatterState CurrentFormatterState
+ {
+ get { return this.Formatter.CurrentState; }
+ }
+
+ protected void ChangeFormatterState(FormatterState formatterState)
+ {
+ this.Formatter.ChangeState(formatterState);
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/FormatterStateAttribute.cs b/common/ASC.Textile/FormatterStateAttribute.cs
index e50ea55458..ab9bdd15e3 100644
--- a/common/ASC.Textile/FormatterStateAttribute.cs
+++ b/common/ASC.Textile/FormatterStateAttribute.cs
@@ -1,21 +1,20 @@
-namespace Textile
+namespace Textile;
+
+[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
+public sealed class FormatterStateAttribute : Attribute
{
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
- public sealed class FormatterStateAttribute : Attribute
+ public string Pattern { get; }
+
+ public FormatterStateAttribute(string pattern)
{
- public string Pattern { get; }
+ Pattern = pattern;
+ }
- public FormatterStateAttribute(string pattern)
- {
- Pattern = pattern;
- }
-
- public static FormatterStateAttribute Get(Type type)
- {
- var atts = type.GetCustomAttributes(typeof(FormatterStateAttribute), false);
- if (atts.Length == 0)
- return null;
- return (FormatterStateAttribute)atts[0];
- }
+ public static FormatterStateAttribute Get(Type type)
+ {
+ var atts = type.GetCustomAttributes(typeof(FormatterStateAttribute), false);
+ if (atts.Length == 0)
+ return null;
+ return (FormatterStateAttribute)atts[0];
}
}
diff --git a/common/ASC.Textile/Globals.cs b/common/ASC.Textile/Globals.cs
index ccf120123f..257a55867f 100644
--- a/common/ASC.Textile/Globals.cs
+++ b/common/ASC.Textile/Globals.cs
@@ -11,78 +11,77 @@
#endregion
-namespace Textile
+namespace Textile;
+
+///
+/// A utility class for global things used by the TextileFormatter.
+///
+static class Globals
{
+ #region Global Regex Patterns
+
+ public const string HorizontalAlignPattern = @"(?:[()]*(\<(?!>)|(?|\<\>|=)[()]*)";
+ public const string VerticalAlignPattern = @"[\-^~]";
+ public const string CssClassPattern = @"(?:\([^)]+\))";
+ public const string LanguagePattern = @"(?:\[[^]]+\])";
+ public const string CssStylePattern = @"(?:\{[^}]+\})";
+ public const string ColumnSpanPattern = @"(?:\\\d+)";
+ public const string RowSpanPattern = @"(?:/\d+)";
+
+ public const string AlignPattern = "(?" + HorizontalAlignPattern + "?" + VerticalAlignPattern + "?|" + VerticalAlignPattern + "?" + HorizontalAlignPattern + "?)";
+ public const string SpanPattern = @"(?" + ColumnSpanPattern + "?" + RowSpanPattern + "?|" + RowSpanPattern + "?" + ColumnSpanPattern + "?)";
+ public const string BlockModifiersPattern = @"(?" + CssClassPattern + "?" + CssStylePattern + "?" + LanguagePattern + "?|" +
+ CssStylePattern + "?" + LanguagePattern + "?" + CssClassPattern + "?|" +
+ LanguagePattern + "?" + CssStylePattern + "?" + CssClassPattern + "?)";
+
+ public const string PunctuationPattern = @"[\!""#\$%&'()\*\+,\-\./:;<=>\?@\[\\\]\^_`{}~]";
+
+ public const string HtmlAttributesPattern = @"(\s+\w+=((""[^""]+"")|('[^']+')))*";
+
+ #endregion
+
///
- /// A utility class for global things used by the TextileFormatter.
+ /// Image alignment tags, mapped to their HTML meanings.
///
- static class Globals
+ public static Dictionary ImageAlign { get; set; }
+ ///
+ /// Horizontal text alignment tags, mapped to their HTML meanings.
+ ///
+ public static Dictionary HorizontalAlign { get; set; }
+ ///
+ /// Vertical text alignment tags, mapped to their HTML meanings.
+ ///
+ public static Dictionary VerticalAlign { get; set;}
+
+ static Globals()
{
- #region Global Regex Patterns
-
- public const string HorizontalAlignPattern = @"(?:[()]*(\<(?!>)|(?|\<\>|=)[()]*)";
- public const string VerticalAlignPattern = @"[\-^~]";
- public const string CssClassPattern = @"(?:\([^)]+\))";
- public const string LanguagePattern = @"(?:\[[^]]+\])";
- public const string CssStylePattern = @"(?:\{[^}]+\})";
- public const string ColumnSpanPattern = @"(?:\\\d+)";
- public const string RowSpanPattern = @"(?:/\d+)";
-
- public const string AlignPattern = "(?" + HorizontalAlignPattern + "?" + VerticalAlignPattern + "?|" + VerticalAlignPattern + "?" + HorizontalAlignPattern + "?)";
- public const string SpanPattern = @"(?" + ColumnSpanPattern + "?" + RowSpanPattern + "?|" + RowSpanPattern + "?" + ColumnSpanPattern + "?)";
- public const string BlockModifiersPattern = @"(?" + CssClassPattern + "?" + CssStylePattern + "?" + LanguagePattern + "?|" +
- CssStylePattern + "?" + LanguagePattern + "?" + CssClassPattern + "?|" +
- LanguagePattern + "?" + CssStylePattern + "?" + CssClassPattern + "?)";
-
- public const string PunctuationPattern = @"[\!""#\$%&'()\*\+,\-\./:;<=>\?@\[\\\]\^_`{}~]";
-
- public const string HtmlAttributesPattern = @"(\s+\w+=((""[^""]+"")|('[^']+')))*";
-
- #endregion
-
- ///
- /// Image alignment tags, mapped to their HTML meanings.
- ///
- public static Dictionary ImageAlign { get; set; }
- ///
- /// Horizontal text alignment tags, mapped to their HTML meanings.
- ///
- public static Dictionary HorizontalAlign { get; set; }
- ///
- /// Vertical text alignment tags, mapped to their HTML meanings.
- ///
- public static Dictionary VerticalAlign { get; set;}
-
- static Globals()
+ ImageAlign = new Dictionary
{
- ImageAlign = new Dictionary
- {
- ["<"] = "left",
- ["="] = "center",
- [">"] = "right"
- };
+ ["<"] = "left",
+ ["="] = "center",
+ [">"] = "right"
+ };
- HorizontalAlign = new Dictionary
- {
- ["<"] = "left",
- ["="] = "center",
- [">"] = "right",
- ["<>"] = "justify"
- };
-
- VerticalAlign = new Dictionary
- {
- ["^"] = "top",
- ["-"] = "middle",
- ["~"] = "bottom"
- };
- }
-
- public static string EncodeHTMLLink(string url)
+ HorizontalAlign = new Dictionary
{
- url = url.Replace("&", "&");
- url = System.Text.RegularExpressions.Regex.Replace(url, "&(?=[^#])", "&");
- return url;
- }
+ ["<"] = "left",
+ ["="] = "center",
+ [">"] = "right",
+ ["<>"] = "justify"
+ };
+
+ VerticalAlign = new Dictionary
+ {
+ ["^"] = "top",
+ ["-"] = "middle",
+ ["~"] = "bottom"
+ };
+ }
+
+ public static string EncodeHTMLLink(string url)
+ {
+ url = url.Replace("&", "&");
+ url = System.Text.RegularExpressions.Regex.Replace(url, "&(?=[^#])", "&");
+ return url;
}
}
diff --git a/common/ASC.Textile/IOutputter.cs b/common/ASC.Textile/IOutputter.cs
index f77c87e717..45d71d5f54 100644
--- a/common/ASC.Textile/IOutputter.cs
+++ b/common/ASC.Textile/IOutputter.cs
@@ -10,44 +10,39 @@
// You must not remove this notice, or any other, from this software.
#endregion
-#region Using Statements
-#endregion
+namespace Textile;
-
-namespace Textile
+///
+/// Interface through which the HTML formatted text
+/// will be sent.
+///
+/// Clients of the TextileFormatter class will have to provide
+/// an outputter that implements this interface. Most of the
+/// time, it'll be the WebForm itself.
+public interface IOutputter
{
///
- /// Interface through which the HTML formatted text
- /// will be sent.
+ /// Method called just before the formatted text
+ /// is sent to the outputter.
///
- /// Clients of the TextileFormatter class will have to provide
- /// an outputter that implements this interface. Most of the
- /// time, it'll be the WebForm itself.
- public interface IOutputter
- {
- ///
- /// Method called just before the formatted text
- /// is sent to the outputter.
- ///
- void Begin();
+ void Begin();
- ///
- /// Metohd called whenever the TextileFormatter wants to
- /// print some text.
- ///
- /// The formatted HTML text.
- void Write(string text);
- ///
- /// Metohd called whenever the TextileFormatter wants to
- /// print some text. This should automatically print an
- /// additionnal end of line character.
- ///
- /// The formatted HTML text.
- void WriteLine(string line);
+ ///
+ /// Metohd called whenever the TextileFormatter wants to
+ /// print some text.
+ ///
+ /// The formatted HTML text.
+ void Write(string text);
+ ///
+ /// Metohd called whenever the TextileFormatter wants to
+ /// print some text. This should automatically print an
+ /// additionnal end of line character.
+ ///
+ /// The formatted HTML text.
+ void WriteLine(string line);
- ///
- /// Method called at the end of the formatting.
- ///
- void End();
- }
+ ///
+ /// Method called at the end of the formatting.
+ ///
+ void End();
}
diff --git a/common/ASC.Textile/States/BlockQuoteFormatterState.cs b/common/ASC.Textile/States/BlockQuoteFormatterState.cs
index eba43a15a9..cdfbcbf877 100644
--- a/common/ASC.Textile/States/BlockQuoteFormatterState.cs
+++ b/common/ASC.Textile/States/BlockQuoteFormatterState.cs
@@ -10,42 +10,41 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(SimpleBlockFormatterState.PatternBegin + @"bq" + SimpleBlockFormatterState.PatternEnd)]
+public class BlockQuoteFormatterState : SimpleBlockFormatterState
{
- [FormatterState(SimpleBlockFormatterState.PatternBegin + @"bq" + SimpleBlockFormatterState.PatternEnd)]
- public class BlockQuoteFormatterState : SimpleBlockFormatterState
+ public BlockQuoteFormatterState(TextileFormatter f)
+ : base(f)
{
- public BlockQuoteFormatterState(TextileFormatter f)
- : base(f)
- {
- }
+ }
- public override void Enter()
- {
- Formatter.Output.Write("");
- }
+ public override void Enter()
+ {
+ Formatter.Output.Write("
");
+ }
- public override void Exit()
- {
- Formatter.Output.WriteLine("
");
- }
+ public override void Exit()
+ {
+ Formatter.Output.WriteLine("
");
+ }
- public override void FormatLine(string input)
- {
- Formatter.Output.Write(input);
- }
+ public override void FormatLine(string input)
+ {
+ Formatter.Output.Write(input);
+ }
- public override bool ShouldExit(string input)
- {
- if (Regex.IsMatch(input, @"^\s*$"))
- return true;
- Formatter.Output.WriteLine("
");
- return false;
- }
+ public override bool ShouldExit(string input)
+ {
+ if (Regex.IsMatch(input, @"^\s*$"))
+ return true;
+ Formatter.Output.WriteLine("
");
+ return false;
+ }
- public override Type FallbackFormattingState
- {
- get { return null; }
- }
+ public override Type FallbackFormattingState
+ {
+ get { return null; }
}
}
diff --git a/common/ASC.Textile/States/CodeFormatterState.cs b/common/ASC.Textile/States/CodeFormatterState.cs
index 70c9a88f79..0dc1a447af 100644
--- a/common/ASC.Textile/States/CodeFormatterState.cs
+++ b/common/ASC.Textile/States/CodeFormatterState.cs
@@ -1,78 +1,77 @@
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(@"^\s*")]
+public class CodeFormatterState : FormatterState
{
- [FormatterState(@"^\s*")]
- public class CodeFormatterState : FormatterState
+ private bool _shouldExitNextTime = false;
+ private bool _shouldFixHtmlEntities = false;
+
+ public CodeFormatterState(TextileFormatter f)
+ : base(f)
{
- bool m_shouldExitNextTime = false;
- bool m_shouldFixHtmlEntities = false;
-
- public CodeFormatterState(TextileFormatter f)
- : base(f)
- {
- }
-
- public override string Consume(string input, Match m)
- {
- if (!Regex.IsMatch(input, "
"))
- {
- this.Formatter.ChangeState(this);
- }
- else
- {
- this.Formatter.ChangeState(new PassthroughFormatterState(this.Formatter));
- }
- return input;
- }
-
- public override bool ShouldNestState(FormatterState other)
- {
- return true;
- }
-
- public override void Enter()
- {
- m_shouldFixHtmlEntities = false;
- }
-
- public override void Exit()
- {
- }
-
- public override void FormatLine(string input)
- {
- if (m_shouldFixHtmlEntities)
- input = FixEntities(input);
- Formatter.Output.WriteLine(input);
- m_shouldFixHtmlEntities = true;
- }
-
- public override bool ShouldExit(string input)
- {
- if (m_shouldExitNextTime)
- return true;
- m_shouldExitNextTime = Regex.IsMatch(input, @"
");
- m_shouldFixHtmlEntities = !m_shouldExitNextTime;
- return false;
- }
-
- public override bool ShouldFormatBlocks(string input)
- {
- return false;
- }
-
- public override bool ShouldParseForNewFormatterState(string input)
- {
- return false;
- }
-
- private string FixEntities(string text)
- {
- // de-entify any remaining angle brackets or ampersands
- text = text.Replace("&", "&");
- text = text.Replace(">", ">");
- text = text.Replace("<", "<");
- //Regex.Replace(text, @"\b&([#a-z0-9]+;)", "x%x%");
- return text;
- }
}
-}
+
+ public override string Consume(string input, Match m)
+ {
+ if (!Regex.IsMatch(input, ""))
+ {
+ this.Formatter.ChangeState(this);
+ }
+ else
+ {
+ this.Formatter.ChangeState(new PassthroughFormatterState(this.Formatter));
+ }
+ return input;
+ }
+
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return true;
+ }
+
+ public override void Enter()
+ {
+ _shouldFixHtmlEntities = false;
+ }
+
+ public override void Exit()
+ {
+ }
+
+ public override void FormatLine(string input)
+ {
+ if (_shouldFixHtmlEntities)
+ input = FixEntities(input);
+ Formatter.Output.WriteLine(input);
+ _shouldFixHtmlEntities = true;
+ }
+
+ public override bool ShouldExit(string input)
+ {
+ if (_shouldExitNextTime)
+ return true;
+ _shouldExitNextTime = Regex.IsMatch(input, @"");
+ _shouldFixHtmlEntities = !_shouldExitNextTime;
+ return false;
+ }
+
+ public override bool ShouldFormatBlocks(string input)
+ {
+ return false;
+ }
+
+ public override bool ShouldParseForNewFormatterState(string input)
+ {
+ return false;
+ }
+
+ private string FixEntities(string text)
+ {
+ // de-entify any remaining angle brackets or ampersands
+ text = text.Replace("&", "&");
+ text = text.Replace(">", ">");
+ text = text.Replace("<", "<");
+ //Regex.Replace(text, @"\b&([#a-z0-9]+;)", "x%x%");
+ return text;
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/States/FootNoteFormatterState.cs b/common/ASC.Textile/States/FootNoteFormatterState.cs
index 9726501888..161e1c93e4 100644
--- a/common/ASC.Textile/States/FootNoteFormatterState.cs
+++ b/common/ASC.Textile/States/FootNoteFormatterState.cs
@@ -11,50 +11,49 @@
#endregion
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(SimpleBlockFormatterState.PatternBegin + @"fn[0-9]+" + SimpleBlockFormatterState.PatternEnd)]
+public class FootNoteFormatterState : SimpleBlockFormatterState
{
- [FormatterState(SimpleBlockFormatterState.PatternBegin + @"fn[0-9]+" + SimpleBlockFormatterState.PatternEnd)]
- public class FootNoteFormatterState : SimpleBlockFormatterState
+ private int _noteID = 0;
+
+ public FootNoteFormatterState(TextileFormatter f)
+ : base(f)
{
- int m_noteID = 0;
+ }
- public FootNoteFormatterState(TextileFormatter f)
- : base(f)
- {
- }
+ public override void Enter()
+ {
+ Formatter.Output.Write(
+ string.Format("{2} ",
+ _noteID,
+ FormattedStylesAndAlignment("p"),
+ _noteID));
+ }
- public override void Enter()
- {
- Formatter.Output.Write(
- string.Format("
{2} ",
- m_noteID,
- FormattedStylesAndAlignment("p"),
- m_noteID));
- }
+ public override void Exit()
+ {
+ Formatter.Output.WriteLine("
");
+ }
- public override void Exit()
- {
- Formatter.Output.WriteLine("");
- }
+ public override void FormatLine(string input)
+ {
+ Formatter.Output.Write(input);
+ }
- public override void FormatLine(string input)
- {
- Formatter.Output.Write(input);
- }
+ public override bool ShouldExit(string input)
+ {
+ return true;
+ }
+ protected override void OnContextAcquired()
+ {
+ var m = Regex.Match(Tag, @"^fn(?[0-9]+)");
+ _noteID = int.Parse(m.Groups["id"].Value);
+ }
- public override bool ShouldExit(string input)
- {
- return true;
- }
- protected override void OnContextAcquired()
- {
- var m = Regex.Match(Tag, @"^fn(?[0-9]+)");
- m_noteID = int.Parse(m.Groups["id"].Value);
- }
-
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
}
}
diff --git a/common/ASC.Textile/States/HeaderFormatterState.cs b/common/ASC.Textile/States/HeaderFormatterState.cs
index 35dfa12ba1..6536c09c1a 100644
--- a/common/ASC.Textile/States/HeaderFormatterState.cs
+++ b/common/ASC.Textile/States/HeaderFormatterState.cs
@@ -11,95 +11,94 @@
#endregion
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(SimpleBlockFormatterState.PatternBegin + @"pad[0-9]+" + SimpleBlockFormatterState.PatternEnd)]
+public class PaddingFormatterState : SimpleBlockFormatterState
{
- [FormatterState(SimpleBlockFormatterState.PatternBegin + @"pad[0-9]+" + SimpleBlockFormatterState.PatternEnd)]
- public class PaddingFormatterState : SimpleBlockFormatterState
+ public PaddingFormatterState(TextileFormatter formatter)
+ : base(formatter)
{
- public PaddingFormatterState(TextileFormatter formatter)
- : base(formatter)
+ }
+
+ public int HeaderLevel { get; private set; } = 0;
+
+
+ public override void Enter()
+ {
+ for (var i = 0; i < HeaderLevel; i++)
{
- }
-
- public int HeaderLevel { get; private set; } = 0;
-
-
- public override void Enter()
- {
- for (var i = 0; i < HeaderLevel; i++)
- {
- Formatter.Output.Write($"
");
- }
- }
-
- public override void Exit()
- {
- }
-
- protected override void OnContextAcquired()
- {
- var m = Regex.Match(Tag, @"^pad(?[0-9]+)");
- HeaderLevel = int.Parse(m.Groups["lvl"].Value);
- }
-
- public override void FormatLine(string input)
- {
- Formatter.Output.Write(input);
- }
-
- public override bool ShouldExit(string intput)
- {
- return true;
- }
-
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
+ Formatter.Output.Write($"
");
}
}
- ///
- /// Formatting state for headers and titles.
- ///
- [FormatterState(SimpleBlockFormatterState.PatternBegin + @"h[0-9]+" + SimpleBlockFormatterState.PatternEnd)]
- public class HeaderFormatterState : SimpleBlockFormatterState
+ public override void Exit()
{
- public int HeaderLevel { get; private set; } = 0;
+ }
- public HeaderFormatterState(TextileFormatter f)
- : base(f)
- {
- }
+ protected override void OnContextAcquired()
+ {
+ var m = Regex.Match(Tag, @"^pad(?[0-9]+)");
+ HeaderLevel = int.Parse(m.Groups["lvl"].Value);
+ }
- public override void Enter()
- {
- Formatter.Output.Write("");
- }
+ public override void FormatLine(string input)
+ {
+ Formatter.Output.Write(input);
+ }
- public override void Exit()
- {
- Formatter.Output.WriteLine("");
- }
+ public override bool ShouldExit(string intput)
+ {
+ return true;
+ }
- protected override void OnContextAcquired()
- {
- var m = Regex.Match(Tag, @"^h(?[0-9]+)");
- HeaderLevel = int.Parse(m.Groups["lvl"].Value);
- }
-
- public override void FormatLine(string input)
- {
- Formatter.Output.Write(input);
- }
-
- public override bool ShouldExit(string intput)
- {
- return true;
- }
-
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
}
}
+
+///
+/// Formatting state for headers and titles.
+///
+[FormatterState(SimpleBlockFormatterState.PatternBegin + @"h[0-9]+" + SimpleBlockFormatterState.PatternEnd)]
+public class HeaderFormatterState : SimpleBlockFormatterState
+{
+ public int HeaderLevel { get; private set; } = 0;
+
+ public HeaderFormatterState(TextileFormatter f)
+ : base(f)
+ {
+ }
+
+ public override void Enter()
+ {
+ Formatter.Output.Write("");
+ }
+
+ public override void Exit()
+ {
+ Formatter.Output.WriteLine("");
+ }
+
+ protected override void OnContextAcquired()
+ {
+ var m = Regex.Match(Tag, @"^h(?[0-9]+)");
+ HeaderLevel = int.Parse(m.Groups["lvl"].Value);
+ }
+
+ public override void FormatLine(string input)
+ {
+ Formatter.Output.Write(input);
+ }
+
+ public override bool ShouldExit(string intput)
+ {
+ return true;
+ }
+
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/States/ListFormatterState.cs b/common/ASC.Textile/States/ListFormatterState.cs
index 2c2bca6d79..2a1190b291 100644
--- a/common/ASC.Textile/States/ListFormatterState.cs
+++ b/common/ASC.Textile/States/ListFormatterState.cs
@@ -21,15 +21,15 @@ namespace Textile.States
internal const string PatternBegin = @"^\s*(?";
internal const string PatternEnd = @")" + Globals.BlockModifiersPattern + @"(?:\s+)? (?.*)$";
- private bool m_firstItem = true;
- private bool m_firstItemLine = true;
- private string m_tag;
- private string m_attsInfo;
- private string m_alignInfo;
+ private bool _firstItem = true;
+ private bool _firstItemLine = true;
+ private string _tag;
+ private string _attsInfo;
+ private string _alignInfo;
protected int NestingDepth
{
- get { return m_tag.Length; }
+ get { return _tag.Length; }
}
protected ListFormatterState(TextileFormatter formatter)
@@ -39,9 +39,9 @@ namespace Textile.States
public override string Consume(string input, Match m)
{
- m_tag = m.Groups["tag"].Value;
- m_alignInfo = m.Groups["align"].Value;
- m_attsInfo = m.Groups["atts"].Value;
+ _tag = m.Groups["tag"].Value;
+ _alignInfo = m.Groups["align"].Value;
+ _attsInfo = m.Groups["atts"].Value;
input = m.Groups["content"].Value;
this.Formatter.ChangeState(this);
@@ -51,8 +51,8 @@ namespace Textile.States
public sealed override void Enter()
{
- m_firstItem = true;
- m_firstItemLine = true;
+ _firstItem = true;
+ _firstItemLine = true;
WriteIndent();
}
@@ -64,19 +64,19 @@ namespace Textile.States
public sealed override void FormatLine(string input)
{
- if (m_firstItemLine)
+ if (_firstItemLine)
{
- if (!m_firstItem)
+ if (!_firstItem)
Formatter.Output.WriteLine("");
Formatter.Output.Write("");
- m_firstItemLine = false;
+ _firstItemLine = false;
}
else
{
Formatter.Output.WriteLine("
");
}
Formatter.Output.Write(input);
- m_firstItem = false;
+ _firstItem = false;
}
public sealed override bool ShouldNestState(FormatterState other)
@@ -109,7 +109,7 @@ namespace Textile.States
// previously (no "**" or "##" tags), or if it's
// a new list item.
if (IsMatchForMe(input, NestingDepth, NestingDepth))
- m_firstItemLine = true;
+ _firstItemLine = true;
return false;
}
@@ -131,7 +131,7 @@ namespace Textile.States
protected string FormattedStylesAndAlignment(string element)
{
- return Blocks.BlockAttributesParser.ParseBlockAttributes(m_alignInfo + m_attsInfo, element);
+ return Blocks.BlockAttributesParser.ParseBlockAttributes(_alignInfo + _attsInfo, element);
}
}
}
diff --git a/common/ASC.Textile/States/NoTextileFormatterState.cs b/common/ASC.Textile/States/NoTextileFormatterState.cs
index 0353a2d0ea..05b84237f6 100644
--- a/common/ASC.Textile/States/NoTextileFormatterState.cs
+++ b/common/ASC.Textile/States/NoTextileFormatterState.cs
@@ -1,64 +1,63 @@
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(@"^\s*\s*$")]
+public class NoTextileFormatterState : FormatterState
{
- [FormatterState(@"^\s*\s*$")]
- public class NoTextileFormatterState : FormatterState
+ private bool _shouldExitNextTime = false;
+
+ public NoTextileFormatterState(TextileFormatter f)
+ : base(f)
{
- bool m_shouldExitNextTime = false;
+ }
- public NoTextileFormatterState(TextileFormatter f)
- : base(f)
- {
- }
+ public override string Consume(string input, Match m)
+ {
+ this.Formatter.ChangeState(this);
+ return string.Empty;
+ }
- public override string Consume(string input, Match m)
- {
- this.Formatter.ChangeState(this);
- return string.Empty;
- }
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
+ public override void Enter()
+ {
+ }
- public override void Enter()
- {
- }
+ public override void Exit()
+ {
+ }
- public override void Exit()
- {
- }
+ public override void FormatLine(string input)
+ {
+ if (!_shouldExitNextTime)
+ Formatter.Output.WriteLine(input);
+ }
- public override void FormatLine(string input)
- {
- if (!m_shouldExitNextTime)
- Formatter.Output.WriteLine(input);
- }
+ public override bool ShouldExit(string input)
+ {
+ if (_shouldExitNextTime)
+ return true;
+ _shouldExitNextTime = Regex.IsMatch(input, @"^\s*\s*$");
+ return false;
+ }
- public override bool ShouldExit(string input)
- {
- if (m_shouldExitNextTime)
- return true;
- m_shouldExitNextTime = Regex.IsMatch(input, @"^\s*\s*$");
- return false;
- }
+ public override bool ShouldFormatBlocks(string input)
+ {
+ return false;
+ }
- public override bool ShouldFormatBlocks(string input)
- {
- return false;
- }
+ public override bool ShouldParseForNewFormatterState(string input)
+ {
+ return false;
+ }
- public override bool ShouldParseForNewFormatterState(string input)
+ public override Type FallbackFormattingState
+ {
+ get
{
- return false;
- }
-
- public override Type FallbackFormattingState
- {
- get
- {
- return null;
- }
+ return null;
}
}
-}
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/States/OrderedListFormatterState.cs b/common/ASC.Textile/States/OrderedListFormatterState.cs
index 5a28d7c72d..942d6ec85b 100644
--- a/common/ASC.Textile/States/OrderedListFormatterState.cs
+++ b/common/ASC.Textile/States/OrderedListFormatterState.cs
@@ -11,37 +11,36 @@
#endregion
-namespace Textile.States
+namespace Textile.States;
+
+///
+/// Formatting state for a numbered list.
+///
+[FormatterState(ListFormatterState.PatternBegin + @"#+" + ListFormatterState.PatternEnd)]
+public class OrderedListFormatterState : ListFormatterState
{
- ///
- /// Formatting state for a numbered list.
- ///
- [FormatterState(ListFormatterState.PatternBegin + @"#+" + ListFormatterState.PatternEnd)]
- public class OrderedListFormatterState : ListFormatterState
+ public OrderedListFormatterState(TextileFormatter formatter)
+ : base(formatter)
{
- public OrderedListFormatterState(TextileFormatter formatter)
- : base(formatter)
- {
- }
+ }
- protected override void WriteIndent()
- {
- Formatter.Output.WriteLine("");
- }
+ protected override void WriteIndent()
+ {
+ Formatter.Output.WriteLine("");
+ }
- protected override void WriteOutdent()
- {
- Formatter.Output.WriteLine("
");
- }
+ protected override void WriteOutdent()
+ {
+ Formatter.Output.WriteLine("
");
+ }
- protected override bool IsMatchForMe(string input, int minNestingDepth, int maxNestingDepth)
- {
- return Regex.IsMatch(input, @"^\s*([\*#]{" + (minNestingDepth - 1) + @"," + (maxNestingDepth - 1) + @"})#" + Globals.BlockModifiersPattern + @"\s");
- }
+ protected override bool IsMatchForMe(string input, int minNestingDepth, int maxNestingDepth)
+ {
+ return Regex.IsMatch(input, @"^\s*([\*#]{" + (minNestingDepth - 1) + @"," + (maxNestingDepth - 1) + @"})#" + Globals.BlockModifiersPattern + @"\s");
+ }
- protected override bool IsMatchForOthers(string input, int minNestingDepth, int maxNestingDepth)
- {
- return Regex.IsMatch(input, @"^\s*([\*#]{" + (minNestingDepth - 1) + @"," + (maxNestingDepth - 1) + @"})\*" + Globals.BlockModifiersPattern + @"\s");
- }
+ protected override bool IsMatchForOthers(string input, int minNestingDepth, int maxNestingDepth)
+ {
+ return Regex.IsMatch(input, @"^\s*([\*#]{" + (minNestingDepth - 1) + @"," + (maxNestingDepth - 1) + @"})\*" + Globals.BlockModifiersPattern + @"\s");
}
}
diff --git a/common/ASC.Textile/States/ParagraphFormatterState.cs b/common/ASC.Textile/States/ParagraphFormatterState.cs
index 88acd5ed5e..d08a2b7a82 100644
--- a/common/ASC.Textile/States/ParagraphFormatterState.cs
+++ b/common/ASC.Textile/States/ParagraphFormatterState.cs
@@ -10,45 +10,44 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.States
+namespace Textile.States;
+
+///
+/// Formatting state for a standard text (i.e. just paragraphs).
+///
+[FormatterState(SimpleBlockFormatterState.PatternBegin + @"p" + SimpleBlockFormatterState.PatternEnd)]
+public class ParagraphFormatterState : SimpleBlockFormatterState
{
- ///
- /// Formatting state for a standard text (i.e. just paragraphs).
- ///
- [FormatterState(SimpleBlockFormatterState.PatternBegin + @"p" + SimpleBlockFormatterState.PatternEnd)]
- public class ParagraphFormatterState : SimpleBlockFormatterState
+ public ParagraphFormatterState(TextileFormatter f)
+ : base(f)
{
- public ParagraphFormatterState(TextileFormatter f)
- : base(f)
- {
- }
+ }
- public override void Enter()
- {
- Formatter.Output.Write("");
- }
+ public override void Enter()
+ {
+ Formatter.Output.Write("
");
+ }
- public override void Exit()
- {
- Formatter.Output.WriteLine("
");
- }
+ public override void Exit()
+ {
+ Formatter.Output.WriteLine("");
+ }
- public override void FormatLine(string input)
- {
- Formatter.Output.Write(input);
- }
+ public override void FormatLine(string input)
+ {
+ Formatter.Output.Write(input);
+ }
- public override bool ShouldExit(string input)
- {
- if (Regex.IsMatch(input, @"^\s*$"))
- return true;
- Formatter.Output.WriteLine("
");
- return false;
- }
+ public override bool ShouldExit(string input)
+ {
+ if (Regex.IsMatch(input, @"^\s*$"))
+ return true;
+ Formatter.Output.WriteLine("
");
+ return false;
+ }
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
}
}
diff --git a/common/ASC.Textile/States/PassthroughFormatterState.cs b/common/ASC.Textile/States/PassthroughFormatterState.cs
index e56c1ba3ed..173c310a52 100644
--- a/common/ASC.Textile/States/PassthroughFormatterState.cs
+++ b/common/ASC.Textile/States/PassthroughFormatterState.cs
@@ -1,40 +1,39 @@
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(@"^\s*<(h[0-9]|p|pre|blockquote)" + Globals.HtmlAttributesPattern + ">")]
+public class PassthroughFormatterState : FormatterState
{
- [FormatterState(@"^\s*<(h[0-9]|p|pre|blockquote)" + Globals.HtmlAttributesPattern + ">")]
- public class PassthroughFormatterState : FormatterState
+ public PassthroughFormatterState(TextileFormatter f)
+ : base(f)
{
- public PassthroughFormatterState(TextileFormatter f)
- : base(f)
- {
- }
+ }
- public override string Consume(string input, Match m)
- {
- this.Formatter.ChangeState(this);
- return input;
- }
+ public override string Consume(string input, Match m)
+ {
+ this.Formatter.ChangeState(this);
+ return input;
+ }
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
- public override void Enter()
- {
- }
+ public override void Enter()
+ {
+ }
- public override void Exit()
- {
- }
+ public override void Exit()
+ {
+ }
- public override void FormatLine(string input)
- {
- Formatter.Output.WriteLine(input);
- }
+ public override void FormatLine(string input)
+ {
+ Formatter.Output.WriteLine(input);
+ }
- public override bool ShouldExit(string input)
- {
- return true;
- }
+ public override bool ShouldExit(string input)
+ {
+ return true;
}
}
diff --git a/common/ASC.Textile/States/PreCodeFormatterState.cs b/common/ASC.Textile/States/PreCodeFormatterState.cs
index 9d86e8de4a..15a2fe97d0 100644
--- a/common/ASC.Textile/States/PreCodeFormatterState.cs
+++ b/common/ASC.Textile/States/PreCodeFormatterState.cs
@@ -1,59 +1,58 @@
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(SimpleBlockFormatterState.PatternBegin + @"bc" + SimpleBlockFormatterState.PatternEnd)]
+public class PreCodeFormatterState : SimpleBlockFormatterState
{
- [FormatterState(SimpleBlockFormatterState.PatternBegin + @"bc" + SimpleBlockFormatterState.PatternEnd)]
- public class PreCodeFormatterState : SimpleBlockFormatterState
+ public PreCodeFormatterState(TextileFormatter formatter)
+ : base(formatter)
{
- public PreCodeFormatterState(TextileFormatter formatter)
- : base(formatter)
- {
- }
+ }
- public override void Enter()
- {
- Formatter.Output.Write("");
- }
+ public override void Enter()
+ {
+ Formatter.Output.Write("");
+ }
- public override void Exit()
- {
- Formatter.Output.WriteLine("
");
- }
+ public override void Exit()
+ {
+ Formatter.Output.WriteLine("
");
+ }
- public override void FormatLine(string input)
- {
- Formatter.Output.WriteLine(FixEntities(input));
- }
+ public override void FormatLine(string input)
+ {
+ Formatter.Output.WriteLine(FixEntities(input));
+ }
- public override bool ShouldExit(string input)
- {
- if (Regex.IsMatch(input, @"^\s*$"))
- return true;
- Formatter.Output.WriteLine("
");
- return false;
- }
+ public override bool ShouldExit(string input)
+ {
+ if (Regex.IsMatch(input, @"^\s*$"))
+ return true;
+ Formatter.Output.WriteLine("
");
+ return false;
+ }
- public override bool ShouldFormatBlocks(string input)
- {
- return false;
- }
+ public override bool ShouldFormatBlocks(string input)
+ {
+ return false;
+ }
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
- public override bool ShouldParseForNewFormatterState(string input)
- {
- return false;
- }
+ public override bool ShouldParseForNewFormatterState(string input)
+ {
+ return false;
+ }
- private string FixEntities(string text)
- {
- // de-entify any remaining angle brackets or ampersands
- text = text.Replace("&", "&");
- text = text.Replace(">", ">");
- text = text.Replace("<", "<");
- //Regex.Replace(text, @"\b&([#a-z0-9]+;)", "x%x%");
- return text;
- }
+ private string FixEntities(string text)
+ {
+ // de-entify any remaining angle brackets or ampersands
+ text = text.Replace("&", "&");
+ text = text.Replace(">", ">");
+ text = text.Replace("<", "<");
+ //Regex.Replace(text, @"\b&([#a-z0-9]+;)", "x%x%");
+ return text;
}
}
diff --git a/common/ASC.Textile/States/PreFormatterState.cs b/common/ASC.Textile/States/PreFormatterState.cs
index afbeeffb63..cff68cdb7e 100644
--- a/common/ASC.Textile/States/PreFormatterState.cs
+++ b/common/ASC.Textile/States/PreFormatterState.cs
@@ -1,75 +1,74 @@
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(@"^\s*")]
+public class PreFormatterState : FormatterState
{
- [FormatterState(@"^\s*")]
- public class PreFormatterState : FormatterState
+ private bool _shouldExitNextTime = false;
+ private int _fakeNestingDepth = 0;
+
+ public PreFormatterState(TextileFormatter f)
+ : base(f)
{
- bool m_shouldExitNextTime = false;
- int m_fakeNestingDepth = 0;
-
- public PreFormatterState(TextileFormatter f)
- : base(f)
- {
- }
-
- public override string Consume(string input, Match m)
- {
- if (!Regex.IsMatch(input, "
"))
- {
- this.Formatter.ChangeState(this);
- }
- else
- {
- this.Formatter.ChangeState(new PassthroughFormatterState(this.Formatter));
- }
- return input;
- }
-
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
-
- public override void Enter()
- {
- }
-
- public override void Exit()
- {
- }
-
- public override void FormatLine(string input)
- {
- if (Regex.IsMatch(input, ""))
- m_fakeNestingDepth++;
-
- Formatter.Output.WriteLine(input);
- }
-
- public override bool ShouldExit(string input)
- {
- if (m_shouldExitNextTime)
- return true;
- if (Regex.IsMatch(input, @"
"))
- m_fakeNestingDepth--;
- if (m_fakeNestingDepth <= 0)
- m_shouldExitNextTime = true;
- return false;
- }
-
- public override bool ShouldFormatBlocks(string input)
- {
- return false;
- }
-
- public override bool ShouldParseForNewFormatterState(string input)
- {
- // Only allow a child formatting state for tag.
- return Regex.IsMatch(input, @"^\s*"))
+ {
+ this.Formatter.ChangeState(this);
+ }
+ else
+ {
+ this.Formatter.ChangeState(new PassthroughFormatterState(this.Formatter));
+ }
+ return input;
+ }
+
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
+
+ public override void Enter()
+ {
+ }
+
+ public override void Exit()
+ {
+ }
+
+ public override void FormatLine(string input)
+ {
+ if (Regex.IsMatch(input, ""))
+ _fakeNestingDepth++;
+
+ Formatter.Output.WriteLine(input);
+ }
+
+ public override bool ShouldExit(string input)
+ {
+ if (_shouldExitNextTime)
+ return true;
+ if (Regex.IsMatch(input, @"
"))
+ _fakeNestingDepth--;
+ if (_fakeNestingDepth <= 0)
+ _shouldExitNextTime = true;
+ return false;
+ }
+
+ public override bool ShouldFormatBlocks(string input)
+ {
+ return false;
+ }
+
+ public override bool ShouldParseForNewFormatterState(string input)
+ {
+ // Only allow a child formatting state for tag.
+ return Regex.IsMatch(input, @"^\s*";
+ internal const string PatternEnd = @")" + Globals.AlignPattern + Globals.BlockModifiersPattern + @"\.(?:\s+)?(?.*)$";
+
+ public string Tag { get; private set; } = null;
+
+ public string AlignInfo { get; private set; } = null;
+
+ public string AttInfo { get; private set; } = null;
+
+ protected SimpleBlockFormatterState(TextileFormatter formatter)
+ : base(formatter)
{
- internal const string PatternBegin = @"^\s*(?";
- internal const string PatternEnd = @")" + Globals.AlignPattern + Globals.BlockModifiersPattern + @"\.(?:\s+)?(?.*)$";
-
- public string Tag { get; private set; } = null;
-
- public string AlignInfo { get; private set; } = null;
-
- public string AttInfo { get; private set; } = null;
-
- protected SimpleBlockFormatterState(TextileFormatter formatter)
- : base(formatter)
- {
- }
-
- public override string Consume(string input, Match m)
- {
- Tag = m.Groups["tag"].Value;
- AlignInfo = m.Groups["align"].Value;
- AttInfo = m.Groups["atts"].Value;
- input = m.Groups["content"].Value;
-
- OnContextAcquired();
-
- this.Formatter.ChangeState(this);
-
- return input;
- }
-
- public override bool ShouldNestState(FormatterState other)
- {
- var blockFormatterState = (SimpleBlockFormatterState)other;
- return blockFormatterState.Tag != Tag ||
- blockFormatterState.AlignInfo != AlignInfo ||
- blockFormatterState.AttInfo != AttInfo;
- }
-
- protected virtual void OnContextAcquired()
- {
- }
-
- ///
- ///
- ///
- ///
- protected string FormattedAlignment()
- {
- return Blocks.BlockAttributesParser.ParseBlockAttributes(AlignInfo);
- }
-
- protected string FormattedStyles(string element)
- {
- return Blocks.BlockAttributesParser.ParseBlockAttributes(AttInfo, element);
- }
-
- protected string FormattedStylesAndAlignment(string element)
- {
- return Blocks.BlockAttributesParser.ParseBlockAttributes(AlignInfo + AttInfo, element);
- }
}
-}
+
+ public override string Consume(string input, Match m)
+ {
+ Tag = m.Groups["tag"].Value;
+ AlignInfo = m.Groups["align"].Value;
+ AttInfo = m.Groups["atts"].Value;
+ input = m.Groups["content"].Value;
+
+ OnContextAcquired();
+
+ this.Formatter.ChangeState(this);
+
+ return input;
+ }
+
+ public override bool ShouldNestState(FormatterState other)
+ {
+ var blockFormatterState = (SimpleBlockFormatterState)other;
+ return blockFormatterState.Tag != Tag ||
+ blockFormatterState.AlignInfo != AlignInfo ||
+ blockFormatterState.AttInfo != AttInfo;
+ }
+
+ protected virtual void OnContextAcquired()
+ {
+ }
+
+ ///
+ ///
+ ///
+ ///
+ protected string FormattedAlignment()
+ {
+ return Blocks.BlockAttributesParser.ParseBlockAttributes(AlignInfo);
+ }
+
+ protected string FormattedStyles(string element)
+ {
+ return Blocks.BlockAttributesParser.ParseBlockAttributes(AttInfo, element);
+ }
+
+ protected string FormattedStylesAndAlignment(string element)
+ {
+ return Blocks.BlockAttributesParser.ParseBlockAttributes(AlignInfo + AttInfo, element);
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/States/TableCellParser.cs b/common/ASC.Textile/States/TableCellParser.cs
index 0450c27a99..5021b71238 100644
--- a/common/ASC.Textile/States/TableCellParser.cs
+++ b/common/ASC.Textile/States/TableCellParser.cs
@@ -1,45 +1,44 @@
-namespace Textile.States
+namespace Textile.States;
+
+public class TableCellParser
{
- public class TableCellParser
+ readonly string _lineFragment;
+
+ public TableCellParser(string input)
{
- readonly string m_lineFragment;
-
- public TableCellParser(string input)
- {
- m_lineFragment = input;
- }
-
- public string GetLineFragmentFormatting()
- {
- var htmlTag = "td";
-
- var m = Regex.Match(m_lineFragment,
- @"^((?_?)" +
- Globals.SpanPattern +
- Globals.AlignPattern +
- Globals.BlockModifiersPattern +
- @"(?\.)\s?)?" +
- @"(?.*)"
- );
- if (!m.Success)
- throw new Exception("Couldn't parse table cell.");
-
- if (m.Groups["head"].Value == "_")
- htmlTag = "th";
- //string opts = BlockAttributesParser.ParseBlockAttributes(m.Groups["span"].Value, "td") +
- // BlockAttributesParser.ParseBlockAttributes(m.Groups["align"].Value, "td") +
- // BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "td");
- var opts = Blocks.BlockAttributesParser.ParseBlockAttributes(m.Groups["span"].Value + m.Groups["align"].Value + m.Groups["atts"].Value, "td");
-
- var res = "<" + htmlTag + opts + ">";
- // It may be possible the user actually intended to have a dot at the beginning of
- // this cell's text, without any formatting (header tag or options).
- if (string.IsNullOrEmpty(opts) && htmlTag == "td" && !string.IsNullOrEmpty(m.Groups["dot"].Value))
- res += ".";
- res += m.Groups["content"].Value;
- res += "" + htmlTag + ">";
-
- return res;
- }
+ _lineFragment = input;
}
-}
+
+ public string GetLineFragmentFormatting()
+ {
+ var htmlTag = "td";
+
+ var m = Regex.Match(_lineFragment,
+ @"^((?_?)" +
+ Globals.SpanPattern +
+ Globals.AlignPattern +
+ Globals.BlockModifiersPattern +
+ @"(?\.)\s?)?" +
+ @"(?.*)"
+ );
+ if (!m.Success)
+ throw new Exception("Couldn't parse table cell.");
+
+ if (m.Groups["head"].Value == "_")
+ htmlTag = "th";
+ //string opts = BlockAttributesParser.ParseBlockAttributes(m.Groups["span"].Value, "td") +
+ // BlockAttributesParser.ParseBlockAttributes(m.Groups["align"].Value, "td") +
+ // BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "td");
+ var opts = Blocks.BlockAttributesParser.ParseBlockAttributes(m.Groups["span"].Value + m.Groups["align"].Value + m.Groups["atts"].Value, "td");
+
+ var res = "<" + htmlTag + opts + ">";
+ // It may be possible the user actually intended to have a dot at the beginning of
+ // this cell's text, without any formatting (header tag or options).
+ if (string.IsNullOrEmpty(opts) && htmlTag == "td" && !string.IsNullOrEmpty(m.Groups["dot"].Value))
+ res += ".";
+ res += m.Groups["content"].Value;
+ res += "" + htmlTag + ">";
+
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/States/TableFormatterState.cs b/common/ASC.Textile/States/TableFormatterState.cs
index cbb0ff0fe5..34c18ec0be 100644
--- a/common/ASC.Textile/States/TableFormatterState.cs
+++ b/common/ASC.Textile/States/TableFormatterState.cs
@@ -1,65 +1,64 @@
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(@"^\s*(?table)" +
+ Globals.SpanPattern +
+ Globals.AlignPattern +
+ Globals.BlockModifiersPattern +
+ @"\.\s*$")]
+public class TableFormatterState : FormatterState
{
- [FormatterState(@"^\s*(?table)" +
- Globals.SpanPattern +
- Globals.AlignPattern +
- Globals.BlockModifiersPattern +
- @"\.\s*$")]
- public class TableFormatterState : FormatterState
+ private string _attsInfo;
+ private string _alignInfo;
+
+ public TableFormatterState(TextileFormatter f)
+ : base(f)
{
- private string m_attsInfo;
- private string m_alignInfo;
+ }
- public TableFormatterState(TextileFormatter f)
- : base(f)
- {
- }
+ public override string Consume(string input, Match m)
+ {
+ _alignInfo = m.Groups["align"].Value;
+ _attsInfo = m.Groups["atts"].Value;
- public override string Consume(string input, Match m)
- {
- m_alignInfo = m.Groups["align"].Value;
- m_attsInfo = m.Groups["atts"].Value;
+ //TODO: check the state (it could already be a table!)
+ this.Formatter.ChangeState(this);
- //TODO: check the state (it could already be a table!)
- this.Formatter.ChangeState(this);
+ return string.Empty;
+ }
- return string.Empty;
- }
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
+ public override void Enter()
+ {
+ Formatter.Output.WriteLine("");
+ }
- public override void Enter()
- {
- Formatter.Output.WriteLine("");
- }
+ public override void Exit()
+ {
+ Formatter.Output.WriteLine("
");
+ }
- public override void Exit()
- {
- Formatter.Output.WriteLine("
");
- }
+ public override void FormatLine(string input)
+ {
+ if (input.Length > 0)
+ throw new Exception("The TableFormatter state is not supposed to format any lines!");
+ }
- public override void FormatLine(string input)
- {
- if (input.Length > 0)
- throw new Exception("The TableFormatter state is not supposed to format any lines!");
- }
+ public override bool ShouldExit(string input)
+ {
+ var m = Regex.Match(input,
+ @"^\s*" + Globals.AlignPattern + Globals.BlockModifiersPattern +
+ @"(\.\s?)?(?\|)" +
+ @"(?.*)(?=\|)"
+ );
+ return !m.Success;
+ }
- public override bool ShouldExit(string input)
- {
- var m = Regex.Match(input,
- @"^\s*" + Globals.AlignPattern + Globals.BlockModifiersPattern +
- @"(\.\s?)?(?\|)" +
- @"(?.*)(?=\|)"
- );
- return !m.Success;
- }
-
- protected string FormattedStylesAndAlignment()
- {
- return Blocks.BlockAttributesParser.ParseBlockAttributes(m_alignInfo + m_attsInfo);
- }
+ protected string FormattedStylesAndAlignment()
+ {
+ return Blocks.BlockAttributesParser.ParseBlockAttributes(_alignInfo + _attsInfo);
}
}
diff --git a/common/ASC.Textile/States/TableRowFormatterState.cs b/common/ASC.Textile/States/TableRowFormatterState.cs
index 9793568396..2048ef8939 100644
--- a/common/ASC.Textile/States/TableRowFormatterState.cs
+++ b/common/ASC.Textile/States/TableRowFormatterState.cs
@@ -1,73 +1,72 @@
-namespace Textile.States
+namespace Textile.States;
+
+[FormatterState(@"^\s*(" + Globals.AlignPattern + Globals.BlockModifiersPattern + @"\.\s?)?" +
+ @"\|(?.*)\|\s*$")]
+public class TableRowFormatterState : FormatterState
{
- [FormatterState(@"^\s*(" + Globals.AlignPattern + Globals.BlockModifiersPattern + @"\.\s?)?" +
- @"\|(?.*)\|\s*$")]
- public class TableRowFormatterState : FormatterState
+ private string _attsInfo;
+ private string _alignInfo;
+
+ public TableRowFormatterState(TextileFormatter f)
+ : base(f)
{
- private string m_attsInfo;
- private string m_alignInfo;
-
- public TableRowFormatterState(TextileFormatter f)
- : base(f)
- {
- }
-
- public override string Consume(string input, Match m)
- {
- m_alignInfo = m.Groups["align"].Value;
- m_attsInfo = m.Groups["atts"].Value;
- input = "|" + m.Groups["content"].Value + "|";
-
- if (!(this.Formatter.CurrentState is TableFormatterState))
- {
- var s = new TableFormatterState(this.Formatter);
- this.Formatter.ChangeState(s);
- }
-
- this.Formatter.ChangeState(this);
-
- return input;
- }
-
- public override bool ShouldNestState(FormatterState other)
- {
- return false;
- }
-
- public override void Enter()
- {
- Formatter.Output.WriteLine("");
- }
-
- public override void Exit()
- {
- Formatter.Output.WriteLine("
");
- }
-
- public override void FormatLine(string input)
- {
- // can get: Align & Classes
-
- var sb = new StringBuilder();
- var cellsInput = input.Split('|');
- for (var i = 1; i < cellsInput.Length - 1; i++)
- {
- var cellInput = cellsInput[i];
- var tcp = new TableCellParser(cellInput);
- sb.Append(tcp.GetLineFragmentFormatting());
- }
-
- Formatter.Output.WriteLine(sb.ToString());
- }
-
- public override bool ShouldExit(string input)
- {
- return true;
- }
-
- protected string FormattedStylesAndAlignment()
- {
- return Blocks.BlockAttributesParser.ParseBlockAttributes(m_alignInfo + m_attsInfo);
- }
}
-}
+
+ public override string Consume(string input, Match m)
+ {
+ _alignInfo = m.Groups["align"].Value;
+ _attsInfo = m.Groups["atts"].Value;
+ input = "|" + m.Groups["content"].Value + "|";
+
+ if (!(this.Formatter.CurrentState is TableFormatterState))
+ {
+ var s = new TableFormatterState(this.Formatter);
+ this.Formatter.ChangeState(s);
+ }
+
+ this.Formatter.ChangeState(this);
+
+ return input;
+ }
+
+ public override bool ShouldNestState(FormatterState other)
+ {
+ return false;
+ }
+
+ public override void Enter()
+ {
+ Formatter.Output.WriteLine("");
+ }
+
+ public override void Exit()
+ {
+ Formatter.Output.WriteLine("
");
+ }
+
+ public override void FormatLine(string input)
+ {
+ // can get: Align & Classes
+
+ var sb = new StringBuilder();
+ var cellsInput = input.Split('|');
+ for (var i = 1; i < cellsInput.Length - 1; i++)
+ {
+ var cellInput = cellsInput[i];
+ var tcp = new TableCellParser(cellInput);
+ sb.Append(tcp.GetLineFragmentFormatting());
+ }
+
+ Formatter.Output.WriteLine(sb.ToString());
+ }
+
+ public override bool ShouldExit(string input)
+ {
+ return true;
+ }
+
+ protected string FormattedStylesAndAlignment()
+ {
+ return Blocks.BlockAttributesParser.ParseBlockAttributes(_alignInfo + _attsInfo);
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/States/UnorderedListFormatterState.cs b/common/ASC.Textile/States/UnorderedListFormatterState.cs
index 96eaf79909..a809f1bf52 100644
--- a/common/ASC.Textile/States/UnorderedListFormatterState.cs
+++ b/common/ASC.Textile/States/UnorderedListFormatterState.cs
@@ -10,37 +10,36 @@
// You must not remove this notice, or any other, from this software.
#endregion
-namespace Textile.States
+namespace Textile.States;
+
+///
+/// Formatting state for a bulleted list.
+///
+[FormatterState(ListFormatterState.PatternBegin + @"\*+" + ListFormatterState.PatternEnd)]
+public class UnorderedListFormatterState : ListFormatterState
{
- ///
- /// Formatting state for a bulleted list.
- ///
- [FormatterState(ListFormatterState.PatternBegin + @"\*+" + ListFormatterState.PatternEnd)]
- public class UnorderedListFormatterState : ListFormatterState
+ public UnorderedListFormatterState(TextileFormatter formatter)
+ : base(formatter)
{
- public UnorderedListFormatterState(TextileFormatter formatter)
- : base(formatter)
- {
- }
-
- protected override void WriteIndent()
- {
- Formatter.Output.WriteLine("");
- }
-
- protected override void WriteOutdent()
- {
- Formatter.Output.WriteLine("
");
- }
-
- protected override bool IsMatchForMe(string input, int minNestingDepth, int maxNestingDepth)
- {
- return Regex.IsMatch(input, @"^\s*[\*]{" + minNestingDepth + @"," + maxNestingDepth + @"}" + Globals.BlockModifiersPattern + @"\s");
- }
-
- protected override bool IsMatchForOthers(string input, int minNestingDepth, int maxNestingDepth)
- {
- return Regex.IsMatch(input, @"^\s*[#]{" + minNestingDepth + @"," + maxNestingDepth + @"}" + Globals.BlockModifiersPattern + @"\s");
- }
}
-}
+
+ protected override void WriteIndent()
+ {
+ Formatter.Output.WriteLine("");
+ }
+
+ protected override void WriteOutdent()
+ {
+ Formatter.Output.WriteLine("
");
+ }
+
+ protected override bool IsMatchForMe(string input, int minNestingDepth, int maxNestingDepth)
+ {
+ return Regex.IsMatch(input, @"^\s*[\*]{" + minNestingDepth + @"," + maxNestingDepth + @"}" + Globals.BlockModifiersPattern + @"\s");
+ }
+
+ protected override bool IsMatchForOthers(string input, int minNestingDepth, int maxNestingDepth)
+ {
+ return Regex.IsMatch(input, @"^\s*[#]{" + minNestingDepth + @"," + maxNestingDepth + @"}" + Globals.BlockModifiersPattern + @"\s");
+ }
+}
\ No newline at end of file
diff --git a/common/ASC.Textile/StringBuilderTextileFormatter.cs b/common/ASC.Textile/StringBuilderTextileFormatter.cs
index ca5f33810a..1ab090d209 100644
--- a/common/ASC.Textile/StringBuilderTextileFormatter.cs
+++ b/common/ASC.Textile/StringBuilderTextileFormatter.cs
@@ -11,42 +11,41 @@
#endregion
-namespace Textile
+namespace Textile;
+
+public class StringBuilderTextileFormatter : IOutputter
{
- public class StringBuilderTextileFormatter : IOutputter
+ private StringBuilder _stringBuilder = null;
+
+ public StringBuilderTextileFormatter()
{
- StringBuilder m_stringBuilder = null;
-
- public StringBuilderTextileFormatter()
- {
- }
-
- public string GetFormattedText()
- {
- return m_stringBuilder.ToString();
- }
-
- #region IOutputter Members
-
- public void Begin()
- {
- m_stringBuilder = new StringBuilder();
- }
-
- public void End()
- {
- }
-
- public void Write(string text)
- {
- m_stringBuilder.Append(text);
- }
-
- public void WriteLine(string line)
- {
- m_stringBuilder.AppendLine(line);
- }
-
- #endregion
}
+
+ public string GetFormattedText()
+ {
+ return _stringBuilder.ToString();
+ }
+
+ #region IOutputter Members
+
+ public void Begin()
+ {
+ _stringBuilder = new StringBuilder();
+ }
+
+ public void End()
+ {
+ }
+
+ public void Write(string text)
+ {
+ _stringBuilder.Append(text);
+ }
+
+ public void WriteLine(string line)
+ {
+ _stringBuilder.AppendLine(line);
+ }
+
+ #endregion
}
diff --git a/common/ASC.Textile/StyleReader.cs b/common/ASC.Textile/StyleReader.cs
index 66c9cabbd0..28be943a6f 100644
--- a/common/ASC.Textile/StyleReader.cs
+++ b/common/ASC.Textile/StyleReader.cs
@@ -1,28 +1,27 @@
-namespace Textile
+namespace Textile;
+
+public class StyleReader
{
- public class StyleReader
+ private readonly Regex _styleParser = new Regex(@"(?[^\{]+)(?