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

- Moved TeknikEntities from global field to disposed local instances.

- Added additional logging/handling of errors.
- Added processed/total bytes for uploads, downloads, and encryption/decryption.
- Fixed paste CSS bundle using a script handler.
- Fixed bad js when viewing a vault
This commit is contained in:
Uncled1023 2017-04-08 21:01:31 -07:00
parent 1058b040a4
commit e163e0ca8c
27 changed files with 1590 additions and 1419 deletions

View File

@ -47,56 +47,57 @@ namespace ServerMaint
if (Directory.Exists(configPath)) if (Directory.Exists(configPath))
{ {
Config config = Config.Load(configPath); Config config = Config.Load(configPath);
TeknikEntities db = new TeknikEntities();
Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now)); Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now));
using (TeknikEntities db = new TeknikEntities())
// Scan all the uploads for viruses, and remove the bad ones
if (options.ScanUploads && config.UploadConfig.VirusScanEnable)
{ {
ScanUploads(config, db); // Scan all the uploads for viruses, and remove the bad ones
} if (options.ScanUploads && config.UploadConfig.VirusScanEnable)
{
ScanUploads(config, db);
}
// Warns all the invalid accounts via email // Warns all the invalid accounts via email
if (options.WarnAccounts) if (options.WarnAccounts)
{ {
WarnInvalidAccounts(config, db); WarnInvalidAccounts(config, db);
} }
// Cleans all inactive users // Cleans all inactive users
if (options.CleanUsers) if (options.CleanUsers)
{ {
CleanAccounts(config, db, options.DaysBeforeDeletion); CleanAccounts(config, db, options.DaysBeforeDeletion);
} }
// Cleans the email for unused accounts // Cleans the email for unused accounts
if (options.CleanEmails) if (options.CleanEmails)
{ {
CleanEmail(config, db); CleanEmail(config, db);
} }
// Cleans all the git accounts that are unused // Cleans all the git accounts that are unused
if (options.CleanGit) if (options.CleanGit)
{ {
CleanGit(config, db); CleanGit(config, db);
} }
// Generates a file for all of the user's last seen dates // Generates a file for all of the user's last seen dates
if (options.GenerateLastSeen) if (options.GenerateLastSeen)
{ {
GenerateLastSeen(config, db, options.LastSeenFile); GenerateLastSeen(config, db, options.LastSeenFile);
} }
// Generates a file for all of the invalid accounts // Generates a file for all of the invalid accounts
if (options.GenerateInvalid) if (options.GenerateInvalid)
{ {
GenerateInvalidAccounts(config, db, options.InvalidFile); GenerateInvalidAccounts(config, db, options.InvalidFile);
} }
// Generates a file for all of the accounts to be cleaned // Generates a file for all of the accounts to be cleaned
if (options.GenerateCleaning) if (options.GenerateCleaning)
{ {
GenerateCleaningList(config, db, options.CleaningFile, options.DaysBeforeDeletion); GenerateCleaningList(config, db, options.CleaningFile, options.DaysBeforeDeletion);
}
} }
Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now)); Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now));

View File

@ -16,8 +16,6 @@ namespace Teknik.Areas.API.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class APIController : DefaultController public class APIController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
{ {

View File

@ -24,8 +24,6 @@ namespace Teknik.Areas.API.Controllers
[TeknikAuthorize(AuthType.Basic)] [TeknikAuthorize(AuthType.Basic)]
public class APIv1Controller : DefaultController public class APIv1Controller : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
{ {
@ -81,49 +79,52 @@ namespace Teknik.Areas.API.Controllers
if (model.blockSize <= 0) if (model.blockSize <= 0)
model.blockSize = Config.UploadConfig.BlockSize; model.blockSize = Config.UploadConfig.BlockSize;
// Save the file data using (TeknikEntities db = new TeknikEntities())
Upload.Models.Upload upload = Uploader.SaveFile(db, Config, model.file.InputStream, model.contentType, contentLength, model.encrypt, fileExt, model.iv, model.key, model.keySize, model.blockSize);
if (upload != null)
{ {
// Associate this with the user if they provided an auth key // Save the file data
if (User.Identity.IsAuthenticated) Upload.Models.Upload upload = Uploader.SaveFile(db, Config, model.file.InputStream, model.contentType, contentLength, model.encrypt, fileExt, model.iv, model.key, model.keySize, model.blockSize);
if (upload != null)
{ {
User foundUser = UserHelper.GetUser(db, User.Identity.Name); // Associate this with the user if they provided an auth key
if (foundUser != null) if (User.Identity.IsAuthenticated)
{ {
upload.UserId = foundUser.UserId; User foundUser = UserHelper.GetUser(db, User.Identity.Name);
if (foundUser != null)
{
upload.UserId = foundUser.UserId;
db.Entry(upload).State = EntityState.Modified;
db.SaveChanges();
}
}
// Generate delete key only if asked to
if (!model.genDeletionKey)
{
upload.DeleteKey = string.Empty;
db.Entry(upload).State = EntityState.Modified; db.Entry(upload).State = EntityState.Modified;
db.SaveChanges(); db.SaveChanges();
} }
// Pull all the information together
string fullUrl = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url });
var returnData = new
{
url = (model.saveKey || string.IsNullOrEmpty(model.key)) ? fullUrl : fullUrl + "#" + model.key,
fileName = upload.Url,
contentType = model.contentType,
contentLength = contentLength,
key = model.key,
keySize = model.keySize,
iv = model.iv,
blockSize = model.blockSize,
deletionKey = upload.DeleteKey
};
return Json(new { result = returnData });
} }
return Json(new { error = new { message = "Unable to save file" } });
// Generate delete key only if asked to
if (!model.genDeletionKey)
{
upload.DeleteKey = string.Empty;
db.Entry(upload).State = EntityState.Modified;
db.SaveChanges();
}
// Pull all the information together
string fullUrl = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url });
var returnData = new
{
url = (model.saveKey || string.IsNullOrEmpty(model.key)) ? fullUrl : fullUrl + "#" + model.key,
fileName = upload.Url,
contentType = model.contentType,
contentLength = contentLength,
key = model.key,
keySize = model.keySize,
iv = model.iv,
blockSize = model.blockSize,
deletionKey = upload.DeleteKey
};
return Json(new { result = returnData });
} }
return Json(new { error = new { message = "Unable to save file" } });
} }
else else
{ {
@ -149,33 +150,36 @@ namespace Teknik.Areas.API.Controllers
{ {
if (model != null && model.code != null) if (model != null && model.code != null)
{ {
Paste.Models.Paste paste = PasteHelper.CreatePaste(model.code, model.title, model.syntax, model.expireUnit, model.expireLength, model.password, model.hide); using (TeknikEntities db = new TeknikEntities())
// Associate this with the user if they are logged in
if (User.Identity.IsAuthenticated)
{ {
User foundUser = UserHelper.GetUser(db, User.Identity.Name); Paste.Models.Paste paste = PasteHelper.CreatePaste(db, model.code, model.title, model.syntax, model.expireUnit, model.expireLength, model.password, model.hide);
if (foundUser != null)
// Associate this with the user if they are logged in
if (User.Identity.IsAuthenticated)
{ {
paste.UserId = foundUser.UserId; User foundUser = UserHelper.GetUser(db, User.Identity.Name);
if (foundUser != null)
{
paste.UserId = foundUser.UserId;
}
} }
db.Pastes.Add(paste);
db.SaveChanges();
return Json(new
{
result = new
{
id = paste.Url,
url = Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url, password = model.password }),
title = paste.Title,
syntax = paste.Syntax,
expiration = paste.ExpireDate,
password = model.password
}
});
} }
db.Pastes.Add(paste);
db.SaveChanges();
return Json(new
{
result = new
{
id = paste.Url,
url = Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url, password = model.password }),
title = paste.Title,
syntax = paste.Syntax,
expiration = paste.ExpireDate,
password = model.password
}
});
} }
return Json(new { error = new { message = "Invalid Paste Request" } }); return Json(new { error = new { message = "Invalid Paste Request" } });
} }
@ -194,35 +198,38 @@ namespace Teknik.Areas.API.Controllers
{ {
if (model.url.IsValidUrl()) if (model.url.IsValidUrl())
{ {
ShortenedUrl newUrl = Shortener.Shortener.ShortenUrl(model.url, Config.ShortenerConfig.UrlLength); using (TeknikEntities db = new TeknikEntities())
// Associate this with the user if they are logged in
if (User.Identity.IsAuthenticated)
{ {
User foundUser = UserHelper.GetUser(db, User.Identity.Name); ShortenedUrl newUrl = Shortener.Shortener.ShortenUrl(db, model.url, Config.ShortenerConfig.UrlLength);
if (foundUser != null)
// Associate this with the user if they are logged in
if (User.Identity.IsAuthenticated)
{ {
newUrl.UserId = foundUser.UserId; User foundUser = UserHelper.GetUser(db, User.Identity.Name);
if (foundUser != null)
{
newUrl.UserId = foundUser.UserId;
}
} }
}
db.ShortenedUrls.Add(newUrl); db.ShortenedUrls.Add(newUrl);
db.SaveChanges(); db.SaveChanges();
string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl); string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
if (Config.DevEnvironment) if (Config.DevEnvironment)
{
shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
}
return Json(new
{
result = new
{ {
shortUrl = shortUrl, shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
originalUrl = model.url
} }
});
return Json(new
{
result = new
{
shortUrl = shortUrl,
originalUrl = model.url
}
});
}
} }
return Json(new { error = new { message = "Must be a valid Url" } }); return Json(new { error = new { message = "Must be a valid Url" } });
} }

View File

@ -17,8 +17,6 @@ namespace Teknik.Areas.Contact.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class ContactController : DefaultController public class ContactController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
// GET: Contact/Contact // GET: Contact/Contact
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
@ -40,15 +38,18 @@ namespace Teknik.Areas.Contact.Controllers
{ {
try try
{ {
// Insert the message into the DB using (TeknikEntities db = new TeknikEntities())
Models.Contact newContact = db.Contact.Create(); {
newContact.Name = model.Name; // Insert the message into the DB
newContact.Email = model.Email; Models.Contact newContact = db.Contact.Create();
newContact.Subject = model.Subject; newContact.Name = model.Name;
newContact.Message = model.Message; newContact.Email = model.Email;
newContact.DateAdded = DateTime.Now; newContact.Subject = model.Subject;
db.Contact.Add(newContact); newContact.Message = model.Message;
db.SaveChanges(); newContact.DateAdded = DateTime.Now;
db.Contact.Add(newContact);
db.SaveChanges();
}
// Let's also email the message to support // Let's also email the message to support
SmtpClient client = new SmtpClient(); SmtpClient client = new SmtpClient();

View File

@ -10,8 +10,6 @@ namespace Teknik.Areas.Contact.ViewModels
{ {
public class ContactViewModel : ViewModelBase public class ContactViewModel : ViewModelBase
{ {
private TeknikEntities db = new TeknikEntities();
[Required] [Required]
[Display(Name = "Name")] [Display(Name = "Name")]
public string Name { get; set; } public string Name { get; set; }
@ -27,27 +25,5 @@ namespace Teknik.Areas.Contact.ViewModels
[Required] [Required]
[Display(Name = "Message")] [Display(Name = "Message")]
public string Message { get; set; } public string Message { get; set; }
public bool Insert()
{
bool success = true;
try
{
Models.Contact newContact = db.Contact.Create();
newContact.Name = Name;
newContact.Email = Email;
newContact.Subject = Subject;
newContact.Message = Message;
newContact.DateAdded = DateTime.Now;
db.Contact.Add(newContact);
db.SaveChanges();
}
catch (Exception ex)
{
success = false;
}
return success;
}
} }
} }

View File

@ -21,8 +21,6 @@ namespace Teknik.Areas.Paste.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class PasteController : DefaultController public class PasteController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
@ -37,6 +35,7 @@ namespace Teknik.Areas.Paste.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult ViewPaste(string type, string url, string password) public ActionResult ViewPaste(string type, string url, string password)
{ {
TeknikEntities db = new TeknikEntities();
Models.Paste paste = db.Pastes.Where(p => p.Url == url).FirstOrDefault(); Models.Paste paste = db.Pastes.Where(p => p.Url == url).FirstOrDefault();
if (paste != null) if (paste != null)
{ {
@ -156,26 +155,29 @@ namespace Teknik.Areas.Paste.Controllers
{ {
try try
{ {
Models.Paste paste = PasteHelper.CreatePaste(model.Content, model.Title, model.Syntax, model.ExpireUnit, model.ExpireLength ?? 1, model.Password, model.Hide); using (TeknikEntities db = new TeknikEntities())
if (model.ExpireUnit == "view")
{ {
paste.Views = -1; Models.Paste paste = PasteHelper.CreatePaste(db, model.Content, model.Title, model.Syntax, model.ExpireUnit, model.ExpireLength ?? 1, model.Password, model.Hide);
}
if (User.Identity.IsAuthenticated) if (model.ExpireUnit == "view")
{
Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
{ {
paste.UserId = user.UserId; paste.Views = -1;
} }
if (User.Identity.IsAuthenticated)
{
Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
{
paste.UserId = user.UserId;
}
}
db.Pastes.Add(paste);
db.SaveChanges();
return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
} }
db.Pastes.Add(paste);
db.SaveChanges();
return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -86,7 +86,7 @@ namespace Teknik.Areas.Paste
BundleTable.Bundles.Add(new CdnScriptBundle("~/bundles/highlight", config.CdnHost).Include( BundleTable.Bundles.Add(new CdnScriptBundle("~/bundles/highlight", config.CdnHost).Include(
"~/Scripts/Highlight/highlight.pack.js")); "~/Scripts/Highlight/highlight.pack.js"));
// Register Style Bundles // Register Style Bundles
BundleTable.Bundles.Add(new CdnScriptBundle("~/Content/paste", config.CdnHost).Include( BundleTable.Bundles.Add(new CdnStyleBundle("~/Content/paste", config.CdnHost).Include(
"~/Content/Highlight/github-gist.css", "~/Content/Highlight/github-gist.css",
"~/Areas/Paste/Content/Paste.css")); "~/Areas/Paste/Content/Paste.css"));
} }

View File

@ -11,9 +11,8 @@ namespace Teknik.Areas.Paste
{ {
public static class PasteHelper public static class PasteHelper
{ {
public static Models.Paste CreatePaste(string content, string title = "", string syntax = "text", string expireUnit = "never", int expireLength = 1, string password = "", bool hide = false) public static Models.Paste CreatePaste(TeknikEntities db, string content, string title = "", string syntax = "text", string expireUnit = "never", int expireLength = 1, string password = "", bool hide = false)
{ {
TeknikEntities db = new TeknikEntities();
Config config = Config.Load(); Config config = Config.Load();
Models.Paste paste = db.Pastes.Create(); Models.Paste paste = db.Pastes.Create();
paste.DatePosted = DateTime.Now; paste.DatePosted = DateTime.Now;

View File

@ -19,8 +19,6 @@ namespace Teknik.Areas.Podcast.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class PodcastController : DefaultController public class PodcastController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
@ -33,15 +31,18 @@ namespace Teknik.Areas.Podcast.Controllers
ViewBag.Title = Config.PodcastConfig.Title + " - " + Config.Title; ViewBag.Title = Config.PodcastConfig.Title + " - " + Config.Title;
ViewBag.Description = Config.PodcastConfig.Description; ViewBag.Description = Config.PodcastConfig.Description;
bool editor = User.IsInRole("Podcast"); bool editor = User.IsInRole("Podcast");
var foundPodcasts = db.Podcasts.Where(p => (p.Published || editor)).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (foundPodcasts != null)
{ {
model.HasPodcasts = (foundPodcasts != null); var foundPodcasts = db.Podcasts.Where(p => (p.Published || editor)).FirstOrDefault();
} if (foundPodcasts != null)
else {
{ model.HasPodcasts = (foundPodcasts != null);
model.Error = true; }
model.ErrorMessage = "No Podcasts Available"; else
{
model.Error = true;
model.ErrorMessage = "No Podcasts Available";
}
} }
return View("~/Areas/Podcast/Views/Podcast/Main.cshtml", model); return View("~/Areas/Podcast/Views/Podcast/Main.cshtml", model);
@ -63,13 +64,16 @@ namespace Teknik.Areas.Podcast.Controllers
PodcastViewModel model = new PodcastViewModel(); PodcastViewModel model = new PodcastViewModel();
// find the podcast specified // find the podcast specified
bool editor = User.IsInRole("Podcast"); bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.Episode == episode)).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (foundPodcast != null)
{ {
model = new PodcastViewModel(foundPodcast); var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.Episode == episode)).FirstOrDefault();
if (foundPodcast != null)
{
model = new PodcastViewModel(foundPodcast);
ViewBag.Title = model.Title + " - Teknikast - " + Config.Title; ViewBag.Title = model.Title + " - Teknikast - " + Config.Title;
return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model); return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model);
}
} }
model.Error = true; model.Error = true;
model.ErrorMessage = "No Podcasts Available"; model.ErrorMessage = "No Podcasts Available";
@ -79,112 +83,130 @@ namespace Teknik.Areas.Podcast.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult Download(int episode, string fileName) public ActionResult Download(int episode, string fileName)
{ {
// find the podcast specified using (TeknikEntities db = new TeknikEntities())
var foundPodcast = db.Podcasts.Where(p => (p.Published && p.Episode == episode)).FirstOrDefault();
if (foundPodcast != null)
{ {
PodcastFile file = foundPodcast.Files.Where(f => f.FileName == fileName).FirstOrDefault(); // find the podcast specified
if (file != null) var foundPodcast = db.Podcasts.Where(p => (p.Published && p.Episode == episode)).FirstOrDefault();
if (foundPodcast != null)
{ {
if (System.IO.File.Exists(file.Path)) PodcastFile file = foundPodcast.Files.Where(f => f.FileName == fileName).FirstOrDefault();
if (file != null)
{ {
FileStream fileStream = new FileStream(file.Path, FileMode.Open, FileAccess.Read); if (System.IO.File.Exists(file.Path))
Response.AddHeader("Content-Length", file.ContentLength.ToString());
var cd = new System.Net.Mime.ContentDisposition
{ {
FileName = file.FileName, FileStream fileStream = new FileStream(file.Path, FileMode.Open, FileAccess.Read);
Inline = true
};
Response.AppendHeader("Content-Disposition", cd.ToString()); Response.AddHeader("Content-Length", file.ContentLength.ToString());
return new FileGenerateResult(file.FileName, file.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, fileStream, file.ContentLength, 4 * 1024), false); var cd = new System.Net.Mime.ContentDisposition
//return File(data, file.ContentType); {
FileName = file.FileName,
Inline = true
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return new FileGenerateResult(file.FileName, file.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, fileStream, file.ContentLength, 4 * 1024), false);
//return File(data, file.ContentType);
}
} }
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
public ActionResult GetPodcasts(int startPodcastID, int count) public ActionResult GetPodcasts(int startPodcastID, int count)
{ {
bool editor = User.IsInRole("Podcast"); using (TeknikEntities db = new TeknikEntities())
var podcasts = db.Podcasts.Where(p => p.Published || editor).OrderByDescending(p => p.DatePosted).Skip(startPodcastID).Take(count).ToList();
List<PodcastViewModel> podcastViews = new List<PodcastViewModel>();
if (podcasts != null)
{ {
foreach (Models.Podcast podcast in podcasts) bool editor = User.IsInRole("Podcast");
var podcasts = db.Podcasts.Where(p => p.Published || editor).OrderByDescending(p => p.DatePosted).Skip(startPodcastID).Take(count).ToList();
List<PodcastViewModel> podcastViews = new List<PodcastViewModel>();
if (podcasts != null)
{ {
podcastViews.Add(new PodcastViewModel(podcast)); foreach (Models.Podcast podcast in podcasts)
{
podcastViews.Add(new PodcastViewModel(podcast));
}
} }
return PartialView("~/Areas/Podcast/Views/Podcast/Podcasts.cshtml", podcastViews);
} }
return PartialView("~/Areas/Podcast/Views/Podcast/Podcasts.cshtml", podcastViews);
} }
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
public ActionResult GetPodcastEpisode(int podcastId) public ActionResult GetPodcastEpisode(int podcastId)
{ {
bool editor = User.IsInRole("Podcast"); using (TeknikEntities db = new TeknikEntities())
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{ {
return Json(new { result = foundPodcast.Episode }); bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{
return Json(new { result = foundPodcast.Episode });
}
return Json(new { error = "No podcast found" });
} }
return Json(new { error = "No podcast found" });
} }
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
public ActionResult GetPodcastTitle(int podcastId) public ActionResult GetPodcastTitle(int podcastId)
{ {
bool editor = User.IsInRole("Podcast"); using (TeknikEntities db = new TeknikEntities())
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{ {
return Json(new { result = foundPodcast.Title }); bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{
return Json(new { result = foundPodcast.Title });
}
return Json(new { error = "No podcast found" });
} }
return Json(new { error = "No podcast found" });
} }
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
public ActionResult GetPodcastDescription(int podcastId) public ActionResult GetPodcastDescription(int podcastId)
{ {
bool editor = User.IsInRole("Podcast"); using (TeknikEntities db = new TeknikEntities())
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{ {
return Json(new { result = foundPodcast.Description }); bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{
return Json(new { result = foundPodcast.Description });
}
return Json(new { error = "No podcast found" });
} }
return Json(new { error = "No podcast found" });
} }
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
public ActionResult GetPodcastFiles(int podcastId) public ActionResult GetPodcastFiles(int podcastId)
{ {
bool editor = User.IsInRole("Podcast"); using (TeknikEntities db = new TeknikEntities())
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{ {
List<object> files = new List<object>(); bool editor = User.IsInRole("Podcast");
foreach (PodcastFile file in foundPodcast.Files) var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
if (foundPodcast != null)
{ {
object fileObj = new List<object> files = new List<object>();
foreach (PodcastFile file in foundPodcast.Files)
{ {
name = file.FileName, object fileObj = new
id = file.PodcastFileId {
}; name = file.FileName,
files.Add(fileObj); id = file.PodcastFileId
};
files.Add(fileObj);
}
return Json(new { result = new { files = files } });
} }
return Json(new { result = new { files = files } }); return Json(new { error = "No podcast found" });
} }
return Json(new { error = "No podcast found" });
} }
[HttpPost] [HttpPost]
@ -194,25 +216,28 @@ namespace Teknik.Areas.Podcast.Controllers
{ {
if (User.IsInRole("Podcast")) if (User.IsInRole("Podcast"))
{ {
// Grab the next episode number using (TeknikEntities db = new TeknikEntities())
Models.Podcast lastPod = db.Podcasts.Where(p => p.Episode == episode).FirstOrDefault();
if (lastPod == null)
{ {
// Create the podcast object // Grab the next episode number
Models.Podcast podcast = db.Podcasts.Create(); Models.Podcast lastPod = db.Podcasts.Where(p => p.Episode == episode).FirstOrDefault();
podcast.Episode = episode; if (lastPod == null)
podcast.Title = title; {
podcast.Description = description; // Create the podcast object
podcast.DatePosted = DateTime.Now; Models.Podcast podcast = db.Podcasts.Create();
podcast.DatePublished = DateTime.Now; podcast.Episode = episode;
podcast.DateEdited = DateTime.Now; podcast.Title = title;
podcast.Files = SaveFiles(Request.Files, episode); podcast.Description = description;
podcast.DatePosted = DateTime.Now;
podcast.DatePublished = DateTime.Now;
podcast.DateEdited = DateTime.Now;
podcast.Files = SaveFiles(Request.Files, episode);
db.Podcasts.Add(podcast); db.Podcasts.Add(podcast);
db.SaveChanges(); db.SaveChanges();
return Json(new { result = true }); return Json(new { result = true });
}
return Json(new { error = "That episode already exists" });
} }
return Json(new { error = "That episode already exists" });
} }
return Json(new { error = "You don't have permission to create a podcast" }); return Json(new { error = "You don't have permission to create a podcast" });
} }
@ -226,49 +251,52 @@ namespace Teknik.Areas.Podcast.Controllers
{ {
if (User.IsInRole("Podcast")) if (User.IsInRole("Podcast"))
{ {
Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (podcast != null)
{ {
if (db.Podcasts.Where(p => p.Episode != episode).FirstOrDefault() == null || podcast.Episode == episode) Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
if (podcast != null)
{ {
podcast.Episode = episode; if (db.Podcasts.Where(p => p.Episode != episode).FirstOrDefault() == null || podcast.Episode == episode)
podcast.Title = title;
podcast.Description = description;
podcast.DateEdited = DateTime.Now;
// Remove any files not in fileIds
List<string> fileIdList = new List<string>();
if (!string.IsNullOrEmpty(fileIds))
{ {
fileIdList = fileIds.Split(',').ToList(); podcast.Episode = episode;
} podcast.Title = title;
for (int i = 0; i < podcast.Files.Count; i++) podcast.Description = description;
{ podcast.DateEdited = DateTime.Now;
PodcastFile curFile = podcast.Files.ElementAt(i); // Remove any files not in fileIds
if (!fileIdList.Exists(id => id == curFile.PodcastFileId.ToString())) List<string> fileIdList = new List<string>();
if (!string.IsNullOrEmpty(fileIds))
{ {
if (System.IO.File.Exists(curFile.Path)) fileIdList = fileIds.Split(',').ToList();
{ }
System.IO.File.Delete(curFile.Path); for (int i = 0; i < podcast.Files.Count; i++)
} {
db.PodcastFiles.Remove(curFile); PodcastFile curFile = podcast.Files.ElementAt(i);
podcast.Files.Remove(curFile); if (!fileIdList.Exists(id => id == curFile.PodcastFileId.ToString()))
{
if (System.IO.File.Exists(curFile.Path))
{
System.IO.File.Delete(curFile.Path);
}
db.PodcastFiles.Remove(curFile);
podcast.Files.Remove(curFile);
}
}
// Add any new files
List<PodcastFile> newFiles = SaveFiles(Request.Files, episode);
foreach (PodcastFile file in newFiles)
{
podcast.Files.Add(file);
} }
}
// Add any new files
List<PodcastFile> newFiles = SaveFiles(Request.Files, episode);
foreach (PodcastFile file in newFiles)
{
podcast.Files.Add(file);
}
// Save podcast // Save podcast
db.Entry(podcast).State = EntityState.Modified; db.Entry(podcast).State = EntityState.Modified;
db.SaveChanges(); db.SaveChanges();
return Json(new { result = true }); return Json(new { result = true });
}
return Json(new { error = "That episode already exists" });
} }
return Json(new { error = "That episode already exists" }); return Json(new { error = "No podcast found" });
} }
return Json(new { error = "No podcast found" });
} }
return Json(new { error = "You don't have permission to edit this podcast" }); return Json(new { error = "You don't have permission to edit this podcast" });
} }
@ -282,17 +310,20 @@ namespace Teknik.Areas.Podcast.Controllers
{ {
if (User.IsInRole("Podcast")) if (User.IsInRole("Podcast"))
{ {
Models.Podcast podcast = db.Podcasts.Find(podcastId); using (TeknikEntities db = new TeknikEntities())
if (podcast != null)
{ {
podcast.Published = publish; Models.Podcast podcast = db.Podcasts.Find(podcastId);
if (publish) if (podcast != null)
podcast.DatePublished = DateTime.Now; {
db.Entry(podcast).State = EntityState.Modified; podcast.Published = publish;
db.SaveChanges(); if (publish)
return Json(new { result = true }); podcast.DatePublished = DateTime.Now;
db.Entry(podcast).State = EntityState.Modified;
db.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "No podcast found" });
} }
return Json(new { error = "No podcast found" });
} }
return Json(new { error = "You don't have permission to publish this podcast" }); return Json(new { error = "You don't have permission to publish this podcast" });
} }
@ -306,18 +337,21 @@ namespace Teknik.Areas.Podcast.Controllers
{ {
if (User.IsInRole("Podcast")) if (User.IsInRole("Podcast"))
{ {
Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (podcast != null)
{ {
foreach (PodcastFile file in podcast.Files) Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
if (podcast != null)
{ {
System.IO.File.Delete(file.Path); foreach (PodcastFile file in podcast.Files)
{
System.IO.File.Delete(file.Path);
}
db.Podcasts.Remove(podcast);
db.SaveChanges();
return Json(new { result = true });
} }
db.Podcasts.Remove(podcast); return Json(new { error = "No podcast found" });
db.SaveChanges();
return Json(new { result = true });
} }
return Json(new { error = "No podcast found" });
} }
return Json(new { error = "You don't have permission to delete this podcast" }); return Json(new { error = "You don't have permission to delete this podcast" });
} }
@ -330,28 +364,34 @@ namespace Teknik.Areas.Podcast.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult GetComments(int podcastId, int startCommentID, int count) public ActionResult GetComments(int podcastId, int startCommentID, int count)
{ {
var comments = db.PodcastComments.Where(p => (p.PodcastId == podcastId)).OrderByDescending(p => p.DatePosted).Skip(startCommentID).Take(count).ToList(); using (TeknikEntities db = new TeknikEntities())
List<CommentViewModel> commentViews = new List<CommentViewModel>();
if (comments != null)
{ {
foreach (PodcastComment comment in comments) var comments = db.PodcastComments.Where(p => (p.PodcastId == podcastId)).OrderByDescending(p => p.DatePosted).Skip(startCommentID).Take(count).ToList();
List<CommentViewModel> commentViews = new List<CommentViewModel>();
if (comments != null)
{ {
commentViews.Add(new CommentViewModel(comment)); foreach (PodcastComment comment in comments)
{
commentViews.Add(new CommentViewModel(comment));
}
} }
return PartialView("~/Areas/Podcast/Views/Podcast/Comments.cshtml", commentViews);
} }
return PartialView("~/Areas/Podcast/Views/Podcast/Comments.cshtml", commentViews);
} }
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
public ActionResult GetCommentArticle(int commentID) public ActionResult GetCommentArticle(int commentID)
{ {
PodcastComment comment = db.PodcastComments.Where(p => (p.PodcastCommentId == commentID)).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (comment != null)
{ {
return Json(new { result = comment.Article }); PodcastComment comment = db.PodcastComments.Where(p => (p.PodcastCommentId == commentID)).FirstOrDefault();
if (comment != null)
{
return Json(new { result = comment.Article });
}
return Json(new { error = "No article found" });
} }
return Json(new { error = "No article found" });
} }
[HttpPost] [HttpPost]
@ -359,20 +399,23 @@ namespace Teknik.Areas.Podcast.Controllers
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
if (db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault() != null) using (TeknikEntities db = new TeknikEntities())
{ {
PodcastComment comment = db.PodcastComments.Create(); if (db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault() != null)
comment.PodcastId = podcastId; {
comment.UserId = UserHelper.GetUser(db, User.Identity.Name).UserId; PodcastComment comment = db.PodcastComments.Create();
comment.Article = article; comment.PodcastId = podcastId;
comment.DatePosted = DateTime.Now; comment.UserId = UserHelper.GetUser(db, User.Identity.Name).UserId;
comment.DateEdited = DateTime.Now; comment.Article = article;
comment.DatePosted = DateTime.Now;
comment.DateEdited = DateTime.Now;
db.PodcastComments.Add(comment); db.PodcastComments.Add(comment);
db.SaveChanges(); db.SaveChanges();
return Json(new { result = true }); return Json(new { result = true });
}
return Json(new { error = "That podcast does not exist" });
} }
return Json(new { error = "That podcast does not exist" });
} }
return Json(new { error = "Invalid Parameters" }); return Json(new { error = "Invalid Parameters" });
} }
@ -382,20 +425,23 @@ namespace Teknik.Areas.Podcast.Controllers
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (comment != null)
{ {
if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin")) PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
if (comment != null)
{ {
comment.Article = article; if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
comment.DateEdited = DateTime.Now; {
db.Entry(comment).State = EntityState.Modified; comment.Article = article;
db.SaveChanges(); comment.DateEdited = DateTime.Now;
return Json(new { result = true }); db.Entry(comment).State = EntityState.Modified;
db.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "You don't have permission to edit this comment" });
} }
return Json(new { error = "You don't have permission to edit this comment" }); return Json(new { error = "No comment found" });
} }
return Json(new { error = "No comment found" });
} }
return Json(new { error = "Invalid Parameters" }); return Json(new { error = "Invalid Parameters" });
} }
@ -405,18 +451,21 @@ namespace Teknik.Areas.Podcast.Controllers
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (comment != null)
{ {
if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin")) PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
if (comment != null)
{ {
db.PodcastComments.Remove(comment); if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
db.SaveChanges(); {
return Json(new { result = true }); db.PodcastComments.Remove(comment);
db.SaveChanges();
return Json(new { result = true });
}
return Json(new { error = "You don't have permission to delete this comment" });
} }
return Json(new { error = "You don't have permission to delete this comment" }); return Json(new { error = "No comment found" });
} }
return Json(new { error = "No comment found" });
} }
return Json(new { error = "Invalid Parameters" }); return Json(new { error = "Invalid Parameters" });
} }

View File

@ -19,8 +19,6 @@ namespace Teknik.Areas.RSS.Controllers
[TeknikAuthorize(AuthType.Basic)] [TeknikAuthorize(AuthType.Basic)]
public class RSSController : DefaultController public class RSSController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
{ {
@ -33,102 +31,108 @@ namespace Teknik.Areas.RSS.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult Blog(string username) public ActionResult Blog(string username)
{ {
// If empty, grab the main blog using (TeknikEntities db = new TeknikEntities())
List<BlogPost> posts = new List<BlogPost>(); {
// If empty, grab the main blog
List<BlogPost> posts = new List<BlogPost>();
string blogUrl = Url.SubRouteUrl("blog", "Blog.Blog"); string blogUrl = Url.SubRouteUrl("blog", "Blog.Blog");
string title = string.Empty; string title = string.Empty;
string description = string.Empty; string description = string.Empty;
bool isSystem = string.IsNullOrEmpty(username); bool isSystem = string.IsNullOrEmpty(username);
if (isSystem)
{
posts = db.BlogPosts.Where(p => (p.System && p.Published)).ToList();
blogUrl = Url.SubRouteUrl("blog", "Blog.Blog");
}
else
{
Blog.Models.Blog blog = db.Blogs.Where(p => p.User.Username == username && p.BlogId != Config.BlogConfig.ServerBlogId).FirstOrDefault();
posts = db.BlogPosts.Where(p => (p.BlogId == blog.BlogId && !p.System) && p.Published).ToList();
blogUrl = Url.SubRouteUrl("blog", "Blog.Blog", new { username = username });
}
if (posts.Any())
{
if (isSystem) if (isSystem)
{ {
title = Config.BlogConfig.Title; posts = db.BlogPosts.Where(p => (p.System && p.Published)).ToList();
description = Config.BlogConfig.Description; blogUrl = Url.SubRouteUrl("blog", "Blog.Blog");
} }
else else
{ {
Users.Models.User user = UserHelper.GetUser(db, username); Blog.Models.Blog blog = db.Blogs.Where(p => p.User.Username == username && p.BlogId != Config.BlogConfig.ServerBlogId).FirstOrDefault();
if (user != null) posts = db.BlogPosts.Where(p => (p.BlogId == blog.BlogId && !p.System) && p.Published).ToList();
blogUrl = Url.SubRouteUrl("blog", "Blog.Blog", new { username = username });
}
if (posts.Any())
{
if (isSystem)
{ {
title = user.BlogSettings.Title; title = Config.BlogConfig.Title;
description = user.BlogSettings.Description; description = Config.BlogConfig.Description;
} }
else else
{ {
SyndicationFeed badUserFeed = new SyndicationFeed("No Blog Available", "The specified user does not exist", new Uri(blogUrl)); Users.Models.User user = UserHelper.GetUser(db, username);
if (user != null)
{
title = user.BlogSettings.Title;
description = user.BlogSettings.Description;
}
else
{
SyndicationFeed badUserFeed = new SyndicationFeed("No Blog Available", "The specified user does not exist", new Uri(blogUrl));
return new RssResult(badUserFeed); return new RssResult(badUserFeed);
}
} }
}
List<SyndicationItem> items = new List<SyndicationItem>(); List<SyndicationItem> items = new List<SyndicationItem>();
foreach (BlogPost post in posts.OrderByDescending(p => p.BlogPostId)) foreach (BlogPost post in posts.OrderByDescending(p => p.BlogPostId))
{
if (post.Published && post.System == isSystem)
{ {
items.Add(new SyndicationItem( if (post.Published && post.System == isSystem)
post.Title, {
MarkdownHelper.Markdown(post.Article).ToHtmlString(), items.Add(new SyndicationItem(
new Uri(Url.SubRouteUrl("blog", "Blog.Post", new { username = post.Blog.User.Username, id = post.BlogPostId })), post.Title,
post.BlogPostId.ToString(), MarkdownHelper.Markdown(post.Article).ToHtmlString(),
post.DateEdited new Uri(Url.SubRouteUrl("blog", "Blog.Post", new { username = post.Blog.User.Username, id = post.BlogPostId })),
)); post.BlogPostId.ToString(),
post.DateEdited
));
}
} }
SyndicationFeed feed = new SyndicationFeed(title, description, new Uri(blogUrl), items);
return new RssResult(feed);
} }
SyndicationFeed badFeed = new SyndicationFeed("No Blog Available", "The specified blog does not exist", new Uri(blogUrl));
SyndicationFeed feed = new SyndicationFeed(title, description, new Uri(blogUrl), items); return new RssResult(badFeed);
return new RssResult(feed);
} }
SyndicationFeed badFeed = new SyndicationFeed("No Blog Available", "The specified blog does not exist", new Uri(blogUrl));
return new RssResult(badFeed);
} }
[TrackDownload] [TrackDownload]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Podcast() public ActionResult Podcast()
{ {
List<SyndicationItem> items = new List<SyndicationItem>(); using (TeknikEntities db = new TeknikEntities())
List<Podcast.Models.Podcast> podcasts = db.Podcasts.Where(p => p.Published).OrderByDescending(p => p.Episode).ToList();
if (podcasts != null)
{ {
foreach (Podcast.Models.Podcast podcast in podcasts) List<SyndicationItem> items = new List<SyndicationItem>();
List<Podcast.Models.Podcast> podcasts = db.Podcasts.Where(p => p.Published).OrderByDescending(p => p.Episode).ToList();
if (podcasts != null)
{ {
SyndicationItem item = new SyndicationItem( foreach (Podcast.Models.Podcast podcast in podcasts)
podcast.Title,
MarkdownHelper.Markdown(podcast.Description).ToHtmlString(),
new Uri(Url.SubRouteUrl("podcast", "Podcast.View", new { episode = podcast.Episode })),
podcast.Episode.ToString(),
podcast.DateEdited
);
foreach (Podcast.Models.PodcastFile file in podcast.Files)
{ {
SyndicationLink enclosure = SyndicationLink.CreateMediaEnclosureLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.Download", new { episode = podcast.Episode, fileName = file.FileName })), file.ContentType, file.ContentLength); SyndicationItem item = new SyndicationItem(
item.Links.Add(enclosure); podcast.Title,
MarkdownHelper.Markdown(podcast.Description).ToHtmlString(),
new Uri(Url.SubRouteUrl("podcast", "Podcast.View", new { episode = podcast.Episode })),
podcast.Episode.ToString(),
podcast.DateEdited
);
foreach (Podcast.Models.PodcastFile file in podcast.Files)
{
SyndicationLink enclosure = SyndicationLink.CreateMediaEnclosureLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.Download", new { episode = podcast.Episode, fileName = file.FileName })), file.ContentType, file.ContentLength);
item.Links.Add(enclosure);
}
items.Add(item);
} }
items.Add(item);
} }
SyndicationFeed feed = new SyndicationFeed(Config.PodcastConfig.Title, Config.PodcastConfig.Description, new Uri(Url.SubRouteUrl("podcast", "Podcast.Index")), items);
return new RssResult(feed);
} }
SyndicationFeed feed = new SyndicationFeed(Config.PodcastConfig.Title, Config.PodcastConfig.Description, new Uri(Url.SubRouteUrl("podcast", "Podcast.Index")), items);
return new RssResult(feed);
} }
} }
} }

View File

@ -17,8 +17,6 @@ namespace Teknik.Areas.Shortener.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class ShortenerController : DefaultController public class ShortenerController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
@ -31,15 +29,18 @@ namespace Teknik.Areas.Shortener.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult RedirectToUrl(string url) public ActionResult RedirectToUrl(string url)
{ {
ShortenedUrl shortUrl = db.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (shortUrl != null)
{ {
shortUrl.Views += 1; ShortenedUrl shortUrl = db.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault();
db.Entry(shortUrl).State = System.Data.Entity.EntityState.Modified; if (shortUrl != null)
db.SaveChanges(); {
return Redirect(shortUrl.OriginalUrl); shortUrl.Views += 1;
db.Entry(shortUrl).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return Redirect(shortUrl.OriginalUrl);
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
[HttpPost] [HttpPost]
@ -48,27 +49,30 @@ namespace Teknik.Areas.Shortener.Controllers
{ {
if (url.IsValidUrl()) if (url.IsValidUrl())
{ {
ShortenedUrl newUrl = Shortener.ShortenUrl(url, Config.ShortenerConfig.UrlLength); using (TeknikEntities db = new TeknikEntities())
if (User.Identity.IsAuthenticated)
{ {
Users.Models.User foundUser = UserHelper.GetUser(db, User.Identity.Name); ShortenedUrl newUrl = Shortener.ShortenUrl(db, url, Config.ShortenerConfig.UrlLength);
if (foundUser != null)
if (User.Identity.IsAuthenticated)
{ {
newUrl.UserId = foundUser.UserId; Users.Models.User foundUser = UserHelper.GetUser(db, User.Identity.Name);
if (foundUser != null)
{
newUrl.UserId = foundUser.UserId;
}
} }
db.ShortenedUrls.Add(newUrl);
db.SaveChanges();
string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
if (Config.DevEnvironment)
{
shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
}
return Json(new { result = new { shortUrl = shortUrl, originalUrl = url } });
} }
db.ShortenedUrls.Add(newUrl);
db.SaveChanges();
string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
if (Config.DevEnvironment)
{
shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
}
return Json(new { result = new { shortUrl = shortUrl, originalUrl = url } });
} }
return Json(new { error = "Must be a valid Url" }); return Json(new { error = "Must be a valid Url" });
} }

View File

@ -11,10 +11,8 @@ namespace Teknik.Areas.Shortener
{ {
public static class Shortener public static class Shortener
{ {
public static ShortenedUrl ShortenUrl(string url, int length) public static ShortenedUrl ShortenUrl(TeknikEntities db, string url, int length)
{ {
TeknikEntities db = new TeknikEntities();
// Generate the shortened url // Generate the shortened url
string shortUrl = StringHelper.RandomString(length); string shortUrl = StringHelper.RandomString(length);
while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null) while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null)

View File

@ -19,8 +19,6 @@ namespace Teknik.Areas.Status.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class StatusController : DefaultController public class StatusController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
@ -30,134 +28,136 @@ namespace Teknik.Areas.Status.Controllers
StatusViewModel model = new StatusViewModel(); StatusViewModel model = new StatusViewModel();
// Load initial status info using (TeknikEntities db = new TeknikEntities())
#region Statistics
Upload.Models.Upload upload = db.Uploads.OrderByDescending(u => u.UploadId).FirstOrDefault();
model.UploadCount = (upload != null) ? upload.UploadId : 0;
model.UploadSize = (upload != null) ? db.Uploads.Sum(u => (long)u.ContentLength) : 0;
Paste.Models.Paste paste = db.Pastes.OrderByDescending(p => p.PasteId).FirstOrDefault();
model.PasteCount = (paste != null) ? paste.PasteId : 0;
Users.Models.User user = db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
model.UserCount = (user != null) ? user.UserId : 0;
Shortener.Models.ShortenedUrl url = db.ShortenedUrls.OrderByDescending(s => s.ShortenedUrlId).FirstOrDefault();
model.ShortenedUrlCount = (url != null) ? url.ShortenedUrlId : 0;
Vault.Models.Vault vault = db.Vaults.OrderByDescending(v => v.VaultId).FirstOrDefault();
model.VaultCount = (url != null) ? vault.VaultId : 0;
#endregion
// Get Transaction Inforomation
#region Transactions
DateTime curTime = DateTime.Now;
var billSums = db.Transactions.OfType<Bill>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year}).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
foreach (var sum in billSums)
{ {
decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency); // Load initial status info
decimal realValue = sum.total * exchangeRate; #region Statistics
model.Transactions.TotalBills += realValue; Upload.Models.Upload upload = db.Uploads.OrderByDescending(u => u.UploadId).FirstOrDefault();
model.Transactions.TotalNet += realValue; model.UploadCount = (upload != null) ? upload.UploadId : 0;
if (curTime.Month == sum.month && curTime.Year == sum.year) model.UploadSize = (upload != null) ? db.Uploads.Sum(u => (long)u.ContentLength) : 0;
Paste.Models.Paste paste = db.Pastes.OrderByDescending(p => p.PasteId).FirstOrDefault();
model.PasteCount = (paste != null) ? paste.PasteId : 0;
Users.Models.User user = db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
model.UserCount = (user != null) ? user.UserId : 0;
Shortener.Models.ShortenedUrl url = db.ShortenedUrls.OrderByDescending(s => s.ShortenedUrlId).FirstOrDefault();
model.ShortenedUrlCount = (url != null) ? url.ShortenedUrlId : 0;
Vault.Models.Vault vault = db.Vaults.OrderByDescending(v => v.VaultId).FirstOrDefault();
model.VaultCount = (url != null) ? vault.VaultId : 0;
#endregion
// Get Transaction Inforomation
#region Transactions
DateTime curTime = DateTime.Now;
var billSums = db.Transactions.OfType<Bill>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
foreach (var sum in billSums)
{ {
model.Transactions.CurrentMonthBills += Math.Abs(realValue); decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
decimal realValue = sum.total * exchangeRate;
model.Transactions.TotalBills += realValue;
model.Transactions.TotalNet += realValue;
if (curTime.Month == sum.month && curTime.Year == sum.year)
{
model.Transactions.CurrentMonthBills += Math.Abs(realValue);
}
} }
}
var oneSums = db.Transactions.OfType<OneTime>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList(); var oneSums = db.Transactions.OfType<OneTime>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
foreach (var sum in oneSums) foreach (var sum in oneSums)
{
decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
decimal realValue = sum.total * exchangeRate;
model.Transactions.TotalOneTimes += realValue;
model.Transactions.TotalNet += realValue;
if (curTime.Month == sum.month && curTime.Year == sum.year)
{ {
model.Transactions.CurrentMonthBills += Math.Abs(realValue); decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
decimal realValue = sum.total * exchangeRate;
model.Transactions.TotalOneTimes += realValue;
model.Transactions.TotalNet += realValue;
if (curTime.Month == sum.month && curTime.Year == sum.year)
{
model.Transactions.CurrentMonthBills += Math.Abs(realValue);
}
} }
}
var donationSums = db.Transactions.OfType<Donation>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList(); var donationSums = db.Transactions.OfType<Donation>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
foreach (var sum in donationSums) foreach (var sum in donationSums)
{
decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
decimal realValue = sum.total * exchangeRate;
model.Transactions.TotalDonations += realValue;
model.Transactions.TotalNet += realValue;
if (curTime.Month == sum.month && curTime.Year == sum.year)
{ {
model.Transactions.CurrentMonthIncome += Math.Abs(realValue); decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
decimal realValue = sum.total * exchangeRate;
model.Transactions.TotalDonations += realValue;
model.Transactions.TotalNet += realValue;
if (curTime.Month == sum.month && curTime.Year == sum.year)
{
model.Transactions.CurrentMonthIncome += Math.Abs(realValue);
}
} }
}
List<Bill> bills = db.Transactions.OfType<Bill>().OrderByDescending(b => b.DateSent).ToList(); List<Bill> bills = db.Transactions.OfType<Bill>().OrderByDescending(b => b.DateSent).ToList();
if (bills != null) if (bills != null)
{
foreach (Bill bill in bills)
{ {
BillViewModel billModel = new BillViewModel(); foreach (Bill bill in bills)
billModel.Amount = bill.Amount; {
billModel.Currency = bill.Currency; BillViewModel billModel = new BillViewModel();
billModel.Reason = bill.Reason; billModel.Amount = bill.Amount;
billModel.DateSent = bill.DateSent; billModel.Currency = bill.Currency;
billModel.Recipient = bill.Recipient; billModel.Reason = bill.Reason;
model.Transactions.Bills.Add(billModel); billModel.DateSent = bill.DateSent;
billModel.Recipient = bill.Recipient;
model.Transactions.Bills.Add(billModel);
}
} }
}
List<OneTime> oneTimes = db.Transactions.OfType<OneTime>().OrderByDescending(b => b.DateSent).ToList(); List<OneTime> oneTimes = db.Transactions.OfType<OneTime>().OrderByDescending(b => b.DateSent).ToList();
if (oneTimes != null) if (oneTimes != null)
{
foreach (OneTime oneTime in oneTimes)
{ {
OneTimeViewModel oneTimeModel = new OneTimeViewModel(); foreach (OneTime oneTime in oneTimes)
oneTimeModel.Amount = oneTime.Amount; {
oneTimeModel.Currency = oneTime.Currency; OneTimeViewModel oneTimeModel = new OneTimeViewModel();
oneTimeModel.Reason = oneTime.Reason; oneTimeModel.Amount = oneTime.Amount;
oneTimeModel.DateSent = oneTime.DateSent; oneTimeModel.Currency = oneTime.Currency;
oneTimeModel.Recipient = oneTime.Recipient; oneTimeModel.Reason = oneTime.Reason;
model.Transactions.OneTimes.Add(oneTimeModel); oneTimeModel.DateSent = oneTime.DateSent;
oneTimeModel.Recipient = oneTime.Recipient;
model.Transactions.OneTimes.Add(oneTimeModel);
}
} }
}
List<Donation> donations = db.Transactions.OfType<Donation>().OrderByDescending(b => b.DateSent).ToList(); List<Donation> donations = db.Transactions.OfType<Donation>().OrderByDescending(b => b.DateSent).ToList();
if (donations != null) if (donations != null)
{
foreach (Donation donation in donations)
{ {
DonationViewModel donationModel = new DonationViewModel(); foreach (Donation donation in donations)
donationModel.Amount = donation.Amount; {
donationModel.Currency = donation.Currency; DonationViewModel donationModel = new DonationViewModel();
donationModel.Reason = donation.Reason; donationModel.Amount = donation.Amount;
donationModel.DateSent = donation.DateSent; donationModel.Currency = donation.Currency;
donationModel.Sender = donation.Sender; donationModel.Reason = donation.Reason;
model.Transactions.Donations.Add(donationModel); donationModel.DateSent = donation.DateSent;
donationModel.Sender = donation.Sender;
model.Transactions.Donations.Add(donationModel);
}
} }
} #endregion
#endregion
// Takedown information // Takedown information
#region Takedowns #region Takedowns
List<Takedown> takedowns = db.Takedowns.OrderByDescending(b => b.DateRequested).ToList(); List<Takedown> takedowns = db.Takedowns.OrderByDescending(b => b.DateRequested).ToList();
if (takedowns != null) if (takedowns != null)
{
foreach (Takedown takedown in takedowns)
{ {
TakedownViewModel takedownModel = new TakedownViewModel(); foreach (Takedown takedown in takedowns)
takedownModel.Requester = takedown.Requester; {
takedownModel.RequesterContact = takedown.RequesterContact; TakedownViewModel takedownModel = new TakedownViewModel();
takedownModel.Reason = takedown.Reason; takedownModel.Requester = takedown.Requester;
takedownModel.ActionTaken = takedown.ActionTaken; takedownModel.RequesterContact = takedown.RequesterContact;
takedownModel.DateRequested = takedown.DateRequested; takedownModel.Reason = takedown.Reason;
takedownModel.DateActionTaken = takedown.DateActionTaken; takedownModel.ActionTaken = takedown.ActionTaken;
takedownModel.DateRequested = takedown.DateRequested;
takedownModel.DateActionTaken = takedown.DateActionTaken;
model.Takedowns.Add(takedownModel); model.Takedowns.Add(takedownModel);
}
} }
#endregion
} }
#endregion
return View(model); return View(model);
} }

View File

@ -26,8 +26,6 @@ namespace Teknik.Areas.Upload.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class UploadController : DefaultController public class UploadController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
// GET: Upload/Upload // GET: Upload/Upload
[HttpGet] [HttpGet]
[TrackPageView] [TrackPageView]
@ -37,15 +35,18 @@ namespace Teknik.Areas.Upload.Controllers
ViewBag.Title = "Teknik Upload - End to End Encryption"; ViewBag.Title = "Teknik Upload - End to End Encryption";
UploadViewModel model = new UploadViewModel(); UploadViewModel model = new UploadViewModel();
model.CurrentSub = Subdomain; model.CurrentSub = Subdomain;
Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name); using (TeknikEntities db = new TeknikEntities())
if (user != null)
{ {
model.Encrypt = user.UploadSettings.Encrypt; Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
model.Vaults = user.Vaults.ToList(); if (user != null)
} {
else model.Encrypt = user.UploadSettings.Encrypt;
{ model.Vaults = user.Vaults.ToList();
model.Encrypt = false; }
else
{
model.Encrypt = false;
}
} }
return View(model); return View(model);
} }
@ -83,22 +84,25 @@ namespace Teknik.Areas.Upload.Controllers
} }
} }
Models.Upload upload = Uploader.SaveFile(db, Config, data.InputStream, fileType, contentLength, encrypt, fileExt, iv, null, keySize, blockSize); using (TeknikEntities db = new TeknikEntities())
if (upload != null)
{ {
if (User.Identity.IsAuthenticated) Models.Upload upload = Uploader.SaveFile(db, Config, data.InputStream, fileType, contentLength, encrypt, fileExt, iv, null, keySize, blockSize);
if (upload != null)
{ {
Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name); if (User.Identity.IsAuthenticated)
if (user != null)
{ {
upload.UserId = user.UserId; Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
db.Entry(upload).State = EntityState.Modified; if (user != null)
db.SaveChanges(); {
upload.UserId = user.UserId;
db.Entry(upload).State = EntityState.Modified;
db.SaveChanges();
}
} }
return Json(new { result = new { name = upload.Url, url = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url }), contentType = upload.ContentType, contentLength = StringHelper.GetBytesReadable(upload.ContentLength), deleteUrl = Url.SubRouteUrl("u", "Upload.Delete", new { file = upload.Url, key = upload.DeleteKey }) } }, "text/plain");
} }
return Json(new { result = new { name = upload.Url, url = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url }), contentType = upload.ContentType, contentLength = StringHelper.GetBytesReadable(upload.ContentLength), deleteUrl = Url.SubRouteUrl("u", "Upload.Delete", new { file = upload.Url, key = upload.DeleteKey }) } }, "text/plain"); return Json(new { error = new { message = "Unable to upload file" } });
} }
return Json(new { error = new { message = "Unable to upload file" } });
} }
else else
{ {
@ -122,98 +126,108 @@ namespace Teknik.Areas.Upload.Controllers
if (Config.UploadConfig.DownloadEnabled) if (Config.UploadConfig.DownloadEnabled)
{ {
ViewBag.Title = "Teknik Download - " + file; ViewBag.Title = "Teknik Download - " + file;
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (upload != null)
{ {
upload.Downloads += 1; Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
db.Entry(upload).State = EntityState.Modified; if (upload != null)
db.SaveChanges();
// We don't have the key, so we need to decrypt it client side
if (string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
{ {
DownloadViewModel model = new DownloadViewModel(); upload.Downloads += 1;
model.FileName = file; db.Entry(upload).State = EntityState.Modified;
model.ContentType = upload.ContentType; db.SaveChanges();
model.ContentLength = upload.ContentLength;
model.IV = upload.IV;
return View(model); // We don't have the key, so we need to decrypt it client side
} if (string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
else // We have the key, so that means server side decryption
{
// Are they downloading it by range?
bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]); // We do not support ranges
// Check to see if they have a cache
bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]);
if (isCached)
{ {
// The file is cached, let's just 304 this DownloadViewModel model = new DownloadViewModel();
Response.StatusCode = 304; model.FileName = file;
Response.StatusDescription = "Not Modified"; model.ContentType = upload.ContentType;
Response.AddHeader("Content-Length", "0"); model.ContentLength = upload.ContentLength;
return Content(string.Empty); model.IV = upload.IV;
return View(model);
} }
else else // We have the key, so that means server side decryption
{ {
string subDir = upload.FileName[0].ToString(); // Are they downloading it by range?
string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName); bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]); // We do not support ranges
if (System.IO.File.Exists(filePath)) // Check to see if they have a cache
bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]);
if (isCached)
{ {
// Add cache parameters // The file is cached, let's just 304 this
Response.Cache.SetCacheability(HttpCacheability.Public); Response.StatusCode = 304;
Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0)); Response.StatusDescription = "Not Modified";
Response.Cache.SetLastModified(upload.DateUploaded); Response.AddHeader("Content-Length", "0");
return Content(string.Empty);
// Notify the client the content length we'll be outputting }
Response.AddHeader("Content-Length", upload.ContentLength.ToString()); else
{
// Create content disposition string subDir = upload.FileName[0].ToString();
var cd = new System.Net.Mime.ContentDisposition string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
if (System.IO.File.Exists(filePath))
{ {
FileName = upload.Url, // Add cache parameters
Inline = true Response.Cache.SetCacheability(HttpCacheability.Public);
}; Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
Response.Cache.SetLastModified(upload.DateUploaded);
Response.AddHeader("Content-Disposition", cd.ToString()); // Notify the client the content length we'll be outputting
Response.AddHeader("Content-Length", upload.ContentLength.ToString());
string contentType = upload.ContentType; // Create content disposition
// We need to prevent html (make cleaner later) var cd = new System.Net.Mime.ContentDisposition
if (contentType == "text/html") {
{ FileName = upload.Url,
contentType = "text/plain"; Inline = true
} };
// Read in the file Response.AddHeader("Content-Disposition", cd.ToString());
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
// If the IV is set, and Key is set, then decrypt it while sending string contentType = upload.ContentType;
if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV)) // We need to prevent html (make cleaner later)
{ if (contentType == "text/html")
byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key); {
byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV); contentType = "text/plain";
}
return new FileGenerateResult(upload.Url, // Read in the file
contentType, FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
(response) => ResponseHelper.StreamToOutput(response, true, new AESCryptoStream(fs, false, keyBytes, ivBytes, "CTR", "NoPadding"), (int)upload.ContentLength, Config.UploadConfig.ChunkSize),
false); try
} {
else // Otherwise just send it // If the IV is set, and Key is set, then decrypt it while sending
{ if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
// Don't buffer the response {
Response.Buffer = false; byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
// Send the file byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
return new FileGenerateResult(upload.Url,
contentType, return new FileGenerateResult(upload.Url,
(response) => ResponseHelper.StreamToOutput(response, true, fs, (int)upload.ContentLength, Config.UploadConfig.ChunkSize), contentType,
false); (response) => ResponseHelper.StreamToOutput(response, true, new AESCryptoStream(fs, false, keyBytes, ivBytes, "CTR", "NoPadding"), (int)upload.ContentLength, Config.UploadConfig.ChunkSize),
false);
}
else // Otherwise just send it
{
// Don't buffer the response
Response.Buffer = false;
// Send the file
return new FileGenerateResult(upload.Url,
contentType,
(response) => ResponseHelper.StreamToOutput(response, true, fs, (int)upload.ContentLength, Config.UploadConfig.ChunkSize),
false);
}
}
catch (Exception ex)
{
Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Download", ex);
}
} }
} }
} }
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http403")); return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
} }
@ -224,19 +238,22 @@ namespace Teknik.Areas.Upload.Controllers
{ {
if (Config.UploadConfig.DownloadEnabled) if (Config.UploadConfig.DownloadEnabled)
{ {
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (upload != null)
{ {
string subDir = upload.FileName[0].ToString(); Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName); if (upload != null)
if (System.IO.File.Exists(filePath))
{ {
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); string subDir = upload.FileName[0].ToString();
return File(fileStream, System.Net.Mime.MediaTypeNames.Application.Octet, file); string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
if (System.IO.File.Exists(filePath))
{
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return File(fileStream, System.Net.Mime.MediaTypeNames.Application.Octet, file);
}
} }
Redirect(Url.SubRouteUrl("error", "Error.Http404"));
return null;
} }
Redirect(Url.SubRouteUrl("error", "Error.Http404"));
return null;
} }
Redirect(Url.SubRouteUrl("error", "Error.Http403")); Redirect(Url.SubRouteUrl("error", "Error.Http403"));
return null; return null;
@ -246,52 +263,58 @@ namespace Teknik.Areas.Upload.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult Delete(string file, string key) public ActionResult Delete(string file, string key)
{ {
ViewBag.Title = "File Delete - " + file + " - " + Config.Title; using (TeknikEntities db = new TeknikEntities())
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
if (upload != null)
{ {
DeleteViewModel model = new DeleteViewModel(); ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
model.File = file; Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key) if (upload != null)
{ {
string filePath = upload.FileName; DeleteViewModel model = new DeleteViewModel();
// Delete from the DB model.File = file;
db.Uploads.Remove(upload); if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
db.SaveChanges();
// Delete the File
if (System.IO.File.Exists(filePath))
{ {
System.IO.File.Delete(filePath); string filePath = upload.FileName;
// Delete from the DB
db.Uploads.Remove(upload);
db.SaveChanges();
// Delete the File
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
model.Deleted = true;
} }
model.Deleted = true; else
{
model.Deleted = false;
}
return View(model);
} }
else return RedirectToRoute("Error.Http404");
{
model.Deleted = false;
}
return View(model);
} }
return RedirectToRoute("Error.Http404");
} }
[HttpPost] [HttpPost]
public ActionResult GenerateDeleteKey(string file) public ActionResult GenerateDeleteKey(string file)
{ {
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (upload != null)
{ {
if (upload.User.Username == User.Identity.Name) Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
if (upload != null)
{ {
string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength); if (upload.User.Username == User.Identity.Name)
upload.DeleteKey = delKey; {
db.Entry(upload).State = EntityState.Modified; string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
db.SaveChanges(); upload.DeleteKey = delKey;
return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.Delete", new { file = file, key = delKey }) } }); db.Entry(upload).State = EntityState.Modified;
db.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.Delete", new { file = file, key = delKey }) } });
}
return Json(new { error = new { message = "You do not own this upload" } });
} }
return Json(new { error = new { message = "You do not own this upload" } }); return Json(new { error = new { message = "Invalid URL" } });
} }
return Json(new { error = new { message = "Invalid URL" } });
} }
} }
} }

View File

@ -46,7 +46,7 @@ function processDownload(key) {
lastTime = curTime; lastTime = curTime;
lastData = e.data.processed; lastData = e.data.processed;
var percentComplete = Math.round(e.data.processed * 100 / e.data.total); var percentComplete = Math.round(e.data.processed * 100 / e.data.total);
setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Decrypting [' + getReadableBandwidthString(speed * 8) + ']'); setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Decrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
} }
break; break;
case 'finish': case 'finish':
@ -92,7 +92,7 @@ function processDownload(key) {
lastTime = curTime; lastTime = curTime;
lastData = e.loaded; lastData = e.loaded;
var percentComplete = Math.round(e.loaded * 100 / e.total); var percentComplete = Math.round(e.loaded * 100 / e.total);
setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Downloading File [' + getReadableBandwidthString(speed * 8) + ']'); setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Downloading File [' + getReadableFileSizeString(e.loaded) + ' / ' + getReadableFileSizeString(e.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
} }
}; };

View File

@ -217,7 +217,7 @@ function encryptFile(file, callback) {
lastTime = curTime; lastTime = curTime;
lastData = e.data.processed; lastData = e.data.processed;
var percentComplete = Math.round(e.data.processed * 100 / e.data.total); var percentComplete = Math.round(e.data.processed * 100 / e.data.total);
setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableBandwidthString(speed * 8) + ']'); setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
} }
break; break;
case 'finish': case 'finish':
@ -306,7 +306,7 @@ function uploadProgress(fileID, lastTime, lastData, evt) {
setProgress(fileID, 100, 'progress-bar-success progress-bar-striped active', '', 'Processing Upload'); setProgress(fileID, 100, 'progress-bar-success progress-bar-striped active', '', 'Processing Upload');
} }
else { else {
setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Uploading to Server [' + getReadableBandwidthString(speed * 8) + ']'); setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Uploading to Server [' + getReadableFileSizeString(evt.loaded) + ' / ' + getReadableFileSizeString(evt.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -20,82 +20,83 @@ namespace Teknik.Areas.Vault.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class VaultController : DefaultController public class VaultController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous] [AllowAnonymous]
public ActionResult ViewVault(string id) public ActionResult ViewVault(string id)
{ {
Models.Vault foundVault = db.Vaults.Where(v => v.Url == id).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (foundVault != null)
{ {
// Update view count Models.Vault foundVault = db.Vaults.Where(v => v.Url == id).FirstOrDefault();
foundVault.Views += 1; if (foundVault != null)
db.Entry(foundVault).State = EntityState.Modified;
db.SaveChanges();
ViewBag.Title = foundVault.Title + " - Teknik Vault";
VaultViewModel model = new VaultViewModel();
model.CurrentSub = Subdomain;
model.Url = foundVault.Url;
model.UserId = foundVault.UserId;
model.User = foundVault.User;
model.Title = foundVault.Title;
model.Description = foundVault.Description;
model.DateCreated = foundVault.DateCreated;
model.DateEdited = foundVault.DateEdited;
if (foundVault.VaultItems.Any())
{ {
foreach (VaultItem item in foundVault.VaultItems) // Update view count
foundVault.Views += 1;
db.Entry(foundVault).State = EntityState.Modified;
db.SaveChanges();
ViewBag.Title = foundVault.Title + " - Teknik Vault";
VaultViewModel model = new VaultViewModel();
model.CurrentSub = Subdomain;
model.Url = foundVault.Url;
model.UserId = foundVault.UserId;
model.User = foundVault.User;
model.Title = foundVault.Title;
model.Description = foundVault.Description;
model.DateCreated = foundVault.DateCreated;
model.DateEdited = foundVault.DateEdited;
if (foundVault.VaultItems.Any())
{ {
if (item.GetType().BaseType == typeof(UploadVaultItem)) foreach (VaultItem item in foundVault.VaultItems)
{ {
UploadVaultItem upload = (UploadVaultItem)item; if (item.GetType().BaseType == typeof(UploadVaultItem))
// Increment Views
upload.Upload.Downloads += 1;
db.Entry(upload.Upload).State = EntityState.Modified;
db.SaveChanges();
UploadItemViewModel uploadModel = new UploadItemViewModel();
upload.VaultItemId = item.VaultItemId;
uploadModel.Title = item.Title;
uploadModel.Description = item.Description;
uploadModel.DateAdded = item.DateAdded;
uploadModel.Upload = upload.Upload;
model.Items.Add(uploadModel);
}
else if (item.GetType().BaseType == typeof(PasteVaultItem))
{
PasteVaultItem paste = (PasteVaultItem)item;
// Increment Views
paste.Paste.Views += 1;
db.Entry(paste.Paste).State = EntityState.Modified;
db.SaveChanges();
// Check Expiration
if (PasteHelper.CheckExpiration(paste.Paste))
{ {
db.Pastes.Remove(paste.Paste); UploadVaultItem upload = (UploadVaultItem)item;
// Increment Views
upload.Upload.Downloads += 1;
db.Entry(upload.Upload).State = EntityState.Modified;
db.SaveChanges(); db.SaveChanges();
break;
}
PasteItemViewModel pasteModel = new PasteItemViewModel(); UploadItemViewModel uploadModel = new UploadItemViewModel();
pasteModel.VaultItemId = item.VaultItemId; uploadModel.VaultItemId = item.VaultItemId;
pasteModel.Title = item.Title; uploadModel.Title = item.Title;
pasteModel.Description = item.Description; uploadModel.Description = item.Description;
pasteModel.DateAdded = item.DateAdded; uploadModel.DateAdded = item.DateAdded;
pasteModel.Paste = paste.Paste; uploadModel.Upload = upload.Upload;
model.Items.Add(pasteModel); model.Items.Add(uploadModel);
}
else if (item.GetType().BaseType == typeof(PasteVaultItem))
{
PasteVaultItem paste = (PasteVaultItem)item;
// Increment Views
paste.Paste.Views += 1;
db.Entry(paste.Paste).State = EntityState.Modified;
db.SaveChanges();
// Check Expiration
if (PasteHelper.CheckExpiration(paste.Paste))
{
db.Pastes.Remove(paste.Paste);
db.SaveChanges();
break;
}
PasteItemViewModel pasteModel = new PasteItemViewModel();
pasteModel.VaultItemId = item.VaultItemId;
pasteModel.Title = item.Title;
pasteModel.Description = item.Description;
pasteModel.DateAdded = item.DateAdded;
pasteModel.Paste = paste.Paste;
model.Items.Add(pasteModel);
}
} }
} }
}
return View(model); return View(model);
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
[HttpGet] [HttpGet]
@ -148,85 +149,88 @@ namespace Teknik.Areas.Vault.Controllers
[HttpGet] [HttpGet]
public ActionResult EditVault(string url, string type, string items) public ActionResult EditVault(string url, string type, string items)
{ {
ViewBag.Title = "Edit Vault"; using (TeknikEntities db = new TeknikEntities())
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.Url == url).FirstOrDefault();
if (foundVault != null)
{ {
if (foundVault.User.Username == User.Identity.Name) ViewBag.Title = "Edit Vault";
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.Url == url).FirstOrDefault();
if (foundVault != null)
{ {
ViewBag.Title = "Edit Vault - " + foundVault.Title; if (foundVault.User.Username == User.Identity.Name)
ModifyVaultViewModel model = new ModifyVaultViewModel();
model.CurrentSub = Subdomain;
model.isEdit = true;
model.vaultId = foundVault.VaultId;
model.title = foundVault.Title;
model.description = foundVault.Description;
int index = 0;
// Add all their existing items for the vault
foreach (VaultItem item in foundVault.VaultItems)
{ {
ModifyVaultItemViewModel itemModel = new ModifyVaultItemViewModel(); ViewBag.Title = "Edit Vault - " + foundVault.Title;
itemModel.index = index;
itemModel.isTemplate = false;
if (item.GetType().BaseType == typeof(UploadVaultItem)) ModifyVaultViewModel model = new ModifyVaultViewModel();
{ model.CurrentSub = Subdomain;
UploadVaultItem upload = (UploadVaultItem)item; model.isEdit = true;
itemModel.title = upload.Title; model.vaultId = foundVault.VaultId;
itemModel.description = upload.Description; model.title = foundVault.Title;
itemModel.type = "Upload"; model.description = foundVault.Description;
itemModel.url = upload.Upload.Url;
model.items.Add(itemModel);
index++;
}
else if (item.GetType().BaseType == typeof(PasteVaultItem))
{
PasteVaultItem paste = (PasteVaultItem)item;
itemModel.title = paste.Title;
itemModel.description = paste.Description;
itemModel.type = "Paste";
itemModel.url = paste.Paste.Url;
model.items.Add(itemModel);
index++;
}
}
// If they passed any new items in via the parameters, let's add them int index = 0;
if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(items)) // Add all their existing items for the vault
{ foreach (VaultItem item in foundVault.VaultItems)
string decodedItems = HttpUtility.UrlDecode(items);
string[] allItems = decodedItems.Split(',');
foreach (string newItem in allItems)
{ {
string[] urlInfo = newItem.Split(':'); ModifyVaultItemViewModel itemModel = new ModifyVaultItemViewModel();
string itemId = urlInfo[0]; itemModel.index = index;
string title = string.Empty; itemModel.isTemplate = false;
if (urlInfo.GetUpperBound(0) >= 1)
if (item.GetType().BaseType == typeof(UploadVaultItem))
{ {
// They also passed in the original filename, so let's use it as our title UploadVaultItem upload = (UploadVaultItem)item;
title = urlInfo[1]; itemModel.title = upload.Title;
itemModel.description = upload.Description;
itemModel.type = "Upload";
itemModel.url = upload.Upload.Url;
model.items.Add(itemModel);
index++;
} }
if (IsValidItem(type, itemId)) else if (item.GetType().BaseType == typeof(PasteVaultItem))
{ {
ModifyVaultItemViewModel item = new ModifyVaultItemViewModel(); PasteVaultItem paste = (PasteVaultItem)item;
item.isTemplate = false; itemModel.title = paste.Title;
item.index = index; itemModel.description = paste.Description;
item.title = title; itemModel.type = "Paste";
item.url = itemId; itemModel.url = paste.Paste.Url;
item.type = type; model.items.Add(itemModel);
model.items.Add(item);
index++; index++;
} }
} }
}
return View("~/Areas/Vault/Views/Vault/ModifyVault.cshtml", model); // If they passed any new items in via the parameters, let's add them
if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(items))
{
string decodedItems = HttpUtility.UrlDecode(items);
string[] allItems = decodedItems.Split(',');
foreach (string newItem in allItems)
{
string[] urlInfo = newItem.Split(':');
string itemId = urlInfo[0];
string title = string.Empty;
if (urlInfo.GetUpperBound(0) >= 1)
{
// They also passed in the original filename, so let's use it as our title
title = urlInfo[1];
}
if (IsValidItem(type, itemId))
{
ModifyVaultItemViewModel item = new ModifyVaultItemViewModel();
item.isTemplate = false;
item.index = index;
item.title = title;
item.url = itemId;
item.type = type;
model.items.Add(item);
index++;
}
}
}
return View("~/Areas/Vault/Views/Vault/ModifyVault.cshtml", model);
}
return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http403")); return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
[HttpPost] [HttpPost]
@ -238,97 +242,27 @@ namespace Teknik.Areas.Vault.Controllers
{ {
if (!string.IsNullOrEmpty(model.title)) if (!string.IsNullOrEmpty(model.title))
{ {
Vault.Models.Vault newVault = db.Vaults.Create(); using (TeknikEntities db = new TeknikEntities())
// Create a new ID
string url = StringHelper.RandomString(Config.VaultConfig.UrlLength);
while (db.Vaults.Where(v => v.Url == url).FirstOrDefault() != null)
{ {
url = StringHelper.RandomString(Config.VaultConfig.UrlLength); Vault.Models.Vault newVault = db.Vaults.Create();
} // Create a new ID
newVault.Url = url; string url = StringHelper.RandomString(Config.VaultConfig.UrlLength);
newVault.DateCreated = DateTime.Now; while (db.Vaults.Where(v => v.Url == url).FirstOrDefault() != null)
newVault.Title = model.title;
newVault.Description = model.description;
if (User.Identity.IsAuthenticated)
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
{ {
newVault.UserId = user.UserId; url = StringHelper.RandomString(Config.VaultConfig.UrlLength);
} }
} newVault.Url = url;
newVault.DateCreated = DateTime.Now;
// Add/Verify items newVault.Title = model.title;
if (model.items.Any()) newVault.Description = model.description;
{ if (User.Identity.IsAuthenticated)
foreach (ModifyVaultItemViewModel item in model.items)
{ {
if (IsValidItem(item.type, item.url)) User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
{ {
switch (item.type.ToLower()) newVault.UserId = user.UserId;
{
case "upload":
UploadVaultItem newUpload = new UploadVaultItem();
newUpload.DateAdded = DateTime.Now;
newUpload.Title = item.title;
newUpload.Description = item.description;
newUpload.UploadId = db.Uploads.Where(u => u.Url == item.url).FirstOrDefault().UploadId;
newVault.VaultItems.Add(newUpload);
break;
case "paste":
PasteVaultItem newPaste = new PasteVaultItem();
newPaste.DateAdded = DateTime.Now;
newPaste.Title = item.title;
newPaste.Description = item.description;
newPaste.PasteId = db.Pastes.Where(p => p.Url == item.url).FirstOrDefault().PasteId;
newVault.VaultItems.Add(newPaste);
break;
default:
return Json(new { error = new { message = "You have an invalid item type: " + item.type } });
}
}
else
{
return Json(new { error = new { message = "You have an invalid item URL: " + item.url } });
} }
} }
}
// Add and save the new vault
db.Vaults.Add(newVault);
db.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("v", "Vault.ViewVault", new { id = url }) } });
}
return Json(new { error = new { message = "You must supply a Title" } });
}
return Json(new { error = new { message = "Invalid Parameters" } });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditVault(ModifyVaultViewModel model)
{
if (model != null)
{
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.VaultId == model.vaultId).FirstOrDefault();
if (foundVault != null)
{
if (foundVault.User.Username == User.Identity.Name)
{
foundVault.DateEdited = DateTime.Now;
foundVault.Title = model.title;
foundVault.Description = model.description;
// Clear previous items
List<VaultItem> vaultItems = db.VaultItems.Where(v => v.VaultId == foundVault.VaultId).ToList();
if (vaultItems != null)
{
foreach (VaultItem item in vaultItems)
{
db.VaultItems.Remove(item);
}
}
foundVault.VaultItems.Clear();
// Add/Verify items // Add/Verify items
if (model.items.Any()) if (model.items.Any())
@ -345,7 +279,7 @@ namespace Teknik.Areas.Vault.Controllers
newUpload.Title = item.title; newUpload.Title = item.title;
newUpload.Description = item.description; newUpload.Description = item.description;
newUpload.UploadId = db.Uploads.Where(u => u.Url == item.url).FirstOrDefault().UploadId; newUpload.UploadId = db.Uploads.Where(u => u.Url == item.url).FirstOrDefault().UploadId;
foundVault.VaultItems.Add(newUpload); newVault.VaultItems.Add(newUpload);
break; break;
case "paste": case "paste":
PasteVaultItem newPaste = new PasteVaultItem(); PasteVaultItem newPaste = new PasteVaultItem();
@ -353,7 +287,7 @@ namespace Teknik.Areas.Vault.Controllers
newPaste.Title = item.title; newPaste.Title = item.title;
newPaste.Description = item.description; newPaste.Description = item.description;
newPaste.PasteId = db.Pastes.Where(p => p.Url == item.url).FirstOrDefault().PasteId; newPaste.PasteId = db.Pastes.Where(p => p.Url == item.url).FirstOrDefault().PasteId;
foundVault.VaultItems.Add(newPaste); newVault.VaultItems.Add(newPaste);
break; break;
default: default:
return Json(new { error = new { message = "You have an invalid item type: " + item.type } }); return Json(new { error = new { message = "You have an invalid item type: " + item.type } });
@ -366,14 +300,90 @@ namespace Teknik.Areas.Vault.Controllers
} }
} }
db.Entry(foundVault).State = EntityState.Modified; // Add and save the new vault
db.Vaults.Add(newVault);
db.SaveChanges(); db.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("v", "Vault.ViewVault", new { id = url }) } });
return Json(new { result = new { url = Url.SubRouteUrl("v", "Vault.ViewVault", new { id = foundVault.Url }) } });
} }
return Json(new { error = new { message = "You do not have permission to edit this Vault" } });
} }
return Json(new { error = new { message = "That Vault does not exist" } }); return Json(new { error = new { message = "You must supply a Title" } });
}
return Json(new { error = new { message = "Invalid Parameters" } });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditVault(ModifyVaultViewModel model)
{
if (model != null)
{
using (TeknikEntities db = new TeknikEntities())
{
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.VaultId == model.vaultId).FirstOrDefault();
if (foundVault != null)
{
if (foundVault.User.Username == User.Identity.Name)
{
foundVault.DateEdited = DateTime.Now;
foundVault.Title = model.title;
foundVault.Description = model.description;
// Clear previous items
List<VaultItem> vaultItems = db.VaultItems.Where(v => v.VaultId == foundVault.VaultId).ToList();
if (vaultItems != null)
{
foreach (VaultItem item in vaultItems)
{
db.VaultItems.Remove(item);
}
}
foundVault.VaultItems.Clear();
// Add/Verify items
if (model.items.Any())
{
foreach (ModifyVaultItemViewModel item in model.items)
{
if (IsValidItem(item.type, item.url))
{
switch (item.type.ToLower())
{
case "upload":
UploadVaultItem newUpload = new UploadVaultItem();
newUpload.DateAdded = DateTime.Now;
newUpload.Title = item.title;
newUpload.Description = item.description;
newUpload.UploadId = db.Uploads.Where(u => u.Url == item.url).FirstOrDefault().UploadId;
foundVault.VaultItems.Add(newUpload);
break;
case "paste":
PasteVaultItem newPaste = new PasteVaultItem();
newPaste.DateAdded = DateTime.Now;
newPaste.Title = item.title;
newPaste.Description = item.description;
newPaste.PasteId = db.Pastes.Where(p => p.Url == item.url).FirstOrDefault().PasteId;
foundVault.VaultItems.Add(newPaste);
break;
default:
return Json(new { error = new { message = "You have an invalid item type: " + item.type } });
}
}
else
{
return Json(new { error = new { message = "You have an invalid item URL: " + item.url } });
}
}
}
db.Entry(foundVault).State = EntityState.Modified;
db.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("v", "Vault.ViewVault", new { id = foundVault.Url }) } });
}
return Json(new { error = new { message = "You do not have permission to edit this Vault" } });
}
return Json(new { error = new { message = "That Vault does not exist" } });
}
} }
return Json(new { error = new { message = "Invalid Parameters" } }); return Json(new { error = new { message = "Invalid Parameters" } });
} }
@ -381,19 +391,22 @@ namespace Teknik.Areas.Vault.Controllers
[HttpPost] [HttpPost]
public ActionResult DeleteVault(string url) public ActionResult DeleteVault(string url)
{ {
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.Url == url).FirstOrDefault(); using (TeknikEntities db = new TeknikEntities())
if (foundVault != null)
{ {
if (foundVault.User.Username == User.Identity.Name) Vault.Models.Vault foundVault = db.Vaults.Where(v => v.Url == url).FirstOrDefault();
if (foundVault != null)
{ {
db.Vaults.Remove(foundVault); if (foundVault.User.Username == User.Identity.Name)
db.SaveChanges(); {
db.Vaults.Remove(foundVault);
db.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("vault", "Vault.CreateVault") } }); return Json(new { result = new { url = Url.SubRouteUrl("vault", "Vault.CreateVault") } });
}
return Json(new { error = new { message = "You do not have permission to edit this Vault" } });
} }
return Json(new { error = new { message = "You do not have permission to edit this Vault" } }); return Json(new { error = new { message = "That Vault does not exist" } });
} }
return Json(new { error = new { message = "That Vault does not exist" } });
} }
[HttpPost] [HttpPost]
@ -416,22 +429,25 @@ namespace Teknik.Areas.Vault.Controllers
bool valid = false; bool valid = false;
if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(url)) if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(url))
{ {
switch (type.ToLower()) using (TeknikEntities db = new TeknikEntities())
{ {
case "upload": switch (type.ToLower())
Upload.Models.Upload foundUpload = db.Uploads.Where(u => u.Url == url).FirstOrDefault(); {
if (foundUpload != null) case "upload":
{ Upload.Models.Upload foundUpload = db.Uploads.Where(u => u.Url == url).FirstOrDefault();
valid = true; if (foundUpload != null)
} {
break; valid = true;
case "paste": }
Paste.Models.Paste foundPaste = db.Pastes.Where(p => p.Url == url).FirstOrDefault(); break;
if (foundPaste != null) case "paste":
{ Paste.Models.Paste foundPaste = db.Pastes.Where(p => p.Url == url).FirstOrDefault();
valid = true; if (foundPaste != null)
} {
break; valid = true;
}
break;
}
} }
} }
return valid; return valid;

View File

@ -7,6 +7,9 @@
@Styles.Render("~/Content/vault") @Styles.Render("~/Content/vault")
<script type="text/javascript"> <script type="text/javascript">
var helpURL = '@Url.SubRouteUrl("help", "Help.Markdown")';
var validateItemURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.Action", new { action = "ValidateItem" })';
var modifyVaultURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.Action", new { action = "EditVault" })';
var deleteVaultURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.DeleteVault")'; var deleteVaultURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.DeleteVault")';
</script> </script>

View File

@ -144,81 +144,98 @@ namespace Teknik
protected void Application_Error(object sender, EventArgs e) protected void Application_Error(object sender, EventArgs e)
{ {
// Get the last exception Exception exception = null;
Exception exception = Server.GetLastError(); try
// Clear the response
Response.Clear();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
routeData.DataTokens.Add("area", "Error");
routeData.Values.Add("controller", "Error");
if (httpException == null)
{ {
routeData.Values.Add("action", "Exception"); // Get the last exception
} exception = Server.GetLastError();
else //It's an Http Exception, Let's handle it.
{
switch (httpException.GetHttpCode())
{
case 401:
// Unauthorized.
routeData.Values.Add("action", "Http401");
break;
case 403:
// Forbidden.
routeData.Values.Add("action", "Http403");
break;
case 404:
// Page not found.
routeData.Values.Add("action", "Http404");
break;
case 500:
// Server error.
routeData.Values.Add("action", "Http500");
break;
// Here you can handle Views to other error codes. // Clear the response
// I choose a General error template Response.Clear();
default:
routeData.Values.Add("action", "General");
break;
}
}
// Pass exception details to the target error View. HttpException httpException = exception as HttpException;
routeData.Values.Add("exception", exception);
// Clear the error on server. RouteData routeData = new RouteData();
Server.ClearError(); routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
routeData.DataTokens.Add("area", "Error");
routeData.Values.Add("controller", "Error");
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
// If it is an Ajax request, we should respond with Json data, otherwise redirect
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
string jsonResult = string.Empty;
if (httpException == null) if (httpException == null)
{ {
jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.GetFullMessage(true) } }); routeData.Values.Add("action", "Exception");
}
else //It's an Http Exception, Let's handle it.
{
switch (httpException.GetHttpCode())
{
case 401:
// Unauthorized.
routeData.Values.Add("action", "Http401");
break;
case 403:
// Forbidden.
routeData.Values.Add("action", "Http403");
break;
case 404:
// Page not found.
routeData.Values.Add("action", "Http404");
break;
case 500:
// Server error.
routeData.Values.Add("action", "Http500");
break;
// Here you can handle Views to other error codes.
// I choose a General error template
default:
routeData.Values.Add("action", "General");
break;
}
}
// Pass exception details to the target error View.
routeData.Values.Add("exception", exception);
// Clear the error on server.
Server.ClearError();
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
// If it is an Ajax request, we should respond with Json data, otherwise redirect
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
string jsonResult = string.Empty;
if (httpException == null)
{
jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.GetFullMessage(true) } });
}
else
{
jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.GetFullMessage(true) } });
}
Response.Write(jsonResult);
} }
else else
{ {
jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.GetFullMessage(true) } }); // Call target Controller and pass the routeData.
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
} }
Response.Write(jsonResult);
} }
else catch (Exception ex)
{ {
// Call target Controller and pass the routeData. // Unable to display error, so try to log it
IController errorController = new ErrorController(); try
errorController.Execute(new RequestContext( {
new HttpContextWrapper(Context), routeData)); Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Application_Error", ex);
if (exception != null)
{
Logging.Logger.WriteEntry(Logging.LogLevel.Error, "Exception Thrown", exception);
}
}
catch(Exception) { }
} }
} }
} }

View File

@ -68,16 +68,18 @@ namespace Teknik.Hubs
// If the password is supplied, verify the password // If the password is supplied, verify the password
if (!string.IsNullOrEmpty(password)) if (!string.IsNullOrEmpty(password))
{ {
TeknikEntities db = new TeknikEntities(); using (TeknikEntities db = new TeknikEntities())
User user = UserHelper.GetUser(db, username);
if (user != null)
{ {
Config config = Config.Load(); User user = UserHelper.GetUser(db, username);
success = UserHelper.UserPasswordCorrect(db, config, user, password); if (user != null)
} {
else Config config = Config.Load();
{ success = UserHelper.UserPasswordCorrect(db, config, user, password);
success = false; }
else
{
success = false;
}
} }
} }

View File

@ -234,6 +234,18 @@ function getReadableBandwidthString(bandwidth) {
return Math.max(bandwidth, 0.1).toFixed(1) + byteUnits[i]; return Math.max(bandwidth, 0.1).toFixed(1) + byteUnits[i];
} }
function getReadableFileSizeString(fileSizeInBytes) {
var i = -1;
var byteUnits = [' KB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
do {
fileSizeInBytes = fileSizeInBytes / 1024;
i++;
} while (fileSizeInBytes > 1024);
return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};
function moveUp(item) { function moveUp(item) {
var prev = item.prev(); var prev = item.prev();
if (prev.length == 0) if (prev.length == 0)

View File

@ -11,8 +11,6 @@ namespace Teknik.Security
{ {
public class TeknikPrincipal : ITeknikPrincipal public class TeknikPrincipal : ITeknikPrincipal
{ {
TeknikEntities entities = new TeknikEntities();
private IIdentity _Identity; private IIdentity _Identity;
public IIdentity Identity public IIdentity Identity
{ {
@ -29,7 +27,8 @@ namespace Teknik.Security
{ {
if (m_Info == null && Identity != null && Identity.IsAuthenticated) if (m_Info == null && Identity != null && Identity.IsAuthenticated)
{ {
m_Info = UserHelper.GetUser(entities, Identity.Name); TeknikEntities db = new TeknikEntities();
m_Info = UserHelper.GetUser(db, Identity.Name);
} }
return m_Info; return m_Info;
} }

View File

@ -40,7 +40,7 @@
<forms domain=".teknik.io" protection="All" enableCrossAppRedirects="true" name="TeknikAuth" /> <forms domain=".teknik.io" protection="All" enableCrossAppRedirects="true" name="TeknikAuth" />
</authentication> </authentication>
<compilation debug="true" targetFramework="4.6.2" /> <compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" maxRequestLength="1048576" executionTimeout="3600" relaxedUrlToFileSystemMapping="true" /> <httpRuntime targetFramework="4.6.2" maxRequestLength="5242880" executionTimeout="3600" relaxedUrlToFileSystemMapping="true" />
<pages buffer="true" enableViewState="false" /> <pages buffer="true" enableViewState="false" />
</system.web> </system.web>
<system.webServer> <system.webServer>
@ -123,7 +123,7 @@
<customHeaders> <customHeaders>
<add name="Access-Control-Allow-Credentials" value="true" /> <add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" /> <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Authorization, Accept, Origin, Content-Type, X-Requested-With" /> <add name="Access-Control-Allow-Headers" value="Authorization, Accept, Origin, Content-Type, X-Requested-With, Connection, Transfer-Encoding" />
<add name="strict-transport-security" value="max-age=31536000; includeSubdomains" /> <add name="strict-transport-security" value="max-age=31536000; includeSubdomains" />
</customHeaders> </customHeaders>
</httpProtocol> </httpProtocol>

View File

@ -39,15 +39,16 @@ namespace TeknikStreaming
private void LoadStreams() private void LoadStreams()
{ {
TeknikEntities db = new TeknikEntities(); using (TeknikEntities db = new TeknikEntities())
List<User> users = db.Users.ToList();
if (users != null)
{ {
foreach (User user in users) List<User> users = db.Users.ToList();
if (users != null)
{ {
RtspSource source = new RtspSource(string.Format("TeknikLiveStream_{0}", user.Username), string.Format("rtsp://localhost/live/{0}/stream.amp", user.Username)); foreach (User user in users)
{
RtspSource source = new RtspSource(string.Format("TeknikLiveStream_{0}", user.Username), string.Format("rtsp://localhost/live/{0}/stream.amp", user.Username));
}
} }
} }
} }

View File

@ -43,6 +43,7 @@ namespace Teknik.Utilities
protected override void WriteFile(System.Web.HttpResponseBase response) protected override void WriteFile(System.Web.HttpResponseBase response)
{ {
response.Buffer = bufferOutput; response.Buffer = bufferOutput;
response.BufferOutput = bufferOutput;
responseDelegate(response); responseDelegate(response);
} }
} }

View File

@ -49,26 +49,18 @@ namespace Teknik.Utilities
} }
while (processedBytes > 0 && bytesRemaining > 0); while (processedBytes > 0 && bytesRemaining > 0);
} }
catch (HttpException httpEx)
{
// If we lost connection, that's fine
if (httpEx.ErrorCode == -2147023667)
{
// do nothing
}
else
{
//throw httpEx;
}
}
catch (Exception ex) catch (Exception ex)
{ {
// Don't bother
throw ex; throw ex;
} }
finally finally
{ {
// dispose of file stream // dispose of file stream
stream.Dispose(); if (stream != null)
{
stream.Dispose();
}
} }
} }