The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
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.

APIv1Controller.cs 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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.Upload;
  9. using Teknik.Areas.Paste;
  10. using Teknik.Controllers;
  11. using Teknik.Utilities;
  12. using Teknik.Models;
  13. using System.Text;
  14. using Teknik.Areas.Shortener.Models;
  15. using nClam;
  16. using Teknik.Filters;
  17. using Teknik.Areas.API.Models;
  18. using Teknik.Areas.Users.Models;
  19. using Teknik.Areas.Users.Utility;
  20. namespace Teknik.Areas.API.Controllers
  21. {
  22. public class APIv1Controller : DefaultController
  23. {
  24. private TeknikEntities db = new TeknikEntities();
  25. [AllowAnonymous]
  26. public ActionResult Index()
  27. {
  28. return Redirect(Url.SubRouteUrl("help", "Help.Topic", new { topic = "API" }));
  29. }
  30. [HttpPost]
  31. [AllowAnonymous]
  32. [TrackPageView]
  33. public ActionResult Upload(APIv1UploadModel model)
  34. {
  35. try
  36. {
  37. if (model.file != null)
  38. {
  39. if (model.file.ContentLength <= Config.UploadConfig.MaxUploadSize)
  40. {
  41. // convert file to bytes
  42. byte[] fileData = null;
  43. string fileExt = Path.GetExtension(model.file.FileName);
  44. int contentLength = model.file.ContentLength;
  45. using (var binaryReader = new BinaryReader(model.file.InputStream))
  46. {
  47. fileData = binaryReader.ReadBytes(model.file.ContentLength);
  48. }
  49. // Scan the file to detect a virus
  50. if (Config.UploadConfig.VirusScanEnable)
  51. {
  52. byte[] scanData = fileData;
  53. // If it was encrypted client side, decrypt it
  54. if (!model.encrypt && model.key != null)
  55. {
  56. // If the IV is set, and Key is set, then decrypt it
  57. if (!string.IsNullOrEmpty(model.key) && !string.IsNullOrEmpty(model.iv))
  58. {
  59. // Decrypt the data
  60. scanData = AES.Decrypt(scanData, model.key, model.iv);
  61. }
  62. }
  63. ClamClient clam = new ClamClient(Config.UploadConfig.ClamServer, Config.UploadConfig.ClamPort);
  64. clam.MaxStreamSize = Config.UploadConfig.MaxUploadSize;
  65. ClamScanResult scanResult = clam.SendAndScanFile(scanData);
  66. switch (scanResult.Result)
  67. {
  68. case ClamScanResults.Clean:
  69. break;
  70. case ClamScanResults.VirusDetected:
  71. return Json(new { error = new { message = string.Format("Virus Detected: {0}. As per our <a href=\"{1}\">Terms of Service</a>, Viruses are not permited.", scanResult.InfectedFiles.First().VirusName, Url.SubRouteUrl("tos", "TOS.Index")) } });
  72. case ClamScanResults.Error:
  73. break;
  74. case ClamScanResults.Unknown:
  75. break;
  76. }
  77. }
  78. // Need to grab the contentType if it's empty
  79. if (string.IsNullOrEmpty(model.contentType))
  80. {
  81. model.contentType = (string.IsNullOrEmpty(model.file.ContentType)) ? "application/octet-stream" : model.file.ContentType;
  82. }
  83. // Initialize the key size and block size if empty
  84. if (model.keySize <= 0)
  85. model.keySize = Config.UploadConfig.KeySize;
  86. if (model.blockSize <= 0)
  87. model.blockSize = Config.UploadConfig.BlockSize;
  88. byte[] data = null;
  89. // If they want us to encrypt the file first, do that here
  90. if (model.encrypt)
  91. {
  92. // Generate key and iv if empty
  93. if (string.IsNullOrEmpty(model.key))
  94. {
  95. model.key = StringHelper.RandomString(model.keySize / 8);
  96. }
  97. if (string.IsNullOrEmpty(model.iv))
  98. {
  99. model.iv = StringHelper.RandomString(model.blockSize / 8);
  100. }
  101. data = AES.Encrypt(fileData, model.key, model.iv);
  102. if (data == null || data.Length <= 0)
  103. {
  104. return Json(new { error = new { message = "Unable to encrypt file" } });
  105. }
  106. }
  107. // Save the file data
  108. Upload.Models.Upload upload = Uploader.SaveFile(db, Config, (model.encrypt) ? data : fileData, model.contentType, contentLength, fileExt, model.iv, (model.saveKey) ? model.key : null, model.keySize, model.blockSize);
  109. if (upload != null)
  110. {
  111. // Associate this with the user if they provided an auth key
  112. if (!string.IsNullOrEmpty(model.authToken))
  113. {
  114. User foundUser = UserHelper.GetUserFromToken(db, Config, model.authToken);
  115. if (foundUser != null)
  116. {
  117. upload.UserId = foundUser.UserId;
  118. db.Entry(upload).State = EntityState.Modified;
  119. db.SaveChanges();
  120. }
  121. }
  122. // Generate delete key if asked to
  123. if (model.genDeletionKey)
  124. {
  125. string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
  126. upload.DeleteKey = delKey;
  127. db.Entry(upload).State = EntityState.Modified;
  128. db.SaveChanges();
  129. }
  130. // Pull all the information together
  131. string fullUrl = Url.SubRouteUrl("upload", "Upload.Download", new { file = upload.Url });
  132. var returnData = new
  133. {
  134. url = (model.saveKey || string.IsNullOrEmpty(model.key)) ? fullUrl : fullUrl + "#" + model.key,
  135. fileName = upload.Url,
  136. contentType = model.contentType,
  137. contentLength = contentLength,
  138. key = model.key,
  139. keySize = model.keySize,
  140. iv = model.iv,
  141. blockSize = model.blockSize,
  142. deletionKey = upload.DeleteKey
  143. };
  144. return Json(new { result = returnData });
  145. }
  146. return Json(new { error = new { message = "Unable to save file" } });
  147. }
  148. else
  149. {
  150. return Json(new { error = new { message = "File Too Large" } });
  151. }
  152. }
  153. return Json(new { error = new { message = "Invalid Upload Request" } });
  154. }
  155. catch(Exception ex)
  156. {
  157. return Json(new { error = new { message = "Exception: " + ex.Message } });
  158. }
  159. }
  160. [HttpPost]
  161. [AllowAnonymous]
  162. [TrackPageView]
  163. public ActionResult Paste(APIv1PasteModel model)
  164. {
  165. try
  166. {
  167. if (model != null && model.code != null)
  168. {
  169. Paste.Models.Paste paste = PasteHelper.CreatePaste(model.code, model.title, model.syntax, model.expireUnit, model.expireLength, model.password, model.hide);
  170. // Associate this with the user if they provided an auth key
  171. if (!string.IsNullOrEmpty(model.authToken))
  172. {
  173. User foundUser = UserHelper.GetUserFromToken(db, Config, model.authToken);
  174. if (foundUser != null)
  175. {
  176. paste.UserId = foundUser.UserId;
  177. }
  178. }
  179. db.Pastes.Add(paste);
  180. db.SaveChanges();
  181. return Json(new
  182. {
  183. result = new
  184. {
  185. id = paste.Url,
  186. url = Url.SubRouteUrl("paste", "Paste.View", new { type = "Full", url = paste.Url, password = model.password }),
  187. title = paste.Title,
  188. syntax = paste.Syntax,
  189. expiration = paste.ExpireDate,
  190. password = model.password
  191. }
  192. });
  193. }
  194. return Json(new { error = new { message = "Invalid Paste Request" } });
  195. }
  196. catch (Exception ex)
  197. {
  198. return Json(new { error = new { message = "Exception: " + ex.Message } });
  199. }
  200. }
  201. [HttpPost]
  202. [AllowAnonymous]
  203. [TrackPageView]
  204. public ActionResult Shorten(APIv1ShortenModel model)
  205. {
  206. try
  207. {
  208. if (model.url.IsValidUrl())
  209. {
  210. ShortenedUrl newUrl = Shortener.Shortener.ShortenUrl(model.url, Config.ShortenerConfig.UrlLength);
  211. // Associate this with the user if they provided an auth key
  212. if (!string.IsNullOrEmpty(model.authToken))
  213. {
  214. User foundUser = UserHelper.GetUserFromToken(db, Config, model.authToken);
  215. if (foundUser != null)
  216. {
  217. newUrl.UserId = foundUser.UserId;
  218. }
  219. }
  220. db.ShortenedUrls.Add(newUrl);
  221. db.SaveChanges();
  222. string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
  223. if (Config.DevEnvironment)
  224. {
  225. shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
  226. }
  227. return Json(new
  228. {
  229. result = new
  230. {
  231. shortUrl = shortUrl,
  232. originalUrl = model.url
  233. }
  234. });
  235. }
  236. return Json(new { error = new { message = "Must be a valid Url" } });
  237. }
  238. catch (Exception ex)
  239. {
  240. return Json(new { error = new { message = "Exception: " + ex.Message } });
  241. }
  242. }
  243. }
  244. }