The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PodcastController.cs 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using Teknik.Areas.Podcast.Models;
  9. using Teknik.Areas.Podcast.ViewModels;
  10. using Teknik.Areas.Users.Utility;
  11. using Teknik.Attributes;
  12. using Teknik.Controllers;
  13. using Teknik.Filters;
  14. using Teknik.Models;
  15. using Teknik.Utilities;
  16. namespace Teknik.Areas.Podcast.Controllers
  17. {
  18. [TeknikAuthorize]
  19. public class PodcastController : DefaultController
  20. {
  21. [TrackPageView]
  22. [AllowAnonymous]
  23. public ActionResult Index()
  24. {
  25. MainViewModel model = new MainViewModel();
  26. model.Title = Config.PodcastConfig.Title;
  27. model.Description = Config.PodcastConfig.Description;
  28. try
  29. {
  30. ViewBag.Title = Config.PodcastConfig.Title + " - " + Config.Title;
  31. ViewBag.Description = Config.PodcastConfig.Description;
  32. bool editor = User.IsInRole("Podcast");
  33. using (TeknikEntities db = new TeknikEntities())
  34. {
  35. var foundPodcasts = db.Podcasts.Where(p => (p.Published || editor)).FirstOrDefault();
  36. if (foundPodcasts != null)
  37. {
  38. model.HasPodcasts = (foundPodcasts != null);
  39. }
  40. else
  41. {
  42. model.Error = true;
  43. model.ErrorMessage = "No Podcasts Available";
  44. }
  45. }
  46. return View("~/Areas/Podcast/Views/Podcast/Main.cshtml", model);
  47. }
  48. catch (Exception ex)
  49. {
  50. model.Error = true;
  51. model.ErrorMessage = ex.Message;
  52. return View("~/Areas/Podcast/Views/Podcast/Main.cshtml", model);
  53. }
  54. }
  55. #region Podcasts
  56. [TrackPageView]
  57. [AllowAnonymous]
  58. public ActionResult View(int episode)
  59. {
  60. PodcastViewModel model = new PodcastViewModel();
  61. // find the podcast specified
  62. bool editor = User.IsInRole("Podcast");
  63. using (TeknikEntities db = new TeknikEntities())
  64. {
  65. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.Episode == episode)).FirstOrDefault();
  66. if (foundPodcast != null)
  67. {
  68. model = new PodcastViewModel(foundPodcast);
  69. ViewBag.Title = model.Title + " - Teknikast - " + Config.Title;
  70. return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model);
  71. }
  72. }
  73. model.Error = true;
  74. model.ErrorMessage = "No Podcasts Available";
  75. return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model);
  76. }
  77. [HttpGet]
  78. [TrackDownload]
  79. [AllowAnonymous]
  80. public ActionResult Download(int episode, string fileName)
  81. {
  82. string path = string.Empty;
  83. string contentType = string.Empty;
  84. long contentLength = 0;
  85. DateTime dateUploaded = new DateTime(1900, 1, 1);
  86. using (TeknikEntities db = new TeknikEntities())
  87. {
  88. // find the podcast specified
  89. var foundPodcast = db.Podcasts.Where(p => (p.Published && p.Episode == episode)).FirstOrDefault();
  90. if (foundPodcast != null)
  91. {
  92. PodcastFile file = foundPodcast.Files.Where(f => f.FileName == fileName).FirstOrDefault();
  93. if (file != null)
  94. {
  95. path = file.Path;
  96. contentType = file.ContentType;
  97. contentLength = file.ContentLength;
  98. fileName = file.FileName;
  99. dateUploaded = foundPodcast.DateEdited;
  100. }
  101. else
  102. {
  103. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  104. }
  105. }
  106. else
  107. {
  108. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  109. }
  110. }
  111. if (System.IO.File.Exists(path))
  112. {
  113. // Are they downloading it by range?
  114. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]); // We do not support ranges
  115. bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]); // Check to see if they have a cache
  116. if (isCached)
  117. {
  118. // The file is cached, let's just 304 this
  119. Response.StatusCode = 304;
  120. Response.StatusDescription = "Not Modified";
  121. Response.AddHeader("Content-Length", "0");
  122. return Content(string.Empty);
  123. }
  124. else
  125. {
  126. long startByte = 0;
  127. long endByte = contentLength - 1;
  128. long length = contentLength;
  129. #region Range Calculation
  130. // check to see if we need to pass a specified range
  131. if (byRange)
  132. {
  133. long anotherStart = startByte;
  134. long anotherEnd = endByte;
  135. string[] arr_split = Request.ServerVariables["HTTP_RANGE"].Split(new char[] { '=' });
  136. string range = arr_split[1];
  137. // Make sure the client hasn't sent us a multibyte range
  138. if (range.IndexOf(",") > -1)
  139. {
  140. // (?) Shoud this be issued here, or should the first
  141. // range be used? Or should the header be ignored and
  142. // we output the whole content?
  143. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  144. throw new HttpException(416, "Requested Range Not Satisfiable");
  145. }
  146. // If the range starts with an '-' we start from the beginning
  147. // If not, we forward the file pointer
  148. // And make sure to get the end byte if spesified
  149. if (range.StartsWith("-"))
  150. {
  151. // The n-number of the last bytes is requested
  152. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  153. }
  154. else
  155. {
  156. arr_split = range.Split(new char[] { '-' });
  157. anotherStart = Convert.ToInt64(arr_split[0]);
  158. long temp = 0;
  159. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
  160. }
  161. /* Check the range and make sure it's treated according to the specs.
  162. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  163. */
  164. // End bytes can not be larger than $end.
  165. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  166. // Validate the requested range and return an error if it's not correct.
  167. if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
  168. {
  169. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  170. throw new HttpException(416, "Requested Range Not Satisfiable");
  171. }
  172. startByte = anotherStart;
  173. endByte = anotherEnd;
  174. length = endByte - startByte + 1; // Calculate new content length
  175. // Ranges are response of 206
  176. Response.StatusCode = 206;
  177. }
  178. #endregion
  179. // Add cache parameters
  180. Response.Cache.SetCacheability(HttpCacheability.Public);
  181. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  182. Response.Cache.SetLastModified(dateUploaded);
  183. // We accept ranges
  184. Response.AddHeader("Accept-Ranges", "0-" + contentLength);
  185. // Notify the client the byte range we'll be outputting
  186. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  187. // Notify the client the content length we'll be outputting
  188. Response.AddHeader("Content-Length", length.ToString());
  189. var cd = new System.Net.Mime.ContentDisposition
  190. {
  191. FileName = fileName,
  192. Inline = true
  193. };
  194. Response.AppendHeader("Content-Disposition", cd.ToString());
  195. FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
  196. // Reset file stream to starting position (or start of range)
  197. fileStream.Seek(startByte, SeekOrigin.Begin);
  198. return new FileGenerateResult(fileName, contentType, (response) => ResponseHelper.StreamToOutput(response, true, fileStream, (int)length, 4 * 1024), false);
  199. }
  200. }
  201. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  202. }
  203. [HttpPost]
  204. [AllowAnonymous]
  205. public ActionResult GetPodcasts(int startPodcastID, int count)
  206. {
  207. using (TeknikEntities db = new TeknikEntities())
  208. {
  209. bool editor = User.IsInRole("Podcast");
  210. var podcasts = db.Podcasts.Where(p => p.Published || editor).OrderByDescending(p => p.DatePosted).Skip(startPodcastID).Take(count).ToList();
  211. List<PodcastViewModel> podcastViews = new List<PodcastViewModel>();
  212. if (podcasts != null)
  213. {
  214. foreach (Models.Podcast podcast in podcasts)
  215. {
  216. podcastViews.Add(new PodcastViewModel(podcast));
  217. }
  218. }
  219. return PartialView("~/Areas/Podcast/Views/Podcast/Podcasts.cshtml", podcastViews);
  220. }
  221. }
  222. [HttpPost]
  223. [AllowAnonymous]
  224. public ActionResult GetPodcastEpisode(int podcastId)
  225. {
  226. using (TeknikEntities db = new TeknikEntities())
  227. {
  228. bool editor = User.IsInRole("Podcast");
  229. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  230. if (foundPodcast != null)
  231. {
  232. return Json(new { result = foundPodcast.Episode });
  233. }
  234. return Json(new { error = "No podcast found" });
  235. }
  236. }
  237. [HttpPost]
  238. [AllowAnonymous]
  239. public ActionResult GetPodcastTitle(int podcastId)
  240. {
  241. using (TeknikEntities db = new TeknikEntities())
  242. {
  243. bool editor = User.IsInRole("Podcast");
  244. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  245. if (foundPodcast != null)
  246. {
  247. return Json(new { result = foundPodcast.Title });
  248. }
  249. return Json(new { error = "No podcast found" });
  250. }
  251. }
  252. [HttpPost]
  253. [AllowAnonymous]
  254. public ActionResult GetPodcastDescription(int podcastId)
  255. {
  256. using (TeknikEntities db = new TeknikEntities())
  257. {
  258. bool editor = User.IsInRole("Podcast");
  259. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  260. if (foundPodcast != null)
  261. {
  262. return Json(new { result = foundPodcast.Description });
  263. }
  264. return Json(new { error = "No podcast found" });
  265. }
  266. }
  267. [HttpPost]
  268. [AllowAnonymous]
  269. public ActionResult GetPodcastFiles(int podcastId)
  270. {
  271. using (TeknikEntities db = new TeknikEntities())
  272. {
  273. bool editor = User.IsInRole("Podcast");
  274. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  275. if (foundPodcast != null)
  276. {
  277. List<object> files = new List<object>();
  278. foreach (PodcastFile file in foundPodcast.Files)
  279. {
  280. object fileObj = new
  281. {
  282. name = file.FileName,
  283. id = file.PodcastFileId
  284. };
  285. files.Add(fileObj);
  286. }
  287. return Json(new { result = new { files = files } });
  288. }
  289. return Json(new { error = "No podcast found" });
  290. }
  291. }
  292. [HttpPost]
  293. public ActionResult CreatePodcast(int episode, string title, string description)
  294. {
  295. if (ModelState.IsValid)
  296. {
  297. if (User.IsInRole("Podcast"))
  298. {
  299. using (TeknikEntities db = new TeknikEntities())
  300. {
  301. // Grab the next episode number
  302. Models.Podcast lastPod = db.Podcasts.Where(p => p.Episode == episode).FirstOrDefault();
  303. if (lastPod == null)
  304. {
  305. // Create the podcast object
  306. Models.Podcast podcast = db.Podcasts.Create();
  307. podcast.Episode = episode;
  308. podcast.Title = title;
  309. podcast.Description = description;
  310. podcast.DatePosted = DateTime.Now;
  311. podcast.DatePublished = DateTime.Now;
  312. podcast.DateEdited = DateTime.Now;
  313. podcast.Files = SaveFiles(Request.Files, episode);
  314. db.Podcasts.Add(podcast);
  315. db.SaveChanges();
  316. return Json(new { result = true });
  317. }
  318. return Json(new { error = "That episode already exists" });
  319. }
  320. }
  321. return Json(new { error = "You don't have permission to create a podcast" });
  322. }
  323. return Json(new { error = "No podcast created" });
  324. }
  325. [HttpPost]
  326. public ActionResult EditPodcast(int podcastId, int episode, string title, string description, string fileIds)
  327. {
  328. if (ModelState.IsValid)
  329. {
  330. if (User.IsInRole("Podcast"))
  331. {
  332. using (TeknikEntities db = new TeknikEntities())
  333. {
  334. Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
  335. if (podcast != null)
  336. {
  337. if (db.Podcasts.Where(p => p.Episode != episode).FirstOrDefault() == null || podcast.Episode == episode)
  338. {
  339. podcast.Episode = episode;
  340. podcast.Title = title;
  341. podcast.Description = description;
  342. podcast.DateEdited = DateTime.Now;
  343. // Remove any files not in fileIds
  344. List<string> fileIdList = new List<string>();
  345. if (!string.IsNullOrEmpty(fileIds))
  346. {
  347. fileIdList = fileIds.Split(',').ToList();
  348. }
  349. for (int i = 0; i < podcast.Files.Count; i++)
  350. {
  351. PodcastFile curFile = podcast.Files.ElementAt(i);
  352. if (!fileIdList.Exists(id => id == curFile.PodcastFileId.ToString()))
  353. {
  354. if (System.IO.File.Exists(curFile.Path))
  355. {
  356. System.IO.File.Delete(curFile.Path);
  357. }
  358. db.PodcastFiles.Remove(curFile);
  359. podcast.Files.Remove(curFile);
  360. }
  361. }
  362. // Add any new files
  363. List<PodcastFile> newFiles = SaveFiles(Request.Files, episode);
  364. foreach (PodcastFile file in newFiles)
  365. {
  366. podcast.Files.Add(file);
  367. }
  368. // Save podcast
  369. db.Entry(podcast).State = EntityState.Modified;
  370. db.SaveChanges();
  371. return Json(new { result = true });
  372. }
  373. return Json(new { error = "That episode already exists" });
  374. }
  375. return Json(new { error = "No podcast found" });
  376. }
  377. }
  378. return Json(new { error = "You don't have permission to edit this podcast" });
  379. }
  380. return Json(new { error = "Invalid Inputs" });
  381. }
  382. [HttpPost]
  383. public ActionResult PublishPodcast(int podcastId, bool publish)
  384. {
  385. if (ModelState.IsValid)
  386. {
  387. if (User.IsInRole("Podcast"))
  388. {
  389. using (TeknikEntities db = new TeknikEntities())
  390. {
  391. Models.Podcast podcast = db.Podcasts.Find(podcastId);
  392. if (podcast != null)
  393. {
  394. podcast.Published = publish;
  395. if (publish)
  396. podcast.DatePublished = DateTime.Now;
  397. db.Entry(podcast).State = EntityState.Modified;
  398. db.SaveChanges();
  399. return Json(new { result = true });
  400. }
  401. return Json(new { error = "No podcast found" });
  402. }
  403. }
  404. return Json(new { error = "You don't have permission to publish this podcast" });
  405. }
  406. return Json(new { error = "Invalid Inputs" });
  407. }
  408. [HttpPost]
  409. public ActionResult DeletePodcast(int podcastId)
  410. {
  411. if (ModelState.IsValid)
  412. {
  413. if (User.IsInRole("Podcast"))
  414. {
  415. using (TeknikEntities db = new TeknikEntities())
  416. {
  417. Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
  418. if (podcast != null)
  419. {
  420. foreach (PodcastFile file in podcast.Files)
  421. {
  422. System.IO.File.Delete(file.Path);
  423. }
  424. db.Podcasts.Remove(podcast);
  425. db.SaveChanges();
  426. return Json(new { result = true });
  427. }
  428. return Json(new { error = "No podcast found" });
  429. }
  430. }
  431. return Json(new { error = "You don't have permission to delete this podcast" });
  432. }
  433. return Json(new { error = "Invalid Inputs" });
  434. }
  435. #endregion
  436. #region Comments
  437. [HttpPost]
  438. [AllowAnonymous]
  439. public ActionResult GetComments(int podcastId, int startCommentID, int count)
  440. {
  441. using (TeknikEntities db = new TeknikEntities())
  442. {
  443. var comments = db.PodcastComments.Where(p => (p.PodcastId == podcastId)).OrderByDescending(p => p.DatePosted).Skip(startCommentID).Take(count).ToList();
  444. List<CommentViewModel> commentViews = new List<CommentViewModel>();
  445. if (comments != null)
  446. {
  447. foreach (PodcastComment comment in comments)
  448. {
  449. commentViews.Add(new CommentViewModel(comment));
  450. }
  451. }
  452. return PartialView("~/Areas/Podcast/Views/Podcast/Comments.cshtml", commentViews);
  453. }
  454. }
  455. [HttpPost]
  456. [AllowAnonymous]
  457. public ActionResult GetCommentArticle(int commentID)
  458. {
  459. using (TeknikEntities db = new TeknikEntities())
  460. {
  461. PodcastComment comment = db.PodcastComments.Where(p => (p.PodcastCommentId == commentID)).FirstOrDefault();
  462. if (comment != null)
  463. {
  464. return Json(new { result = comment.Article });
  465. }
  466. return Json(new { error = "No article found" });
  467. }
  468. }
  469. [HttpPost]
  470. public ActionResult CreateComment(int podcastId, string article)
  471. {
  472. if (ModelState.IsValid)
  473. {
  474. using (TeknikEntities db = new TeknikEntities())
  475. {
  476. if (db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault() != null)
  477. {
  478. PodcastComment comment = db.PodcastComments.Create();
  479. comment.PodcastId = podcastId;
  480. comment.UserId = UserHelper.GetUser(db, User.Identity.Name).UserId;
  481. comment.Article = article;
  482. comment.DatePosted = DateTime.Now;
  483. comment.DateEdited = DateTime.Now;
  484. db.PodcastComments.Add(comment);
  485. db.SaveChanges();
  486. return Json(new { result = true });
  487. }
  488. return Json(new { error = "That podcast does not exist" });
  489. }
  490. }
  491. return Json(new { error = "Invalid Parameters" });
  492. }
  493. [HttpPost]
  494. public ActionResult EditComment(int commentID, string article)
  495. {
  496. if (ModelState.IsValid)
  497. {
  498. using (TeknikEntities db = new TeknikEntities())
  499. {
  500. PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
  501. if (comment != null)
  502. {
  503. if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
  504. {
  505. comment.Article = article;
  506. comment.DateEdited = DateTime.Now;
  507. db.Entry(comment).State = EntityState.Modified;
  508. db.SaveChanges();
  509. return Json(new { result = true });
  510. }
  511. return Json(new { error = "You don't have permission to edit this comment" });
  512. }
  513. return Json(new { error = "No comment found" });
  514. }
  515. }
  516. return Json(new { error = "Invalid Parameters" });
  517. }
  518. [HttpPost]
  519. public ActionResult DeleteComment(int commentID)
  520. {
  521. if (ModelState.IsValid)
  522. {
  523. using (TeknikEntities db = new TeknikEntities())
  524. {
  525. PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
  526. if (comment != null)
  527. {
  528. if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
  529. {
  530. db.PodcastComments.Remove(comment);
  531. db.SaveChanges();
  532. return Json(new { result = true });
  533. }
  534. return Json(new { error = "You don't have permission to delete this comment" });
  535. }
  536. return Json(new { error = "No comment found" });
  537. }
  538. }
  539. return Json(new { error = "Invalid Parameters" });
  540. }
  541. #endregion
  542. public List<PodcastFile> SaveFiles(HttpFileCollectionBase files, int episode)
  543. {
  544. List<PodcastFile> podFiles = new List<PodcastFile>();
  545. if (files.Count > 0)
  546. {
  547. for (int i = 0; i < files.Count; i++)
  548. {
  549. HttpPostedFileBase file = files[i];
  550. int fileSize = file.ContentLength;
  551. string fileName = file.FileName;
  552. string fileExt = Path.GetExtension(fileName);
  553. if (!Directory.Exists(Config.PodcastConfig.PodcastDirectory))
  554. {
  555. Directory.CreateDirectory(Config.PodcastConfig.PodcastDirectory);
  556. }
  557. string newName = string.Format("Teknikast_Episode_{0}{1}", episode, fileExt);
  558. int index = 1;
  559. while (System.IO.File.Exists(Path.Combine(Config.PodcastConfig.PodcastDirectory, newName)))
  560. {
  561. newName = string.Format("Teknikast_Episode_{0} ({1}){2}", episode, index, fileExt);
  562. index++;
  563. }
  564. string fullPath = Path.Combine(Config.PodcastConfig.PodcastDirectory, newName);
  565. PodcastFile podFile = new PodcastFile();
  566. podFile.Path = fullPath;
  567. podFile.FileName = newName;
  568. podFile.ContentType = file.ContentType;
  569. podFile.ContentLength = file.ContentLength;
  570. podFiles.Add(podFile);
  571. file.SaveAs(fullPath);
  572. }
  573. }
  574. return podFiles;
  575. }
  576. }
  577. }