1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00

Added shortener helper to generate short urls.

This commit is contained in:
Uncled1023 2016-02-23 16:53:17 -08:00
parent 2c9bcf5fec
commit dada112d84
5 changed files with 58 additions and 1 deletions

View File

@ -31,10 +31,24 @@ namespace Teknik.Areas.Shortener.Controllers
}
[HttpPost]
[AllowAnonymous]
public ActionResult ShortenUrl(string url)
{
ShortenedUrl newUrl = Shortener.ShortenUrl(url, Config.ShortenerConfig.UrlLength);
return Json(new { result = true });
if (User.Identity.IsAuthenticated)
{
Profile.Models.User foundUser = db.Users.Where(u => u.Username == User.Identity.Name).FirstOrDefault();
if (foundUser != null)
{
newUrl.UserId = foundUser.UserId;
}
}
db.ShortenedUrls.Add(newUrl);
db.SaveChanges();
return Json(new { result = new { shortUrl = newUrl.ShortUrl, originalUrl = url } });
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teknik.Areas.Shortener.Models;
using Teknik.Models;
namespace Teknik.Areas.Shortener
{
public static class Shortener
{
public static ShortenedUrl ShortenUrl(string url, int length)
{
TeknikEntities db = new TeknikEntities();
// Generate the shortened url
string shortUrl = Utility.RandomString(length);
while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null)
{
shortUrl = Utility.RandomString(length);
}
ShortenedUrl newUrl = new ShortenedUrl();
newUrl.OriginalUrl = url;
newUrl.ShortUrl = shortUrl;
return newUrl;
}
}
}

View File

@ -25,6 +25,14 @@ namespace Teknik.Areas.Shortener
new { controller = "Shortener", action = "Index" }, // Parameter defaults
new[] { typeof(Controllers.ShortenerController).Namespace }
);
context.MapSubdomainRoute(
"Shortener.Action", // Route name
new List<string>() { "dev", "shorten", "s" }, // Subdomains
new List<string>() { config.Host }, // domains
"Action/{controller}/{action}", // URL with parameters
new { controller = "Shortener", action = "Index" }, // Parameter defaults
new[] { typeof(Controllers.ShortenerController).Namespace }
);
context.MapSubdomainRoute(
"Shortener.View", // Route name
new List<string>() { "dev", "*" }, // Subdomains

View File

@ -9,9 +9,12 @@ namespace Teknik.Configuration
{
public string ShortenerHost { get; set; }
public int UrlLength { get; set; }
public ShortenerConfig()
{
ShortenerHost = string.Empty;
UrlLength = 4;
}
}
}

View File

@ -210,6 +210,7 @@
<Compile Include="Areas\Shortener\Controllers\ShortenerController.cs" />
<Compile Include="Areas\Shortener\Models\ShortenedUrl.cs" />
<Compile Include="Areas\Shortener\ShortenerAreaRegistration.cs" />
<Compile Include="Areas\Shortener\Shortener.cs" />
<Compile Include="Areas\Shortener\ViewModels\ShortenViewModel.cs" />
<Compile Include="Areas\Stream\Controllers\StreamController.cs" />
<Compile Include="Areas\Stream\StreamAreaRegistration.cs" />