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 25KB

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