using Ionic.Zip; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using Tango.BL; using Tango.Core.Cryptography; using Tango.Portal.Enumerations; using Tango.Portal.Models; using Tango.Portal.Utils; using Tango.Portal.ViewModels; using System.Data.Entity; using Newtonsoft.Json; namespace Tango.Portal.Controllers { public class HomeController : Controller { public SessionUser SessionUser { get { if (Session["SessionUser"] == null) { Session["SessionUser"] = new SessionUser(); } return Session["SessionUser"] as SessionUser; } set { Session["SessionUser"] = value; } } protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (Request.IsAuthenticated) { SessionUser.IsAuthenticated = true; SessionUser.IsTwineUser = true; SessionUser.Name = User.Identity.Name; } } public ActionResult Index() { var vm = new IndexVM(SessionUser); vm.Stats = StatisticsUtils.Default.GetStats(); return View(vm); } public ActionResult Product(String key, PortalEnvironment environment = PortalEnvironment.Production) { ProductVM vm = new ProductVM(SessionUser); if (key != null) { StorageUtils storage = new StorageUtils(); Product product = storage.GetTableData("PortalProducts").SingleOrDefault(x => x.RowKey == key); vm.ProductKey = product.RowKey; vm.ProductName = product.Name; vm.ProductDescription = product.Description; vm.ProductImage = product.Image; vm.Environments = Enum.GetNames(typeof(PortalEnvironment)).ToList(); vm.SelectedEnvironment = environment.ToString(); var blobs = storage.GetContainerLatestBlobs(product.Container + environment.ToDescription(), product.BlobStartsWith, product.MaxResults); foreach (var blob in blobs) { vm.Downloads.Add(new DownloadItem() { Name = blob.Name, Date = blob.LastModified.Date.ToString("d MMMM yyyy"), URL = PortalConfig.CDN_ENDPOINT + blob.URL }); } } return View(vm); } public ActionResult Firmware(PortalEnvironment environment = PortalEnvironment.Production, String model = "TS-1800") { FirmwareVM vm = new FirmwareVM(SessionUser); vm.Environments = Enum.GetNames(typeof(PortalEnvironment)).ToList(); vm.SelectedEnvironment = environment.ToString(); vm.Models = new List() { "TS-1800", "X4", "X1" }; vm.SelectedModel = model; using (ObservablesContext db = DbUtils.CreateContext(environment)) { string lastTwo = model.Substring(model.Length - 2); var machine_version = db.MachineVersions.Select(x => new { x.Guid, x.Name }).SingleOrDefault(x => x.Name.EndsWith(lastTwo)); if (machine_version != null) { var versions = db.TangoVersions .Where(x => x.MachineVersionGuid == machine_version.Guid) .GroupBy(x => x.FirmwareVersion) .Select(g => g .OrderByDescending(x => x.LastUpdated) .FirstOrDefault()) .OrderByDescending(x => x.FirmwareVersion) .Take(5) .Select(x => new { x.FirmwareVersion, x.LastUpdated, x.BlobName }) .ToList(); foreach (var version in versions) { vm.Downloads.Add(new DownloadItem() { Date = version.LastUpdated.ToString("d MMMM yyyy"), Name = $"{model} v{version.FirmwareVersion}.tfp", URL = $"/DownloadFirmware?environment={environment}&blob={version.BlobName}&model={model}&version={version.FirmwareVersion}" }); } } } return View(vm); } public ActionResult DownloadFirmware(PortalEnvironment environment, String blob, String model, String version) { String innerFileName = "firmware_package.tfp"; String finalTfpName = $"{model} v{version}.tfp"; String container = "tango-versions" + environment.ToDescription(); String cacheContainer = "portal-firmware-cache"; var storageUtils = new StorageUtils(); if (!storageUtils.CheckBlobExists(cacheContainer, finalTfpName)) { using (var blobStream = storageUtils.GetBlobStream(container, blob)) { using (var zip = ZipFile.Read(blobStream)) { var entry = zip[innerFileName]; using (var outputStream = new MemoryStream()) { entry.Extract(outputStream); outputStream.Seek(0, SeekOrigin.Begin); string contentType = MimeMapping.GetMimeMapping(innerFileName); var data = outputStream.ToArray(); storageUtils.CreateBlobFromBytes(data, cacheContainer, finalTfpName); return File(data, contentType, finalTfpName); } } } } else { var blobCache = storageUtils.GetBlob(cacheContainer, finalTfpName); return Redirect(PortalConfig.CDN_ENDPOINT + storageUtils.GetBlob(cacheContainer, finalTfpName).URL); } } public ActionResult AI() { if (!SessionUser.IsTwineUser) return RedirectToAction(nameof(Login)); SessionUser.Expires = DateTime.UtcNow.AddHours(1); String json = SimpleCryptoHelper.Encrypt(JsonConvert.SerializeObject(SessionUser)); return new RedirectResult($"https://ai.twine-srv.com?session={json}"); } public ActionResult Docs() { DocsVM vm = new DocsVM(SessionUser); StorageUtils storage = new StorageUtils(); foreach (var blob in storage.GetAllBlobs("portal-documents").OrderBy(x => x.Name)) { String cdnUrl = PortalConfig.CDN_ENDPOINT + blob.URL; vm.Downloads.Add(new DownloadItem() { Name = blob.Name, Date = blob.LastModified.ToString("d MMMM yyyy"), URL = blob.Name.EndsWith(".pptx") ? "https://view.officeapps.live.com/op/view.aspx?src=" + cdnUrl : cdnUrl }); } return View(vm); } public ActionResult Utilities() { UtilitiesVM vm = new UtilitiesVM(SessionUser); StorageUtils storage = new StorageUtils(); foreach (var blob in storage.GetAllBlobs("portal-utilities").OrderBy(x => x.Name)) { String cdnUrl = PortalConfig.CDN_ENDPOINT + blob.URL; vm.Downloads.Add(new DownloadItem() { Name = blob.Name, Date = blob.LastModified.ToString("d MMMM yyyy"), URL = cdnUrl }); } return View(vm); } public ActionResult Login() { return View(new ViewModel(SessionUser)); } public ActionResult SignIn(String email, String password) { Tango.BL.Entities.User user = null; var hash = new BasicHashGenerator(); var pass = hash.Encrypt(password); foreach (var env in Enum.GetValues(typeof(PortalEnvironment)).Cast().ToList()) { using (ObservablesContext db = DbUtils.CreateContext(env)) { user = db.Users.Include(x => x.Organization).Include(x => x.Contact).FirstOrDefault(x => x.Email.ToLower() == email.ToLower() && x.Password == pass); if (user != null) break; } } if (user != null) { SessionUser.IsAuthenticated = true; SessionUser.IsTwineUser = user.Organization.Name == "Twine"; SessionUser.Name = user.Contact.FirstName; SessionUser.FullName = user.Contact.FullName; SessionUser.Email = user.Email; SessionUser.Organization = user.Organization.Name; return RedirectToAction(nameof(Index)); } else { return RedirectToAction(nameof(Login)); } } public void SignInMicrosoft() { string callbackUrl = Url.Action("Index", "Home", routeValues: null, protocol: Request.Url.Scheme); // Send an OpenID Connect sign-in request. if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = callbackUrl }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } public void SignOut() { SessionUser = null; string callbackUrl = Url.Action("Index", "Home", routeValues: null, protocol: Request.Url.Scheme); HttpContext.GetOwinContext().Authentication.SignOut( new AuthenticationProperties { RedirectUri = callbackUrl }, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } } }