DocSpace-client/web/ASC.Web.Core/Utility/UrlShortener.cs

95 lines
2.9 KiB
C#
Raw Normal View History

2019-06-07 08:59:07 +00:00
using System;
using System.Net;
using System.Security.Cryptography;
using System.Text;
2019-08-15 12:04:42 +00:00
using System.Web;
2019-06-07 08:59:07 +00:00
using ASC.Common.Utils;
using ASC.FederatedLogin.LoginProviders;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Core.Utility
{
public interface IUrlShortener
{
string GetShortenLink(string shareLink);
}
public static class UrlShortener
{
public static bool Enabled { get { return !(Instance is NullShortener); } }
private static IUrlShortener _instance;
public static IUrlShortener Instance
{
get
{
if (_instance == null)
{
if (BitlyLoginProvider.Enabled)
{
_instance = new BitLyShortener();
}
else if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["web.url-shortener"]))
{
_instance = new OnlyoShortener();
}
else
{
_instance = new NullShortener();
}
}
return _instance;
}
}
}
public class BitLyShortener : IUrlShortener
{
public string GetShortenLink(string shareLink)
{
return BitlyLoginProvider.GetShortenLink(shareLink);
}
}
public class OnlyoShortener : IUrlShortener
{
private readonly string url;
private readonly string internalUrl;
private readonly string sKey;
public OnlyoShortener()
{
url = ConfigurationManager.AppSettings["web.url-shortener"];
internalUrl = ConfigurationManager.AppSettings["web.url-shortener.internal"];
sKey = ConfigurationManager.AppSettings["core.machinekey"];
if (!url.EndsWith("/"))
url += '/';
}
public string GetShortenLink(string shareLink)
{
2019-08-15 15:08:40 +00:00
using var client = new WebClient { Encoding = Encoding.UTF8 };
client.Headers.Add("Authorization", CreateAuthToken());
return CommonLinkUtility.GetFullAbsolutePath(url + client.DownloadString(new Uri(internalUrl + "?url=" + HttpUtility.UrlEncode(shareLink))));
2019-06-07 08:59:07 +00:00
}
private string CreateAuthToken(string pkey = "urlShortener")
{
2019-08-15 15:08:40 +00:00
using var hasher = new HMACSHA1(Encoding.UTF8.GetBytes(sKey));
var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
var hash = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", now, pkey))));
return string.Format("ASC {0}:{1}:{2}", pkey, now, hash);
2019-06-07 08:59:07 +00:00
}
}
public class NullShortener : IUrlShortener
{
public string GetShortenLink(string shareLink)
{
return null;
}
}
}