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.

211 lines
6.8 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Caching;
  8. using System.Web.Hosting;
  9. public static class Blog
  10. {
  11. static Blog()
  12. {
  13. Theme = ConfigurationManager.AppSettings.Get("blog:theme");
  14. Title = ConfigurationManager.AppSettings.Get("blog:name");
  15. Description = ConfigurationManager.AppSettings.Get("blog:description");
  16. PostsPerPage = int.Parse(ConfigurationManager.AppSettings.Get("blog:postsPerPage"));
  17. DaysToComment = int.Parse(ConfigurationManager.AppSettings.Get("blog:daysToComment"));
  18. Image = ConfigurationManager.AppSettings.Get("blog:image");
  19. ModerateComments = bool.Parse(ConfigurationManager.AppSettings.Get("blog:moderateComments"));
  20. }
  21. public static string Title { get; private set; }
  22. public static string Description { get; private set; }
  23. public static string Theme { get; private set; }
  24. public static string Image { get; private set; }
  25. public static int PostsPerPage { get; private set; }
  26. public static int DaysToComment { get; private set; }
  27. public static bool ModerateComments { get; private set; }
  28. public static int UniqueId
  29. {
  30. get { return FingerPrint("/web.config").GetHashCode(); }
  31. }
  32. public static string CurrentSlug
  33. {
  34. get { return (HttpContext.Current.Request.QueryString["slug"] ?? string.Empty).Trim().ToLowerInvariant(); }
  35. }
  36. public static string CurrentCategory
  37. {
  38. get { return (HttpContext.Current.Request.QueryString["category"] ?? string.Empty).Trim().ToLowerInvariant(); }
  39. }
  40. public static bool IsNewPost
  41. {
  42. get { return HttpContext.Current.Request.RawUrl.Trim('/') == "post/new"; }
  43. }
  44. public static Post CurrentPost
  45. {
  46. get
  47. {
  48. if (HttpContext.Current.Items["currentpost"] == null && !string.IsNullOrEmpty(CurrentSlug))
  49. {
  50. var post = Storage.GetAllPosts().FirstOrDefault(p => p.Slug == CurrentSlug);
  51. if (post != null && (post.IsPublished || HttpContext.Current.User.Identity.IsAuthenticated))
  52. HttpContext.Current.Items["currentpost"] = Storage.GetAllPosts().FirstOrDefault(p => p.Slug == CurrentSlug);
  53. }
  54. return HttpContext.Current.Items["currentpost"] as Post;
  55. }
  56. }
  57. public static string GetNextPage()
  58. {
  59. if (!string.IsNullOrEmpty(CurrentSlug))
  60. {
  61. var current = Storage.GetAllPosts().IndexOf(CurrentPost);
  62. if (current > 0)
  63. return Storage.GetAllPosts()[current - 1].Url.ToString();
  64. }
  65. else if (CurrentPage > 1)
  66. {
  67. return GetPagingUrl(-1);
  68. }
  69. return null;
  70. }
  71. public static string GetPrevPage()
  72. {
  73. if (!string.IsNullOrEmpty(CurrentSlug))
  74. {
  75. var current = Storage.GetAllPosts().IndexOf(CurrentPost);
  76. if (current > -1)
  77. return Storage.GetAllPosts()[current + 1].Url.ToString();
  78. }
  79. else
  80. {
  81. return GetPagingUrl(1);
  82. }
  83. return null;
  84. }
  85. public static int CurrentPage
  86. {
  87. get
  88. {
  89. int page = 0;
  90. if (int.TryParse(HttpContext.Current.Request.QueryString["page"], out page))
  91. return page;
  92. return 1;
  93. }
  94. }
  95. public static IEnumerable<Post> GetPosts(int postsPerPage = 0)
  96. {
  97. var posts = from p in Storage.GetAllPosts()
  98. where (p.IsPublished && p.PubDate <= DateTime.UtcNow) || HttpContext.Current.User.Identity.IsAuthenticated
  99. select p;
  100. string category = HttpContext.Current.Request.QueryString["category"];
  101. if (!string.IsNullOrEmpty(category))
  102. {
  103. posts = posts.Where(p => p.Categories.Any(c => string.Equals(c, category, StringComparison.OrdinalIgnoreCase)));
  104. }
  105. if (postsPerPage > 0)
  106. {
  107. posts = posts.Skip(postsPerPage * (CurrentPage - 1)).Take(postsPerPage);
  108. }
  109. return posts;
  110. }
  111. public static bool MatchesUniqueId(HttpContext context)
  112. {
  113. int token;
  114. return int.TryParse(context.Request.Form["token"], out token) && token == Blog.UniqueId;
  115. }
  116. public static string SaveFileToDisk(byte[] bytes, string extension)
  117. {
  118. string relative = "~/posts/files/" + Guid.NewGuid() + "." + extension.Trim('.');
  119. string file = HostingEnvironment.MapPath(relative);
  120. File.WriteAllBytes(file, bytes);
  121. var cruncher = new ImageCruncher.Cruncher();
  122. cruncher.CrunchImages(file);
  123. return VirtualPathUtility.ToAbsolute(relative);
  124. }
  125. public static string GetPagingUrl(int move)
  126. {
  127. string url = "/page/{0}/";
  128. string category = HttpContext.Current.Request.QueryString["category"];
  129. if (!string.IsNullOrEmpty(category))
  130. {
  131. url = "/category/" + HttpUtility.UrlEncode(category.ToLowerInvariant()) + "/" + url;
  132. }
  133. string relative = string.Format("~" + url, Blog.CurrentPage + move);
  134. return VirtualPathUtility.ToAbsolute(relative);
  135. }
  136. public static string FingerPrint(string rootRelativePath, string cdnPath = "")
  137. {
  138. if (!string.IsNullOrEmpty(cdnPath) && !HttpContext.Current.IsDebuggingEnabled)
  139. {
  140. return cdnPath;
  141. }
  142. if (HttpRuntime.Cache[rootRelativePath] == null)
  143. {
  144. string relative = VirtualPathUtility.ToAbsolute("~" + rootRelativePath);
  145. string absolute = HostingEnvironment.MapPath(relative);
  146. if (!File.Exists(absolute))
  147. {
  148. throw new FileNotFoundException("File not found", absolute);
  149. }
  150. DateTime date = File.GetLastWriteTime(absolute);
  151. int index = relative.LastIndexOf('/');
  152. string result = relative.Insert(index, "/v-" + date.Ticks);
  153. HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute));
  154. }
  155. return HttpRuntime.Cache[rootRelativePath] as string;
  156. }
  157. public static void SetConditionalGetHeaders(DateTime lastModified, HttpContextBase context)
  158. {
  159. HttpResponseBase response = context.Response;
  160. HttpRequestBase request = context.Request;
  161. lastModified = new DateTime(lastModified.Year, lastModified.Month, lastModified.Day, lastModified.Hour, lastModified.Minute, lastModified.Second);
  162. string incomingDate = request.Headers["If-Modified-Since"];
  163. response.Cache.SetLastModified(lastModified);
  164. DateTime testDate = DateTime.MinValue;
  165. if (DateTime.TryParse(incomingDate, out testDate) && testDate == lastModified)
  166. {
  167. response.ClearContent();
  168. response.StatusCode = (int)System.Net.HttpStatusCode.NotModified;
  169. response.SuppressContent = true;
  170. }
  171. }
  172. }