Merge branch 'develop' of github.com:ONLYOFFICE/AppServer into feature/virtual-rooms-1.2

This commit is contained in:
Viktor Fomin 2022-03-21 17:15:55 +03:00
commit 8381b3e9c6
31 changed files with 269 additions and 155 deletions

View File

@ -220,14 +220,15 @@ namespace ASC.Common.Threading
var token = cancelation.Token; var token = cancelation.Token;
Cancelations[distributedTask.Id] = cancelation; Cancelations[distributedTask.Id] = cancelation;
var task = new Task(async () => var task = new Task(() =>
{ {
var t = action(distributedTask, token); var t = action(distributedTask, token);
t.ConfigureAwait(false) t.ConfigureAwait(false)
.GetAwaiter() .GetAwaiter()
.OnCompleted(() => OnCompleted(t, distributedTask.Id)); .OnCompleted(() => OnCompleted(t, distributedTask.Id));
await t;
}, token, TaskCreationOptions.LongRunning); }, token, TaskCreationOptions.LongRunning);
task.ConfigureAwait(false);
distributedTask.Status = DistributedTaskStatus.Running; distributedTask.Status = DistributedTaskStatus.Running;

View File

@ -50,21 +50,19 @@ namespace ASC.Core.Billing
private readonly string _billingKey; private readonly string _billingKey;
private readonly string _billingSecret; private readonly string _billingSecret;
private readonly bool _test; private readonly bool _test;
private readonly IHttpClientFactory _httpClientFactory;
private const int AvangatePaymentSystemId = 1; private const int AvangatePaymentSystemId = 1;
static readonly HttpClient HttpClient = new HttpClient();
public BillingClient(IConfiguration configuration, IHttpClientFactory httpClientFactory)
public BillingClient(IConfiguration configuration) : this(false, configuration, httpClientFactory)
: this(false, configuration)
{ {
} }
public BillingClient(bool test, IConfiguration configuration) public BillingClient(bool test, IConfiguration configuration, IHttpClientFactory httpClientFactory)
{ {
_test = test; _test = test;
_httpClientFactory = httpClientFactory;
var billingDomain = configuration["core:payment-url"]; var billingDomain = configuration["core:payment-url"];
_billingDomain = (billingDomain ?? "").Trim().TrimEnd('/'); _billingDomain = (billingDomain ?? "").Trim().TrimEnd('/');
@ -234,7 +232,8 @@ namespace ASC.Core.Billing
request.Headers.Add("Authorization", CreateAuthToken(_billingKey, _billingSecret)); request.Headers.Add("Authorization", CreateAuthToken(_billingKey, _billingSecret));
} }
HttpClient.Timeout = TimeSpan.FromMilliseconds(60000); var httpClient = _httpClientFactory.CreateClient();
httpClient.Timeout = TimeSpan.FromMilliseconds(60000);
var data = new Dictionary<string, List<string>>(); var data = new Dictionary<string, List<string>>();
if (!string.IsNullOrEmpty(portalId)) if (!string.IsNullOrEmpty(portalId))
@ -257,7 +256,7 @@ namespace ASC.Core.Billing
request.Content = new StringContent(body, Encoding.UTF8, "application/json"); request.Content = new StringContent(body, Encoding.UTF8, "application/json");
string result; string result;
using (var response = HttpClient.Send(request)) using (var response = httpClient.Send(request))
using (var stream = response.Content.ReadAsStream()) using (var stream = response.Content.ReadAsStream())
{ {
if (stream == null) if (stream == null)

View File

@ -27,6 +27,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -162,6 +163,7 @@ namespace ASC.Core.Billing
internal TariffServiceStorage TariffServiceStorage { get; set; } internal TariffServiceStorage TariffServiceStorage { get; set; }
internal IOptionsMonitor<ILog> Options { get; set; } internal IOptionsMonitor<ILog> Options { get; set; }
public BillingClient BillingClient { get; } public BillingClient BillingClient { get; }
public IHttpClientFactory HttpClientFactory { get; }
public readonly int ACTIVE_USERS_MIN; public readonly int ACTIVE_USERS_MIN;
public readonly int ACTIVE_USERS_MAX; public readonly int ACTIVE_USERS_MAX;
@ -181,7 +183,8 @@ namespace ASC.Core.Billing
TariffServiceStorage tariffServiceStorage, TariffServiceStorage tariffServiceStorage,
IOptionsMonitor<ILog> options, IOptionsMonitor<ILog> options,
Constants constants, Constants constants,
BillingClient billingClient) BillingClient billingClient,
IHttpClientFactory httpClientFactory)
: this() : this()
{ {
@ -193,6 +196,7 @@ namespace ASC.Core.Billing
TariffServiceStorage = tariffServiceStorage; TariffServiceStorage = tariffServiceStorage;
Options = options; Options = options;
BillingClient = billingClient; BillingClient = billingClient;
HttpClientFactory = httpClientFactory;
CoreBaseSettings = coreBaseSettings; CoreBaseSettings = coreBaseSettings;
Test = configuration["core:payment:test"] == "true"; Test = configuration["core:payment:test"] == "true";
int.TryParse(configuration["core:payment:delay"], out var paymentDelay); int.TryParse(configuration["core:payment:delay"], out var paymentDelay);
@ -640,7 +644,7 @@ namespace ASC.Core.Billing
{ {
try try
{ {
return new BillingClient(Test, Configuration); return new BillingClient(Test, Configuration, HttpClientFactory);
} }
catch (InvalidOperationException ioe) catch (InvalidOperationException ioe)
{ {

View File

@ -28,6 +28,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using ASC.Common;
using ASC.Common.Logging; using ASC.Common.Logging;
using ASC.Notify.Channels; using ASC.Notify.Channels;
using ASC.Notify.Engine; using ASC.Notify.Engine;
@ -39,7 +40,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace ASC.Notify namespace ASC.Notify
{ {
[Singletone]
public sealed class Context : INotifyRegistry public sealed class Context : INotifyRegistry
{ {
public const string SYS_RECIPIENT_ID = "_#" + _SYS_RECIPIENT_ID + "#_"; public const string SYS_RECIPIENT_ID = "_#" + _SYS_RECIPIENT_ID + "#_";

View File

@ -40,13 +40,16 @@ namespace ASC.FederatedLogin.Helpers
[Scope] [Scope]
public class OAuth20TokenHelper public class OAuth20TokenHelper
{ {
private readonly RequestHelper _requestHelper;
private IHttpContextAccessor HttpContextAccessor { get; } private IHttpContextAccessor HttpContextAccessor { get; }
private ConsumerFactory ConsumerFactory { get; } private ConsumerFactory ConsumerFactory { get; }
public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFactory consumerFactory) public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFactory consumerFactory, RequestHelper requestHelper)
{ {
HttpContextAccessor = httpContextAccessor; HttpContextAccessor = httpContextAccessor;
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
_requestHelper = requestHelper;
} }
public string RequestCode<T>(string scope = null, IDictionary<string, string> additionalArgs = null, IDictionary<string, string> additionalStateArgs = null) where T : Consumer, IOAuthProvider, new() public string RequestCode<T>(string scope = null, IDictionary<string, string> additionalArgs = null, IDictionary<string, string> additionalStateArgs = null) where T : Consumer, IOAuthProvider, new()
@ -95,7 +98,7 @@ namespace ASC.FederatedLogin.Helpers
return uriBuilder.Uri + "?" + query; return uriBuilder.Uri + "?" + query;
} }
public static OAuth20Token GetAccessToken<T>(ConsumerFactory consumerFactory, string authCode) where T : Consumer, IOAuthProvider, new() public OAuth20Token GetAccessToken<T>(ConsumerFactory consumerFactory, string authCode) where T : Consumer, IOAuthProvider, new()
{ {
var loginProvider = consumerFactory.Get<T>(); var loginProvider = consumerFactory.Get<T>();
var requestUrl = loginProvider.AccessTokenUrl; var requestUrl = loginProvider.AccessTokenUrl;
@ -114,7 +117,7 @@ namespace ASC.FederatedLogin.Helpers
data += "&grant_type=authorization_code"; data += "&grant_type=authorization_code";
var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data); var json = _requestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data);
if (json != null) if (json != null)
{ {
if (!json.StartsWith('{')) if (!json.StartsWith('{'))
@ -134,19 +137,19 @@ namespace ASC.FederatedLogin.Helpers
return null; return null;
} }
public static OAuth20Token RefreshToken<T>(ConsumerFactory consumerFactory, OAuth20Token token) where T : Consumer, IOAuthProvider, new() public OAuth20Token RefreshToken<T>(ConsumerFactory consumerFactory, OAuth20Token token) where T : Consumer, IOAuthProvider, new()
{ {
var loginProvider = consumerFactory.Get<T>(); var loginProvider = consumerFactory.Get<T>();
return RefreshToken(loginProvider.AccessTokenUrl, token); return RefreshToken(loginProvider.AccessTokenUrl, token);
} }
public static OAuth20Token RefreshToken(string requestUrl, OAuth20Token token) public OAuth20Token RefreshToken(string requestUrl, OAuth20Token token)
{ {
if (token == null || !CanRefresh(token)) throw new ArgumentException("Can not refresh given token", nameof(token)); if (token == null || !CanRefresh(token)) throw new ArgumentException("Can not refresh given token", nameof(token));
var data = $"client_id={HttpUtility.UrlEncode(token.ClientID)}&client_secret={HttpUtility.UrlEncode(token.ClientSecret)}&refresh_token={HttpUtility.UrlEncode(token.RefreshToken)}&grant_type=refresh_token"; var data = $"client_id={HttpUtility.UrlEncode(token.ClientID)}&client_secret={HttpUtility.UrlEncode(token.ClientSecret)}&refresh_token={HttpUtility.UrlEncode(token.RefreshToken)}&grant_type=refresh_token";
var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data); var json = _requestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data);
if (json != null) if (json != null)
{ {
var refreshed = OAuth20Token.FromJson(json); var refreshed = OAuth20Token.FromJson(json);

View File

@ -31,13 +31,21 @@ using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using ASC.Common;
namespace ASC.FederatedLogin.Helpers namespace ASC.FederatedLogin.Helpers
{ {
public static class RequestHelper [Singletone]
public class RequestHelper
{ {
private static HttpClient HttpClient { get; } = new HttpClient(); private readonly IHttpClientFactory _httpClientFactory;
public static string PerformRequest(string uri, string contentType = "", string method = "GET", string body = "", Dictionary<string, string> headers = null, int timeout = 30000) public RequestHelper(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public string PerformRequest(string uri, string contentType = "", string method = "GET", string body = "", Dictionary<string, string> headers = null, int timeout = 30000)
{ {
if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException(nameof(uri)); if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException(nameof(uri));
@ -45,7 +53,8 @@ namespace ASC.FederatedLogin.Helpers
request.RequestUri = new Uri(uri); request.RequestUri = new Uri(uri);
request.Method = new HttpMethod(method); request.Method = new HttpMethod(method);
HttpClient.Timeout = TimeSpan.FromMilliseconds(timeout); var httpClient = _httpClientFactory.CreateClient();
httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
if (headers != null) if (headers != null)
{ {
@ -65,7 +74,7 @@ namespace ASC.FederatedLogin.Helpers
} }
} }
using var response = HttpClient.Send(request); using var response = httpClient.Send(request);
using var stream = response.Content.ReadAsStream(); using var stream = response.Content.ReadAsStream();
if (stream == null) return null; if (stream == null) return null;
using var readStream = new StreamReader(stream); using var readStream = new StreamReader(stream);

View File

@ -68,10 +68,12 @@ namespace ASC.FederatedLogin.LoginProviders
CoreSettings coreSettings, CoreSettings coreSettings,
IConfiguration configuration, IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache, ICacheNotify<ConsumerCacheItem> cache,
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional)
{ {
_requestHelper = requestHelper;
} }
@ -84,8 +86,10 @@ namespace ASC.FederatedLogin.LoginProviders
var codeAuthBase64 = Convert.ToBase64String(codeAuthBytes); var codeAuthBase64 = Convert.ToBase64String(codeAuthBytes);
return "Basic " + codeAuthBase64; return "Basic " + codeAuthBase64;
} }
} }
private readonly RequestHelper _requestHelper;
public OAuth20Token GetAccessToken(string authCode) public OAuth20Token GetAccessToken(string authCode)
{ {
if (string.IsNullOrEmpty(authCode)) throw new ArgumentNullException(nameof(authCode)); if (string.IsNullOrEmpty(authCode)) throw new ArgumentNullException(nameof(authCode));
@ -95,7 +99,7 @@ namespace ASC.FederatedLogin.LoginProviders
var data = $"grant_type=authorization_code&code={authCode}"; var data = $"grant_type=authorization_code&code={authCode}";
var headers = new Dictionary<string, string> { { "Authorization", AuthHeader } }; var headers = new Dictionary<string, string> { { "Authorization", AuthHeader } };
var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers); var json = _requestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers);
if (json == null) throw new Exception("Can not get token"); if (json == null) throw new Exception("Can not get token");
if (!json.StartsWith('{')) if (!json.StartsWith('{'))
@ -120,7 +124,7 @@ namespace ASC.FederatedLogin.LoginProviders
var data = $"grant_type=refresh_token&refresh_token={refreshToken}"; var data = $"grant_type=refresh_token&refresh_token={refreshToken}";
var headers = new Dictionary<string, string> { { "Authorization", AuthHeader } }; var headers = new Dictionary<string, string> { { "Authorization", AuthHeader } };
var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers); var json = _requestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers);
if (json == null) throw new Exception("Can not get token"); if (json == null) throw new Exception("Can not get token");
var refreshed = OAuth20Token.FromJson(json); var refreshed = OAuth20Token.FromJson(json);

View File

@ -54,6 +54,8 @@ namespace ASC.FederatedLogin.LoginProviders
public override string CodeUrl { get { return "https://www.facebook.com/v2.7/dialog/oauth/"; } } public override string CodeUrl { get { return "https://www.facebook.com/v2.7/dialog/oauth/"; } }
public override string Scopes { get { return "email,public_profile"; } } public override string Scopes { get { return "email,public_profile"; } }
private readonly RequestHelper _requestHelper;
public FacebookLoginProvider() { } public FacebookLoginProvider() { }
public FacebookLoginProvider( public FacebookLoginProvider(
OAuth20TokenHelper oAuth20TokenHelper, OAuth20TokenHelper oAuth20TokenHelper,
@ -65,8 +67,12 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) { } : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{
_requestHelper = requestHelper;
}
public override LoginProfile GetLoginProfile(string accessToken) public override LoginProfile GetLoginProfile(string accessToken)
{ {
@ -78,7 +84,7 @@ namespace ASC.FederatedLogin.LoginProviders
private LoginProfile RequestProfile(string accessToken) private LoginProfile RequestProfile(string accessToken)
{ {
var facebookProfile = RequestHelper.PerformRequest(FacebookProfileUrl + "&access_token=" + accessToken); var facebookProfile = _requestHelper.PerformRequest(FacebookProfileUrl + "&access_token=" + accessToken);
var loginProfile = ProfileFromFacebook(facebookProfile); var loginProfile = ProfileFromFacebook(facebookProfile);
return loginProfile; return loginProfile;
} }

View File

@ -69,6 +69,8 @@ namespace ASC.FederatedLogin.LoginProviders
public override string ClientSecret { get { return this["googleClientSecret"]; } } public override string ClientSecret { get { return this["googleClientSecret"]; } }
public override string Scopes { get { return "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"; } } public override string Scopes { get { return "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"; } }
private readonly RequestHelper _requestHelper;
public GoogleLoginProvider() { } public GoogleLoginProvider() { }
public GoogleLoginProvider( public GoogleLoginProvider(
OAuth20TokenHelper oAuth20TokenHelper, OAuth20TokenHelper oAuth20TokenHelper,
@ -80,8 +82,12 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) { } : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{
_requestHelper = requestHelper;
}
public override LoginProfile GetLoginProfile(string accessToken) public override LoginProfile GetLoginProfile(string accessToken)
{ {
@ -104,7 +110,7 @@ namespace ASC.FederatedLogin.LoginProviders
private LoginProfile RequestProfile(string accessToken) private LoginProfile RequestProfile(string accessToken)
{ {
var googleProfile = RequestHelper.PerformRequest(GoogleUrlProfile + "?personFields=" + HttpUtility.UrlEncode(ProfileFields), headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var googleProfile = _requestHelper.PerformRequest(GoogleUrlProfile + "?personFields=" + HttpUtility.UrlEncode(ProfileFields), headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } });
var loginProfile = ProfileFromGoogle(googleProfile); var loginProfile = ProfileFromGoogle(googleProfile);
return loginProfile; return loginProfile;
} }

View File

@ -94,6 +94,8 @@ namespace ASC.FederatedLogin.LoginProviders
get { return BaseDomain + "/rs/prns/"; } get { return BaseDomain + "/rs/prns/"; }
} }
private readonly RequestHelper _requestHelper;
public GosUslugiLoginProvider() public GosUslugiLoginProvider()
{ {
} }
@ -108,9 +110,11 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{ {
_requestHelper = requestHelper;
} }
@ -216,7 +220,7 @@ namespace ASC.FederatedLogin.LoginProviders
}; };
var requestQuery = string.Join("&", requestParams.Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value))); var requestQuery = string.Join("&", requestParams.Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value)));
var result = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", requestQuery); var result = _requestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", requestQuery);
return OAuth20Token.FromJson(result); return OAuth20Token.FromJson(result);
} }
@ -231,7 +235,7 @@ namespace ASC.FederatedLogin.LoginProviders
} }
var oid = tokenPayload.Value<string>("urn:esia:sbj_id"); var oid = tokenPayload.Value<string>("urn:esia:sbj_id");
var userInfoString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid, "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var userInfoString = _requestHelper.PerformRequest(GosUslugiProfileUrl + oid, "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } });
var userInfo = JObject.Parse(userInfoString); var userInfo = JObject.Parse(userInfoString);
if (userInfo == null) if (userInfo == null)
{ {
@ -247,7 +251,7 @@ namespace ASC.FederatedLogin.LoginProviders
Provider = ProviderConstants.GosUslugi, Provider = ProviderConstants.GosUslugi,
}; };
var userContactsString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid + "/ctts", "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var userContactsString = _requestHelper.PerformRequest(GosUslugiProfileUrl + oid + "/ctts", "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } });
var userContacts = JObject.Parse(userContactsString); var userContacts = JObject.Parse(userContactsString);
if (userContacts == null) if (userContacts == null)
{ {
@ -262,7 +266,7 @@ namespace ASC.FederatedLogin.LoginProviders
foreach (var contactElement in contactElements.ToObject<List<string>>()) foreach (var contactElement in contactElements.ToObject<List<string>>())
{ {
var userContactString = RequestHelper.PerformRequest(contactElement, "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var userContactString = _requestHelper.PerformRequest(contactElement, "application/x-www-form-urlencoded", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } });
var userContact = JObject.Parse(userContactString); var userContact = JObject.Parse(userContactString);
if (userContact == null) if (userContact == null)

View File

@ -78,6 +78,8 @@ namespace ASC.FederatedLogin.LoginProviders
get { return "r_liteprofile r_emailaddress"; } get { return "r_liteprofile r_emailaddress"; }
} }
private readonly RequestHelper _requestHelper;
public LinkedInLoginProvider() { } public LinkedInLoginProvider() { }
public LinkedInLoginProvider( public LinkedInLoginProvider(
OAuth20TokenHelper oAuth20TokenHelper, OAuth20TokenHelper oAuth20TokenHelper,
@ -89,8 +91,12 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) { } : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{
_requestHelper = requestHelper;
}
public override LoginProfile GetLoginProfile(string accessToken) public override LoginProfile GetLoginProfile(string accessToken)
{ {
@ -102,11 +108,11 @@ namespace ASC.FederatedLogin.LoginProviders
private LoginProfile RequestProfile(string accessToken) private LoginProfile RequestProfile(string accessToken)
{ {
var linkedInProfile = RequestHelper.PerformRequest(LinkedInProfileUrl, var linkedInProfile = _requestHelper.PerformRequest(LinkedInProfileUrl,
headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } });
var loginProfile = ProfileFromLinkedIn(linkedInProfile); var loginProfile = ProfileFromLinkedIn(linkedInProfile);
var linkedInEmail = RequestHelper.PerformRequest(LinkedInEmailUrl, headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } }); var linkedInEmail = _requestHelper.PerformRequest(LinkedInEmailUrl, headers: new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } });
loginProfile.EMail = EmailFromLinkedIn(linkedInEmail); loginProfile.EMail = EmailFromLinkedIn(linkedInEmail);
return loginProfile; return loginProfile;

View File

@ -76,6 +76,8 @@ namespace ASC.FederatedLogin.LoginProviders
get { return this["mailRuRedirectUrl"]; } get { return this["mailRuRedirectUrl"]; }
} }
private readonly RequestHelper _requestHelper;
private const string MailRuApiUrl = "http://www.appsmail.ru/platform/api"; private const string MailRuApiUrl = "http://www.appsmail.ru/platform/api";
public MailRuLoginProvider() public MailRuLoginProvider()
@ -92,9 +94,11 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{ {
_requestHelper = requestHelper;
} }
public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs)
@ -150,7 +154,7 @@ namespace ASC.FederatedLogin.LoginProviders
var mailruParams = string.Join("", sortedKeys.Select(key => key + "=" + queryDictionary[key]).ToList()); var mailruParams = string.Join("", sortedKeys.Select(key => key + "=" + queryDictionary[key]).ToList());
var sig = string.Join("", md5.ComputeHash(Encoding.ASCII.GetBytes(mailruParams + ClientSecret)).Select(b => b.ToString("x2"))); var sig = string.Join("", md5.ComputeHash(Encoding.ASCII.GetBytes(mailruParams + ClientSecret)).Select(b => b.ToString("x2")));
var mailRuProfile = RequestHelper.PerformRequest( var mailRuProfile = _requestHelper.PerformRequest(
MailRuApiUrl MailRuApiUrl
+ "?" + string.Join("&", queryDictionary.Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value))) + "?" + string.Join("&", queryDictionary.Select(pair => pair.Key + "=" + HttpUtility.UrlEncode(pair.Value)))
+ "&sig=" + HttpUtility.UrlEncode(sig)); + "&sig=" + HttpUtility.UrlEncode(sig));

View File

@ -79,6 +79,8 @@ namespace ASC.FederatedLogin.LoginProviders
get { return (new[] { 4194304 }).Sum().ToString(); } get { return (new[] { 4194304 }).Sum().ToString(); }
} }
private readonly RequestHelper _requestHelper;
private const string VKProfileUrl = "https://api.vk.com/method/users.get?v=5.103"; private const string VKProfileUrl = "https://api.vk.com/method/users.get?v=5.103";
@ -96,9 +98,11 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{ {
_requestHelper = requestHelper;
} }
@ -150,7 +154,7 @@ namespace ASC.FederatedLogin.LoginProviders
private LoginProfile RequestProfile(string accessToken) private LoginProfile RequestProfile(string accessToken)
{ {
var fields = new[] { "sex" }; var fields = new[] { "sex" };
var vkProfile = RequestHelper.PerformRequest(VKProfileUrl + "&fields=" + HttpUtility.UrlEncode(string.Join(",", fields)) + "&access_token=" + accessToken); var vkProfile = _requestHelper.PerformRequest(VKProfileUrl + "&fields=" + HttpUtility.UrlEncode(string.Join(",", fields)) + "&access_token=" + accessToken);
var loginProfile = ProfileFromVK(vkProfile); var loginProfile = ProfileFromVK(vkProfile);
return loginProfile; return loginProfile;

View File

@ -61,21 +61,23 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{ {
_requestHelper = requestHelper;
} }
public static string GetWordpressMeInfo(string token) public static string GetWordpressMeInfo(RequestHelper requestHelper, string token)
{ {
var headers = new Dictionary<string, string> var headers = new Dictionary<string, string>
{ {
{ "Authorization", "bearer " + token } { "Authorization", "bearer " + token }
}; };
return RequestHelper.PerformRequest(WordpressMeInfoUrl, "", "GET", "", headers); return requestHelper.PerformRequest(WordpressMeInfoUrl, "", "GET", "", headers);
} }
public static bool CreateWordpressPost(string title, string content, string status, string blogId, OAuth20Token token) public static bool CreateWordpressPost(RequestHelper requestHelper, string title, string content, string status, string blogId, OAuth20Token token)
{ {
try try
{ {
@ -88,7 +90,7 @@ namespace ASC.FederatedLogin.LoginProviders
{ "Authorization", "bearer " + token.AccessToken } { "Authorization", "bearer " + token.AccessToken }
}; };
RequestHelper.PerformRequest(uri, contentType, method, body, headers); requestHelper.PerformRequest(uri, contentType, method, body, headers);
return true; return true;
} }
catch (Exception) catch (Exception)
@ -120,8 +122,10 @@ namespace ASC.FederatedLogin.LoginProviders
public override string ClientSecret public override string ClientSecret
{ {
get { return this["wpClientSecret"]; } get { return this["wpClientSecret"]; }
} }
private readonly RequestHelper _requestHelper;
public override LoginProfile GetLoginProfile(string accessToken) public override LoginProfile GetLoginProfile(string accessToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();

View File

@ -72,6 +72,8 @@ namespace ASC.FederatedLogin.LoginProviders
get { return this["yandexRedirectUrl"]; } get { return this["yandexRedirectUrl"]; }
} }
private readonly RequestHelper _requestHelper;
private const string YandexProfileUrl = "https://login.yandex.ru/info"; private const string YandexProfileUrl = "https://login.yandex.ru/info";
@ -89,9 +91,11 @@ namespace ASC.FederatedLogin.LoginProviders
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
Signature signature, Signature signature,
InstanceCrypto instanceCrypto, InstanceCrypto instanceCrypto,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null)
: base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional) : base(oAuth20TokenHelper, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, signature, instanceCrypto, name, order, props, additional)
{ {
_requestHelper = requestHelper;
} }
public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs)
@ -131,7 +135,7 @@ namespace ASC.FederatedLogin.LoginProviders
private LoginProfile RequestProfile(string accessToken) private LoginProfile RequestProfile(string accessToken)
{ {
var yandexProfile = RequestHelper.PerformRequest(YandexProfileUrl + "?format=json&oauth_token=" + accessToken); var yandexProfile = _requestHelper.PerformRequest(YandexProfileUrl + "?format=json&oauth_token=" + accessToken);
var loginProfile = ProfileFromYandex(yandexProfile); var loginProfile = ProfileFromYandex(yandexProfile);
return loginProfile; return loginProfile;

View File

@ -21,15 +21,17 @@ namespace ASC.Webhooks.Service
[Singletone] [Singletone]
public class WebhookSender public class WebhookSender
{ {
public int? RepeatCount { get; } public int? RepeatCount { get; }
private static readonly HttpClient httpClient = new HttpClient(); private readonly IHttpClientFactory _httpClientFactory;
private IServiceProvider ServiceProvider { get; } private IServiceProvider ServiceProvider { get; }
private ILog Log { get; } private ILog Log { get; }
public WebhookSender(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider, Settings settings) public WebhookSender(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider, Settings settings, IHttpClientFactory httpClientFactory)
{ {
Log = options.Get("ASC.Webhooks.Core"); Log = options.Get("ASC.Webhooks.Core");
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
_httpClientFactory = httpClientFactory;
RepeatCount = settings.RepeatCount; RepeatCount = settings.RepeatCount;
} }
@ -58,8 +60,9 @@ namespace ASC.Webhooks.Service
request.Content = new StringContent( request.Content = new StringContent(
data, data,
Encoding.UTF8, Encoding.UTF8,
"application/json"); "application/json");
var httpClient = _httpClientFactory.CreateClient();
response = await httpClient.SendAsync(request, cancellationToken); response = await httpClient.SendAsync(request, cancellationToken);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
@ -104,7 +107,7 @@ namespace ASC.Webhooks.Service
private void UpdateDb(DbWorker dbWorker, int id, HttpResponseMessage response, HttpRequestMessage request, ProcessStatus status) private void UpdateDb(DbWorker dbWorker, int id, HttpResponseMessage response, HttpRequestMessage request, ProcessStatus status)
{ {
var responseHeaders = JsonSerializer.Serialize(response.Headers.ToDictionary(r => r.Key, v => v.Value)); var responseHeaders = JsonSerializer.Serialize(response.Headers.ToDictionary(r => r.Key, v => v.Value));
var requestHeaders = JsonSerializer.Serialize(request.Headers.ToDictionary(r => r.Key , v => v.Value)); var requestHeaders = JsonSerializer.Serialize(request.Headers.ToDictionary(r => r.Key, v => v.Value));
string responsePayload; string responsePayload;
using (var streamReader = new StreamReader(response.Content.ReadAsStream())) using (var streamReader = new StreamReader(response.Content.ReadAsStream()))

View File

@ -61,7 +61,7 @@ namespace ASC.Web.CRM.Configuration
} }
public override async Task<List<UsageSpaceStatItem>> GetStatDataAsync() public override async ValueTask<List<UsageSpaceStatItem>> GetStatDataAsync()
{ {
var spaceUsage = await _filesDbContext.Files.AsQueryable().Join(_filesDbContext.Tree, var spaceUsage = await _filesDbContext.Files.AsQueryable().Join(_filesDbContext.Tree,
x => x.FolderId, x => x.FolderId,

View File

@ -180,13 +180,15 @@ namespace ASC.Files.Thirdparty.Box
public BoxStorage Storage { get; private set; } public BoxStorage Storage { get; private set; }
private ConsumerFactory ConsumerFactory { get; } private ConsumerFactory ConsumerFactory { get; }
private TempStream TempStream { get; } private TempStream TempStream { get; }
private IServiceProvider ServiceProvider { get; } private IServiceProvider ServiceProvider { get; }
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
public BoxStorageDisposableWrapper(ConsumerFactory consumerFactory, TempStream tempStream, IServiceProvider serviceProvider)
public BoxStorageDisposableWrapper(ConsumerFactory consumerFactory, TempStream tempStream, IServiceProvider serviceProvider, OAuth20TokenHelper oAuth20TokenHelper)
{ {
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
TempStream = tempStream; TempStream = tempStream;
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
_oAuth20TokenHelper = oAuth20TokenHelper;
} }
internal Task<BoxStorage> CreateStorageAsync(OAuth20Token token, int id) internal Task<BoxStorage> CreateStorageAsync(OAuth20Token token, int id)
@ -215,7 +217,7 @@ namespace ASC.Files.Thirdparty.Box
{ {
if (token.IsExpired) if (token.IsExpired)
{ {
token = OAuth20TokenHelper.RefreshToken<BoxLoginProvider>(ConsumerFactory, token); token = _oAuth20TokenHelper.RefreshToken<BoxLoginProvider>(ConsumerFactory, token);
var dbDao = ServiceProvider.GetService<ProviderAccountDao>(); var dbDao = ServiceProvider.GetService<ProviderAccountDao>();
await dbDao.UpdateProviderInfoAsync(id, new AuthData(token: token.ToJson())).ConfigureAwait(false); await dbDao.UpdateProviderInfoAsync(id, new AuthData(token: token.ToJson())).ConfigureAwait(false);

View File

@ -188,12 +188,14 @@ namespace ASC.Files.Thirdparty.GoogleDrive
{ {
internal GoogleDriveStorage Storage { get; set; } internal GoogleDriveStorage Storage { get; set; }
internal ConsumerFactory ConsumerFactory { get; } internal ConsumerFactory ConsumerFactory { get; }
internal IServiceProvider ServiceProvider { get; } internal IServiceProvider ServiceProvider { get; }
internal OAuth20TokenHelper _oAuth20TokenHelper { get; }
public GoogleDriveStorageDisposableWrapper(ConsumerFactory consumerFactory, IServiceProvider serviceProvider)
public GoogleDriveStorageDisposableWrapper(ConsumerFactory consumerFactory, IServiceProvider serviceProvider, OAuth20TokenHelper oAuth20TokenHelper)
{ {
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
_oAuth20TokenHelper = oAuth20TokenHelper;
} }
public Task<GoogleDriveStorage> CreateStorageAsync(OAuth20Token token, int id) public Task<GoogleDriveStorage> CreateStorageAsync(OAuth20Token token, int id)
@ -223,7 +225,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive
{ {
if (token.IsExpired) if (token.IsExpired)
{ {
token = OAuth20TokenHelper.RefreshToken<GoogleLoginProvider>(ConsumerFactory, token); token = _oAuth20TokenHelper.RefreshToken<GoogleLoginProvider>(ConsumerFactory, token);
var dbDao = ServiceProvider.GetService<ProviderAccountDao>(); var dbDao = ServiceProvider.GetService<ProviderAccountDao>();
var authData = new AuthData(token: token.ToJson()); var authData = new AuthData(token: token.ToJson());

View File

@ -71,7 +71,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive
get get
{ {
if (_token == null) throw new Exception("Cannot create GoogleDrive session with given token"); if (_token == null) throw new Exception("Cannot create GoogleDrive session with given token");
if (_token.IsExpired) _token = OAuth20TokenHelper.RefreshToken<GoogleLoginProvider>(ConsumerFactory, _token); if (_token.IsExpired) _token = _oAuth20TokenHelper.RefreshToken<GoogleLoginProvider>(ConsumerFactory, _token);
return _token.AccessToken; return _token.AccessToken;
} }
} }
@ -83,7 +83,9 @@ namespace ASC.Files.Thirdparty.GoogleDrive
private FileUtility FileUtility { get; } private FileUtility FileUtility { get; }
public ILog Log { get; } public ILog Log { get; }
private TempStream TempStream { get; } private TempStream TempStream { get; }
private IHttpClientFactory ClientFactory { get; }
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
private readonly IHttpClientFactory _clientFactory;
public const long MaxChunkedUploadFileSize = 2L * 1024L * 1024L * 1024L; public const long MaxChunkedUploadFileSize = 2L * 1024L * 1024L * 1024L;
@ -92,13 +94,15 @@ namespace ASC.Files.Thirdparty.GoogleDrive
FileUtility fileUtility, FileUtility fileUtility,
IOptionsMonitor<ILog> monitor, IOptionsMonitor<ILog> monitor,
TempStream tempStream, TempStream tempStream,
OAuth20TokenHelper oAuth20TokenHelper,
IHttpClientFactory clientFactory) IHttpClientFactory clientFactory)
{ {
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
FileUtility = fileUtility; FileUtility = fileUtility;
Log = monitor.Get("ASC.Files"); Log = monitor.Get("ASC.Files");
TempStream = tempStream; TempStream = tempStream;
ClientFactory = clientFactory; _oAuth20TokenHelper = oAuth20TokenHelper;
_clientFactory = clientFactory;
} }
public void Open(OAuth20Token token) public void Open(OAuth20Token token)
@ -284,7 +288,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive
request.Method = HttpMethod.Get; request.Method = HttpMethod.Get;
request.Headers.Add("Authorization", "Bearer " + AccessToken); request.Headers.Add("Authorization", "Bearer " + AccessToken);
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
using var response = await httpClient.SendAsync(request); using var response = await httpClient.SendAsync(request);
if (offset == 0 && file.Size.HasValue && file.Size > 0) if (offset == 0 && file.Size.HasValue && file.Size > 0)
@ -530,7 +534,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive
request.Headers.Add("Authorization", "Bearer " + AccessToken); request.Headers.Add("Authorization", "Bearer " + AccessToken);
request.Content = new StringContent(body, Encoding.UTF8, "application/json"); request.Content = new StringContent(body, Encoding.UTF8, "application/json");
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
using var response = await httpClient.SendAsync(request); using var response = await httpClient.SendAsync(request);
var uploadSession = new ResumableUploadSession(driveFile.Id, folderId, contentLength); var uploadSession = new ResumableUploadSession(driveFile.Id, folderId, contentLength);
@ -563,7 +567,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive
googleDriveSession.BytesTransfered + chunkLength - 1, googleDriveSession.BytesTransfered + chunkLength - 1,
googleDriveSession.BytesToTransfer)); googleDriveSession.BytesToTransfer));
request.Content = new StreamContent(stream); request.Content = new StreamContent(stream);
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
HttpResponseMessage response; HttpResponseMessage response;
try try

View File

@ -150,12 +150,14 @@ namespace ASC.Files.Thirdparty.OneDrive
{ {
internal OneDriveStorage Storage { get; private set; } internal OneDriveStorage Storage { get; private set; }
internal ConsumerFactory ConsumerFactory { get; } internal ConsumerFactory ConsumerFactory { get; }
internal IServiceProvider ServiceProvider { get; } internal IServiceProvider ServiceProvider { get; }
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
public OneDriveStorageDisposableWrapper(ConsumerFactory consumerFactory, IServiceProvider serviceProvider)
public OneDriveStorageDisposableWrapper(ConsumerFactory consumerFactory, IServiceProvider serviceProvider, OAuth20TokenHelper oAuth20TokenHelper)
{ {
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
_oAuth20TokenHelper = oAuth20TokenHelper;
} }
public Task<OneDriveStorage> CreateStorageAsync(OAuth20Token token, int id) public Task<OneDriveStorage> CreateStorageAsync(OAuth20Token token, int id)
@ -185,7 +187,7 @@ namespace ASC.Files.Thirdparty.OneDrive
{ {
if (token.IsExpired) if (token.IsExpired)
{ {
token = OAuth20TokenHelper.RefreshToken<OneDriveLoginProvider>(ConsumerFactory, token); token = _oAuth20TokenHelper.RefreshToken<OneDriveLoginProvider>(ConsumerFactory, token);
var dbDao = ServiceProvider.GetService<ProviderAccountDao>(); var dbDao = ServiceProvider.GetService<ProviderAccountDao>();
var authData = new AuthData(token: token.ToJson()); var authData = new AuthData(token: token.ToJson());

View File

@ -59,7 +59,7 @@ namespace ASC.Files.Thirdparty.OneDrive
if (_token == null) throw new Exception("Cannot create OneDrive session with given token"); if (_token == null) throw new Exception("Cannot create OneDrive session with given token");
if (_token.IsExpired) if (_token.IsExpired)
{ {
_token = OAuth20TokenHelper.RefreshToken<OneDriveLoginProvider>(ConsumerFactory, _token); _token = _oAuth20TokenHelper.RefreshToken<OneDriveLoginProvider>(ConsumerFactory, _token);
_onedriveClientCache = null; _onedriveClientCache = null;
} }
return _token.AccessToken; return _token.AccessToken;
@ -75,14 +75,16 @@ namespace ASC.Files.Thirdparty.OneDrive
public bool IsOpened { get; private set; } public bool IsOpened { get; private set; }
private ConsumerFactory ConsumerFactory { get; } private ConsumerFactory ConsumerFactory { get; }
private IHttpClientFactory ClientFactory { get; } private IHttpClientFactory ClientFactory { get; }
private OAuth20TokenHelper _oAuth20TokenHelper;
public long MaxChunkedUploadFileSize = 10L * 1024L * 1024L * 1024L; public long MaxChunkedUploadFileSize = 10L * 1024L * 1024L * 1024L;
public OneDriveStorage(ConsumerFactory consumerFactory, IHttpClientFactory clientFactory) public OneDriveStorage(ConsumerFactory consumerFactory, IHttpClientFactory clientFactory, OAuth20TokenHelper oAuth20TokenHelper)
{ {
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
ClientFactory = clientFactory; ClientFactory = clientFactory;
_oAuth20TokenHelper = oAuth20TokenHelper;
} }
public void Open(OAuth20Token token) public void Open(OAuth20Token token)

View File

@ -82,13 +82,13 @@ namespace ASC.Files.Thirdparty
internal class ProviderAccountDao : IProviderDao internal class ProviderAccountDao : IProviderDao
{ {
private int tenantID; private int tenantID;
protected int TenantID protected int TenantID
{ {
get get
{ {
if (tenantID == 0) tenantID = TenantManager.GetCurrentTenant().TenantId; if (tenantID == 0) tenantID = TenantManager.GetCurrentTenant().TenantId;
return tenantID; return tenantID;
} }
} }
private Lazy<FilesDbContext> LazyFilesDbContext { get; } private Lazy<FilesDbContext> LazyFilesDbContext { get; }
private FilesDbContext FilesDbContext { get => LazyFilesDbContext.Value; } private FilesDbContext FilesDbContext { get => LazyFilesDbContext.Value; }
@ -100,6 +100,7 @@ namespace ASC.Files.Thirdparty
private SecurityContext SecurityContext { get; } private SecurityContext SecurityContext { get; }
private ConsumerFactory ConsumerFactory { get; } private ConsumerFactory ConsumerFactory { get; }
private ThirdpartyConfiguration ThirdpartyConfiguration { get; } private ThirdpartyConfiguration ThirdpartyConfiguration { get; }
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
public ProviderAccountDao( public ProviderAccountDao(
IServiceProvider serviceProvider, IServiceProvider serviceProvider,
@ -109,7 +110,8 @@ namespace ASC.Files.Thirdparty
SecurityContext securityContext, SecurityContext securityContext,
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
ThirdpartyConfiguration thirdpartyConfiguration, ThirdpartyConfiguration thirdpartyConfiguration,
DbContextManager<FilesDbContext> dbContextManager, DbContextManager<FilesDbContext> dbContextManager,
OAuth20TokenHelper oAuth20TokenHelper,
IOptionsMonitor<ILog> options) IOptionsMonitor<ILog> options)
{ {
LazyFilesDbContext = new Lazy<FilesDbContext>(() => dbContextManager.Get(FileConstant.DatabaseId)); LazyFilesDbContext = new Lazy<FilesDbContext>(() => dbContextManager.Get(FileConstant.DatabaseId));
@ -121,6 +123,7 @@ namespace ASC.Files.Thirdparty
SecurityContext = securityContext; SecurityContext = securityContext;
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
ThirdpartyConfiguration = thirdpartyConfiguration; ThirdpartyConfiguration = thirdpartyConfiguration;
_oAuth20TokenHelper = oAuth20TokenHelper;
} }
public virtual Task<IProviderInfo> GetProviderInfoAsync(int linkId) public virtual Task<IProviderInfo> GetProviderInfoAsync(int linkId)
@ -521,7 +524,7 @@ namespace ASC.Files.Thirdparty
{ {
case ProviderTypes.GoogleDrive: case ProviderTypes.GoogleDrive:
code = authData.Token; code = authData.Token;
token = OAuth20TokenHelper.GetAccessToken<GoogleLoginProvider>(ConsumerFactory, code); token = _oAuth20TokenHelper.GetAccessToken<GoogleLoginProvider>(ConsumerFactory, code);
if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider)); if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider));
@ -529,7 +532,7 @@ namespace ASC.Files.Thirdparty
case ProviderTypes.Box: case ProviderTypes.Box:
code = authData.Token; code = authData.Token;
token = OAuth20TokenHelper.GetAccessToken<BoxLoginProvider>(ConsumerFactory, code); token = _oAuth20TokenHelper.GetAccessToken<BoxLoginProvider>(ConsumerFactory, code);
if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider)); if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider));
@ -537,7 +540,7 @@ namespace ASC.Files.Thirdparty
case ProviderTypes.DropboxV2: case ProviderTypes.DropboxV2:
code = authData.Token; code = authData.Token;
token = OAuth20TokenHelper.GetAccessToken<DropboxLoginProvider>(ConsumerFactory, code); token = _oAuth20TokenHelper.GetAccessToken<DropboxLoginProvider>(ConsumerFactory, code);
if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider)); if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider));
@ -559,7 +562,7 @@ namespace ASC.Files.Thirdparty
case ProviderTypes.OneDrive: case ProviderTypes.OneDrive:
code = authData.Token; code = authData.Token;
token = OAuth20TokenHelper.GetAccessToken<OneDriveLoginProvider>(ConsumerFactory, code); token = _oAuth20TokenHelper.GetAccessToken<OneDriveLoginProvider>(ConsumerFactory, code);
if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider)); if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider));
@ -569,7 +572,7 @@ namespace ASC.Files.Thirdparty
code = authData.Token; code = authData.Token;
token = OAuth20TokenHelper.GetAccessToken<OneDriveLoginProvider>(ConsumerFactory, code); token = _oAuth20TokenHelper.GetAccessToken<OneDriveLoginProvider>(ConsumerFactory, code);
if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider)); if (token == null) throw new UnauthorizedAccessException(string.Format(FilesCommonResource.ErrorMassage_SecurityException_Auth, provider));

View File

@ -166,8 +166,9 @@ namespace ASC.Web.Files.Helpers
private FilesMessageService FilesMessageService { get; } private FilesMessageService FilesMessageService { get; }
private FilesLinkUtility FilesLinkUtility { get; } private FilesLinkUtility FilesLinkUtility { get; }
private IServiceProvider ServiceProvider { get; } private IServiceProvider ServiceProvider { get; }
private ConsumerFactory ConsumerFactory { get; } private ConsumerFactory ConsumerFactory { get; }
private readonly RequestHelper _requestHelper;
public DocuSignHelper( public DocuSignHelper(
DocuSignToken docuSignToken, DocuSignToken docuSignToken,
FileSecurity fileSecurity, FileSecurity fileSecurity,
@ -182,7 +183,8 @@ namespace ASC.Web.Files.Helpers
FilesMessageService filesMessageService, FilesMessageService filesMessageService,
FilesLinkUtility filesLinkUtility, FilesLinkUtility filesLinkUtility,
IServiceProvider serviceProvider, IServiceProvider serviceProvider,
ConsumerFactory consumerFactory) ConsumerFactory consumerFactory,
RequestHelper requestHelper)
{ {
DocuSignToken = docuSignToken; DocuSignToken = docuSignToken;
FileSecurity = fileSecurity; FileSecurity = fileSecurity;
@ -196,7 +198,8 @@ namespace ASC.Web.Files.Helpers
FilesMessageService = filesMessageService; FilesMessageService = filesMessageService;
FilesLinkUtility = filesLinkUtility; FilesLinkUtility = filesLinkUtility;
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
_requestHelper = requestHelper;
Log = options.CurrentValue; Log = options.CurrentValue;
} }
@ -226,7 +229,7 @@ namespace ASC.Web.Files.Helpers
{ {
if (token == null) throw new ArgumentNullException(nameof(token)); if (token == null) throw new ArgumentNullException(nameof(token));
var userInfoString = RequestHelper.PerformRequest(ConsumerFactory.Get<DocuSignLoginProvider>().DocuSignHost + "/oauth/userinfo", var userInfoString = _requestHelper.PerformRequest(ConsumerFactory.Get<DocuSignLoginProvider>().DocuSignHost + "/oauth/userinfo",
headers: new Dictionary<string, string> { { "Authorization", "Bearer " + DocuSignToken.GetRefreshedToken(token) } }); headers: new Dictionary<string, string> { { "Authorization", "Bearer " + DocuSignToken.GetRefreshedToken(token) } });
Log.Debug("DocuSing userInfo: " + userInfoString); Log.Debug("DocuSing userInfo: " + userInfoString);

View File

@ -61,8 +61,10 @@ namespace ASC.Web.Files.Helpers
public string AppKey public string AppKey
{ {
get { return this["easyBibappkey"]; } get { return this["easyBibappkey"]; }
} }
private readonly RequestHelper _requestHelper;
public EasyBibHelper() public EasyBibHelper()
{ {
@ -75,17 +77,19 @@ namespace ASC.Web.Files.Helpers
CoreSettings coreSettings, CoreSettings coreSettings,
IConfiguration configuration, IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache, ICacheNotify<ConsumerCacheItem> cache,
ConsumerFactory factory, ConsumerFactory factory,
RequestHelper requestHelper,
string name, string name,
int order, int order,
Dictionary<string, string> props, Dictionary<string, string> props,
Dictionary<string, string> additional = null) Dictionary<string, string> additional = null)
: base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, factory, name, order, props, additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, factory, name, order, props, additional)
{ {
Log = option.CurrentValue; Log = option.CurrentValue;
_requestHelper = requestHelper;
} }
public static string GetEasyBibCitationsList(int source, string data) public string GetEasyBibCitationsList(int source, string data)
{ {
var uri = ""; var uri = "";
switch (source) switch (source)
@ -108,7 +112,7 @@ namespace ASC.Web.Files.Helpers
var headers = new Dictionary<string, string>() { }; var headers = new Dictionary<string, string>() { };
try try
{ {
return RequestHelper.PerformRequest(uri, "", method, "", headers); return _requestHelper.PerformRequest(uri, "", method, "", headers);
} }
catch (Exception) catch (Exception)
{ {
@ -117,14 +121,14 @@ namespace ASC.Web.Files.Helpers
} }
public static string GetEasyBibStyles() public string GetEasyBibStyles()
{ {
const string method = "GET"; const string method = "GET";
var headers = new Dictionary<string, string>() { }; var headers = new Dictionary<string, string>() { };
try try
{ {
return RequestHelper.PerformRequest(easyBibStyles, "", method, "", headers); return _requestHelper.PerformRequest(easyBibStyles, "", method, "", headers);
} }
catch (Exception) catch (Exception)
{ {
@ -147,7 +151,7 @@ namespace ASC.Web.Files.Helpers
var body = citationData; var body = citationData;
var headers = new Dictionary<string, string>() { }; var headers = new Dictionary<string, string>() { };
return RequestHelper.PerformRequest(uri, contentType, method, body, headers); return _requestHelper.PerformRequest(uri, contentType, method, body, headers);
} }
catch (Exception) catch (Exception)

View File

@ -44,14 +44,17 @@ namespace ASC.Web.Files.Helpers
public ILog Log { get; set; } public ILog Log { get; set; }
private TokenHelper TokenHelper { get; } private TokenHelper TokenHelper { get; }
public ConsumerFactory ConsumerFactory { get; } public ConsumerFactory ConsumerFactory { get; }
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
public const string AppAttr = "wordpress"; public const string AppAttr = "wordpress";
public WordpressToken(IOptionsMonitor<ILog> optionsMonitor, TokenHelper tokenHelper, ConsumerFactory consumerFactory) public WordpressToken(IOptionsMonitor<ILog> optionsMonitor, TokenHelper tokenHelper, ConsumerFactory consumerFactory, OAuth20TokenHelper oAuth20TokenHelper)
{ {
Log = optionsMonitor.CurrentValue; Log = optionsMonitor.CurrentValue;
TokenHelper = tokenHelper; TokenHelper = tokenHelper;
ConsumerFactory = consumerFactory; ConsumerFactory = consumerFactory;
_oAuth20TokenHelper = oAuth20TokenHelper;
} }
public OAuth20Token GetToken() public OAuth20Token GetToken()
@ -67,7 +70,7 @@ namespace ASC.Web.Files.Helpers
public OAuth20Token SaveTokenFromCode(string code) public OAuth20Token SaveTokenFromCode(string code)
{ {
var token = OAuth20TokenHelper.GetAccessToken<WordpressLoginProvider>(ConsumerFactory, code); var token = _oAuth20TokenHelper.GetAccessToken<WordpressLoginProvider>(ConsumerFactory, code);
if (token == null) throw new ArgumentNullException("token"); if (token == null) throw new ArgumentNullException("token");
TokenHelper.SaveToken(new Token(token, AppAttr)); TokenHelper.SaveToken(new Token(token, AppAttr));
return token; return token;
@ -84,23 +87,26 @@ namespace ASC.Web.Files.Helpers
[Singletone] [Singletone]
public class WordpressHelper public class WordpressHelper
{ {
public ILog Log { get; set; } public ILog Log { get; set; }
public RequestHelper RequestHelper { get; }
public enum WordpressStatus public enum WordpressStatus
{ {
draft = 0, draft = 0,
publish = 1 publish = 1
} }
public WordpressHelper(IOptionsMonitor<ILog> optionsMonitor) public WordpressHelper(IOptionsMonitor<ILog> optionsMonitor, RequestHelper requestHelper)
{ {
Log = optionsMonitor.CurrentValue; Log = optionsMonitor.CurrentValue;
RequestHelper = requestHelper;
} }
public string GetWordpressMeInfo(string token) public string GetWordpressMeInfo(string token)
{ {
try try
{ {
return WordpressLoginProvider.GetWordpressMeInfo(token); return WordpressLoginProvider.GetWordpressMeInfo(RequestHelper, token);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -115,7 +121,7 @@ namespace ASC.Web.Files.Helpers
try try
{ {
var wpStatus = ((WordpressStatus)status).ToString(); var wpStatus = ((WordpressStatus)status).ToString();
WordpressLoginProvider.CreateWordpressPost(title, content, wpStatus, blogId, token); WordpressLoginProvider.CreateWordpressPost(RequestHelper, title, content, wpStatus, blogId, token);
return true; return true;
} }
catch (Exception ex) catch (Exception ex)

View File

@ -34,6 +34,7 @@ using ASC.Core;
using ASC.Core.Common; using ASC.Core.Common;
using ASC.Files.Core.Resources; using ASC.Files.Core.Resources;
using ASC.Files.Core.Security; using ASC.Files.Core.Security;
using ASC.Notify;
using ASC.Notify.Patterns; using ASC.Notify.Patterns;
using ASC.Web.Core.Files; using ASC.Web.Core.Files;
using ASC.Web.Files.Classes; using ASC.Web.Files.Classes;
@ -46,11 +47,13 @@ namespace ASC.Files.Core.Services.NotifyService
[Scope(Additional = typeof(NotifyClientExtension))] [Scope(Additional = typeof(NotifyClientExtension))]
public class NotifyClient public class NotifyClient
{ {
private IServiceProvider ServiceProvider { get; } private IServiceProvider ServiceProvider { get; }
private Context NotifyContext { get; }
public NotifyClient(IServiceProvider serviceProvider)
public NotifyClient(IServiceProvider serviceProvider, Context notifyContext)
{ {
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
NotifyContext = notifyContext;
} }
public void SendDocuSignComplete<T>(File<T> file, string sourceTitle) public void SendDocuSignComplete<T>(File<T> file, string sourceTitle)
@ -58,7 +61,7 @@ namespace ASC.Files.Core.Services.NotifyService
using var scope = ServiceProvider.CreateScope(); using var scope = ServiceProvider.CreateScope();
var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>(); var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>();
var (notifySource, securityContext, filesLinkUtility, fileUtility, baseCommonLinkUtility, _, _, _, _) = scopeClass; var (notifySource, securityContext, filesLinkUtility, fileUtility, baseCommonLinkUtility, _, _, _, _) = scopeClass;
var client = WorkContext.NotifyContext.NotifyService.RegisterClient(notifySource, scope); var client = NotifyContext.NotifyService.RegisterClient(notifySource, scope);
var recipient = notifySource.GetRecipientsProvider().GetRecipient(securityContext.CurrentAccount.ID.ToString()); var recipient = notifySource.GetRecipientsProvider().GetRecipient(securityContext.CurrentAccount.ID.ToString());
client.SendNoticeAsync( client.SendNoticeAsync(
@ -77,7 +80,7 @@ namespace ASC.Files.Core.Services.NotifyService
using var scope = ServiceProvider.CreateScope(); using var scope = ServiceProvider.CreateScope();
var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>(); var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>();
var (notifySource, securityContext, _, _, _, _, _, _, _) = scopeClass; var (notifySource, securityContext, _, _, _, _, _, _, _) = scopeClass;
var client = WorkContext.NotifyContext.NotifyService.RegisterClient(notifySource, scope); var client = NotifyContext.NotifyService.RegisterClient(notifySource, scope);
var recipient = notifySource.GetRecipientsProvider().GetRecipient(securityContext.CurrentAccount.ID.ToString()); var recipient = notifySource.GetRecipientsProvider().GetRecipient(securityContext.CurrentAccount.ID.ToString());
@ -95,7 +98,7 @@ namespace ASC.Files.Core.Services.NotifyService
{ {
using var scope = ServiceProvider.CreateScope(); using var scope = ServiceProvider.CreateScope();
var notifySource = scope.ServiceProvider.GetService<NotifySource>(); var notifySource = scope.ServiceProvider.GetService<NotifySource>();
var client = WorkContext.NotifyContext.NotifyService.RegisterClient(notifySource, scope); var client = NotifyContext.NotifyService.RegisterClient(notifySource, scope);
var recipient = notifySource.GetRecipientsProvider().GetRecipient(userId.ToString()); var recipient = notifySource.GetRecipientsProvider().GetRecipient(userId.ToString());
@ -116,7 +119,7 @@ namespace ASC.Files.Core.Services.NotifyService
using var scope = ServiceProvider.CreateScope(); using var scope = ServiceProvider.CreateScope();
var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>(); var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>();
var (notifySource, _, filesLinkUtility, fileUtility, baseCommonLinkUtility, daoFactory, pathProvider, userManager, tenantManager) = scopeClass; var (notifySource, _, filesLinkUtility, fileUtility, baseCommonLinkUtility, daoFactory, pathProvider, userManager, tenantManager) = scopeClass;
var client = WorkContext.NotifyContext.NotifyService.RegisterClient(notifySource, scope); var client = NotifyContext.NotifyService.RegisterClient(notifySource, scope);
var studioNotifyHelper = scope.ServiceProvider.GetService<StudioNotifyHelper>(); var studioNotifyHelper = scope.ServiceProvider.GetService<StudioNotifyHelper>();
var folderDao = daoFactory.GetFolderDao<T>(); var folderDao = daoFactory.GetFolderDao<T>();
@ -166,7 +169,7 @@ namespace ASC.Files.Core.Services.NotifyService
using var scope = ServiceProvider.CreateScope(); using var scope = ServiceProvider.CreateScope();
var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>(); var scopeClass = scope.ServiceProvider.GetService<NotifyClientScope>();
var (notifySource, _, _, _, baseCommonLinkUtility, _, _, userManager, _) = scopeClass; var (notifySource, _, _, _, baseCommonLinkUtility, _, _, userManager, _) = scopeClass;
var client = WorkContext.NotifyContext.NotifyService.RegisterClient(notifySource, scope); var client = NotifyContext.NotifyService.RegisterClient(notifySource, scope);
var recipientsProvider = notifySource.GetRecipientsProvider(); var recipientsProvider = notifySource.GetRecipientsProvider();

View File

@ -114,9 +114,13 @@ namespace ASC.Web.Files.ThirdPartyApp
private DocumentServiceConnector DocumentServiceConnector { get; } private DocumentServiceConnector DocumentServiceConnector { get; }
private ThirdPartyAppHandlerService ThirdPartyAppHandlerService { get; } private ThirdPartyAppHandlerService ThirdPartyAppHandlerService { get; }
private IServiceProvider ServiceProvider { get; } private IServiceProvider ServiceProvider { get; }
public ILog Logger { get; } public ILog Logger { get; }
public IHttpClientFactory ClientFactory { get; }
private readonly IHttpClientFactory _clientFactory;
private readonly RequestHelper _requestHelper;
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
public BoxApp() public BoxApp()
{ {
} }
@ -149,7 +153,9 @@ namespace ASC.Web.Files.ThirdPartyApp
IConfiguration configuration, IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache, ICacheNotify<ConsumerCacheItem> cache,
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
IHttpClientFactory clientFactory, IHttpClientFactory clientFactory,
RequestHelper requestHelper,
OAuth20TokenHelper oAuth20TokenHelper,
string name, int order, Dictionary<string, string> additional) string name, int order, Dictionary<string, string> additional)
: base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional)
{ {
@ -174,7 +180,9 @@ namespace ASC.Web.Files.ThirdPartyApp
ThirdPartyAppHandlerService = thirdPartyAppHandlerService; ThirdPartyAppHandlerService = thirdPartyAppHandlerService;
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
Logger = option.CurrentValue; Logger = option.CurrentValue;
ClientFactory = clientFactory; _clientFactory = clientFactory;
_requestHelper = requestHelper;
_oAuth20TokenHelper = oAuth20TokenHelper;
} }
public async Task<bool> RequestAsync(HttpContext context) public async Task<bool> RequestAsync(HttpContext context)
@ -318,7 +326,7 @@ namespace ASC.Web.Files.ThirdPartyApp
} }
} }
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
var request = new HttpRequestMessage(); var request = new HttpRequestMessage();
request.RequestUri = new Uri(BoxUrlUpload.Replace("{fileId}", fileId)); request.RequestUri = new Uri(BoxUrlUpload.Replace("{fileId}", fileId));
@ -439,7 +447,7 @@ namespace ASC.Web.Files.ThirdPartyApp
var fileId = context.Request.Query["id"]; var fileId = context.Request.Query["id"];
context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true); context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
} }
private async Task StreamFileAsync(HttpContext context) private async Task StreamFileAsync(HttpContext context)
{ {
@ -479,7 +487,7 @@ namespace ASC.Web.Files.ThirdPartyApp
request.Method = HttpMethod.Get; request.Method = HttpMethod.Get;
request.Headers.Add("Authorization", "Bearer " + token); request.Headers.Add("Authorization", "Bearer " + token);
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
using var response = await httpClient.SendAsync(request); using var response = await httpClient.SendAsync(request);
using var stream = new ResponseStream(response); using var stream = new ResponseStream(response);
await stream.CopyToAsync(context.Response.Body); await stream.CopyToAsync(context.Response.Body);
@ -530,7 +538,7 @@ namespace ASC.Web.Files.ThirdPartyApp
var resultResponse = string.Empty; var resultResponse = string.Empty;
try try
{ {
resultResponse = RequestHelper.PerformRequest(BoxUrlUserInfo, resultResponse = _requestHelper.PerformRequest(BoxUrlUserInfo,
headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } }); headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } });
Logger.Debug("BoxApp: userinfo response - " + resultResponse); Logger.Debug("BoxApp: userinfo response - " + resultResponse);
} }
@ -607,7 +615,7 @@ namespace ASC.Web.Files.ThirdPartyApp
try try
{ {
var resultResponse = RequestHelper.PerformRequest(BoxUrlFile.Replace("{fileId}", boxFileId), var resultResponse = _requestHelper.PerformRequest(BoxUrlFile.Replace("{fileId}", boxFileId),
headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } }); headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } });
Logger.Debug("BoxApp: file response - " + resultResponse); Logger.Debug("BoxApp: file response - " + resultResponse);
return resultResponse; return resultResponse;
@ -624,7 +632,7 @@ namespace ASC.Web.Files.ThirdPartyApp
try try
{ {
Logger.Debug("BoxApp: GetAccessToken by code " + code); Logger.Debug("BoxApp: GetAccessToken by code " + code);
var token = OAuth20TokenHelper.GetAccessToken<BoxApp>(ConsumerFactory, code); var token = _oAuth20TokenHelper.GetAccessToken<BoxApp>(ConsumerFactory, code);
return new Token(token, AppAttr); return new Token(token, AppAttr);
} }
catch (Exception ex) catch (Exception ex)

View File

@ -120,9 +120,14 @@ namespace ASC.Web.Files.ThirdPartyApp
private TokenHelper TokenHelper { get; } private TokenHelper TokenHelper { get; }
private DocumentServiceConnector DocumentServiceConnector { get; } private DocumentServiceConnector DocumentServiceConnector { get; }
private ThirdPartyAppHandlerService ThirdPartyAppHandlerService { get; } private ThirdPartyAppHandlerService ThirdPartyAppHandlerService { get; }
private IServiceProvider ServiceProvider { get; } private IServiceProvider ServiceProvider { get; }
private IHttpClientFactory ClientFactory { get; }
private readonly RequestHelper _requestHelper;
private readonly IHttpClientFactory _clientFactory;
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
public GoogleDriveApp() public GoogleDriveApp()
{ {
} }
@ -159,7 +164,9 @@ namespace ASC.Web.Files.ThirdPartyApp
IConfiguration configuration, IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache, ICacheNotify<ConsumerCacheItem> cache,
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
IHttpClientFactory clientFactory, IHttpClientFactory clientFactory,
OAuth20TokenHelper oAuth20TokenHelper,
RequestHelper requestHelper,
string name, int order, Dictionary<string, string> additional) string name, int order, Dictionary<string, string> additional)
: base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional)
{ {
@ -188,7 +195,9 @@ namespace ASC.Web.Files.ThirdPartyApp
DocumentServiceConnector = documentServiceConnector; DocumentServiceConnector = documentServiceConnector;
ThirdPartyAppHandlerService = thirdPartyAppHandlerService; ThirdPartyAppHandlerService = thirdPartyAppHandlerService;
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
ClientFactory = clientFactory; _clientFactory = clientFactory;
_oAuth20TokenHelper = oAuth20TokenHelper;
_requestHelper = requestHelper;
} }
public async Task<bool> RequestAsync(HttpContext context) public async Task<bool> RequestAsync(HttpContext context)
@ -323,7 +332,7 @@ namespace ASC.Web.Files.ThirdPartyApp
} }
} }
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
var request = new HttpRequestMessage(); var request = new HttpRequestMessage();
request.RequestUri = new Uri(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId)); request.RequestUri = new Uri(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));
@ -528,7 +537,7 @@ namespace ASC.Web.Files.ThirdPartyApp
request.Method = HttpMethod.Get; request.Method = HttpMethod.Get;
request.Headers.Add("Authorization", "Bearer " + token); request.Headers.Add("Authorization", "Bearer " + token);
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
using var response = await httpClient.SendAsync(request); using var response = await httpClient.SendAsync(request);
using var stream = new ResponseStream(response); using var stream = new ResponseStream(response);
await stream.CopyToAsync(context.Response.Body); await stream.CopyToAsync(context.Response.Body);
@ -617,7 +626,7 @@ namespace ASC.Web.Files.ThirdPartyApp
try try
{ {
Logger.Debug("GoogleDriveApp: GetAccessToken by code " + code); Logger.Debug("GoogleDriveApp: GetAccessToken by code " + code);
var token = OAuth20TokenHelper.GetAccessToken<GoogleDriveApp>(ConsumerFactory, code); var token = _oAuth20TokenHelper.GetAccessToken<GoogleDriveApp>(ConsumerFactory, code);
return new Token(token, AppAttr); return new Token(token, AppAttr);
} }
catch (Exception ex) catch (Exception ex)
@ -654,7 +663,7 @@ namespace ASC.Web.Files.ThirdPartyApp
LoginProfile loginProfile = null; LoginProfile loginProfile = null;
try try
{ {
loginProfile = GoogleLoginProvider.Instance.GetLoginProfile(token.GetRefreshedToken(TokenHelper)); loginProfile = GoogleLoginProvider.Instance.GetLoginProfile(token.GetRefreshedToken(TokenHelper, _oAuth20TokenHelper));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -714,7 +723,7 @@ namespace ASC.Web.Files.ThirdPartyApp
try try
{ {
var requestUrl = GoogleLoginProvider.GoogleUrlFile + googleFileId + "?fields=" + HttpUtility.UrlEncode(GoogleLoginProvider.FilesFields); var requestUrl = GoogleLoginProvider.GoogleUrlFile + googleFileId + "?fields=" + HttpUtility.UrlEncode(GoogleLoginProvider.FilesFields);
var resultResponse = RequestHelper.PerformRequest(requestUrl, var resultResponse = _requestHelper.PerformRequest(requestUrl,
headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } }); headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } });
Logger.Debug("GoogleDriveApp: file response - " + resultResponse); Logger.Debug("GoogleDriveApp: file response - " + resultResponse);
return resultResponse; return resultResponse;
@ -738,17 +747,17 @@ namespace ASC.Web.Files.ThirdPartyApp
var request = new HttpRequestMessage(); var request = new HttpRequestMessage();
request.RequestUri = new Uri(contentUrl); request.RequestUri = new Uri(contentUrl);
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
using var response = await httpClient.SendAsync(request); using var response = await httpClient.SendAsync(request);
using var content = new ResponseStream(response); using var content = new ResponseStream(response);
return await CreateFileAsync(content, fileName, folderId, token); return await CreateFileAsync(content, fileName, folderId, token);
} }
private async Task<string> CreateFileAsync(Stream content, string fileName, string folderId, Token token) private async Task<string> CreateFileAsync(Stream content, string fileName, string folderId, Token token)
{ {
Logger.Debug("GoogleDriveApp: create file"); Logger.Debug("GoogleDriveApp: create file");
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
var request = new HttpRequestMessage(); var request = new HttpRequestMessage();
request.RequestUri = new Uri(GoogleLoginProvider.GoogleUrlFileUpload + "?uploadType=multipart"); request.RequestUri = new Uri(GoogleLoginProvider.GoogleUrlFileUpload + "?uploadType=multipart");
@ -853,7 +862,7 @@ namespace ASC.Web.Files.ThirdPartyApp
var downloadUrl = GoogleLoginProvider.GoogleUrlFile + $"{fileId}/export?mimeType={HttpUtility.UrlEncode(requiredMimeType)}"; var downloadUrl = GoogleLoginProvider.GoogleUrlFile + $"{fileId}/export?mimeType={HttpUtility.UrlEncode(requiredMimeType)}";
var httpClient = ClientFactory.CreateClient(); var httpClient = _clientFactory.CreateClient();
var request = new HttpRequestMessage(); var request = new HttpRequestMessage();
request.RequestUri = new Uri(downloadUrl); request.RequestUri = new Uri(downloadUrl);

View File

@ -53,7 +53,7 @@ namespace ASC.Web.Files.ThirdPartyApp
App = app; App = app;
} }
public string GetRefreshedToken(TokenHelper tokenHelper) public string GetRefreshedToken(TokenHelper tokenHelper, OAuth20TokenHelper oAuth20TokenHelper)
{ {
if (IsExpired) if (IsExpired)
{ {
@ -64,7 +64,7 @@ namespace ASC.Web.Files.ThirdPartyApp
var refreshUrl = app.GetRefreshUrl(); var refreshUrl = app.GetRefreshUrl();
var refreshed = OAuth20TokenHelper.RefreshToken(refreshUrl, this); var refreshed = oAuth20TokenHelper.RefreshToken(refreshUrl, this);
if (refreshed != null) if (refreshed != null)
{ {

View File

@ -76,6 +76,7 @@ namespace ASC.Api.Documents
public class FilesController : ControllerBase public class FilesController : ControllerBase
{ {
private readonly FileStorageService<string> FileStorageService; private readonly FileStorageService<string> FileStorageService;
private readonly RequestHelper _requestHelper;
private FilesControllerHelper<string> FilesControllerHelperString { get; } private FilesControllerHelper<string> FilesControllerHelperString { get; }
private FilesControllerHelper<int> FilesControllerHelperInt { get; } private FilesControllerHelper<int> FilesControllerHelperInt { get; }
@ -129,6 +130,7 @@ namespace ASC.Api.Documents
TenantManager tenantManager, TenantManager tenantManager,
FileUtility fileUtility, FileUtility fileUtility,
ConsumerFactory consumerFactory, ConsumerFactory consumerFactory,
RequestHelper requestHelper,
IServiceProvider serviceProvider) IServiceProvider serviceProvider)
{ {
FilesControllerHelperString = filesControllerHelperString; FilesControllerHelperString = filesControllerHelperString;
@ -154,6 +156,7 @@ namespace ASC.Api.Documents
ProductEntryPoint = productEntryPoint; ProductEntryPoint = productEntryPoint;
TenantManager = tenantManager; TenantManager = tenantManager;
FileUtility = fileUtility; FileUtility = fileUtility;
this._requestHelper = requestHelper;
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
} }
@ -2499,7 +2502,7 @@ namespace ASC.Api.Documents
var blogId = JObject.Parse(meInfo).Value<string>("token_site_id"); var blogId = JObject.Parse(meInfo).Value<string>("token_site_id");
var wordpressUserName = JObject.Parse(meInfo).Value<string>("username"); var wordpressUserName = JObject.Parse(meInfo).Value<string>("username");
var blogInfo = RequestHelper.PerformRequest(WordpressLoginProvider.WordpressSites + blogId, "", "GET", ""); var blogInfo = _requestHelper.PerformRequest(WordpressLoginProvider.WordpressSites + blogId, "", "GET", "");
var jsonBlogInfo = JObject.Parse(blogInfo); var jsonBlogInfo = JObject.Parse(blogInfo);
jsonBlogInfo.Add("username", wordpressUserName); jsonBlogInfo.Add("username", wordpressUserName);
@ -2566,7 +2569,7 @@ namespace ASC.Api.Documents
var wordpressUserName = JObject.Parse(meInfo).Value<string>("username"); var wordpressUserName = JObject.Parse(meInfo).Value<string>("username");
var blogInfo = RequestHelper.PerformRequest(WordpressLoginProvider.WordpressSites + blogId, "", "GET", ""); var blogInfo = _requestHelper.PerformRequest(WordpressLoginProvider.WordpressSites + blogId, "", "GET", "");
var jsonBlogInfo = JObject.Parse(blogInfo); var jsonBlogInfo = JObject.Parse(blogInfo);
jsonBlogInfo.Add("username", wordpressUserName); jsonBlogInfo.Add("username", wordpressUserName);