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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. [AllowAnonymous]
  79. public ActionResult Download(int episode, string fileName)
  80. {
  81. string path = string.Empty;
  82. string contentType = string.Empty;
  83. long contentLength = 0;
  84. DateTime dateUploaded = new DateTime(1900, 1, 1);
  85. using (TeknikEntities db = new TeknikEntities())
  86. {
  87. // find the podcast specified
  88. var foundPodcast = db.Podcasts.Where(p => (p.Published && p.Episode == episode)).FirstOrDefault();
  89. if (foundPodcast != null)
  90. {
  91. PodcastFile file = foundPodcast.Files.Where(f => f.FileName == fileName).FirstOrDefault();
  92. if (file != null)
  93. {
  94. path = file.Path;
  95. contentType = file.ContentType;
  96. contentLength = file.ContentLength;
  97. fileName = file.FileName;
  98. dateUploaded = foundPodcast.DateEdited;
  99. }
  100. else
  101. {
  102. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  103. }
  104. }
  105. else
  106. {
  107. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  108. }
  109. }
  110. if (System.IO.File.Exists(path))
  111. {
  112. // Are they downloading it by range?
  113. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]); // We do not support ranges
  114. bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]); // Check to see if they have a cache
  115. if (isCached)
  116. {
  117. // The file is cached, let's just 304 this
  118. Response.StatusCode = 304;
  119. Response.StatusDescription = "Not Modified";
  120. Response.AddHeader("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.ServerVariables["HTTP_RANGE"].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.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  143. throw new HttpException(416, "Requested Range Not Satisfiable");
  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.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  169. throw new HttpException(416, "Requested Range Not Satisfiable");
  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. // Add cache parameters
  179. Response.Cache.SetCacheability(HttpCacheability.Public);
  180. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  181. Response.Cache.SetLastModified(dateUploaded);
  182. // We accept ranges
  183. Response.AddHeader("Accept-Ranges", "0-" + contentLength);
  184. // Notify the client the byte range we'll be outputting
  185. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  186. // Notify the client the content length we'll be outputting
  187. Response.AddHeader("Content-Length", length.ToString());
  188. var cd = new System.Net.Mime.ContentDisposition
  189. {
  190. FileName = fileName,
  191. Inline = true
  192. };
  193. Response.AppendHeader("Content-Disposition", cd.ToString());
  194. FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
  195. // Reset file stream to starting position (or start of range)
  196. fileStream.Seek(startByte, SeekOrigin.Begin);
  197. return new FileGenerateResult(fileName, contentType, (response) => ResponseHelper.StreamToOutput(response, true, fileStream, (int)length, 4 * 1024), false);
  198. }
  199. }
  200. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  201. }
  202. [HttpPost]
  203. [AllowAnonymous]
  204. public ActionResult GetPodcasts(int startPodcastID, int count)
  205. {
  206. using (TeknikEntities db = new TeknikEntities())
  207. {
  208. bool editor = User.IsInRole("Podcast");
  209. var podcasts = db.Podcasts.Where(p => p.Published || editor).OrderByDescending(p => p.DatePosted).Skip(startPodcastID).Take(count).ToList();
  210. List<PodcastViewModel> podcastViews = new List<PodcastViewModel>();
  211. if (podcasts != null)
  212. {
  213. foreach (Models.Podcast podcast in podcasts)
  214. {
  215. podcastViews.Add(new PodcastViewModel(podcast));
  216. }
  217. }
  218. return PartialView("~/Areas/Podcast/Views/Podcast/Podcasts.cshtml", podcastViews);
  219. }
  220. }
  221. [HttpPost]
  222. [AllowAnonymous]
  223. public ActionResult GetPodcastEpisode(int podcastId)
  224. {
  225. using (TeknikEntities db = new TeknikEntities())
  226. {
  227. bool editor = User.IsInRole("Podcast");
  228. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  229. if (foundPodcast != null)
  230. {
  231. return Json(new { result = foundPodcast.Episode });
  232. }
  233. return Json(new { error = "No podcast found" });
  234. }
  235. }
  236. [HttpPost]
  237. [AllowAnonymous]
  238. public ActionResult GetPodcastTitle(int podcastId)
  239. {
  240. using (TeknikEntities db = new TeknikEntities())
  241. {
  242. bool editor = User.IsInRole("Podcast");
  243. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  244. if (foundPodcast != null)
  245. {
  246. return Json(new { result = foundPodcast.Title });
  247. }
  248. return Json(new { error = "No podcast found" });
  249. }
  250. }
  251. [HttpPost]
  252. [AllowAnonymous]
  253. public ActionResult GetPodcastDescription(int podcastId)
  254. {
  255. using (TeknikEntities db = new TeknikEntities())
  256. {
  257. bool editor = User.IsInRole("Podcast");
  258. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  259. if (foundPodcast != null)
  260. {
  261. return Json(new { result = foundPodcast.Description });
  262. }
  263. return Json(new { error = "No podcast found" });
  264. }
  265. }
  266. [HttpPost]
  267. [AllowAnonymous]
  268. public ActionResult GetPodcastFiles(int podcastId)
  269. {
  270. using (TeknikEntities db = new TeknikEntities())
  271. {
  272. bool editor = User.IsInRole("Podcast");
  273. var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
  274. if (foundPodcast != null)
  275. {
  276. List<object> files = new List<object>();
  277. foreach (PodcastFile file in foundPodcast.Files)
  278. {
  279. object fileObj = new
  280. {
  281. name = file.FileName,
  282. id = file.PodcastFileId
  283. };
  284. files.Add(fileObj);
  285. }
  286. return Json(new { result = new { files = files } });
  287. }
  288. return Json(new { error = "No podcast found" });
  289. }
  290. }
  291. [HttpPost]
  292. public ActionResult CreatePodcast(int episode, string title, string description)
  293. {
  294. if (ModelState.IsValid)
  295. {
  296. if (User.IsInRole("Podcast"))
  297. {
  298. using (TeknikEntities db = new TeknikEntities())
  299. {
  300. // Grab the next episode number
  301. Models.Podcast lastPod = db.Podcasts.Where(p => p.Episode == episode).FirstOrDefault();
  302. if (lastPod == null)
  303. {
  304. // Create the podcast object
  305. Models.Podcast podcast = db.Podcasts.Create();
  306. podcast.Episode = episode;
  307. podcast.Title = title;
  308. podcast.Description = description;
  309. podcast.DatePosted = DateTime.Now;
  310. podcast.DatePublished = DateTime.Now;
  311. podcast.DateEdited = DateTime.Now;
  312. podcast.Files = SaveFiles(Request.Files, episode);
  313. db.Podcasts.Add(podcast);
  314. db.SaveChanges();
  315. return Json(new { result = true });
  316. }
  317. return Json(new { error = "That episode already exists" });
  318. }
  319. }
  320. return Json(new { error = "You don't have permission to create a podcast" });
  321. }
  322. return Json(new { error = "No podcast created" });
  323. }
  324. [HttpPost]
  325. public ActionResult EditPodcast(int podcastId, int episode, string title, string description, string fileIds)
  326. {
  327. if (ModelState.IsValid)
  328. {
  329. if (User.IsInRole("Podcast"))
  330. {
  331. using (TeknikEntities db = new TeknikEntities())
  332. {
  333. Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
  334. if (podcast != null)
  335. {
  336. if (db.Podcasts.Where(p => p.Episode != episode).FirstOrDefault() == null || podcast.Episode == episode)
  337. {
  338. podcast.Episode = episode;
  339. podcast.Title = title;
  340. podcast.Description = description;
  341. podcast.DateEdited = DateTime.Now;
  342. // Remove any files not in fileIds
  343. List<string> fileIdList = new List<string>();
  344. if (!string.IsNullOrEmpty(fileIds))
  345. {
  346. fileIdList = fileIds.Split(',').ToList();
  347. }
  348. for (int i = 0; i < podcast.Files.Count; i++)
  349. {
  350. PodcastFile curFile = podcast.Files.ElementAt(i);
  351. if (!fileIdList.Exists(id => id == curFile.PodcastFileId.ToString()))
  352. {
  353. if (System.IO.File.Exists(curFile.Path))
  354. {
  355. System.IO.File.Delete(curFile.Path);
  356. }
  357. db.PodcastFiles.Remove(curFile);
  358. podcast.Files.Remove(curFile);
  359. }
  360. }
  361. // Add any new files
  362. List<PodcastFile> newFiles = SaveFiles(Request.Files, episode);
  363. foreach (PodcastFile file in newFiles)
  364. {
  365. podcast.Files.Add(file);
  366. }
  367. // Save podcast
  368. db.Entry(podcast).State = EntityState.Modified;
  369. db.SaveChanges();
  370. return Json(new { result = true });
  371. }
  372. return Json(new { error = "That episode already exists" });
  373. }
  374. return Json(new { error = "No podcast found" });
  375. }
  376. }
  377. return Json(new { error = "You don't have permission to edit this podcast" });
  378. }
  379. return Json(new { error = "Invalid Inputs" });
  380. }
  381. [HttpPost]
  382. public ActionResult PublishPodcast(int podcastId, bool publish)
  383. {
  384. if (ModelState.IsValid)
  385. {
  386. if (User.IsInRole("Podcast"))
  387. {
  388. using (TeknikEntities db = new TeknikEntities())
  389. {
  390. Models.Podcast podcast = db.Podcasts.Find(podcastId);
  391. if (podcast != null)
  392. {
  393. podcast.Published = publish;
  394. if (publish)
  395. podcast.DatePublished = DateTime.Now;
  396. db.Entry(podcast).State = EntityState.Modified;
  397. db.SaveChanges();
  398. return Json(new { result = true });
  399. }
  400. return Json(new { error = "No podcast found" });
  401. }
  402. }
  403. return Json(new { error = "You don't have permission to publish this podcast" });
  404. }
  405. return Json(new { error = "Invalid Inputs" });
  406. }
  407. [HttpPost]
  408. public ActionResult DeletePodcast(int podcastId)
  409. {
  410. if (ModelState.IsValid)
  411. {
  412. if (User.IsInRole("Podcast"))
  413. {
  414. using (TeknikEntities db = new TeknikEntities())
  415. {
  416. Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
  417. if (podcast != null)
  418. {
  419. foreach (PodcastFile file in podcast.Files)
  420. {
  421. System.IO.File.Delete(file.Path);
  422. }
  423. db.Podcasts.Remove(podcast);
  424. db.SaveChanges();
  425. return Json(new { result = true });
  426. }
  427. return Json(new { error = "No podcast found" });
  428. }
  429. }
  430. return Json(new { error = "You don't have permission to delete this podcast" });
  431. }
  432. return Json(new { error = "Invalid Inputs" });
  433. }
  434. #endregion
  435. #region Comments
  436. [HttpPost]
  437. [AllowAnonymous]
  438. public ActionResult GetComments(int podcastId, int startCommentID, int count)
  439. {
  440. using (TeknikEntities db = new TeknikEntities())
  441. {
  442. var comments = db.PodcastComments.Where(p => (p.PodcastId == podcastId)).OrderByDescending(p => p.DatePosted).Skip(startCommentID).Take(count).ToList();
  443. List<CommentViewModel> commentViews = new List<CommentViewModel>();
  444. if (comments != null)
  445. {
  446. foreach (PodcastComment comment in comments)
  447. {
  448. commentViews.Add(new CommentViewModel(comment));
  449. }
  450. }
  451. return PartialView("~/Areas/Podcast/Views/Podcast/Comments.cshtml", commentViews);
  452. }
  453. }
  454. [HttpPost]
  455. [AllowAnonymous]
  456. public ActionResult GetCommentArticle(int commentID)
  457. {
  458. using (TeknikEntities db = new TeknikEntities())
  459. {
  460. PodcastComment comment = db.PodcastComments.Where(p => (p.PodcastCommentId == commentID)).FirstOrDefault();
  461. if (comment != null)
  462. {
  463. return Json(new { result = comment.Article });
  464. }
  465. return Json(new { error = "No article found" });
  466. }
  467. }
  468. [HttpPost]
  469. public ActionResult CreateComment(int podcastId, string article)
  470. {
  471. if (ModelState.IsValid)
  472. {
  473. using (TeknikEntities db = new TeknikEntities())
  474. {
  475. if (db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault() != null)
  476. {
  477. PodcastComment comment = db.PodcastComments.Create();
  478. comment.PodcastId = podcastId;
  479. comment.UserId = UserHelper.GetUser(db, User.Identity.Name).UserId;
  480. comment.Article = article;
  481. comment.DatePosted = DateTime.Now;
  482. comment.DateEdited = DateTime.Now;
  483. db.PodcastComments.Add(comment);
  484. db.SaveChanges();
  485. return Json(new { result = true });
  486. }
  487. return Json(new { error = "That podcast does not exist" });
  488. }
  489. }
  490. return Json(new { error = "Invalid Parameters" });
  491. }
  492. [HttpPost]
  493. public ActionResult EditComment(int commentID, string article)
  494. {
  495. if (ModelState.IsValid)
  496. {
  497. using (TeknikEntities db = new TeknikEntities())
  498. {
  499. PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
  500. if (comment != null)
  501. {
  502. if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
  503. {
  504. comment.Article = article;
  505. comment.DateEdited = DateTime.Now;
  506. db.Entry(comment).State = EntityState.Modified;
  507. db.SaveChanges();
  508. return Json(new { result = true });
  509. }
  510. return Json(new { error = "You don't have permission to edit this comment" });
  511. }
  512. return Json(new { error = "No comment found" });
  513. }
  514. }
  515. return Json(new { error = "Invalid Parameters" });
  516. }
  517. [HttpPost]
  518. public ActionResult DeleteComment(int commentID)
  519. {
  520. if (ModelState.IsValid)
  521. {
  522. using (TeknikEntities db = new TeknikEntities())
  523. {
  524. PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
  525. if (comment != null)
  526. {
  527. if (comment.User.Username == User.Identity.Name || User.IsInRole("Admin"))
  528. {
  529. db.PodcastComments.Remove(comment);
  530. db.SaveChanges();
  531. return Json(new { result = true });
  532. }
  533. return Json(new { error = "You don't have permission to delete this comment" });
  534. }
  535. return Json(new { error = "No comment found" });
  536. }
  537. }
  538. return Json(new { error = "Invalid Parameters" });
  539. }
  540. #endregion
  541. public List<PodcastFile> SaveFiles(HttpFileCollectionBase files, int episode)
  542. {
  543. List<PodcastFile> podFiles = new List<PodcastFile>();
  544. if (files.Count > 0)
  545. {
  546. for (int i = 0; i < files.Count; i++)
  547. {
  548. HttpPostedFileBase file = files[i];
  549. int fileSize = file.ContentLength;
  550. string fileName = file.FileName;
  551. string fileExt = Path.GetExtension(fileName);
  552. if (!Directory.Exists(Config.PodcastConfig.PodcastDirectory))
  553. {
  554. Directory.CreateDirectory(Config.PodcastConfig.PodcastDirectory);
  555. }
  556. string newName = string.Format("Teknikast_Episode_{0}{1}", episode, fileExt);
  557. int index = 1;
  558. while (System.IO.File.Exists(Path.Combine(Config.PodcastConfig.PodcastDirectory, newName)))
  559. {
  560. newName = string.Format("Teknikast_Episode_{0} ({1}){2}", episode, index, fileExt);
  561. index++;
  562. }
  563. string fullPath = Path.Combine(Config.PodcastConfig.PodcastDirectory, newName);
  564. PodcastFile podFile = new PodcastFile();
  565. podFile.Path = fullPath;
  566. podFile.FileName = newName;
  567. podFile.ContentType = file.ContentType;
  568. podFile.ContentLength = file.ContentLength;
  569. podFiles.Add(podFile);
  570. file.SaveAs(fullPath);
  571. }
  572. }
  573. return podFiles;
  574. }
  575. }
  576. }