diff options
43 files changed, 1788 insertions, 1798 deletions
diff --git a/apps/blog/context_processors.py b/apps/blog/context_processors.py index fe2b79aa..38cf12ad 100644 --- a/apps/blog/context_processors.py +++ b/apps/blog/context_processors.py @@ -1,16 +1,17 @@ import os import re -import akismet +# import akismet import dotenv import requests from bs4 import BeautifulSoup from django.conf import settings from django.core.cache import cache -from pygments import highlight -from pygments.formatters import HtmlFormatter -from pygments.lexers import get_lexer_by_name, guess_lexer -import google.generativeai as genai + +# from pygments import highlight +# from pygments.formatters import HtmlFormatter +# from pygments.lexers import get_lexer_by_name, guess_lexer +# import google.generativeai as genai from .models import Category, Comment, Post @@ -18,14 +19,14 @@ dotenv.load_dotenv() gemini_api_key = os.getenv("GEMINI_API_KEY") -akismet_api = akismet.Akismet( - key=os.getenv("AKISMET_API_KEY"), - blog_url=( - "https://preview.thatcomputerscientist.com" - if settings.DEBUG - else "https://thatcomputerscientist.com" - ), -) +# akismet_api = akismet.Akismet( +# key=os.getenv("AKISMET_API_KEY"), +# blog_url=( +# "https://preview.thatcomputerscientist.com" +# if settings.DEBUG +# else "https://thatcomputerscientist.com" +# ), +# ) def check_spam(comment, post): @@ -42,48 +43,50 @@ def check_spam(comment, post): # return spam # Now we check with Google Generative AI - if gemini_api_key is None: - return True - else: - genai.configure(api_key=gemini_api_key) - - model = genai.GenerativeModel("gemini-pro") - print(comment) - - input_prompt = f"Comment Processing Checker. This is for a personal blog site. Output only Y or N for the included text. Y if the comment seems like spam, or random gibberish or a bunch of letters which make no sense or looks like a coupon code or something. Only block spam, nothing else. If a comment contains cuss words, personal attacks, profanity or any possible harrasment, it is NOT spam (unless it contains spammy gibberish or links). This is a strict spam only filter. N if the comment is not spam. Do not access links. Just mark Y or N for the text. Post Title: {post.title}. \n Comment: {comment}. \n Judge if the comment belongs on the post or not. Random texts, links, and gibberish are considered spam. Trying to phish or promote shady links are also considered spam. Output single character - either Y or N only." - - bn = [ - { - "category": "HARM_CATEGORY_DANGEROUS", - "threshold": "BLOCK_NONE", - }, - { - "category": "HARM_CATEGORY_HARASSMENT", - "threshold": "BLOCK_NONE", - }, - { - "category": "HARM_CATEGORY_HATE_SPEECH", - "threshold": "BLOCK_NONE", - }, - { - "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", - "threshold": "BLOCK_NONE", - }, - { - "category": "HARM_CATEGORY_DANGEROUS_CONTENT", - "threshold": "BLOCK_NONE", - }, - ] - - response = model.generate_content(input_prompt, safety_settings=bn) + # if gemini_api_key is None: + # return True + # else: + # genai.configure(api_key=gemini_api_key) + + # model = genai.GenerativeModel("gemini-pro") + # print(comment) + + # input_prompt = f"Comment Processing Checker. This is for a personal blog site. Output only Y or N for the included text. Y if the comment seems like spam, or random gibberish or a bunch of letters which make no sense or looks like a coupon code or something. Only block spam, nothing else. If a comment contains cuss words, personal attacks, profanity or any possible harrasment, it is NOT spam (unless it contains spammy gibberish or links). This is a strict spam only filter. N if the comment is not spam. Do not access links. Just mark Y or N for the text. Post Title: {post.title}. \n Comment: {comment}. \n Judge if the comment belongs on the post or not. Random texts, links, and gibberish are considered spam. Trying to phish or promote shady links are also considered spam. Output single character - either Y or N only." + + # bn = [ + # { + # "category": "HARM_CATEGORY_DANGEROUS", + # "threshold": "BLOCK_NONE", + # }, + # { + # "category": "HARM_CATEGORY_HARASSMENT", + # "threshold": "BLOCK_NONE", + # }, + # { + # "category": "HARM_CATEGORY_HATE_SPEECH", + # "threshold": "BLOCK_NONE", + # }, + # { + # "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", + # "threshold": "BLOCK_NONE", + # }, + # { + # "category": "HARM_CATEGORY_DANGEROUS_CONTENT", + # "threshold": "BLOCK_NONE", + # }, + # ] + + # response = model.generate_content(input_prompt, safety_settings=bn) + + # r_text = response.text + + # r_text = r_text.strip() + + # print(r_text) + + # return r_text - r_text = response.text - - r_text = r_text.strip() - - print(r_text) - - return r_text + return False def add_excerpt(post): diff --git a/apps/blog/urls.py b/apps/blog/urls.py index 68b3ca6c..226fb9d9 100644 --- a/apps/blog/urls.py +++ b/apps/blog/urls.py @@ -5,46 +5,46 @@ from .feed import RSSFeed app_name = "weblog" urlpatterns = [ - path("", views.home, name="home"), - path("account", views.account, name="account"), - path("register", views.register, name="register"), - path("forgotpassword", views.forgotpassword, name="forgotpassword"), - path( - "forgotpassword/reset?uid=<str:uid>&token=<str:token>", - views.resetpassword, - name="resetpassword", - ), - path("search", views.search, name="search"), - path("weblog", views.articles, name="articles"), - path("weblog/<str:slug>", views.post, name="post"), - path("weblog/<str:slug>/comment", views.comment, name="comment"), - path("weblog/<str:slug>/anon_comment", views.anon_comment, name="anon_comment"), - path("weblog/<str:slug>/edit_comment", views.edit_comment, name="edit_comment"), - path( - "weblog/<str:slug>/anon_edit_comment", - views.anon_edit_comment, - name="anon_edit_comment", - ), - path( - "weblog/<str:slug>/delete_comment/<int:comment_id>", - views.delete_comment, - name="delete_comment", - ), - path( - "weblog/<str:slug>/anon_delete_comment/<int:comment_id>", - views.anon_delete_comment, - name="anon_delete_comment", - ), - path("archives", views.archives, name="archives"), - path("archives/<str:date>", views.articles, name="archive_posts"), - path("categories", views.categories, name="categories"), - path("categories/<str:cg>", views.articles, name="category_posts"), - path("tags", views.tags, name="tags"), - path("tags/<str:tag_slug>", views.tag_posts, name="tag_posts"), - path("~<str:username>", views.user_activity, name="user_activity"), - path("policy", views.policy, name="policy"), - path("socialify", views.socialify, name="socialify"), - path("rss/", RSSFeed(), name="rss_feed"), - path("anidata", views.anidata, name="anidata"), - path("anilist", views.anilist, name="anilist"), + # path("", views.home, name="home"), + # path("account", views.account, name="account"), + # path("register", views.register, name="register"), + # path("forgotpassword", views.forgotpassword, name="forgotpassword"), + # path( + # "forgotpassword/reset?uid=<str:uid>&token=<str:token>", + # views.resetpassword, + # name="resetpassword", + # ), + # path("search", views.search, name="search"), + # path("weblog", views.articles, name="articles"), + # path("weblog/<str:slug>", views.post, name="post"), + # path("weblog/<str:slug>/comment", views.comment, name="comment"), + # path("weblog/<str:slug>/anon_comment", views.anon_comment, name="anon_comment"), + # path("weblog/<str:slug>/edit_comment", views.edit_comment, name="edit_comment"), + # path( + # "weblog/<str:slug>/anon_edit_comment", + # views.anon_edit_comment, + # name="anon_edit_comment", + # ), + # path( + # "weblog/<str:slug>/delete_comment/<int:comment_id>", + # views.delete_comment, + # name="delete_comment", + # ), + # path( + # "weblog/<str:slug>/anon_delete_comment/<int:comment_id>", + # views.anon_delete_comment, + # name="anon_delete_comment", + # ), + # path("archives", views.archives, name="archives"), + # path("archives/<str:date>", views.articles, name="archive_posts"), + # path("categories", views.categories, name="categories"), + # path("categories/<str:cg>", views.articles, name="category_posts"), + # path("tags", views.tags, name="tags"), + # path("tags/<str:tag_slug>", views.tag_posts, name="tag_posts"), + # path("~<str:username>", views.user_activity, name="user_activity"), + # path("policy", views.policy, name="policy"), + # path("socialify", views.socialify, name="socialify"), + # path("rss/", RSSFeed(), name="rss_feed"), + # path("anidata", views.anidata, name="anidata"), + # path("anilist", views.anilist, name="anilist"), ] diff --git a/apps/blog/views.py b/apps/blog/views.py index 07022263..2ea99457 100644 --- a/apps/blog/views.py +++ b/apps/blog/views.py @@ -1,1034 +1,1034 @@ -import hashlib -import os -import random -import re -import string -from datetime import datetime -from random import choice -from string import ascii_letters, digits - -from datetime import timedelta -from django.utils import timezone -import requests -from bs4 import BeautifulSoup -from django.contrib import messages -from django.contrib.auth.models import User -from django.core.cache import cache -from django.core.paginator import Paginator -from django.http import Http404, HttpResponse, HttpResponseRedirect -from django.shortcuts import redirect, render, reverse -from django.views.decorators.clickjacking import xframe_options_sameorigin -from dotenv import load_dotenv -from haystack.query import SearchQuerySet -from user_agents import parse - -from apps.administration.models import Announcement -from services.users.accountFunctions import verify_token -from services.users.forms import ( - RegisterForm, - ResetPasswordForm, - UpdateUserDetailsForm, - ForgotPasswordForm, -) -from services.users.models import UserProfile -from services.users.tokens import CaptchaTokenGenerator - -from .context_processors import ( - add_excerpt, - add_num_comments, - avatar_list, - check_spam, - comment_processor, - highlight_code_blocks, - recent_posts, -) -from .models import AnonymousCommentUser, Category, Comment, Post, Tag -from .recommender import next_read - -load_dotenv() - - -def atoi(text): - return int(text) if text.isdigit() else text - - -def natural_keys(text): - """ - alist.sort(key=natural_keys) sorts in human order - http://nedbatchelder.com/blog/200712/human_sorting.html - (See Toothy's implementation in the comments) - """ - return [atoi(c) for c in re.split(r"(\d+)", text)] - - -# Create your views here. - - -def home(request): - announcements = Announcement.objects.filter(is_public=True).order_by("-created_at") - announcements = announcements if len(announcements) > 0 else None - return render( - request, - "blog/home.html", - {"title": "Home", "posts": recent_posts(), "announcements": announcements}, - ) - - -def tags(request): - tags = Tag.objects.all() - # add occurance count to each tag - for tag in tags: - tag.count = len(Post.objects.filter(tags__name__in=[tag.name], is_public=True)) - tag.pxs = 10 + tag.count * 2 if tag.count < 10 else 30 + tag.count - tag.pxs = min(tag.pxs, 36) - tags = sorted(tags, key=lambda x: x.count, reverse=True) - tags = [tag for tag in tags if tag.count > 0] - return render(request, "blog/tags.html", {"title": "Tags", "tags": tags}) - - -def tag_posts(request, tag_slug): - try: - tag = Tag.objects.get(slug=tag_slug) - except Tag.DoesNotExist: - tag = { - "name": tag_slug, - "slug": tag_slug, - "count": 0, - } - return render( - request, - "blog/tagged.html", - {"title": "Posts Tagged With: " + tag_slug, "posts": None, "tag": tag}, - ) - posts = Post.objects.filter(tags__name__in=[tag.name], is_public=True).order_by( - "views" - ) - for post in posts: - post.excerpt = add_excerpt(post) - post.num_comments = add_num_comments(post) - return render( - request, - "blog/tagged.html", - {"title": "Posts Tagged With: " + tag.name, "posts": posts, "tag": tag}, - ) - - -def account(request): - user = request.user - avatarlist = avatar_list() - for key in avatarlist: - avatarlist[key] = [re.sub(r"\.gif$", "", string) for string in avatarlist[key]] - avatarlist[key].sort(key=natural_keys) - avatarlist = {k: avatarlist[k] for k in sorted(avatarlist)} - - blinkies = [ - re.sub(r"\.gif$", "", string) for string in os.listdir("static/images/blinkies") - ] - blinkies.sort(key=natural_keys) - - if user.is_authenticated: - try: - user_profile = UserProfile.objects.get(user=user) - if not user_profile.avatar_url: - # Set a random avatar - avatar_dir = choice(list(avatarlist.keys())) - avatar_file = choice(avatarlist[avatar_dir]) - user_profile.avatar_url = avatar_dir + "/" + avatar_file - user_profile.save() - except UserProfile.DoesNotExist: - # Create a new user profile and set a random avatar - user_profile = UserProfile.objects.create(user=user) - avatar_dir = choice(list(avatarlist.keys())) - avatar_file = choice(avatarlist[avatar_dir]) - user_profile.avatar_url = avatar_dir + "/" + avatar_file - user_profile.save() - - if request.GET.get("tab") == "details": - update_form = UpdateUserDetailsForm( - user=user, - initial={ - "first_name": user.first_name, - "last_name": user.last_name, - "bio": user_profile.bio, - "is_public": user_profile.is_public, - "email_public": user_profile.email_public, - "location": user_profile.location, - }, - ) - else: - update_form = None - - return render( - request, - "blog/account.html", - { - "title": "Account", - "user_profile": user_profile, - "avatarlist": avatarlist, - "update_form": update_form, - "blinkies": blinkies, - }, - ) - else: - # Redirect to login page - return redirect("blog:home") - - -def register(request): - user = request.user - if user.is_authenticated: - return redirect("blog:account") - else: - random_string = "".join([choice(ascii_letters + digits) for n in range(6)]) - captcha = CaptchaTokenGenerator().encrypt(random_string) - if request.method == "POST": - expected_captcha = CaptchaTokenGenerator().decrypt( - request.POST.get("expected_captcha") - ) - form = RegisterForm(request.POST, expected_captcha=expected_captcha) - if form.is_valid(): - form.save(request=request) - messages.success( - request, - "Account was created! Please check your email to verify your account.", - extra_tags="accountCreated", - ) - return redirect("blog:register") - else: - return render( - request, - "blog/register.html", - {"title": "Register", "form": form, "captcha": captcha}, - ) - else: - form = RegisterForm(expected_captcha=random_string) - return render( - request, - "blog/register.html", - {"title": "Register", "form": form, "captcha": captcha}, - ) - - -def forgotpassword(request): - user = request.user - if user.is_authenticated: - return redirect("blog:account") - else: - if request.method == "POST": - form = ForgotPasswordForm(request.POST) - if form.is_valid(): - form.save(request) - messages.success( - request, - "An email has been sent to you with instructions on how to reset your password.", - extra_tags="passwordReset", - ) - return redirect("blog:forgotpassword") - else: - return render( - request, - "blog/resetpass.html", - {"title": "Forgot Password", "form": form}, - ) - else: - form = ForgotPasswordForm() - return render( - request, - "blog/resetpass.html", - {"title": "Forgot Password", "form": form}, - ) - - -def resetpassword(request, uid, token): - user = request.user - if user.is_authenticated: - return redirect("blog:account") - else: - if request.method == "POST": - form = ResetPasswordForm(request.POST) - if form.is_valid(): - token_object = verify_token("resetpassword", uid, token) - if token_object is not None and token_object.verified: - user = User.objects.get(pk=token_object.user_id) - form.save(user) - messages.success( - request, - "Your password has been reset. You can now login with your new password.", - extra_tags="passwordReset", - ) - token_object.delete() - return redirect("blog:resetpassword", uid=uid, token=token) - else: - messages.error( - request, - "Invalid or expired reset password link. Please try again.", - extra_tags="passwordReset", - ) - return redirect("blog:forgotpassword") - else: - return render( - request, - "blog/resetpass_input.html", - {"title": "Reset Password", "form": form}, - ) - else: - form = ResetPasswordForm() - return render( - request, - "blog/resetpass_input.html", - {"title": "Reset Password", "form": form}, - ) - - -def post(request, slug): - try: - post = Post.objects.get(slug=slug) - - # Get the number of views for this post - x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") - if x_forwarded_for: - ip = x_forwarded_for.split(",")[0] - else: - ip = request.META.get("REMOTE_ADDR") - user_agent_string = request.META.get("HTTP_USER_AGENT", "") - user_agent = parse(user_agent_string) - user_identifier = f"{ip}_{user_agent.browser.family}_{user_agent.browser.version_string}_{user_agent.os.family}_{user_agent.os.version_string}" - cache_key = f"post_view_count_{slug}_{user_identifier}" - view_count = cache.get(cache_key, 0) - if view_count == 0: - post.views += 1 - post.save() - cache.set(cache_key, 1, 60 * 60 * 24 * 7) # 1 week - - # code stored in .ql-syntax class - soup = BeautifulSoup(post.body, "html.parser") - code_blocks = soup.find_all("pre") - for code_block in code_blocks: - data_language = code_block.get("data-language") - if data_language == "true": - data_language = None - code_block.replace_with( - BeautifulSoup( - highlight_code_blocks(code_block, language=data_language), - "html.parser", - ) - ) - - # float: right every other image - images = soup.find_all("img") - for i in range(len(images)): - if i % 2 != 0: - images[i][ - "style" - ] = "float: right; margin-right: 0px; margin-left: 11px;" - - # remove all paragraphs which are: "<p class="ql-align-justify"><br></p>" - for p in soup.find_all("p", class_="ql-align-justify"): - if p.find("br") is not None: - p.decompose() - - # separate the body in two parts -> the first paragraph and the rest - first_paragraph = soup.find("p") - if first_paragraph is not None: - first_paragraph = str(first_paragraph) - first_paragraph = first_paragraph.replace("<p>", '<p class="subhead">') - soup.find("p").decompose() - - post.first_paragraph = first_paragraph - post.body = str(soup) - post.views = "{:,}".format(post.views) - - tags = post.tags.all() - comments = Comment.objects.filter(post=post) - for comment in comments: - if comment.user: - user_profile = UserProfile.objects.get(user=comment.user) - comment.avatar_url = user_profile.avatar_url - comment.processed_body = comment_processor(comment.body) - - if comment.anonymous_user: - user_profile = comment.anonymous_user - comment.avatar_url = user_profile.avatar - comment.processed_body = comment_processor(comment.body) - - if post.is_public: - # modify request.meta description (only text) and image - request.meta["description"] = BeautifulSoup( - first_paragraph, "html.parser" - ).get_text() - request.meta["image"] = ( - "https://shi.foo/ignis/post_image/720/" + str(post.id) + ".gif" - ) - - read_next = next_read(post) - - return render( - request, - "blog/post.html", - { - "title": post.title, - "post": post, - "tags": tags, - "comments": comments, - "view_count": view_count, - "read_next": read_next, - }, - ) - else: - if ( - request.user.is_authenticated - and request.user.is_superuser - or request.user.is_staff - ): - return render( - request, - "blog/post.html", - { - "title": post.title, - "post": post, - "tags": tags, - "comments": comments, - "view_count": view_count, - }, - ) - else: - raise Http404 - except Post.DoesNotExist: - raise Http404 - - -def comment(request, slug): - if request.method == "POST": - if request.user.is_authenticated: - try: - print(request.POST.get("comment")) - r_spam = check_spam( - comment=request.POST.get("comment"), - post=Post.objects.get(slug=slug), - ) - if r_spam != "N": - messages.error(request, r_spam, extra_tags="spam") - return redirect( - reverse("blog:post", kwargs={"slug": slug}) + "#new-comment" - ) - - # then we continue - post = Post.objects.get(slug=slug) - if post.is_public: - comment = Comment.objects.create( - user=request.user, post=post, body=request.POST.get("comment") - ) - return redirect( - reverse("blog:post", kwargs={"slug": slug}) - + "#comment-" - + str(comment.id) - ) - else: - if ( - request.user.is_authenticated - and request.user.is_superuser - or request.user.is_staff - ): - Comment.objects.create( - user=request.user, - post=post, - body=request.POST.get("comment"), - ) - return redirect( - reverse("blog:post", kwargs={"slug": slug}) - + "#comment-" - + str(comment.id) - ) - else: - return HttpResponse("Post not found!", status=404) - except Post.DoesNotExist: - return HttpResponse("Post not found!", status=404) - - else: - return redirect("blog:home") - else: - return redirect("blog:home") - - -def anon_comment(request, slug): - if request.method == "POST": - if request.user.is_authenticated: - # not allowed this is anonymous comment form - return redirect(reverse("blog:post", kwargs={"slug": slug})) - else: - anonymous_name = request.POST.get("anonymous-name") - anonymous_email = request.POST.get("anonymous-email") - anonymous_token, at = request.POST.get("anonymous-token"), request.POST.get( - "anonymous-token" - ) - new_anonymous_token = request.POST.get("new-anonymous-token") - anonymous_comment = request.POST.get("anonymous-comment") - res_spam = check_spam( - comment=anonymous_comment, post=Post.objects.get(slug=slug) - ) - if res_spam != "N": - messages.error(request, res_spam, extra_tags="spam") - return redirect( - reverse("blog:post", kwargs={"slug": slug}) + "#new-comment" - ) - - # now continue with the comment - if not anonymous_name: - messages.error(request, "Please enter a name!") - return redirect(reverse("blog:post", kwargs={"slug": slug})) - if not anonymous_comment: - messages.error(request, "Please enter a comment!") - return redirect(reverse("blog:post", kwargs={"slug": slug})) - if not anonymous_email: - anonymous_email = ( - "".join(random.choice(string.ascii_lowercase) for i in range(10)) - + "@anonymous.shi.foo" - ) - if not anonymous_token: - anonymous_token = "".join( - random.choice(string.ascii_lowercase) for i in range(10) - ) - at = anonymous_token - - # generate a random avatar for the anonymous user - avatarlist = avatar_list() - for key in avatarlist: - avatarlist[key] = [ - re.sub(r"\.gif$", "", string) for string in avatarlist[key] - ] - avatarlist[key].sort(key=natural_keys) - avatarlist = {k: avatarlist[k] for k in sorted(avatarlist)} - avatar_dir = choice(list(avatarlist.keys())) - avatar_file = choice(avatarlist[avatar_dir]) - anonymous_avatar = avatar_dir + "/" + avatar_file - anonymous_token = hashlib.sha256( - anonymous_token.encode("utf-8") - ).hexdigest() - try: - anonymous_user = AnonymousCommentUser.objects.get( - email=anonymous_email, token=anonymous_token - ) - except AnonymousCommentUser.DoesNotExist: - anonymous_user = AnonymousCommentUser.objects.create( - email=anonymous_email, - token=anonymous_token, - avatar=anonymous_avatar, - ) - if new_anonymous_token: - at = new_anonymous_token - new_anonymous_token = hashlib.sha256( - new_anonymous_token.encode("utf-8") - ).hexdigest() - anonymous_user.token = new_anonymous_token - anonymous_user.save() - - # update the anonymous user's name if it has changed - if anonymous_user.name != anonymous_name: - anonymous_user.name = anonymous_name - anonymous_user.save() - - comment = Comment.objects.create( - anonymous_user=anonymous_user, - post=Post.objects.get(slug=slug), - body=anonymous_comment, - ) - - # redirect to the post with the comment but set the anonymous user cookie - response = redirect( - reverse("blog:post", kwargs={"slug": slug}) - + "#comment-" - + str(comment.id) - ) - response.set_cookie( - "anonymous_name", anonymous_user.name, max_age=60 * 60 * 24 * 365 - ) - response.set_cookie( - "anonymous_email", anonymous_user.email, max_age=60 * 60 * 24 * 365 - ) - response.set_cookie("anonymous_token", at, max_age=60 * 60 * 24 * 365) - - return response - - else: - return redirect("blog:home") - - -def edit_comment(request, slug): - if request.method == "POST": - if request.user.is_authenticated: - - try: - comment = Comment.objects.get(id=request.POST.get("comment_id")) - # check for spam first - user_ip = request.META.get("HTTP_X_FORWARDED_FOR") - if user_ip: - user_ip = user_ip.split(",")[0] - else: - user_ip = request.META.get("REMOTE_ADDR") - user_agent_string = request.META.get("HTTP_USER_AGENT", "") - user_agent = parse(user_agent_string) - # if check_spam(user_ip=user_ip, user_agent=user_agent, comment=request.POST.get('body'), author=request.user.username - res_spam = check_spam( - comment=request.POST.get("body"), post=comment.post - ) - if res_spam != "N": - messages.error(request, request.POST.get("body"), extra_tags="spam") - return redirect( - reverse("blog:post", kwargs={"slug": slug}) - + "#comment-" - + str(comment.id) - ) - if comment.user == request.user: - comment.body = request.POST.get("body") - comment.edited = True - comment.edited_at = datetime.now() - comment.save() - return redirect( - reverse("blog:post", kwargs={"slug": slug}) - + "#comment-" - + str(comment.id) - ) - else: - return HttpResponse("Unauthorized!", status=401) - except Comment.DoesNotExist: - return HttpResponse("Comment not found!", status=404) - else: - return redirect("blog:home") - else: - return redirect("blog:home") - - -def anon_edit_comment(request, slug): - if request.method == "POST": - if request.user.is_authenticated: - # not allowed this is anonymous comment form - return redirect(reverse("blog:post", kwargs={"slug": slug})) - else: - - anonymous_token = request.COOKIES.get("anonymous_token") - if not anonymous_token: - return HttpResponse("Unauthorized!", status=401) - try: - anonymous_token = hashlib.sha256( - anonymous_token.encode("utf-8") - ).hexdigest() - comment = Comment.objects.get(id=request.POST.get("comment_id")) - # check for spam first - user_ip = request.META.get("HTTP_X_FORWARDED_FOR") - if user_ip: - user_ip = user_ip.split(",")[0] - else: - user_ip = request.META.get("REMOTE_ADDR") - user_agent_string = request.META.get("HTTP_USER_AGENT", "") - user_agent = parse(user_agent_string) - res_spam = check_spam( - comment=request.POST.get("body"), post=comment.post - ) - if res_spam != "N": - # if check_spam(user_ip=user_ip, user_agent=user_agent, comment=request.POST.get('body'), author=comment.anonymous_user.name): - messages.error(request, request.POST.get("body"), extra_tags="spam") - return redirect( - reverse("blog:post", kwargs={"slug": slug}) - + "#comment-" - + str(comment.id) - ) - if comment.anonymous_user.token == anonymous_token: - comment.body = request.POST.get("body") - comment.edited = True - comment.edited_at = datetime.now() - comment.save() - return redirect( - reverse("blog:post", kwargs={"slug": slug}) - + "#comment-" - + str(comment.id) - ) - else: - return HttpResponse("Unauthorized!", status=401) - except Comment.DoesNotExist: - return HttpResponse("Comment not found!", status=404) - else: - return redirect("blog:home") - - -def delete_comment(request, slug, comment_id): - if request.user.is_authenticated: - try: - comment = Comment.objects.get(id=comment_id) - if comment.user == request.user: - comment.delete() - return redirect( - reverse("blog:post", kwargs={"slug": slug}) + "#comments" - ) - else: - return HttpResponse("Unauthorized!", status=401) - except Comment.DoesNotExist: - return HttpResponse("Comment not found!", status=404) - else: - return HttpResponseRedirect(request.META.get("HTTP_REFERER")) - - -def anon_delete_comment(request, slug, comment_id): - if request.user.is_authenticated: - # not allowed this is anonymous comment form - return HttpResponseRedirect(request.META.get("HTTP_REFERER")) - else: - anonymous_token = request.COOKIES.get("anonymous_token") - if not anonymous_token: - return HttpResponse("Unauthorized!", status=401) - anonymous_token = hashlib.sha256(anonymous_token.encode("utf-8")).hexdigest() - try: - comment = Comment.objects.get( - id=comment_id, anonymous_user__token=anonymous_token - ) - comment.delete() - return redirect(reverse("blog:post", kwargs={"slug": slug}) + "#comments") - except Comment.DoesNotExist: - return HttpResponse("Comment not found!", status=404) - - -def search(request): - query = request.GET.get("q") - search_in = ( - request.GET.getlist("search_in") if request.GET.get("search_in") else ["posts"] - ) - sort_by = request.GET.get("sort_by") if request.GET.get("sort_by") else "relevance" - order = request.GET.get("order") if request.GET.get("order") else "ascending" - date_range = ( - request.GET.get("date_range") if request.GET.get("date_range") else "any" - ) - search_model_map = { - "posts": Post, - "users": User, - "comments": Comment, - } - now = timezone.now() - - if query: - search_results = SearchQuerySet().filter(content=query) - if search_in: - search_results = search_results.models( - *[search_model_map[model] for model in search_in] - ) - - # search_results = [result.object for result in search_results] - posts = [ - result.object - for result in search_results - if isinstance(result.object, Post) - ] - users = [ - result.object - for result in search_results - if isinstance(result.object, User) - ] - comments = [ - result.object - for result in search_results - if isinstance(result.object, Comment) - ] - - # match-case sort_by - if sort_by == "relevance" and order == "ascending": - posts = sorted(posts, key=lambda post: post.views) - users = sorted(users, key=lambda user: user.username) - comments = sorted(comments, key=lambda comment: comment.id) - elif sort_by == "relevance" and order == "descending": - posts = sorted(posts, key=lambda post: post.views, reverse=True) - users = sorted(users, key=lambda user: user.username, reverse=True) - comments = sorted(comments, key=lambda comment: comment.id, reverse=True) - elif sort_by == "date" and order == "ascending": - posts = sorted(posts, key=lambda post: post.date) - users = sorted(users, key=lambda user: user.date_joined) - comments = sorted(comments, key=lambda comment: comment.created_at) - elif sort_by == "date" and order == "descending": - posts = sorted(posts, key=lambda post: post.date, reverse=True) - users = sorted(users, key=lambda user: user.date_joined, reverse=True) - comments = sorted( - comments, key=lambda comment: comment.created_at, reverse=True - ) - - # filter by date_range - if date_range == "past_day": - posts = [post for post in posts if post.date >= now - timedelta(days=1)] - users = [ - user for user in users if user.date_joined >= now - timedelta(days=1) - ] - comments = [ - comment - for comment in comments - if comment.created_at >= now - timedelta(days=1) - ] - elif date_range == "past_week": - posts = [post for post in posts if post.date >= now - timedelta(days=7)] - users = [ - user for user in users if user.date_joined >= now - timedelta(days=7) - ] - comments = [ - comment - for comment in comments - if comment.created_at >= now - timedelta(days=7) - ] - elif date_range == "past_month": - posts = [post for post in posts if post.date >= now - timedelta(days=30)] - users = [ - user for user in users if user.date_joined >= now - timedelta(days=30) - ] - comments = [ - comment - for comment in comments - if comment.created_at >= now - timedelta(days=30) - ] - elif date_range == "past_year": - posts = [post for post in posts if post.date >= now - timedelta(days=365)] - users = [ - user for user in users if user.date_joined >= now - timedelta(days=365) - ] - comments = [ - comment - for comment in comments - if comment.created_at >= now - timedelta(days=365) - ] - elif date_range == "any": - # no need to filter - pass - - search_results = len(posts) + len(users) + len(comments) - else: - search_results = 0 - - # attach user profiles - for user in users: - user.profile = UserProfile.objects.get(user=user) - - # parse comments - for comment in comments: - comment.body = comment_processor(comment.body) - - return render( - request, - "blog/search.html", - { - "title": f"Search results for '{query}'", - "query": query, - "search_results": search_results, - "search_in": search_in, - "sort_by": sort_by, - "order": order, - "date_range": date_range, - "posts": posts, - "users": users, - "comments": comments, - }, - ) - - -def articles(request, date=None, cg=None): - type = "articles" - page = request.GET.get("page") if request.GET.get("page") else 1 - order_by = request.GET.get("order_by") if request.GET.get("order_by") else "date" - direction = request.GET.get("direction") if request.GET.get("direction") else "desc" - categories = Category.objects.all() - category = request.GET.get("category") - try: - page = int(page) - except: - page = 1 - - posts = Post.objects.filter(is_public=True) - - if date: - date_month = date.split("_")[0] # month name like 'Decemeber' - date_year = date.split("_")[1] # year like '2019' - date_m = datetime.strptime( - date_month, "%B" - ).month # convert month name to month number - posts = Post.objects.filter( - is_public=True, date__month=date_m, date__year=date_year - ) - type = "articles-archive" - date = date_month + " " + date_year - - if cg: - cg = str.lower(cg) - if category and cg != category and category != "all": - return redirect(reverse("blog:categories") + "/{}".format(category)) - category = cg - posts = Post.objects.filter(is_public=True, category__slug=cg) - type = "articles-category" - - posts = ( - posts.order_by("-" + order_by) - if direction == "desc" - else Post.objects.filter(is_public=True).order_by(order_by) - ) - if category and category != "all": - posts = posts.filter(category__slug=category) - category_name = Category.objects.get(slug=category).name - else: - category = "all" - posts = Paginator(posts, 10) - num_pages = posts.num_pages - try: - posts = posts.page(page) - except: - posts = posts.page(num_pages) - - for post in posts: - post.excerpt = add_excerpt(post) - post.num_comments = add_num_comments(post) - return render( - request, - "blog/articles.html", - { - "title": "Articles", - "posts": posts, - "num_pages": num_pages, - "page": page, - "order_by": order_by, - "direction": direction, - "categories": categories, - "category": category, - "category_name": category_name if category != "all" else "", - "type": type, - "date": date if date else "", - "cg": cg if cg else "", - }, - ) - - -def user_activity(request, username): - try: - user = User.objects.get(username__iexact=username) - user_profile = UserProfile.objects.get(user=user) - if user_profile.is_public or user == request.user: - recent_comments = Comment.objects.filter(user=user).order_by("-created_at")[ - :5 - ] - else: - recent_comments = [] - - if user_profile.email_public: - user_email = user.email - else: - user_email = "" - - for comment in recent_comments: - comment.body = comment_processor(comment.body) - - return render( - request, - "blog/activity.html", - { - "title": "User Activity", - "activity_user": user, - "activity_user_profile": user_profile, - "activity_recent_comments": recent_comments, - "activity_user_email": user_email, - }, - ) - except User.DoesNotExist: - # return default 404 page - raise Http404 - - -def archives(request): - archives = Post.objects.filter(is_public=True).dates("date", "month", order="DESC") - return render( - request, "blog/archives.html", {"title": "Archives", "archives": archives} - ) - - -def categories(request): - categories = Category.objects.all() - return render( - request, - "blog/categories.html", - {"title": "Categories", "categories": categories}, - ) - - -def policy(request): - return render(request, "blog/site_policy.html", {"title": "Site Policy"}) - - -def socialify(request): - url = request.GET.get("url") if request.GET.get("url") else None - if url: - # convert Github URL to repo owner/name - if "github.com" in url: - url = url.split("github.com/")[1] - url = url.split("/") - url = url[0] + "/" + url[1] - socialify_options = { - "theme": "Dark" if not request.GET.get("theme") else request.GET.get("theme"), - "font": "Inter" if not request.GET.get("font") else request.GET.get("font"), - "description": ( - 0 if not request.GET.get("description") else request.GET.get("description") - ), - "forks": 0 if not request.GET.get("forks") else request.GET.get("forks"), - "issues": 0 if not request.GET.get("issues") else request.GET.get("issues"), - "language_1": ( - 0 if not request.GET.get("language_1") else request.GET.get("language_1") - ), - "language_2": ( - 0 if not request.GET.get("language_2") else request.GET.get("language_2") - ), - "name": 0 if not request.GET.get("name") else request.GET.get("name"), - "owner": 1 if not request.GET.get("owner") else request.GET.get("owner"), - "stargazers": ( - 0 if not request.GET.get("stargazers") else request.GET.get("stargazers") - ), - "pulls": 0 if not request.GET.get("pulls") else request.GET.get("pulls"), - "pattern": ( - "Plus" if not request.GET.get("pattern") else request.GET.get("pattern") - ), - } - - for key, value in socialify_options.items(): - if value == "on": - socialify_options[key] = 1 - elif value == "off": - socialify_options[key] = 0 - - return render( - request, - "blog/socialify.html", - {"title": "Socialify", "options": socialify_options, "url": url}, - ) - - -def anilist(request): - return render(request, "blog/anilist.html", {"title": "My Anime List"}) - - -@xframe_options_sameorigin -def anidata(request): - malURL = "https://myanimelist.net/animelist/crvs" - MAL = requests.get(malURL) - MALContent = MAL.content - MALStatus = MAL.status_code - - if MALStatus != 200: - MALContent = '<html><head><link rel="stylesheet" href="/static/css/styles.css"><style>img { width: 75%; display: block; margin: -20px auto 20px auto; } h1 { text-align: center; } p { text-align: center; } body {background: transparent !important;} </style></head><body><img src="/static/images/site/sad-failure.gif" alt="Sad Failure"><h1>MyAnimeList does not seem to respond at the moment.</h1><p>Maybe, we go <a href="https://myanimelist.net/animelist/crvs" target="_blank">knock on their door</a> instead?</p></body></html>' - else: - MALContent = MALContent.decode("utf-8") - MALParsed = BeautifulSoup(MALContent, "html.parser") - # remove script tags - for tag in MALParsed(["script", "meta", "noscript"]): - tag.extract() - - # add myanimelist.net to relative links - for link in MALParsed.find_all("a"): - if link.get("href") and link.get("href")[0] == "/": - link["href"] = "https://myanimelist.net" + link["href"] - - # make all links open in new tab - link["target"] = "_blank" - - MALContent = MALParsed.prettify() - - return render( - request, - "blog/anidata.html", - {"title": "My Anime List", "MALContent": MALContent}, - ) +# import hashlib +# import os +# import random +# import re +# import string +# from datetime import datetime +# from random import choice +# from string import ascii_letters, digits + +# from datetime import timedelta +# from django.utils import timezone +# import requests +# from bs4 import BeautifulSoup +# from django.contrib import messages +# from django.contrib.auth.models import User +# from django.core.cache import cache +# from django.core.paginator import Paginator +# from django.http import Http404, HttpResponse, HttpResponseRedirect +# from django.shortcuts import redirect, render, reverse +# from django.views.decorators.clickjacking import xframe_options_sameorigin +# from dotenv import load_dotenv +# from haystack.query import SearchQuerySet +# from user_agents import parse + +# from apps.administration.models import Announcement +# from services.users.accountFunctions import verify_token +# from services.users.forms import ( +# RegisterForm, +# ResetPasswordForm, +# UpdateUserDetailsForm, +# ForgotPasswordForm, +# ) +# from services.users.models import UserProfile +# from services.users.tokens import CaptchaTokenGenerator + +# from .context_processors import ( +# add_excerpt, +# add_num_comments, +# avatar_list, +# check_spam, +# comment_processor, +# highlight_code_blocks, +# recent_posts, +# ) +# from .models import AnonymousCommentUser, Category, Comment, Post, Tag +# from .recommender import next_read + +# load_dotenv() + + +# def atoi(text): +# return int(text) if text.isdigit() else text + + +# def natural_keys(text): +# """ +# alist.sort(key=natural_keys) sorts in human order +# http://nedbatchelder.com/blog/200712/human_sorting.html +# (See Toothy's implementation in the comments) +# """ +# return [atoi(c) for c in re.split(r"(\d+)", text)] + + +# # Create your views here. + + +# def home(request): +# announcements = Announcement.objects.filter(is_public=True).order_by("-created_at") +# announcements = announcements if len(announcements) > 0 else None +# return render( +# request, +# "blog/home.html", +# {"title": "Home", "posts": recent_posts(), "announcements": announcements}, +# ) + + +# def tags(request): +# tags = Tag.objects.all() +# # add occurance count to each tag +# for tag in tags: +# tag.count = len(Post.objects.filter(tags__name__in=[tag.name], is_public=True)) +# tag.pxs = 10 + tag.count * 2 if tag.count < 10 else 30 + tag.count +# tag.pxs = min(tag.pxs, 36) +# tags = sorted(tags, key=lambda x: x.count, reverse=True) +# tags = [tag for tag in tags if tag.count > 0] +# return render(request, "blog/tags.html", {"title": "Tags", "tags": tags}) + + +# def tag_posts(request, tag_slug): +# try: +# tag = Tag.objects.get(slug=tag_slug) +# except Tag.DoesNotExist: +# tag = { +# "name": tag_slug, +# "slug": tag_slug, +# "count": 0, +# } +# return render( +# request, +# "blog/tagged.html", +# {"title": "Posts Tagged With: " + tag_slug, "posts": None, "tag": tag}, +# ) +# posts = Post.objects.filter(tags__name__in=[tag.name], is_public=True).order_by( +# "views" +# ) +# for post in posts: +# post.excerpt = add_excerpt(post) +# post.num_comments = add_num_comments(post) +# return render( +# request, +# "blog/tagged.html", +# {"title": "Posts Tagged With: " + tag.name, "posts": posts, "tag": tag}, +# ) + + +# def account(request): +# user = request.user +# avatarlist = avatar_list() +# for key in avatarlist: +# avatarlist[key] = [re.sub(r"\.gif$", "", string) for string in avatarlist[key]] +# avatarlist[key].sort(key=natural_keys) +# avatarlist = {k: avatarlist[k] for k in sorted(avatarlist)} + +# blinkies = [ +# re.sub(r"\.gif$", "", string) for string in os.listdir("static/images/blinkies") +# ] +# blinkies.sort(key=natural_keys) + +# if user.is_authenticated: +# try: +# user_profile = UserProfile.objects.get(user=user) +# if not user_profile.avatar_url: +# # Set a random avatar +# avatar_dir = choice(list(avatarlist.keys())) +# avatar_file = choice(avatarlist[avatar_dir]) +# user_profile.avatar_url = avatar_dir + "/" + avatar_file +# user_profile.save() +# except UserProfile.DoesNotExist: +# # Create a new user profile and set a random avatar +# user_profile = UserProfile.objects.create(user=user) +# avatar_dir = choice(list(avatarlist.keys())) +# avatar_file = choice(avatarlist[avatar_dir]) +# user_profile.avatar_url = avatar_dir + "/" + avatar_file +# user_profile.save() + +# if request.GET.get("tab") == "details": +# update_form = UpdateUserDetailsForm( +# user=user, +# initial={ +# "first_name": user.first_name, +# "last_name": user.last_name, +# "bio": user_profile.bio, +# "is_public": user_profile.is_public, +# "email_public": user_profile.email_public, +# "location": user_profile.location, +# }, +# ) +# else: +# update_form = None + +# return render( +# request, +# "blog/account.html", +# { +# "title": "Account", +# "user_profile": user_profile, +# "avatarlist": avatarlist, +# "update_form": update_form, +# "blinkies": blinkies, +# }, +# ) +# else: +# # Redirect to login page +# return redirect("blog:home") + + +# def register(request): +# user = request.user +# if user.is_authenticated: +# return redirect("blog:account") +# else: +# random_string = "".join([choice(ascii_letters + digits) for n in range(6)]) +# captcha = CaptchaTokenGenerator().encrypt(random_string) +# if request.method == "POST": +# expected_captcha = CaptchaTokenGenerator().decrypt( +# request.POST.get("expected_captcha") +# ) +# form = RegisterForm(request.POST, expected_captcha=expected_captcha) +# if form.is_valid(): +# form.save(request=request) +# messages.success( +# request, +# "Account was created! Please check your email to verify your account.", +# extra_tags="accountCreated", +# ) +# return redirect("blog:register") +# else: +# return render( +# request, +# "blog/register.html", +# {"title": "Register", "form": form, "captcha": captcha}, +# ) +# else: +# form = RegisterForm(expected_captcha=random_string) +# return render( +# request, +# "blog/register.html", +# {"title": "Register", "form": form, "captcha": captcha}, +# ) + + +# def forgotpassword(request): +# user = request.user +# if user.is_authenticated: +# return redirect("blog:account") +# else: +# if request.method == "POST": +# form = ForgotPasswordForm(request.POST) +# if form.is_valid(): +# form.save(request) +# messages.success( +# request, +# "An email has been sent to you with instructions on how to reset your password.", +# extra_tags="passwordReset", +# ) +# return redirect("blog:forgotpassword") +# else: +# return render( +# request, +# "blog/resetpass.html", +# {"title": "Forgot Password", "form": form}, +# ) +# else: +# form = ForgotPasswordForm() +# return render( +# request, +# "blog/resetpass.html", +# {"title": "Forgot Password", "form": form}, +# ) + + +# def resetpassword(request, uid, token): +# user = request.user +# if user.is_authenticated: +# return redirect("blog:account") +# else: +# if request.method == "POST": +# form = ResetPasswordForm(request.POST) +# if form.is_valid(): +# token_object = verify_token("resetpassword", uid, token) +# if token_object is not None and token_object.verified: +# user = User.objects.get(pk=token_object.user_id) +# form.save(user) +# messages.success( +# request, +# "Your password has been reset. You can now login with your new password.", +# extra_tags="passwordReset", +# ) +# token_object.delete() +# return redirect("blog:resetpassword", uid=uid, token=token) +# else: +# messages.error( +# request, +# "Invalid or expired reset password link. Please try again.", +# extra_tags="passwordReset", +# ) +# return redirect("blog:forgotpassword") +# else: +# return render( +# request, +# "blog/resetpass_input.html", +# {"title": "Reset Password", "form": form}, +# ) +# else: +# form = ResetPasswordForm() +# return render( +# request, +# "blog/resetpass_input.html", +# {"title": "Reset Password", "form": form}, +# ) + + +# def post(request, slug): +# try: +# post = Post.objects.get(slug=slug) + +# # Get the number of views for this post +# x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") +# if x_forwarded_for: +# ip = x_forwarded_for.split(",")[0] +# else: +# ip = request.META.get("REMOTE_ADDR") +# user_agent_string = request.META.get("HTTP_USER_AGENT", "") +# user_agent = parse(user_agent_string) +# user_identifier = f"{ip}_{user_agent.browser.family}_{user_agent.browser.version_string}_{user_agent.os.family}_{user_agent.os.version_string}" +# cache_key = f"post_view_count_{slug}_{user_identifier}" +# view_count = cache.get(cache_key, 0) +# if view_count == 0: +# post.views += 1 +# post.save() +# cache.set(cache_key, 1, 60 * 60 * 24 * 7) # 1 week + +# # code stored in .ql-syntax class +# soup = BeautifulSoup(post.body, "html.parser") +# code_blocks = soup.find_all("pre") +# for code_block in code_blocks: +# data_language = code_block.get("data-language") +# if data_language == "true": +# data_language = None +# code_block.replace_with( +# BeautifulSoup( +# highlight_code_blocks(code_block, language=data_language), +# "html.parser", +# ) +# ) + +# # float: right every other image +# images = soup.find_all("img") +# for i in range(len(images)): +# if i % 2 != 0: +# images[i][ +# "style" +# ] = "float: right; margin-right: 0px; margin-left: 11px;" + +# # remove all paragraphs which are: "<p class="ql-align-justify"><br></p>" +# for p in soup.find_all("p", class_="ql-align-justify"): +# if p.find("br") is not None: +# p.decompose() + +# # separate the body in two parts -> the first paragraph and the rest +# first_paragraph = soup.find("p") +# if first_paragraph is not None: +# first_paragraph = str(first_paragraph) +# first_paragraph = first_paragraph.replace("<p>", '<p class="subhead">') +# soup.find("p").decompose() + +# post.first_paragraph = first_paragraph +# post.body = str(soup) +# post.views = "{:,}".format(post.views) + +# tags = post.tags.all() +# comments = Comment.objects.filter(post=post) +# for comment in comments: +# if comment.user: +# user_profile = UserProfile.objects.get(user=comment.user) +# comment.avatar_url = user_profile.avatar_url +# comment.processed_body = comment_processor(comment.body) + +# if comment.anonymous_user: +# user_profile = comment.anonymous_user +# comment.avatar_url = user_profile.avatar +# comment.processed_body = comment_processor(comment.body) + +# if post.is_public: +# # modify request.meta description (only text) and image +# request.meta["description"] = BeautifulSoup( +# first_paragraph, "html.parser" +# ).get_text() +# request.meta["image"] = ( +# "https://shi.foo/ignis/post_image/720/" + str(post.id) + ".gif" +# ) + +# read_next = next_read(post) + +# return render( +# request, +# "blog/post.html", +# { +# "title": post.title, +# "post": post, +# "tags": tags, +# "comments": comments, +# "view_count": view_count, +# "read_next": read_next, +# }, +# ) +# else: +# if ( +# request.user.is_authenticated +# and request.user.is_superuser +# or request.user.is_staff +# ): +# return render( +# request, +# "blog/post.html", +# { +# "title": post.title, +# "post": post, +# "tags": tags, +# "comments": comments, +# "view_count": view_count, +# }, +# ) +# else: +# raise Http404 +# except Post.DoesNotExist: +# raise Http404 + + +# def comment(request, slug): +# if request.method == "POST": +# if request.user.is_authenticated: +# try: +# print(request.POST.get("comment")) +# r_spam = check_spam( +# comment=request.POST.get("comment"), +# post=Post.objects.get(slug=slug), +# ) +# if r_spam != "N": +# messages.error(request, r_spam, extra_tags="spam") +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) + "#new-comment" +# ) + +# # then we continue +# post = Post.objects.get(slug=slug) +# if post.is_public: +# comment = Comment.objects.create( +# user=request.user, post=post, body=request.POST.get("comment") +# ) +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) +# + "#comment-" +# + str(comment.id) +# ) +# else: +# if ( +# request.user.is_authenticated +# and request.user.is_superuser +# or request.user.is_staff +# ): +# Comment.objects.create( +# user=request.user, +# post=post, +# body=request.POST.get("comment"), +# ) +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) +# + "#comment-" +# + str(comment.id) +# ) +# else: +# return HttpResponse("Post not found!", status=404) +# except Post.DoesNotExist: +# return HttpResponse("Post not found!", status=404) + +# else: +# return redirect("blog:home") +# else: +# return redirect("blog:home") + + +# def anon_comment(request, slug): +# if request.method == "POST": +# if request.user.is_authenticated: +# # not allowed this is anonymous comment form +# return redirect(reverse("blog:post", kwargs={"slug": slug})) +# else: +# anonymous_name = request.POST.get("anonymous-name") +# anonymous_email = request.POST.get("anonymous-email") +# anonymous_token, at = request.POST.get("anonymous-token"), request.POST.get( +# "anonymous-token" +# ) +# new_anonymous_token = request.POST.get("new-anonymous-token") +# anonymous_comment = request.POST.get("anonymous-comment") +# res_spam = check_spam( +# comment=anonymous_comment, post=Post.objects.get(slug=slug) +# ) +# if res_spam != "N": +# messages.error(request, res_spam, extra_tags="spam") +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) + "#new-comment" +# ) + +# # now continue with the comment +# if not anonymous_name: +# messages.error(request, "Please enter a name!") +# return redirect(reverse("blog:post", kwargs={"slug": slug})) +# if not anonymous_comment: +# messages.error(request, "Please enter a comment!") +# return redirect(reverse("blog:post", kwargs={"slug": slug})) +# if not anonymous_email: +# anonymous_email = ( +# "".join(random.choice(string.ascii_lowercase) for i in range(10)) +# + "@anonymous.shi.foo" +# ) +# if not anonymous_token: +# anonymous_token = "".join( +# random.choice(string.ascii_lowercase) for i in range(10) +# ) +# at = anonymous_token + +# # generate a random avatar for the anonymous user +# avatarlist = avatar_list() +# for key in avatarlist: +# avatarlist[key] = [ +# re.sub(r"\.gif$", "", string) for string in avatarlist[key] +# ] +# avatarlist[key].sort(key=natural_keys) +# avatarlist = {k: avatarlist[k] for k in sorted(avatarlist)} +# avatar_dir = choice(list(avatarlist.keys())) +# avatar_file = choice(avatarlist[avatar_dir]) +# anonymous_avatar = avatar_dir + "/" + avatar_file +# anonymous_token = hashlib.sha256( +# anonymous_token.encode("utf-8") +# ).hexdigest() +# try: +# anonymous_user = AnonymousCommentUser.objects.get( +# email=anonymous_email, token=anonymous_token +# ) +# except AnonymousCommentUser.DoesNotExist: +# anonymous_user = AnonymousCommentUser.objects.create( +# email=anonymous_email, +# token=anonymous_token, +# avatar=anonymous_avatar, +# ) +# if new_anonymous_token: +# at = new_anonymous_token +# new_anonymous_token = hashlib.sha256( +# new_anonymous_token.encode("utf-8") +# ).hexdigest() +# anonymous_user.token = new_anonymous_token +# anonymous_user.save() + +# # update the anonymous user's name if it has changed +# if anonymous_user.name != anonymous_name: +# anonymous_user.name = anonymous_name +# anonymous_user.save() + +# comment = Comment.objects.create( +# anonymous_user=anonymous_user, +# post=Post.objects.get(slug=slug), +# body=anonymous_comment, +# ) + +# # redirect to the post with the comment but set the anonymous user cookie +# response = redirect( +# reverse("blog:post", kwargs={"slug": slug}) +# + "#comment-" +# + str(comment.id) +# ) +# response.set_cookie( +# "anonymous_name", anonymous_user.name, max_age=60 * 60 * 24 * 365 +# ) +# response.set_cookie( +# "anonymous_email", anonymous_user.email, max_age=60 * 60 * 24 * 365 +# ) +# response.set_cookie("anonymous_token", at, max_age=60 * 60 * 24 * 365) + +# return response + +# else: +# return redirect("blog:home") + + +# def edit_comment(request, slug): +# if request.method == "POST": +# if request.user.is_authenticated: + +# try: +# comment = Comment.objects.get(id=request.POST.get("comment_id")) +# # check for spam first +# user_ip = request.META.get("HTTP_X_FORWARDED_FOR") +# if user_ip: +# user_ip = user_ip.split(",")[0] +# else: +# user_ip = request.META.get("REMOTE_ADDR") +# user_agent_string = request.META.get("HTTP_USER_AGENT", "") +# user_agent = parse(user_agent_string) +# # if check_spam(user_ip=user_ip, user_agent=user_agent, comment=request.POST.get('body'), author=request.user.username +# res_spam = check_spam( +# comment=request.POST.get("body"), post=comment.post +# ) +# if res_spam != "N": +# messages.error(request, request.POST.get("body"), extra_tags="spam") +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) +# + "#comment-" +# + str(comment.id) +# ) +# if comment.user == request.user: +# comment.body = request.POST.get("body") +# comment.edited = True +# comment.edited_at = datetime.now() +# comment.save() +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) +# + "#comment-" +# + str(comment.id) +# ) +# else: +# return HttpResponse("Unauthorized!", status=401) +# except Comment.DoesNotExist: +# return HttpResponse("Comment not found!", status=404) +# else: +# return redirect("blog:home") +# else: +# return redirect("blog:home") + + +# def anon_edit_comment(request, slug): +# if request.method == "POST": +# if request.user.is_authenticated: +# # not allowed this is anonymous comment form +# return redirect(reverse("blog:post", kwargs={"slug": slug})) +# else: + +# anonymous_token = request.COOKIES.get("anonymous_token") +# if not anonymous_token: +# return HttpResponse("Unauthorized!", status=401) +# try: +# anonymous_token = hashlib.sha256( +# anonymous_token.encode("utf-8") +# ).hexdigest() +# comment = Comment.objects.get(id=request.POST.get("comment_id")) +# # check for spam first +# user_ip = request.META.get("HTTP_X_FORWARDED_FOR") +# if user_ip: +# user_ip = user_ip.split(",")[0] +# else: +# user_ip = request.META.get("REMOTE_ADDR") +# user_agent_string = request.META.get("HTTP_USER_AGENT", "") +# user_agent = parse(user_agent_string) +# res_spam = check_spam( +# comment=request.POST.get("body"), post=comment.post +# ) +# if res_spam != "N": +# # if check_spam(user_ip=user_ip, user_agent=user_agent, comment=request.POST.get('body'), author=comment.anonymous_user.name): +# messages.error(request, request.POST.get("body"), extra_tags="spam") +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) +# + "#comment-" +# + str(comment.id) +# ) +# if comment.anonymous_user.token == anonymous_token: +# comment.body = request.POST.get("body") +# comment.edited = True +# comment.edited_at = datetime.now() +# comment.save() +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) +# + "#comment-" +# + str(comment.id) +# ) +# else: +# return HttpResponse("Unauthorized!", status=401) +# except Comment.DoesNotExist: +# return HttpResponse("Comment not found!", status=404) +# else: +# return redirect("blog:home") + + +# def delete_comment(request, slug, comment_id): +# if request.user.is_authenticated: +# try: +# comment = Comment.objects.get(id=comment_id) +# if comment.user == request.user: +# comment.delete() +# return redirect( +# reverse("blog:post", kwargs={"slug": slug}) + "#comments" +# ) +# else: +# return HttpResponse("Unauthorized!", status=401) +# except Comment.DoesNotExist: +# return HttpResponse("Comment not found!", status=404) +# else: +# return HttpResponseRedirect(request.META.get("HTTP_REFERER")) + + +# def anon_delete_comment(request, slug, comment_id): +# if request.user.is_authenticated: +# # not allowed this is anonymous comment form +# return HttpResponseRedirect(request.META.get("HTTP_REFERER")) +# else: +# anonymous_token = request.COOKIES.get("anonymous_token") +# if not anonymous_token: +# return HttpResponse("Unauthorized!", status=401) +# anonymous_token = hashlib.sha256(anonymous_token.encode("utf-8")).hexdigest() +# try: +# comment = Comment.objects.get( +# id=comment_id, anonymous_user__token=anonymous_token +# ) +# comment.delete() +# return redirect(reverse("blog:post", kwargs={"slug": slug}) + "#comments") +# except Comment.DoesNotExist: +# return HttpResponse("Comment not found!", status=404) + + +# def search(request): +# query = request.GET.get("q") +# search_in = ( +# request.GET.getlist("search_in") if request.GET.get("search_in") else ["posts"] +# ) +# sort_by = request.GET.get("sort_by") if request.GET.get("sort_by") else "relevance" +# order = request.GET.get("order") if request.GET.get("order") else "ascending" +# date_range = ( +# request.GET.get("date_range") if request.GET.get("date_range") else "any" +# ) +# search_model_map = { +# "posts": Post, +# "users": User, +# "comments": Comment, +# } +# now = timezone.now() + +# if query: +# search_results = SearchQuerySet().filter(content=query) +# if search_in: +# search_results = search_results.models( +# *[search_model_map[model] for model in search_in] +# ) + +# # search_results = [result.object for result in search_results] +# posts = [ +# result.object +# for result in search_results +# if isinstance(result.object, Post) +# ] +# users = [ +# result.object +# for result in search_results +# if isinstance(result.object, User) +# ] +# comments = [ +# result.object +# for result in search_results +# if isinstance(result.object, Comment) +# ] + +# # match-case sort_by +# if sort_by == "relevance" and order == "ascending": +# posts = sorted(posts, key=lambda post: post.views) +# users = sorted(users, key=lambda user: user.username) +# comments = sorted(comments, key=lambda comment: comment.id) +# elif sort_by == "relevance" and order == "descending": +# posts = sorted(posts, key=lambda post: post.views, reverse=True) +# users = sorted(users, key=lambda user: user.username, reverse=True) +# comments = sorted(comments, key=lambda comment: comment.id, reverse=True) +# elif sort_by == "date" and order == "ascending": +# posts = sorted(posts, key=lambda post: post.date) +# users = sorted(users, key=lambda user: user.date_joined) +# comments = sorted(comments, key=lambda comment: comment.created_at) +# elif sort_by == "date" and order == "descending": +# posts = sorted(posts, key=lambda post: post.date, reverse=True) +# users = sorted(users, key=lambda user: user.date_joined, reverse=True) +# comments = sorted( +# comments, key=lambda comment: comment.created_at, reverse=True +# ) + +# # filter by date_range +# if date_range == "past_day": +# posts = [post for post in posts if post.date >= now - timedelta(days=1)] +# users = [ +# user for user in users if user.date_joined >= now - timedelta(days=1) +# ] +# comments = [ +# comment +# for comment in comments +# if comment.created_at >= now - timedelta(days=1) +# ] +# elif date_range == "past_week": +# posts = [post for post in posts if post.date >= now - timedelta(days=7)] +# users = [ +# user for user in users if user.date_joined >= now - timedelta(days=7) +# ] +# comments = [ +# comment +# for comment in comments +# if comment.created_at >= now - timedelta(days=7) +# ] +# elif date_range == "past_month": +# posts = [post for post in posts if post.date >= now - timedelta(days=30)] +# users = [ +# user for user in users if user.date_joined >= now - timedelta(days=30) +# ] +# comments = [ +# comment +# for comment in comments +# if comment.created_at >= now - timedelta(days=30) +# ] +# elif date_range == "past_year": +# posts = [post for post in posts if post.date >= now - timedelta(days=365)] +# users = [ +# user for user in users if user.date_joined >= now - timedelta(days=365) +# ] +# comments = [ +# comment +# for comment in comments +# if comment.created_at >= now - timedelta(days=365) +# ] +# elif date_range == "any": +# # no need to filter +# pass + +# search_results = len(posts) + len(users) + len(comments) +# else: +# search_results = 0 + +# # attach user profiles +# for user in users: +# user.profile = UserProfile.objects.get(user=user) + +# # parse comments +# for comment in comments: +# comment.body = comment_processor(comment.body) + +# return render( +# request, +# "blog/search.html", +# { +# "title": f"Search results for '{query}'", +# "query": query, +# "search_results": search_results, +# "search_in": search_in, +# "sort_by": sort_by, +# "order": order, +# "date_range": date_range, +# "posts": posts, +# "users": users, +# "comments": comments, +# }, +# ) + + +# def articles(request, date=None, cg=None): +# type = "articles" +# page = request.GET.get("page") if request.GET.get("page") else 1 +# order_by = request.GET.get("order_by") if request.GET.get("order_by") else "date" +# direction = request.GET.get("direction") if request.GET.get("direction") else "desc" +# categories = Category.objects.all() +# category = request.GET.get("category") +# try: +# page = int(page) +# except: +# page = 1 + +# posts = Post.objects.filter(is_public=True) + +# if date: +# date_month = date.split("_")[0] # month name like 'Decemeber' +# date_year = date.split("_")[1] # year like '2019' +# date_m = datetime.strptime( +# date_month, "%B" +# ).month # convert month name to month number +# posts = Post.objects.filter( +# is_public=True, date__month=date_m, date__year=date_year +# ) +# type = "articles-archive" +# date = date_month + " " + date_year + +# if cg: +# cg = str.lower(cg) +# if category and cg != category and category != "all": +# return redirect(reverse("blog:categories") + "/{}".format(category)) +# category = cg +# posts = Post.objects.filter(is_public=True, category__slug=cg) +# type = "articles-category" + +# posts = ( +# posts.order_by("-" + order_by) +# if direction == "desc" +# else Post.objects.filter(is_public=True).order_by(order_by) +# ) +# if category and category != "all": +# posts = posts.filter(category__slug=category) +# category_name = Category.objects.get(slug=category).name +# else: +# category = "all" +# posts = Paginator(posts, 10) +# num_pages = posts.num_pages +# try: +# posts = posts.page(page) +# except: +# posts = posts.page(num_pages) + +# for post in posts: +# post.excerpt = add_excerpt(post) +# post.num_comments = add_num_comments(post) +# return render( +# request, +# "blog/articles.html", +# { +# "title": "Articles", +# "posts": posts, +# "num_pages": num_pages, +# "page": page, +# "order_by": order_by, +# "direction": direction, +# "categories": categories, +# "category": category, +# "category_name": category_name if category != "all" else "", +# "type": type, +# "date": date if date else "", +# "cg": cg if cg else "", +# }, +# ) + + +# def user_activity(request, username): +# try: +# user = User.objects.get(username__iexact=username) +# user_profile = UserProfile.objects.get(user=user) +# if user_profile.is_public or user == request.user: +# recent_comments = Comment.objects.filter(user=user).order_by("-created_at")[ +# :5 +# ] +# else: +# recent_comments = [] + +# if user_profile.email_public: +# user_email = user.email +# else: +# user_email = "" + +# for comment in recent_comments: +# comment.body = comment_processor(comment.body) + +# return render( +# request, +# "blog/activity.html", +# { +# "title": "User Activity", +# "activity_user": user, +# "activity_user_profile": user_profile, +# "activity_recent_comments": recent_comments, +# "activity_user_email": user_email, +# }, +# ) +# except User.DoesNotExist: +# # return default 404 page +# raise Http404 + + +# def archives(request): +# archives = Post.objects.filter(is_public=True).dates("date", "month", order="DESC") +# return render( +# request, "blog/archives.html", {"title": "Archives", "archives": archives} +# ) + + +# def categories(request): +# categories = Category.objects.all() +# return render( +# request, +# "blog/categories.html", +# {"title": "Categories", "categories": categories}, +# ) + + +# def policy(request): +# return render(request, "blog/site_policy.html", {"title": "Site Policy"}) + + +# def socialify(request): +# url = request.GET.get("url") if request.GET.get("url") else None +# if url: +# # convert Github URL to repo owner/name +# if "github.com" in url: +# url = url.split("github.com/")[1] +# url = url.split("/") +# url = url[0] + "/" + url[1] +# socialify_options = { +# "theme": "Dark" if not request.GET.get("theme") else request.GET.get("theme"), +# "font": "Inter" if not request.GET.get("font") else request.GET.get("font"), +# "description": ( +# 0 if not request.GET.get("description") else request.GET.get("description") +# ), +# "forks": 0 if not request.GET.get("forks") else request.GET.get("forks"), +# "issues": 0 if not request.GET.get("issues") else request.GET.get("issues"), +# "language_1": ( +# 0 if not request.GET.get("language_1") else request.GET.get("language_1") +# ), +# "language_2": ( +# 0 if not request.GET.get("language_2") else request.GET.get("language_2") +# ), +# "name": 0 if not request.GET.get("name") else request.GET.get("name"), +# "owner": 1 if not request.GET.get("owner") else request.GET.get("owner"), +# "stargazers": ( +# 0 if not request.GET.get("stargazers") else request.GET.get("stargazers") +# ), +# "pulls": 0 if not request.GET.get("pulls") else request.GET.get("pulls"), +# "pattern": ( +# "Plus" if not request.GET.get("pattern") else request.GET.get("pattern") +# ), +# } + +# for key, value in socialify_options.items(): +# if value == "on": +# socialify_options[key] = 1 +# elif value == "off": +# socialify_options[key] = 0 + +# return render( +# request, +# "blog/socialify.html", +# {"title": "Socialify", "options": socialify_options, "url": url}, +# ) + + +# def anilist(request): +# return render(request, "blog/anilist.html", {"title": "My Anime List"}) + + +# @xframe_options_sameorigin +# def anidata(request): +# malURL = "https://myanimelist.net/animelist/crvs" +# MAL = requests.get(malURL) +# MALContent = MAL.content +# MALStatus = MAL.status_code + +# if MALStatus != 200: +# MALContent = '<html><head><link rel="stylesheet" href="/static/css/styles.css"><style>img { width: 75%; display: block; margin: -20px auto 20px auto; } h1 { text-align: center; } p { text-align: center; } body {background: transparent !important;} </style></head><body><img src="/static/images/site/sad-failure.gif" alt="Sad Failure"><h1>MyAnimeList does not seem to respond at the moment.</h1><p>Maybe, we go <a href="https://myanimelist.net/animelist/crvs" target="_blank">knock on their door</a> instead?</p></body></html>' +# else: +# MALContent = MALContent.decode("utf-8") +# MALParsed = BeautifulSoup(MALContent, "html.parser") +# # remove script tags +# for tag in MALParsed(["script", "meta", "noscript"]): +# tag.extract() + +# # add myanimelist.net to relative links +# for link in MALParsed.find_all("a"): +# if link.get("href") and link.get("href")[0] == "/": +# link["href"] = "https://myanimelist.net" + link["href"] + +# # make all links open in new tab +# link["target"] = "_blank" + +# MALContent = MALParsed.prettify() + +# return render( +# request, +# "blog/anidata.html", +# {"title": "My Anime List", "MALContent": MALContent}, +# ) diff --git a/apps/core/views.py b/apps/core/views.py index 0e23722a..037f52c2 100644 --- a/apps/core/views.py +++ b/apps/core/views.py @@ -12,7 +12,7 @@ def home(request): "title": "Home", } LANGUAGE_CODE = i18npatterns(request.LANGUAGE_CODE) - request.meta.update(META) + request.META.update(META) announcements = Announcement.objects.filter(is_public=True).order_by("-created_at") context = { "announcements": announcements, diff --git a/chat/chat_cache.py b/chat/chat_cache.py index 8c107a6c..ed08c5dd 100644 --- a/chat/chat_cache.py +++ b/chat/chat_cache.py @@ -1,54 +1,54 @@ -import json - -import redis - -import os -from dotenv import load_dotenv - -load_dotenv() - -r = redis.Redis( - host=os.getenv('REDIS_HOST'), - port=os.getenv('REDIS_PORT'), - password=os.getenv('REDIS_PASSWORD'), - db=0 -) - -def handle_connect(): - # increase number of connected users - r.set('n_connected_lc_users', max(1, int(r.get('n_connected_lc_users')) + 1)) - print('There are now {} connected users.'.format(r.get('n_connected_lc_users'))) - -def handle_disconnect(): - # decrease number of connected users - r.set('n_connected_lc_users', max(0, int(r.get('n_connected_lc_users')) - 1)) - print('There are now {} connected users.'.format(r.get('n_connected_lc_users'))) - -def handle_alone_user(): - if int(r.get('n_connected_lc_users')) == 1: - return True - else: - return False - -def save_user_messages(user_identifier, message): - # get user_messages from redis - user_messages = r.get(user_identifier) - if user_messages: - user_messages = json.loads(user_messages) - else: - user_messages = [] - # append new message - user_messages.append(message) - # save user_messages to redis - r.set(user_identifier, json.dumps(user_messages)) - -def get_user_messages(user_identifier): - # get user_messages from redis - user_messages = r.get(user_identifier) - if user_messages: - return json.loads(user_messages) - else: - return [] - -def discard_user_messages(user_identifier): - r.delete(user_identifier)
\ No newline at end of file +# import json + +# import redis + +# import os +# from dotenv import load_dotenv + +# load_dotenv() + +# r = redis.Redis( +# host=os.getenv('REDIS_HOST'), +# port=os.getenv('REDIS_PORT'), +# password=os.getenv('REDIS_PASSWORD'), +# db=0 +# ) + +# def handle_connect(): +# # increase number of connected users +# r.set('n_connected_lc_users', max(1, int(r.get('n_connected_lc_users')) + 1)) +# print('There are now {} connected users.'.format(r.get('n_connected_lc_users'))) + +# def handle_disconnect(): +# # decrease number of connected users +# r.set('n_connected_lc_users', max(0, int(r.get('n_connected_lc_users')) - 1)) +# print('There are now {} connected users.'.format(r.get('n_connected_lc_users'))) + +# def handle_alone_user(): +# if int(r.get('n_connected_lc_users')) == 1: +# return True +# else: +# return False + +# def save_user_messages(user_identifier, message): +# # get user_messages from redis +# user_messages = r.get(user_identifier) +# if user_messages: +# user_messages = json.loads(user_messages) +# else: +# user_messages = [] +# # append new message +# user_messages.append(message) +# # save user_messages to redis +# r.set(user_identifier, json.dumps(user_messages)) + +# def get_user_messages(user_identifier): +# # get user_messages from redis +# user_messages = r.get(user_identifier) +# if user_messages: +# return json.loads(user_messages) +# else: +# return [] + +# def discard_user_messages(user_identifier): +# r.delete(user_identifier) diff --git a/chat/consumers.py b/chat/consumers.py index da81449c..f5e89851 100644 --- a/chat/consumers.py +++ b/chat/consumers.py @@ -3,46 +3,50 @@ import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer -from .chat_cache import (discard_user_messages, handle_alone_user, - handle_connect, handle_disconnect) +# from .chat_cache import (discard_user_messages, handle_alone_user, +# handle_connect, handle_disconnect) from .skippy import invokeMFSkippy class ChatConsumer(WebsocketConsumer): - def connect(self): - self.room_group_name = "chat" - # Join room group - async_to_sync(self.channel_layer.group_add)( - self.room_group_name, self.channel_name - ) - - self.accept() - handle_connect() - - def disconnect(self, close_code): - # Leave room group - async_to_sync(self.channel_layer.group_discard)( - self.room_group_name, self.channel_name - ) - handle_disconnect() - discard_user_messages(user_identifier=self.channel_name) - - def receive(self, text_data): - text_data_json = json.loads(text_data) - message = text_data_json['message'] - username = text_data_json['username'] - - # Send message to room group - async_to_sync(self.channel_layer.group_send)( - self.room_group_name, {"type": "chat", "message": message, "username": username} - ) - is_alone_user = handle_alone_user() - if is_alone_user: - skippy_message = invokeMFSkippy(message=message, identifier=self.channel_name) - if skippy_message: - async_to_sync(self.channel_layer.group_send)( - self.room_group_name, {"type": "chat", "message": skippy_message, "username": "Skippy"} - ) + # def connect(self): + # self.room_group_name = "chat" + # # Join room group + # async_to_sync(self.channel_layer.group_add)( + # self.room_group_name, self.channel_name + # ) + + # self.accept() + # handle_connect() + + # def disconnect(self, close_code): + # # Leave room group + # async_to_sync(self.channel_layer.group_discard)( + # self.room_group_name, self.channel_name + # ) + # handle_disconnect() + # discard_user_messages(user_identifier=self.channel_name) + + # def receive(self, text_data): + # text_data_json = json.loads(text_data) + # message = text_data_json["message"] + # username = text_data_json["username"] + + # # Send message to room group + # async_to_sync(self.channel_layer.group_send)( + # self.room_group_name, + # {"type": "chat", "message": message, "username": username}, + # ) + # is_alone_user = handle_alone_user() + # if is_alone_user: + # skippy_message = invokeMFSkippy( + # message=message, identifier=self.channel_name + # ) + # if skippy_message: + # async_to_sync(self.channel_layer.group_send)( + # self.room_group_name, + # {"type": "chat", "message": skippy_message, "username": "Skippy"}, + # ) # Receive message from room group def chat(self, event): @@ -51,4 +55,3 @@ class ChatConsumer(WebsocketConsumer): # Send message to WebSocket self.send(text_data=json.dumps({"message": message, "username": username})) - diff --git a/chat/skippy.py b/chat/skippy.py index 6fa3aaa1..55b6e593 100644 --- a/chat/skippy.py +++ b/chat/skippy.py @@ -1,10 +1,14 @@ -from .chat_cache import get_user_messages, save_user_messages +# from .chat_cache import get_user_messages, save_user_messages def invokeMFSkippy(message, identifier): - save_user_messages(user_identifier=identifier, message={'content': message, 'role': 'user'}) - user_messages = get_user_messages(user_identifier=identifier) - if len(user_messages) == 1: - return "Skippy here. No one's around, you are free to browse around or keep sending messages like a weirdo. Bye." - else: - return None + # save_user_messages( + # user_identifier=identifier, message={"content": message, "role": "user"} + # ) + # user_messages = get_user_messages(user_identifier=identifier) + # if len(user_messages) == 1: + return "Skippy here. No one's around, you are free to browse around or keep sending messages like a weirdo. Bye." + + +# else: +# return None diff --git a/dev_status/urls.py b/dev_status/urls.py index 62c4c3a2..904114fc 100644 --- a/dev_status/urls.py +++ b/dev_status/urls.py @@ -3,9 +3,9 @@ from django.views.generic import RedirectView from . import views -app_name = 'dev_status' +app_name = "dev_status" urlpatterns = [ - path('', views.home, name='home'), - path('/<str:r>', views.get_repo, name='repo'), - path('/<str:r>/<path:p>', views.get_repo, name='repo-path'), + # path('', views.home, name='home'), + # path('/<str:r>', views.get_repo, name='repo'), + # path('/<str:r>/<path:p>', views.get_repo, name='repo-path'), ] diff --git a/dev_status/views.py b/dev_status/views.py index 217f7121..ae6afb7c 100644 --- a/dev_status/views.py +++ b/dev_status/views.py @@ -1,268 +1,268 @@ -import math -import os -import re +# import math +# import os +# import re -import requests -from django.shortcuts import render -from dotenv import load_dotenv -from github import Github -from dev_status.utils import ( - relative_date, - text_lines, - text_loc, - size_format, - highlight_code, -) +# import requests +# from django.shortcuts import render +# from dotenv import load_dotenv +# from github import Github +# from dev_status.utils import ( +# relative_date, +# text_lines, +# text_loc, +# size_format, +# highlight_code, +# ) -load_dotenv() -g = Github(os.getenv("GH_TOKEN")) +# load_dotenv() +# g = Github(os.getenv("GH_TOKEN")) -# Create your views here. -def home(request): - page = request.GET.get("page") or 1 - items = request.GET.get("items") or 10 - sort = request.GET.get("sort") or "pushed" - direction = request.GET.get("direction") or "desc" - search = request.GET.get("search") or "" - context = {} - sort_map = { - "updated": "UPDATED_AT", - "stars": "STARGAZERS", - "pushed": "PUSHED_AT", - "created": "CREATED_AT", - "name": "NAME", - } - direction_map = {"desc": "DESC", "asc": "ASC"} +# # Create your views here. +# def home(request): +# page = request.GET.get("page") or 1 +# items = request.GET.get("items") or 10 +# sort = request.GET.get("sort") or "pushed" +# direction = request.GET.get("direction") or "desc" +# search = request.GET.get("search") or "" +# context = {} +# sort_map = { +# "updated": "UPDATED_AT", +# "stars": "STARGAZERS", +# "pushed": "PUSHED_AT", +# "created": "CREATED_AT", +# "name": "NAME", +# } +# direction_map = {"desc": "DESC", "asc": "ASC"} - # make request to github api to get page of repos and total count of repos - url = "https://api.github.com/graphql" - headers = {"Authorization": "token " + os.getenv("GH_TOKEN")} - user = "luciferreeves" +# # make request to github api to get page of repos and total count of repos +# url = "https://api.github.com/graphql" +# headers = {"Authorization": "token " + os.getenv("GH_TOKEN")} +# user = "luciferreeves" - query = """ - query {{ - user(login: "{user}") {{ - repositories( - first: 100 - orderBy: {{field: {sort}, direction: {direction}}} - ownerAffiliations: OWNER - privacy: PUBLIC - ) {{ - totalCount - edges {{ - node {{ - name - description - forkCount - homepageUrl - isArchived - isFork - licenseInfo {{ - name - }} - pushedAt - stargazerCount - }} - }} - }} - }} - }} - """.format( - user=user, sort=sort_map[sort], direction=direction_map[direction] - ) - data = requests.post(url, json={"query": query}, headers=headers).json() - repos = [ - { - "name": repo["node"]["name"], - "description": repo["node"]["description"], - "forkCount": repo["node"]["forkCount"], - "homepageUrl": repo["node"]["homepageUrl"], - "isArchived": repo["node"]["isArchived"], - "isFork": repo["node"]["isFork"], - "licenseInfo": repo["node"]["licenseInfo"], - "pushedAt": repo["node"]["pushedAt"], - "stargazerCount": repo["node"]["stargazerCount"], - } - for repo in data["data"]["user"]["repositories"]["edges"] - ] - total_count = data["data"]["user"]["repositories"]["totalCount"] +# query = """ +# query {{ +# user(login: "{user}") {{ +# repositories( +# first: 100 +# orderBy: {{field: {sort}, direction: {direction}}} +# ownerAffiliations: OWNER +# privacy: PUBLIC +# ) {{ +# totalCount +# edges {{ +# node {{ +# name +# description +# forkCount +# homepageUrl +# isArchived +# isFork +# licenseInfo {{ +# name +# }} +# pushedAt +# stargazerCount +# }} +# }} +# }} +# }} +# }} +# """.format( +# user=user, sort=sort_map[sort], direction=direction_map[direction] +# ) +# data = requests.post(url, json={"query": query}, headers=headers).json() +# repos = [ +# { +# "name": repo["node"]["name"], +# "description": repo["node"]["description"], +# "forkCount": repo["node"]["forkCount"], +# "homepageUrl": repo["node"]["homepageUrl"], +# "isArchived": repo["node"]["isArchived"], +# "isFork": repo["node"]["isFork"], +# "licenseInfo": repo["node"]["licenseInfo"], +# "pushedAt": repo["node"]["pushedAt"], +# "stargazerCount": repo["node"]["stargazerCount"], +# } +# for repo in data["data"]["user"]["repositories"]["edges"] +# ] +# total_count = data["data"]["user"]["repositories"]["totalCount"] - # convert pushedAt to date - for repo in repos: - repo["pushedAt"] = repo["pushedAt"].split("T")[0] +# # convert pushedAt to date +# for repo in repos: +# repo["pushedAt"] = repo["pushedAt"].split("T")[0] - context["search"] = search - if search is not None: - search_term = search.lower() - filtered_repos = [] +# context["search"] = search +# if search is not None: +# search_term = search.lower() +# filtered_repos = [] - for repo in repos: - repo_name = repo["name"] - repo_description = repo["description"] +# for repo in repos: +# repo_name = repo["name"] +# repo_description = repo["description"] - if repo_name is not None and search_term in repo_name.lower(): - filtered_repos.append(repo) - elif ( - repo_description is not None and search_term in repo_description.lower() - ): - filtered_repos.append(repo) +# if repo_name is not None and search_term in repo_name.lower(): +# filtered_repos.append(repo) +# elif ( +# repo_description is not None and search_term in repo_description.lower() +# ): +# filtered_repos.append(repo) - context["repos"] = filtered_repos - context["total_count"] = len(filtered_repos) +# context["repos"] = filtered_repos +# context["total_count"] = len(filtered_repos) - # context["repos"] = [ - # repo - # for repo in repos - # if search.lower() in repo["name"].lower() - # or search.lower() in repo["description"].lower() - # ] - # context["total_count"] = len(context["repos"]) - else: - context["repos"] = repos - context["total_count"] = total_count +# # context["repos"] = [ +# # repo +# # for repo in repos +# # if search.lower() in repo["name"].lower() +# # or search.lower() in repo["description"].lower() +# # ] +# # context["total_count"] = len(context["repos"]) +# else: +# context["repos"] = repos +# context["total_count"] = total_count - # calculate pagination - context["page"] = int(page) - context["items"] = int(items) - context["sort"] = sort - context["title"] = "My Repositories" if not search else ": Search " + search - context["direction"] = direction - context["num_pages"] = math.ceil(context["total_count"] / context["items"]) - context["repos"] = context["repos"][ - (context["page"] - 1) * context["items"] : context["page"] * context["items"] - ] +# # calculate pagination +# context["page"] = int(page) +# context["items"] = int(items) +# context["sort"] = sort +# context["title"] = "My Repositories" if not search else ": Search " + search +# context["direction"] = direction +# context["num_pages"] = math.ceil(context["total_count"] / context["items"]) +# context["repos"] = context["repos"][ +# (context["page"] - 1) * context["items"] : context["page"] * context["items"] +# ] - return render(request, "dev_status/home.html", context) +# return render(request, "dev_status/home.html", context) -def get_repo(request, r=None, p=None): - # this function handles request for browsing the contents of a repository - # the path parameter is optional and is used to browse the contents of a directory - # if the path is not provided, the root directory is displayed - # if the path is a file, the file is displayed +# def get_repo(request, r=None, p=None): +# # this function handles request for browsing the contents of a repository +# # the path parameter is optional and is used to browse the contents of a directory +# # if the path is not provided, the root directory is displayed +# # if the path is a file, the file is displayed - r = r or "thatcomputerscientist" # repository. - p = p or "" # path. +# r = r or "thatcomputerscientist" # repository. +# p = p or "" # path. - url = "https://api.github.com/graphql" - headers = {"Authorization": "token " + os.getenv("GH_TOKEN")} - parent = "/".join(p.split("/")[:-1]) if p and not len(p.split("/")) == 0 else None +# url = "https://api.github.com/graphql" +# headers = {"Authorization": "token " + os.getenv("GH_TOKEN")} +# parent = "/".join(p.split("/")[:-1]) if p and not len(p.split("/")) == 0 else None - # get the contents of the repository along with the latest commit associated with each file or directory - query = """ - query {{ - repository(owner: "luciferreeves", name: "{repo}") {{ - defaultBranchRef {{ - name - }} - object(expression: "HEAD:{path}") {{ - ... on Tree {{ - entries {{ - oid - name - type - path - }} - }} - ... on Blob {{ - oid - byteSize - text - isBinary - }} - }} - }} - }} - """.format( - repo=r, path=p - ) +# # get the contents of the repository along with the latest commit associated with each file or directory +# query = """ +# query {{ +# repository(owner: "luciferreeves", name: "{repo}") {{ +# defaultBranchRef {{ +# name +# }} +# object(expression: "HEAD:{path}") {{ +# ... on Tree {{ +# entries {{ +# oid +# name +# type +# path +# }} +# }} +# ... on Blob {{ +# oid +# byteSize +# text +# isBinary +# }} +# }} +# }} +# }} +# """.format( +# repo=r, path=p +# ) - data = requests.post(url, json={"query": query}, headers=headers).json() +# data = requests.post(url, json={"query": query}, headers=headers).json() - tree = [] - try: - viewMode = ( - "tree" if "entries" in data["data"]["repository"]["object"] else "blob" - ) - except: - viewMode = "blob" +# tree = [] +# try: +# viewMode = ( +# "tree" if "entries" in data["data"]["repository"]["object"] else "blob" +# ) +# except: +# viewMode = "blob" - # default_branch = data["data"]["repository"]["defaultBranchRef"]["name"] +# # default_branch = data["data"]["repository"]["defaultBranchRef"]["name"] - # order tree by name and folder first if it is a tree - if viewMode == "tree": - tree = sorted( - data["data"]["repository"]["object"]["entries"], - key=lambda x: (x["type"], x["name"]), - ) - # place folders first - tree = sorted(tree, key=lambda x: x["type"], reverse=True) - else: - # if it is a blob, display the file - tree = data["data"]["repository"]["object"] - tree["path"] = p - tree["name"] = p.split("/")[-1] - if not tree["isBinary"]: - tree["lines"] = text_lines(tree["text"]) - tree["loc"] = text_loc(tree["text"]) - tree["text"] = highlight_code(tree["text"], tree["name"]) +# # order tree by name and folder first if it is a tree +# if viewMode == "tree": +# tree = sorted( +# data["data"]["repository"]["object"]["entries"], +# key=lambda x: (x["type"], x["name"]), +# ) +# # place folders first +# tree = sorted(tree, key=lambda x: x["type"], reverse=True) +# else: +# # if it is a blob, display the file +# tree = data["data"]["repository"]["object"] +# tree["path"] = p +# tree["name"] = p.split("/")[-1] +# if not tree["isBinary"]: +# tree["lines"] = text_lines(tree["text"]) +# tree["loc"] = text_loc(tree["text"]) +# tree["text"] = highlight_code(tree["text"], tree["name"]) - # get commit information for each file or directory - if viewMode == "tree": - query = """ - query {{ - repository(owner: "luciferreeves", name: "{repo}") {{ - defaultBranchRef {{ - target {{ - ... on Commit {{ - """.format( - repo=r - ) +# # get commit information for each file or directory +# if viewMode == "tree": +# query = """ +# query {{ +# repository(owner: "luciferreeves", name: "{repo}") {{ +# defaultBranchRef {{ +# target {{ +# ... on Commit {{ +# """.format( +# repo=r +# ) - for entry in tree: - # make path character only - entry["uniquename"] = re.sub(r"[^a-zA-Z]", "", entry["path"]) +# for entry in tree: +# # make path character only +# entry["uniquename"] = re.sub(r"[^a-zA-Z]", "", entry["path"]) - query += """ - {uniquename}: history(first: 1, path: "{path}") {{ - nodes {{ - committedDate - message - }} - }} - """.format( - path=entry["path"], uniquename=entry["uniquename"] - ) +# query += """ +# {uniquename}: history(first: 1, path: "{path}") {{ +# nodes {{ +# committedDate +# message +# }} +# }} +# """.format( +# path=entry["path"], uniquename=entry["uniquename"] +# ) - query += "\n}\n}\n}\n}\n}" +# query += "\n}\n}\n}\n}\n}" - commit_data = requests.post(url, json={"query": query}, headers=headers).json() - try: - for entry in tree: - entry["commit"] = commit_data["data"]["repository"]["defaultBranchRef"][ - "target" - ][entry["uniquename"]]["nodes"][0] - entry = relative_date(entry) - except: - pass +# commit_data = requests.post(url, json={"query": query}, headers=headers).json() +# try: +# for entry in tree: +# entry["commit"] = commit_data["data"]["repository"]["defaultBranchRef"][ +# "target" +# ][entry["uniquename"]]["nodes"][0] +# entry = relative_date(entry) +# except: +# pass - context = {} - context["title"] = "Repository: " + r + " - " + p - context["files"] = tree - context["parent"] = parent - context["repo"] = r +# context = {} +# context["title"] = "Repository: " + r + " - " + p +# context["files"] = tree +# context["parent"] = parent +# context["repo"] = r - if "byteSize" in tree: - tree["size"] = size_format(tree["byteSize"]) - # isImage? - if viewMode == "blob": - context["files"]["def_branch"] = data["data"]["repository"]["defaultBranchRef"][ - "name" - ] - if tree["name"].endswith( - (".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".ico", ".bmp") - ): - context["files"]["isImage"] = True +# if "byteSize" in tree: +# tree["size"] = size_format(tree["byteSize"]) +# # isImage? +# if viewMode == "blob": +# context["files"]["def_branch"] = data["data"]["repository"]["defaultBranchRef"][ +# "name" +# ] +# if tree["name"].endswith( +# (".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".ico", ".bmp") +# ): +# context["files"]["isImage"] = True - return render(request, "dev_status/repo.html", context) +# return render(request, "dev_status/repo.html", context) diff --git a/ignis/views.py b/ignis/views.py index f681f64d..1a8f38ae 100644 --- a/ignis/views.py +++ b/ignis/views.py @@ -2,11 +2,13 @@ import json from io import BytesIO import requests -from captcha.image import ImageCaptcha + +# from captcha.image import ImageCaptcha from django.core.files.base import ContentFile from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt -from PIL import Image + +# from PIL import Image from apps.blog.models import Post from services.users.tokens import CaptchaTokenGenerator @@ -31,10 +33,10 @@ def tex(request): + expression ).content - # Image is a transparent GIF with black text. Invert the colors. - image = Image.open(BytesIO(image)) - image = image.convert("RGBA") - image = Image.eval(image, lambda x: 255 - x) + # # Image is a transparent GIF with black text. Invert the colors. + # image = Image.open(BytesIO(image)) + # image = image.convert("RGBA") + # image = Image.eval(image, lambda x: 255 - x) # Convert back to gif and return output = BytesIO() @@ -62,14 +64,14 @@ def post_image(request, size, post_id): elif size > 1000: size = 1000 - image = Image.open(f) + # image = Image.open(f) # resize width to size, compute height width, height = image.size height = int(height * (size / width)) width = size # resize image - image = image.resize((width, height), Image.ANTIALIAS) + # image = image.resize((width, height), Image.ANTIALIAS) output = BytesIO() image.save(output, format="GIF") return HttpResponse(output.getvalue(), content_type="image/gif") @@ -93,7 +95,7 @@ def get_image(request, post_id, image_name): with open(image.path, "rb") as f: image_file = f.read() # convert to gif - image = Image.open(BytesIO(image_file)) + # image = Image.open(BytesIO(image_file)) # check image format if image.format != "GIF": image = image.convert("RGBA") @@ -122,8 +124,8 @@ def cover_image(request, repository): image = requests.get(url).content # reduce image size to 320x160 - image = Image.open(BytesIO(image)) - image = image.resize((320, 160), Image.ANTIALIAS) + # image = Image.open(BytesIO(image)) + # image = image.resize((320, 160), Image.ANTIALIAS) # remove black background image = image.convert("RGBA").getdata() @@ -136,7 +138,7 @@ def cover_image(request, repository): # Convert back to png and return output = BytesIO() - image = Image.new("RGBA", (320, 160)) + # image = Image.new("RGBA", (320, 160)) image.putdata(new_data) image.save(output, format="GIF") image = output.getvalue() @@ -178,14 +180,14 @@ def upload_image(request): def captcha_image(request, captcha_string): captcha = CaptchaTokenGenerator().decrypt(captcha_string) - imgcaptcha = ImageCaptcha() - imgcaptcha.character_rotate = (-15, 15) - imgcaptcha.character_warp_dx = (0, 0) - imgcaptcha.character_warp_dy = (0, 0) - imgcaptcha.character_offset_dx = (12, 20) - imgcaptcha.character_offset_dy = (0, 6) - data = imgcaptcha.generate(captcha) - return HttpResponse(data, content_type="image/png") + # imgcaptcha = ImageCaptcha() + # imgcaptcha.character_rotate = (-15, 15) + # imgcaptcha.character_warp_dx = (0, 0) + # imgcaptcha.character_warp_dy = (0, 0) + # imgcaptcha.character_offset_dx = (12, 20) + # imgcaptcha.character_offset_dy = (0, 6) + # data = imgcaptcha.generate(captcha) + return HttpResponse("", content_type="image/png") def socialify(request): diff --git a/middleware/userprofilemiddleware.py b/middleware/userprofilemiddleware.py index 96a7997e..a7d2a281 100644 --- a/middleware/userprofilemiddleware.py +++ b/middleware/userprofilemiddleware.py @@ -6,7 +6,11 @@ from apps.blog.models import Post class UserProfileMiddleware(MiddlewareMixin): def process_request(self, request): if request.user.is_authenticated: - user_profile = UserProfile.objects.get(user=request.user) + try: + user_profile = UserProfile.objects.get(user=request.user) + except UserProfile.DoesNotExist: + user_profile = UserProfile(user=request.user) + user_profile.save() request.user.profile = user_profile request.user.profile.weblogs_created = Post.objects.filter( author=request.user diff --git a/middleware/uuidmiddleware.py b/middleware/uuidmiddleware.py index 42fe5903..90200e97 100644 --- a/middleware/uuidmiddleware.py +++ b/middleware/uuidmiddleware.py @@ -1,81 +1,81 @@ -import json -import uuid +# import json +# import uuid -import redis -import os -from dotenv import load_dotenv +# import redis +# import os +# from dotenv import load_dotenv -load_dotenv() +# load_dotenv() -redis_instance = redis.StrictRedis( - host=os.getenv('REDIS_HOST'), - port=os.getenv('REDIS_PORT'), - password=os.getenv('REDIS_PASSWORD'), - db=0 -) +# redis_instance = redis.StrictRedis( +# host=os.getenv('REDIS_HOST'), +# port=os.getenv('REDIS_PORT'), +# password=os.getenv('REDIS_PASSWORD'), +# db=0 +# ) -class UserUUIDMiddleware: - # assign a uuid to the user if they don't have one - # store in cookies for 365 days - def __init__(self, get_response): - self.get_response = get_response - self.cookie_name = 'user_uuid' +# class UserUUIDMiddleware: +# # assign a uuid to the user if they don't have one +# # store in cookies for 365 days +# def __init__(self, get_response): +# self.get_response = get_response +# self.cookie_name = 'user_uuid' - def __call__(self, request): - if not request.COOKIES.get(self.cookie_name): - response = self.get_response(request) - response.set_cookie(self.cookie_name, uuid.uuid4(), max_age=31536000) - return response - return self.get_response(request) +# def __call__(self, request): +# if not request.COOKIES.get(self.cookie_name): +# response = self.get_response(request) +# response.set_cookie(self.cookie_name, uuid.uuid4(), max_age=31536000) +# return response +# return self.get_response(request) -def userTrackingContextProcessor(request): - # ignore /rss/ path - if '/rss/' in request.path: - return { - 'anonymous_users': 0, - 'logged_in_users': 0, - 'admin_users': 0, - } +# def userTrackingContextProcessor(request): +# # ignore /rss/ path +# if '/rss/' in request.path: +# return { +# 'anonymous_users': 0, +# 'logged_in_users': 0, +# 'admin_users': 0, +# } - # user tracking context processor - track 3 types of users (anonymous, logged in, admin) - # based on the user's uuid cookie. Only UUID are necessary to track online users. Then we - # separate them into anonymous, logged in, and admin users based on their permissions. +# # user tracking context processor - track 3 types of users (anonymous, logged in, admin) +# # based on the user's uuid cookie. Only UUID are necessary to track online users. Then we +# # separate them into anonymous, logged in, and admin users based on their permissions. - # get the user's uuid from the cookie - user_uuid = request.COOKIES.get('user_uuid') - user_data = { - 'is_authenticated': request.user.is_authenticated, - 'is_staff': request.user.is_staff, - } +# # get the user's uuid from the cookie +# user_uuid = request.COOKIES.get('user_uuid') +# user_data = { +# 'is_authenticated': request.user.is_authenticated, +# 'is_staff': request.user.is_staff, +# } - redis_instance.set(f"presence_{user_uuid}", json.dumps(user_data), ex=300) +# redis_instance.set(f"presence_{user_uuid}", json.dumps(user_data), ex=300) - # get all online users - online_now = redis_instance.keys('presence_*') +# # get all online users +# online_now = redis_instance.keys('presence_*') - # separate online users into anonymous, logged in, and admin users - anonymous_users = [] - logged_in_users = [] - admin_users = [] +# # separate online users into anonymous, logged in, and admin users +# anonymous_users = [] +# logged_in_users = [] +# admin_users = [] - for user in online_now: - user_data = redis_instance.get(user) - user_data = json.loads(user_data) - if user_data['is_authenticated'] == False and user_data['is_staff'] == False: - anonymous_users.append(user_data) - elif user_data['is_authenticated'] == True and user_data['is_staff'] == False: - logged_in_users.append(user_data) - if user_data['is_staff'] == True: - admin_users.append(user_data) +# for user in online_now: +# user_data = redis_instance.get(user) +# user_data = json.loads(user_data) +# if user_data['is_authenticated'] == False and user_data['is_staff'] == False: +# anonymous_users.append(user_data) +# elif user_data['is_authenticated'] == True and user_data['is_staff'] == False: +# logged_in_users.append(user_data) +# if user_data['is_staff'] == True: +# admin_users.append(user_data) - an = len(anonymous_users) - lo = len(logged_in_users) - ad = len(admin_users) - if user_uuid is not None: - an = max((an - 1), 0) if lo + ad > 0 else max(an - 1, 1) +# an = len(anonymous_users) +# lo = len(logged_in_users) +# ad = len(admin_users) +# if user_uuid is not None: +# an = max((an - 1), 0) if lo + ad > 0 else max(an - 1, 1) - return { - 'anonymous_users': an, - 'logged_in_users': lo, - 'admin_users': ad, - } +# return { +# 'anonymous_users': an, +# 'logged_in_users': lo, +# 'admin_users': ad, +# } diff --git a/requirements.txt b/requirements.txt index 424177b1..d3847555 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,34 +1,8 @@ django -dnspython -django-redis python-dotenv -gunicorn -whitenoise -six -cryptocode -captcha -PyGithub +daphne +channels +dnspython requests -pillow==9.5.0 -pycryptodome -pygments bs4 -jellyfish -fuzzywuzzy -python-Levenshtein -selenium -django-haystack -channels -channels_redis -daphne -user_agents -numpy -scikit-learn -akismet -google-cloud-translate -django-hosts -apscheduler -django-sslserver -djangorestframework -django-cors-headers -google-generativeai +pillow diff --git a/services/users/templates/email_change_verification_email.html b/services/users/templates/email_change_verification_email.html index f6f9b127..87a46cbf 100644 --- a/services/users/templates/email_change_verification_email.html +++ b/services/users/templates/email_change_verification_email.html @@ -14,11 +14,11 @@ verify and change your email address, please click the link below. </p> <a - href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}" + {% comment %} href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}" {% endcomment %} >Change Email</a > <p>If the above link does not work, copy and paste the URL below into your browser:</p> - <a href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}">{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}</a> + {% comment %} <a href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}">{{ protocol }}{{ domain }}{% url 'users:changeemail' 'changeemail' uid token %}</a> {% endcomment %} <p>Please ignore this email if you did not make this request.</p> <p>Thanks,</p> diff --git a/services/users/templates/reset_password_email.html b/services/users/templates/reset_password_email.html index f9651a13..7c8a5edc 100644 --- a/services/users/templates/reset_password_email.html +++ b/services/users/templates/reset_password_email.html @@ -13,11 +13,11 @@ We received a request to reset your password on {{ site_name }}. To reset your password, please click the link below. </p> - <a href="{{ protocol }}{{ domain }}{% url 'blog:resetpassword' uid token %}" + <a href="{{ protocol }}{{ domain }}#" >Reset Password</a > <p>If the above link does not work, copy and paste the URL below into your browser:</p> - <a href="{{ protocol }}{{ domain }}{% url 'blog:resetpassword' uid token %}">{{ protocol }}{{ domain }}{% url 'blog:resetpassword' uid token %}</a> + <a href="{{ protocol }}{{ domain }}#">{{ protocol }}{{ domain }}#</a> <p>Please ignore this email if you did not make this request.</p> <p>Thanks,</p> <p>Bobby from {{ site_name }}</p> diff --git a/services/users/templates/verification_email.html b/services/users/templates/verification_email.html index 06e91a79..ca98c4cf 100644 --- a/services/users/templates/verification_email.html +++ b/services/users/templates/verification_email.html @@ -14,11 +14,11 @@ address, please click the link below. </p> <a - href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}" + {% comment %} href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}" {% endcomment %} >Verify Email</a > <p>If the above link does not work, copy and paste the URL below into your browser:</p> - <a href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}">{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}</a> + {% comment %} <a href="{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}">{{ protocol }}{{ domain }}{% url 'users:changeemail' 'verifyemail' uid token %}</a> {% endcomment %} <p>Please ignore this email if you did not make this request.</p> <p>Thanks,</p> <p>Bobby from {{ site_name }}</p> diff --git a/templates/400.html b/templates/400.html index 41beaa4e..e45508f8 100644 --- a/templates/400.html +++ b/templates/400.html @@ -4,7 +4,7 @@ <div style="text-align: center;"> <h1>400 Bad Request</h1> <p>Unfortunately, something went wrong. The server could not understand your request.</p> - <p><a href="{% url 'blog:home' %}" class="button button-special">Go Home</a></p> + <p><a href="#" class="button button-special">Go Home</a></p> </div> </div> {% endblock %} diff --git a/templates/403.html b/templates/403.html index 1ab86cd6..9e0e766e 100644 --- a/templates/403.html +++ b/templates/403.html @@ -4,7 +4,7 @@ <div style="text-align: center;"> <h1>403 Permission Denied</h1> <p>You do not have permission to access this page.</p> - <p><<a href="{% url 'blog:home' %}" class="button button-special">Go Home</a></p> + <p><<a href="#" class="button button-special">Go Home</a></p> </div> </div> {% endblock %} diff --git a/templates/404.html b/templates/404.html index 455f1659..ae858be7 100644 --- a/templates/404.html +++ b/templates/404.html @@ -15,7 +15,7 @@ <p>Hey! Skippy here! I am the 404 Assistant Bot for this site. Looks like you are trying to search an article, but I couldn't find the page. {% if context.similar_posts %}Maybe you are looking for one of these?{% endif %}</p> <ul style="position: relative; left: 30px; top: 10px;"> {% for post in context.similar_posts %} - <li><a href="{% url 'blog:post' post.slug %}">{{ post.title }}</a></li> + <li><a href="#">{{ post.title }}</a></li> {% endfor %} </ul> {% elif context.mode == 'user' %} @@ -24,7 +24,7 @@ <p>Hey! Skippy here! I am the 404 Assistant Bot for this site. Looks like you are trying to search a user with username <b>{{ context.username }}</b> but I couldn't find any user with that username. {% if context.similar_users %}Maybe you are looking for one of these users?{% endif %}</p> <ul style="position: relative; left: 30px; top: 10px;"> {% for user in context.similar_users %} - <li><a href="{% url 'blog:user_activity' user.username %}">{{ user.username }}</a></li> + <li><a href="#">{{ user.username }}</a></li> {% endfor %} </ul> {% else %} @@ -32,7 +32,7 @@ <p>Hey! Skippy here! I am the 404 Assistant Bot for this site. Unfortunately, I couldn't find the page you were looking for. Let me guide you home!</p> {% endif %} <br> - <p><a href="{% url 'blog:home' %}" class="button button-special">Go Home</a></p> + <p><a href="#" class="button button-special">Go Home</a></p> </div> <div style="clear:both;"></div> <div style="margin-top: 28px; border-bottom: dotted 1px #fefefe;"></div> diff --git a/templates/500.html b/templates/500.html index f61b46fa..5cfdd6ca 100644 --- a/templates/500.html +++ b/templates/500.html @@ -4,7 +4,7 @@ <div style="text-align: center;"> <h1>500 Server Error</h1> <p>Sorry, something went wrong. The server encountered an internal error or misconfiguration and was unable to complete your request.</p> - <p><a href="{% url 'blog:home' %}" class="button button-special">Go Home</a></p> + <p><a href="#" class="button button-special">Go Home</a></p> </div> </div> {% endblock %} diff --git a/templates/blog/account.html b/templates/blog/account.html index 7af89675..968433e4 100644 --- a/templates/blog/account.html +++ b/templates/blog/account.html @@ -7,14 +7,14 @@ <img src="{% static 'images/avatars/' %}{{ user_profile.avatar_url }}.gif" alt="{{ user.username }}'s avatar" width="140" height="140" style="display: block; margin: 0 auto;" /> </div> <div id="side-links"> - <p><a href="{% url 'blog:account' %}">Account Home</a></p> - <p><a href="{% url 'blog:account' %}?tab=blinkies">Change profile blinkie</a></p> - <p><a href="{% url 'blog:account' %}?tab=avatar">Change avatar</a></p> - <p><a href="{% url 'blog:account' %}?tab=details">Change details</a></p> - <p><a href="{% url 'blog:account' %}?tab=email">Change email</a></p> - <p><a href="{% url 'blog:account' %}?tab=password">Change password</a></p> + <p><a href="#">Account Home</a></p> + <p><a href="#?tab=blinkies">Change profile blinkie</a></p> + <p><a href="#?tab=avatar">Change avatar</a></p> + <p><a href="#?tab=details">Change details</a></p> + <p><a href="#?tab=email">Change email</a></p> + <p><a href="#?tab=password">Change password</a></p> {% if not user.is_superuser %} - <p><a href="{% url 'blog:account' %}?tab=delete" class="error">Delete account</a></p> + <p><a href="#?tab=delete" class="error">Delete account</a></p> {% endif %} </div> </div> @@ -27,7 +27,7 @@ {% if request.GET.tab == 'avatar' %} <div id="avatar-chooser"> <p>Choose an avatar from the list below. The avatars are grouped by their theme.</p> - <form method="post" action="{% url 'users:updateavatar' %}"> + {% comment %} <form method="post" action="{% url 'users:updateavatar' %}"> {% endcomment %} {% csrf_token %} {% for avatar_dir, avatar_files in avatarlist.items %} <h2 style="clear:both;background-color: #3E4245;padding: 8px 10px;border: none;background: -moz-linear-gradient(90deg, #3E4245 0%, #2E3131 100%); @@ -57,7 +57,7 @@ {% elif request.GET.tab == 'blinkies' %} <div id="blinkie-chooser"> <p>Choose a blinkie to display on your public profile.</p> - <form method="post" action="{% url 'users:updateblinkie' %}"> + {% comment %} <form method="post" action="{% url 'users:updateblinkie' %}"> {% endcomment %} {% csrf_token %} <div style="display: inline; width: 250px; float: left;"> <input type="radio" name="blinkie" value="" id="blinkie_none" checked /> @@ -80,7 +80,7 @@ {% elif request.GET.tab == 'details' %} <div id="details"> <p>Change your account details here. You can change your first name, last name, bio, email and activity visibility.</p> - <form method="post" action="{% url 'users:update' %}"> + {% comment %} <form method="post" action="{% url 'users:update' %}"> {% endcomment %} {% csrf_token %} <table> {{ update_form.as_table }} @@ -91,7 +91,7 @@ {% elif request.GET.tab == 'email' %} <div id="email"> <p>Change your email address here. Your current registered email is <em><u>{{ user.email }}</u></em>. Please note that a verification email will be sent to the new email address in order to update the current email address. Please provide the new email address in the box below:</p> - <form method="post" action = "{% url 'users:sendchangeuseremail' %}"> + {% comment %} <form method="post" action = "{% url 'users:sendchangeuseremail' %}"> {% endcomment %} {% csrf_token %} <p><input type="email" name="email" id="email" required placeholder="New email address" /></p> <input type="submit" value="Update Email" class="button button-special" /> @@ -99,7 +99,7 @@ </div> {% elif request.GET.tab == 'password' %} <div id="password"> - <form method="post" action="{% url 'users:changepassword' %}"> + {% comment %} <form method="post" action="{% url 'users:changepassword' %}"> {% endcomment %} {% csrf_token %} <table> <tr> @@ -122,7 +122,7 @@ {% elif request.GET.tab == 'delete' and not user.is_superuser %} <div id="delete"> <p>Deleting your account will remove all your posts, comments and other data from the website. Please note that this action is irreversible. If you wish to delete your account, please enter your password in the box below:</p> - <form method="post" action="{% url 'users:delete' %}"> + {% comment %} <form method="post" action="{% url 'users:delete' %}"> {% endcomment %} {% csrf_token %} <p><input type="password" name="password" id="password" required placeholder="Password" /></p> <input type="submit" value="Delete Account" class="button button-special" /> diff --git a/templates/blog/activity.html b/templates/blog/activity.html index d963fe1d..e47dd537 100644 --- a/templates/blog/activity.html +++ b/templates/blog/activity.html @@ -9,7 +9,7 @@ <td style="padding-left: 20px;"> <p style="margin-top: 0px;"> <span style="font-size: 16px; font-weight: bold;">{{ activity_user.first_name }} {{ activity_user.last_name }}</span> - <a style="position: relative; top: -2px;" href="{% url 'blog:user_activity' activity_user.username %}"><b>@{{ activity_user.username }}</b></a> + <a style="position: relative; top: -2px;" href="#"><b>@{{ activity_user.username }}</b></a> {% if activity_user_profile.blinkie_url %} <img src="{% static 'images/blinkies/' %}{{ activity_user_profile.blinkie_url }}.gif" alt="{{ activity_user_profile.blinkie_url }}" height="20" width="150" style="position: relative; top: 2px; left: 10px;" /> {% endif %} @@ -37,12 +37,12 @@ {% if activity_recent_comments %} <h2>Recent Comments</h2> {% if not activity_user_profile.is_public and request.user.username == activity_user.username %} - <p class="info">Your profile is not public. Only you can see this information. If you want to change this, go to your <a href="{% url 'blog:account' %}?tab=details">account settings</a>.</p> + <p class="info">Your profile is not public. Only you can see this information. If you want to change this, go to your <a href="#?tab=details">account settings</a>.</p> {% endif %} <ul> {% for comment in activity_recent_comments %} <li style="background: #1c1c1c;padding: 20px 10px 10px 10px;margin-bottom: 10px;border-radius: 8px;"> - <p>On <a href="{% url 'blog:post' comment.post.slug %}#comment-{{ comment.id }}">{{ comment.post.title }}</a>: + <p>On <a href="#comment-{{ comment.id }}">{{ comment.post.title }}</a>: <blockquote style="background: none; margin-top: 15px; padding: 0px 20px; width: 640px; margin-left: 20px;">{{ comment.body|safe }}</blockquote></p> </li> {% endfor %} diff --git a/templates/blog/anilist.html b/templates/blog/anilist.html index 2ab01484..7e60a48b 100644 --- a/templates/blog/anilist.html +++ b/templates/blog/anilist.html @@ -1,7 +1,7 @@ {% extends 'blog/partials/base.html' %} {% block content %} {% load static %} <div class="iframe-loader" style="margin-top: 36px"> <iframe - src="{% url 'blog:anidata' %}" + src="#" width="100%" height="100%" frameborder="0" diff --git a/templates/blog/archives.html b/templates/blog/archives.html index 09ec4963..6c3420a4 100644 --- a/templates/blog/archives.html +++ b/templates/blog/archives.html @@ -10,7 +10,7 @@ <img src="{% static 'images/site/icons/cabinet.gif' %}" alt="Archive" border="0"> </span> <span> - <a href="{% url 'blog:archives' %}/{{ archive | date:"F_Y" }}"> + <a href="#/{{ archive | date:"F_Y" }}"> {{ archive | date:"F Y" }} </a> </span> diff --git a/templates/blog/articles.html b/templates/blog/articles.html index 87bb53cf..79a90732 100644 --- a/templates/blog/articles.html +++ b/templates/blog/articles.html @@ -42,19 +42,19 @@ <td><a class="disabled">«</a></td> <td style="margin-right: 15px;"><a class="disabled">‹</a></td> {% else %} - <td><a href="{% url 'blog:articles' %}?page=1&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">«</a></td> - <td style="margin-right: 15px;"><a href="{% url 'blog:articles' %}?page={{ page|add:'-1' }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">‹</a></td> + <td><a href="#?page=1&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">«</a></td> + <td style="margin-right: 15px;"><a href="#?page={{ page|add:'-1' }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">‹</a></td> {% endif %} {% load times %} {% for i in num_pages|times %} - <td><a {% if i == page %}class="active"{% endif %} href="{% url 'blog:articles' %}?page={{ i }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">{{ i }}</a></td> + <td><a {% if i == page %}class="active"{% endif %} href="#?page={{ i }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">{{ i }}</a></td> {% endfor %} {% if page == num_pages %} <td style="margin-left: 15px;" class="disabled"><a class="disabled">›</a></td> <td><a class="disabled">»</a></td> {% else %} - <td style="margin-left: 15px;"><a href="{% url 'blog:articles' %}?page={{ page|add:'1' }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">›</a></td> - <td><a href="{% url 'blog:articles' %}?page={{ num_pages }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">»</a></td> + <td style="margin-left: 15px;"><a href="#?page={{ page|add:'1' }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">›</a></td> + <td><a href="#?page={{ num_pages }}&order_by={{ order_by }}&direction={{ direction }}&category={{ category }}">»</a></td> {% endif %} </tr> </table> diff --git a/templates/blog/categories.html b/templates/blog/categories.html index b95403ea..aa1eeff6 100644 --- a/templates/blog/categories.html +++ b/templates/blog/categories.html @@ -10,7 +10,7 @@ <img src="{% static 'images/site/icons/books.gif' %}" alt="Archive" border="0"> </span> <span> - <a href="{% url 'blog:categories' %}/{{ category.slug }}"> + <a href="#/{{ category.slug }}"> {{ category }} </a> </span> diff --git a/templates/blog/home.html b/templates/blog/home.html index 739c5227..683afcbe 100644 --- a/templates/blog/home.html +++ b/templates/blog/home.html @@ -3,8 +3,8 @@ {% load i18n %} <link rel="stylesheet" href="{% static 'css/home.css' %}"> <div id="welcome" class="mtctitem"> - {% url 'blog:user_activity' 'bobby' as bobby_profile_url %} - {% url 'blog:register' as register_url %} + {% comment %} {% url 'blog:user_activity' 'bobby' as bobby_profile_url %} + {% url 'blog:register' as register_url %} {% endcomment %} {% blocktrans %} <p> Welcome to the home of <b>Shifoo</b> (previously <i>That Computer Scientist</i>). My name is <a href="{{ bobby_profile_url }}">@bobby</a>, and this is my personal diff --git a/templates/blog/partials/base.html b/templates/blog/partials/base.html index ea517166..6f7affb7 100644 --- a/templates/blog/partials/base.html +++ b/templates/blog/partials/base.html @@ -78,7 +78,7 @@ </div> </div> <div id="search-area"> - <form action="{% url 'blog:search' %}" method="get" id="search-form"> + <form action="#" method="get" id="search-form"> <input type="text" name="q" @@ -140,8 +140,8 @@ clicking them will redirect you to any other website. If you have any questions, comments, or concerns about how this site operates and how your data is handled, please check out the - <a href="{% url 'blog:policy' %}">site policy</a> page. View - <a href="{% url 'django.contrib.sitemaps.views.sitemap' %}">Sitemap</a + <a href="#">site policy</a> page. View + <a href="#">Sitemap</a >. </p> </div> diff --git a/templates/blog/partials/post_list.html b/templates/blog/partials/post_list.html index d72bd723..96a76a19 100644 --- a/templates/blog/partials/post_list.html +++ b/templates/blog/partials/post_list.html @@ -4,20 +4,20 @@ <div class="post"> <div class="post-header"> <h1> - <a style="color: #f4ebff;" href="{% url 'blog:post' post.slug %}">{{ post.title }}</a> + <a style="color: #f4ebff;" href="#">{{ post.title }}</a> </h1> <div class="author-info"> {% with post.author.userprofile_set.first as userprofile %} <span style="background-image: url('{% static 'images/avatars/' %}{{ userprofile.avatar_url }}.gif');" class="post-profile-image"></span> {% endwith %} <span> - <a href="{% url 'blog:user_activity' post.author %}" style="font-weight: bold;"> + <a href="#" style="font-weight: bold;"> {{ post.author.first_name }} {{ post.author.last_name }} </a> </span> <span>posted in</span> <span> - <a href="{% url 'blog:categories' %}/{{ post.category.slug }}" style=""> + <a href="#/{{ post.category.slug }}" style=""> {{ post.category }} </a> </span> @@ -31,13 +31,13 @@ </div> <div class="post-actions" style="clear: both;"> <span style="float: left; margin: 8px 0 0 0;"> - <a href="{% url 'blog:post' post.slug %}">Continue Reading</a> | <a href="{% url 'blog:post' post.slug %}#comments">{{ post.num_comments }} + <a href="#">Continue Reading</a> | <a href="##comments">{{ post.num_comments }} Comment{% if not post.num_comments == 1 %}s{% endif %}</a> </span> {% comment %} tags {% endcomment %} <span style="float: right;"> {% for tag in post.tags.all %} - <a class="tag" href="{% url 'blog:tag_posts' tag.slug %}">{{ tag.name }}</a> + <a class="tag" href="#">{{ tag.name }}</a> {% endfor %} </span> </div> diff --git a/templates/blog/partials/search/comment_list.html b/templates/blog/partials/search/comment_list.html index 7afbced0..d539c6b7 100644 --- a/templates/blog/partials/search/comment_list.html +++ b/templates/blog/partials/search/comment_list.html @@ -2,7 +2,7 @@ <ul style="list-style: none; padding: 0px; margin: 0px;"> {% for comment in comments %} <li style="background: #1c1c1c;padding: 10px; margin-bottom: 10px;border-radius: 8px; max-width: 530px;"> - <p><a class="notranslate" {% if comment.user%}href="{% url 'blog:user_activity' comment.user.username %}"{% endif %}>{% if comment.user %}{{ comment.user.username }}{% else %}{{ comment.anonymous_user.name }}{% endif %}</a> commented on <a href="{% url 'blog:post' comment.post.slug %}#comment-{{ comment.id }}">{{ comment.post.title }}</a> on <em>{{ comment.created_at | date:"M d, Y" }}</em>: + <p><a class="notranslate" {% if comment.user%}href="#"{% endif %}>{% if comment.user %}{{ comment.user.username }}{% else %}{{ comment.anonymous_user.name }}{% endif %}</a> commented on <a href="##comment-{{ comment.id }}">{{ comment.post.title }}</a> on <em>{{ comment.created_at | date:"M d, Y" }}</em>: <blockquote style="background: none; margin-top: 15px; padding: 0px 20px; margin-left: 20px;">{{ comment.body|safe }}</blockquote></p> </li> {% endfor %} diff --git a/templates/blog/partials/search/post_list.html b/templates/blog/partials/search/post_list.html index 811c417e..81afb03e 100644 --- a/templates/blog/partials/search/post_list.html +++ b/templates/blog/partials/search/post_list.html @@ -3,9 +3,9 @@ {% for post in posts %} {% comment %} This is the plain small version for search list {% endcomment %} <h1 style="font-size: 16px; margin: 0 0 4px 0;"> - <a style="color: #f4ebff;" href="{% url 'blog:post' post.slug %}">{{ post.title }}</a> + <a style="color: #f4ebff;" href="#">{{ post.title }}</a> </h1> - <p>Posted by <a href="{% url 'blog:user_activity' post.author %}">{{ post.author.first_name }} {{ post.author.last_name }}</a> in <a href="{% url 'blog:categories' %}/{{ post.category.slug }}">{{ post.category }}</a> on {% localtime on %}{{ post.date | date:"M d, Y" }}{% endlocaltime %}</p> + <p>Posted by <a href="#">{{ post.author.first_name }} {{ post.author.last_name }}</a> in <a href="#/{{ post.category.slug }}">{{ post.category }}</a> on {% localtime on %}{{ post.date | date:"M d, Y" }}{% endlocaltime %}</p> <img style="width: 150px; height: auto; float: left; margin: 0 8px 8px 0;" src="{% url 'ignis:post_image' '150' post.id %}.gif"> <div style="margin: -4px 0 8px 0;"> {{ post.body|truncatewords:150|safe }} @@ -13,11 +13,11 @@ <div style="clear: both; border-top: 1px dashed #fff;"></div> <p><b>Tags:</b> {% for tag in post.tags.all %} - <a class="tag" href="{% url 'blog:tag_posts' tag.slug %}">{{ tag.name }}</a> + <a class="tag" href="#">{{ tag.name }}</a> {% endfor %} </p> <p> - <a href="{% url 'blog:post' post.slug %}">Read complete post...</a> + <a href="#">Read complete post...</a> </p> <br> {% endfor %}
\ No newline at end of file diff --git a/templates/blog/partials/search/user_list.html b/templates/blog/partials/search/user_list.html index 3493508c..3d9ab865 100644 --- a/templates/blog/partials/search/user_list.html +++ b/templates/blog/partials/search/user_list.html @@ -3,7 +3,7 @@ <div class="user_info" style="border: 1px solid #ccc; padding: 10px; margin-bottom: 10px;"> <img src="{% static 'images/avatars/' %}{{ user.profile.avatar_url }}.gif" alt="Profile Picture" style="width: 50px; border-radius: 50%; float: left; margin-right: 10px; margin-top: 5px;"> <div> - <p><a href="{% url 'blog:user_activity' user.username %}">@{{ user.username }}</a> {% if user.first_name %}| <a href="{% url 'blog:user_activity' user.username %}">{{ user.first_name }}{% endif %} {% if user.last_name %}{{ user.last_name }}{% endif %}</a></p> + <p><a href="#">@{{ user.username }}</a> {% if user.first_name %}| <a href="#">{{ user.first_name }}{% endif %} {% if user.last_name %}{{ user.last_name }}{% endif %}</a></p> {% if user.profile.bio %} <p><b>Bio:</b> {{ user.profile.bio }}</p> {% endif %} diff --git a/templates/blog/partials/sidebar.html b/templates/blog/partials/sidebar.html index 458ddbee..83f7628f 100644 --- a/templates/blog/partials/sidebar.html +++ b/templates/blog/partials/sidebar.html @@ -5,7 +5,7 @@ {% for message in messages %} {% if 'loginError' in message.tags %} {% if message.message == "ENVERR" and request.GET.username %} - <form method="post" action="{% url 'users:sendverificationemail' %}" style="position: relative;"> + {% comment %} <form method="post" action="{% url 'users:sendverificationemail' %}" style="position: relative;"> {% endcomment %} {% csrf_token %} <input type="hidden" name="username" value="{{ request.GET.username }}"> <input type="submit" value="" style=" display: block; @@ -26,15 +26,15 @@ {% endif %} {% endfor %} <div id="login-area"> - <form method="post" action="{% url 'users:login' %}" id="login-form"> + {% comment %} <form method="post" action="{% url 'users:login' %}" id="login-form"> {% endcomment %} <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> <input type="text" id="username" name="username" placeholder="Username" autocomplete="off" value="{{ request.GET.username }}"> <input type="password" id="password" name="password" placeholder="Password" autocomplete="off"> <input type="hidden" name="next" value="{{ request.path }}"> <input type="submit" value=""> </form> - <a href="{% url 'blog:register' %}" id="register-now-button"></a> - <a href="{% url 'blog:forgotpassword' %}" id="forgot-password-button"></a> + <a href="#" id="register-now-button"></a> + <a href="#" id="forgot-password-button"></a> </div> {% endif %} @@ -47,7 +47,7 @@ <img src="{% static 'images/site/icons/email.gif' %}" alt="Home" border="0"> </span> <span> - <a href="{% url 'blog:user_activity' user.username %}"> + <a href="#"> Profile </a> </span> @@ -57,7 +57,7 @@ <img src="{% static 'images/site/icons/mouse.gif' %}" alt="Home" border="0"> </span> <span> - <a href="{% url 'blog:account' %}"> + <a href="#"> Account </a> </span> @@ -67,7 +67,7 @@ <img src="{% static 'images/site/icons/key.gif' %}" alt="Home" border="0"> </span> <span> - <a href="{% url 'users:logout' %}"> + {% comment %} <a href="{% url 'users:logout' %}"> {% endcomment %} Logout </a> </span> @@ -84,7 +84,7 @@ <img src="{% static 'images/site/icons/news.gif' %}" alt="Home" border="0"> </span> <span> - <a href="{% url 'blog:home' %}"> + <a href="#"> Home </a> </span> @@ -94,7 +94,7 @@ <img src="{% static 'images/site/icons/pencil.gif' %}" alt="Blog" border="0"> </span> <span> - <a href="{% url 'blog:articles' %}"> + <a href="#"> Weblog </a> </span> @@ -104,7 +104,7 @@ <img src="{% static 'images/site/icons/cabinet.gif' %}" alt="Archives" border="0"> </span> <span> - <a href="{% url 'blog:archives' %}"> + <a href="#"> Archives </a> </span> @@ -114,7 +114,7 @@ <img src="{% static 'images/site/icons/books.gif' %}" alt="Categories" border="0"> </span> <span> - <a href="{% url 'blog:categories' %}"> + <a href="#"> Categories </a> </span> @@ -124,7 +124,7 @@ <img src="{% static 'images/site/icons/issues.gif' %}" alt="Tags" border="0"> </span> <span> - <a href="{% url 'blog:tags' %}"> + <a href="#"> Tags </a> </span> @@ -160,7 +160,7 @@ <img src="{% static 'images/site/icons/fork.png' %}" alt="Repositories" border="0" style="padding: 2px; height: 20px; width: 20px;"> </span> <span> - <a href="{% url 'dev_status:home' %}"> + {% comment %} <a href="{% url 'dev_status:home' %}"> {% endcomment %} My Repositories </a> </span> @@ -170,7 +170,7 @@ <img src="{% static 'images/site/icons/anistar.gif' %}" alt="Socialify" border="0" style="padding: 2px; height: 20px; width: 20px;"> </span> <span> - <a href="{% url 'blog:anilist' %}"> + <a href="#"> My Anime List </a> </span> @@ -180,7 +180,7 @@ <img src="{% static 'images/site/icons/windows.gif' %}" alt="Socialify" border="0"> </span> <span> - <a href="{% url 'blog:socialify' %}"> + <a href="#"> Socialify </a> </span> @@ -258,7 +258,7 @@ <img src="{% static 'images/site/icons/cabinet.gif' %}" alt="Archive" border="0"> </span> <span> - <a href="{% url 'blog:archives' %}/{{ archive | date:"F_Y" }}"> + <a href="#/{{ archive | date:"F_Y" }}"> {{ archive | date:"F Y" }} </a> </span> @@ -269,7 +269,7 @@ <img src="{% static 'images/site/icons/cabinet.gif' %}" alt="Archives" border="0"> </span> <span> - <a href="{% url 'blog:archives' %}"> + <a href="#"> All Archives... </a> </span> @@ -286,7 +286,7 @@ <img src="{% static 'images/site/icons/books.gif' %}" alt="Archive" border="0"> </span> <span> - <a href="{% url 'blog:categories' %}/{{ category.slug }}"> + <a href="#/{{ category.slug }}"> {{ category }} </a> </span> @@ -297,7 +297,7 @@ <img src="{% static 'images/site/icons/books.gif' %}" alt="Categories" border="0"> </span> <span> - <a href="{% url 'blog:categories' %}"> + <a href="#"> All Categories... </a> </span> diff --git a/templates/blog/post.html b/templates/blog/post.html index 5a98e981..7043f387 100644 --- a/templates/blog/post.html +++ b/templates/blog/post.html @@ -3,7 +3,7 @@ {% load tz %} {% load sha256 %} <div id="post-actions-bar" class="mtsbitem" style="margin-top: 12px;"> - <a class="pa-btn" href="{% url 'blog:home' %}">Home</a> + <a class="pa-btn" href="#">Home</a> <a class="pa-btn" href="#comments">Opinions</a> <a class="pa-btn" href="javascript:;" onclick="lightsOff()">Focus <img id="lightsStatus" data-status="off" src="{% static 'images/site/off.png' %}" alt="Off" style="height: 11px; position: relative; top: 2px;"></a> <a class="pa-btn" href="javascript:;" onclick="blindMode()">Spectacles <img id="blindStatus" data-status="off" src="{% static 'images/site/off.png' %}" alt="Off" style="height: 11px; position: relative; top: 2px;"></a> @@ -25,13 +25,13 @@ <span style="background-image: url('{% static 'images/avatars/' %}{{ userprofile.avatar_url }}.gif');" class="post-profile-image"></span> {% endwith %} <span> - <a href="{% url 'blog:user_activity' post.author %}" style="font-weight: bold;"> + <a href="" style="font-weight: bold;"> {{ post.author.first_name }} {{ post.author.last_name }} </a> </span> <span>posted in</span> <span> - <a href="{% url 'blog:categories' %}/{{ post.category.slug }}" style=""> + <a href="#/{{ post.category.slug }}" style=""> {{ post.category }} </a> </span> @@ -43,7 +43,7 @@ </div> <p> {% for tag in post.tags.all %} - <a class="tag" href="{% url 'blog:tag_posts' tag.slug %}">{{ tag.name }}</a> + <a class="tag" href="#">{{ tag.name }}</a> {% endfor %} </p> @@ -71,19 +71,19 @@ background: #ffffff0d; <div id="read-next"> <div class="post"> <div class="post-header"> - <h1 style="margin: auto !important;"><a style="color: #f4ebff;" href="{% url 'blog:post' read_next.slug %}">{{ read_next.title }}</a></h1> + <h1 style="margin: auto !important;"><a style="color: #f4ebff;" href="#">{{ read_next.title }}</a></h1> <div class="author-info"> {% with read_next.author.userprofile_set.first as userprofile %} <span style="background-image: url('{% static 'images/avatars/' %}{{ userprofile.avatar_url }}.gif');" class="post-profile-image"></span> {% endwith %} <span> - <a href="{% url 'blog:user_activity' read_next.author %}" style="font-weight: bold;"> + <a href="#" style="font-weight: bold;"> {{ read_next.author.first_name }} {{ read_next.author.last_name }} </a> </span> <span>posted in</span> <span> - <a href="{% url 'blog:categories' %}/{{ read_next.category.slug }}" style=""> + <a href="#" style=""> {{ read_next.category }} </a> </span> @@ -96,7 +96,7 @@ background: #ffffff0d; {{ read_next.excerpt | safe }} </div> <div class="post-actions" style="clear: both;"> - <a href="{% url 'blog:post' read_next.slug %}">Continue Reading</a> | <a href="{% url 'blog:post' read_next.slug %}#comments">{{ read_next.num_comments }} + <a href="#">Continue Reading</a> | <a href="##comments">{{ read_next.num_comments }} Opinion{% if not read_next.num_comments == 1 %}s{% endif %}</a> </div> </div> @@ -123,7 +123,7 @@ background: #ffffff0d; </td> <td style="vertical-align: top; width: 668px;"> <div style="margin-bottom: 13px; border-bottom: dashed 1px white; padding-bottom: 13px;"> - <a class="notranslate" {% if comment.user%}href="{% url 'blog:user_activity' comment.user.username %}"{% endif %}>{% if comment.user %}{{ comment.user.username }}{% else %}{{ comment.anonymous_user.name }}{% endif %}</a> on <em>{{ comment.created_at | date:"M d, Y" }}</em> + <a class="notranslate" {% if comment.user%}href="#"{% endif %}>{% if comment.user %}{{ comment.user.username }}{% else %}{{ comment.anonymous_user.name }}{% endif %}</a> on <em>{{ comment.created_at | date:"M d, Y" }}</em> {% if comment.edited %} <em>(Edited)</em> {% endif %} @@ -131,13 +131,13 @@ background: #ffffff0d; <a href="javascript:;" onclick="editComment({{ comment.id }})">Edit</a> - <a href="{% url 'blog:delete_comment' post.slug comment.id %}" onclick="return confirm('Are you sure you want to delete this comment?')">Delete</a> + <a href="#" onclick="return confirm('Are you sure you want to delete this comment?')">Delete</a> {% endif %} {% if comment.anonymous_user.name and comment.anonymous_user.email and comment.anonymous_user.token and comment.anonymous_user.token == request.COOKIES.anonymous_token|sha256 %} <a href="javascript:;" onclick="editComment({{ comment.id }})">Edit</a> - <a href="{% url 'blog:anon_delete_comment' post.slug comment.id %}" onclick="return confirm('Are you sure you want to delete this comment?')">Delete</a> + <a href="#" onclick="return confirm('Are you sure you want to delete this comment?')">Delete</a> {% endif %} </div> <div id="comment-body-{{ comment.id }}" class="comment notranslate"> @@ -145,7 +145,7 @@ background: #ffffff0d; </div> {% if comment.user == user %} <div id="edit-form-{{ comment.id }}" style="display: none; margin-bottom: 20px;"> - <form action="{% url 'blog:edit_comment' post.slug %}" method="POST"> + <form action="#" method="POST"> {% csrf_token %} <input type = "hidden" name="comment_id" value="{{ comment.id }}"> <textarea class="notranslate" name="body" id="body" cols="78" rows="10" style="width: 640px; display: block; margin-bottom: 10px;">{{ comment.body }}</textarea> @@ -156,7 +156,7 @@ background: #ffffff0d; {% endif %} {% if comment.anonymous_user.name and comment.anonymous_user.email and comment.anonymous_user.token and comment.anonymous_user.token == request.COOKIES.anonymous_token|sha256 %} <div id="edit-form-{{ comment.id }}" style="display: none; margin-bottom: 20px;"> - <form action="{% url 'blog:anon_edit_comment' post.slug %}" method="POST"> + <form action="#" method="POST"> {% csrf_token %} <input type = "hidden" name="comment_id" value="{{ comment.id }}"> <textarea class="notranslate" name="body" id="body" cols="78" rows="10" style="width: 640px; display: block; margin-bottom: 10px;">{{ comment.body }}</textarea> @@ -187,7 +187,7 @@ background: #ffffff0d; {% endif %} {% endfor %} {% endif %} - <form action="{% url 'blog:comment' post.slug %}" method="POST"> + <form action="#" method="POST"> {% csrf_token %} <textarea required name="comment" id="comment" cols="88" rows="10" style="width: 710px; display: block; margin-bottom: 15px;" placeholder="Your comment here..."></textarea> <div id="comment-tips" style=" /* background-color: #2d1d3d; */ @@ -261,7 +261,7 @@ background: #ffffff0d; {% endif %} <p id="ancmClick">You must be <em>logged in</em> to leave a comment. Or, you can <a href="javascript:;" onclick="toggleAnon()">leave an anonymous comment</a>.</p> <div id="anonymous-comment-form" style="display: none;"> - <form action="{% url 'blog:anon_comment' post.slug %}" method="POST"> + <form action="#" method="POST"> {% csrf_token %} <div id="anonymous-comment-area"> <div id="anonymous-profile-info"> @@ -358,7 +358,7 @@ background: #ffffff0d; <li>Anytime, you wish to change your secret token, this can be done by entering a new secret token in the 'Credentials' area. It will be stored locally and the site will remember your information, so you don't have to enter it again.</li> <li>If you lose your secret token, that's basically permanent damage. You can always set a new secret token for the same email, but you will not be able to edit your previous comments.</li> <li>You will not be able to customize your avatar. You will be assigned a random site specific avatar.</li> - <li>If anytime, you wish to <a href="{% url 'blog:register' %}">register</a> for a full account, you can do so with the same email address. However, your previous comments will not be migrated to your new account.</li> + <li>If anytime, you wish to <a href="#">register</a> for a full account, you can do so with the same email address. However, your previous comments will not be migrated to your new account.</li> </ul> </div> </div> diff --git a/templates/blog/register.html b/templates/blog/register.html index 16ff128a..2f05874a 100644 --- a/templates/blog/register.html +++ b/templates/blog/register.html @@ -30,7 +30,7 @@ <br /><br /> <p> By registering on this site, you agree to everything that's - <a href="{% url 'blog:policy' %}">written here</a>. + <a href="#">written here</a>. </p> <p> <b>Note</b>: Upon registering, you will be sent an email with a link to diff --git a/templates/blog/search.html b/templates/blog/search.html index 721f8d8d..fcf98c99 100644 --- a/templates/blog/search.html +++ b/templates/blog/search.html @@ -4,7 +4,7 @@ <table id="search" cellpadding="0" cellspacing="0"> <tr> <td id="search_sidebar" style="width: 200px; vertical-align: top;"> - <form method="get" url="{% url 'blog:search' %}"> + <form method="get" url="#"> <h2>Search</h2> <input type="text" name="q" value="{{ request.GET.q }}" placeholder="Query" style="width: 180px; display: block; margin: 10px 0;" required/> <h2 class="mtsbitem">Search In</h2> diff --git a/templates/blog/tags.html b/templates/blog/tags.html index 44dcac61..96743843 100644 --- a/templates/blog/tags.html +++ b/templates/blog/tags.html @@ -7,7 +7,7 @@ <center> {% for tag in tags %} <span style="margin-bottom:8px;"> - <a class="tag" style="font-size:{{ tag.pxs }}px;" href="{% url 'blog:tag_posts' tag.slug %}">{{ tag.name }} ({{ tag.count }} post{{ tag.count|pluralize }})</a> + <a class="tag" style="font-size:{{ tag.pxs }}px;" href="#">{{ tag.name }} ({{ tag.count }} post{{ tag.count|pluralize }})</a> </span> {% endfor %} </center> diff --git a/templates/blog_admin/posts.html b/templates/blog_admin/posts.html index a8aac92c..3e6fad17 100644 --- a/templates/blog_admin/posts.html +++ b/templates/blog_admin/posts.html @@ -35,13 +35,13 @@ <img src="{% url 'ignis:post_image' '80' post.id %}.gif" alt="Cover Image" style="width: 80px; display: block; margin: 0 auto;"> </td> <td colspan='1'> - <a href="{% url 'blog:post' post.slug %}"> + <a href="#"> {{ post.title }} </a> </td> - <td><a href="{% url 'blog:user_activity' post.author %}">{{ post.author }}</a></td> + <td><a href="#">{{ post.author }}</a></td> <td>{{ post.date | date:"d M Y" }}</td> - <td><a href="{% url 'blog:categories' %}/{{ post.category.slug }}">{{ post.category }}</a></td> + <td><a href="#/{{ post.category.slug }}">{{ post.category }}</a></td> <td> <p><a href="{% url 'blog-admin:new-post'%}?mode=edit&post_id={{post.id}}">Edit Post Metadata</a></p> <p><a href="{% url 'blog-admin:edit-post' post.slug %}">Edit Post Contents</a></p> diff --git a/templates/dev_status/home.html b/templates/dev_status/home.html index 18574c0a..2b4eaba0 100644 --- a/templates/dev_status/home.html +++ b/templates/dev_status/home.html @@ -53,13 +53,13 @@ <table style="width=100%; margin: 0 auto; table-layout: fixed;"> {% for repo in repos %} <tr> - <td><a href="{% url 'dev_status:repo' repo.name %}"> + {% comment %} <td><a href="{% url 'dev_status:repo' repo.name %}"> {% endcomment %} <img src="{% url 'ignis:cover_image' repo.name %}.gif" style="display: inline-block; margin-right: 10px;" class="zoom" border="0"> </a> </td> <td> <p style="font-size: 14px; font-weight: bold;"> - <a href="{% url 'dev_status:repo' repo.name %}">{{ repo.name }}</a> + {% comment %} <a href="{% url 'dev_status:repo' repo.name %}">{{ repo.name }}</a> {% endcomment %} {% if repo.isFork %} <span title="Forked Repository"><img src="{% static 'images/site/icons/isFork.png' %}" style="display: inline-block; margin-left: 5px; height: 16px; position: relative; top: 4px;" border="0"></span> {% endif %} @@ -99,18 +99,18 @@ <td><a class="disabled">«</a></td> <td style="margin-right: 15px;"><a class="disabled">‹</a></td> {% else %} - <td><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page=1">«</a></td> - <td style="margin-right: 15px;"><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ page|add:-1 }}">‹</a></td> + {% comment %} <td><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page=1">«</a></td> {% endcomment %} + {% comment %} <td style="margin-right: 15px;"><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ page|add:-1 }}">‹</a></td> {% endcomment %} {% endif %} {% for i in num_pages|times %} - <td><a {% if i == page %}class="active"{% endif %} href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ i }}">{{ i }}</a></td> + {% comment %} <td><a {% if i == page %}class="active"{% endif %} href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ i }}">{{ i }}</a></td> {% endcomment %} {% endfor %} {% if page == num_pages %} <td style="margin-left: 15px;"><a class="disabled">›</a></td> <td><a class="disabled">»</a></td> {% else %} - <td style="margin-left: 15px;"><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ page|add:1 }}">›</a></td> - <td><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ num_pages }}">»</a></td> + {% comment %} <td style="margin-left: 15px;"><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ page|add:1 }}">›</a></td> + <td><a href="{% url 'dev_status:home'%}?search={{ search }}&items={{ items }}&filter={{ filter }}&sort={{ sort }}&direction={{ direction }}&page={{ num_pages }}">»</a></td> {% endcomment %} {% endif %} </tr> </table> diff --git a/templates/dev_status/repo.html b/templates/dev_status/repo.html index c5df710b..23230a12 100644 --- a/templates/dev_status/repo.html +++ b/templates/dev_status/repo.html @@ -23,7 +23,7 @@ /> </span> <a - href="{% if parent == '' %}{% url 'dev_status:repo' repo %}{% else %}{% url 'dev_status:repo-path' repo parent %}{% endif %}" + {% comment %} href="{% if parent == '' %}{% url 'dev_status:repo' repo %}{% else %}{% url 'dev_status:repo-path' repo parent %}{% endif %}" {% endcomment %} >..</a > {% endif %} @@ -58,7 +58,7 @@ /> </span> {% endif %} - <a href="{% url 'dev_status:repo-path' repo file.path %}" + {% comment %} <a href="{% url 'dev_status:repo-path' repo file.path %}" {% endcomment %} >{{ file.name }}</a > </td> @@ -85,7 +85,7 @@ > <h4 style="margin: 0"> Viewing - <a href="{% url 'dev_status:repo-path' repo files.path %}" + {% comment %} <a href="{% url 'dev_status:repo-path' repo files.path %}" {% endcomment %} >{{ files.name }}</a > <pre style="display: inline-block; margin-left: 10px"> @@ -113,7 +113,7 @@ > <h4 style="margin: 0; margin-left: 10px"> Viewing - <a href="{% url 'dev_status:repo-path' repo files.path %}" + {% comment %} <a href="{% url 'dev_status:repo-path' repo files.path %}" {% endcomment %} >{{ files.name }}</a > <pre style="display: inline-block; margin-left: 10px"> diff --git a/thatcomputerscientist/error_handler.py b/thatcomputerscientist/error_handler.py index a6f8e2ea..d22bfc54 100644 --- a/thatcomputerscientist/error_handler.py +++ b/thatcomputerscientist/error_handler.py @@ -1,9 +1,10 @@ import re -import jellyfish +# import jellyfish from django.contrib.auth.models import User from django.shortcuts import render -from fuzzywuzzy import process + +# from fuzzywuzzy import process from apps.blog.models import Post @@ -12,19 +13,19 @@ def get_similar_posts(slug): posts = Post.objects.all().filter(is_public=True) similar_posts = set() - title_choices = [post.title for post in posts] - slug_choices = [post.slug for post in posts] + # title_choices = [post.title for post in posts] + # slug_choices = [post.slug for post in posts] - title_match = process.extract(slug.replace("-", " "), title_choices, limit=5) - slug_match = process.extract(slug, slug_choices, limit=5) + # title_match = process.extract(slug.replace("-", " "), title_choices, limit=5) + # slug_match = process.extract(slug, slug_choices, limit=5) - for title, score in title_match: - if score > 80: - similar_posts.add(posts.get(title=title)) + # for title, score in title_match: + # if score > 80: + # similar_posts.add(posts.get(title=title)) - for slug, score in slug_match: - if score > 80: - similar_posts.add(posts.get(slug=slug)) + # for slug, score in slug_match: + # if score > 80: + # similar_posts.add(posts.get(slug=slug)) return similar_posts @@ -33,10 +34,10 @@ def get_similar_users(username): users = User.objects.all() similar_users = [] - for user in users: - username_similarity = jellyfish.jaro_winkler(username, user.username) - if username_similarity > 0.8: - similar_users.append(user) + # for user in users: + # username_similarity = jellyfish.jaro_winkler(username, user.username) + # if username_similarity > 0.8: + # similar_users.append(user) return similar_users diff --git a/thatcomputerscientist/settings.py b/thatcomputerscientist/settings.py index ca703842..b1062055 100644 --- a/thatcomputerscientist/settings.py +++ b/thatcomputerscientist/settings.py @@ -24,16 +24,16 @@ LOGIN_URL = "/" # set n_connected_lc_users to 0 on startup -import redis +# import redis # r = redis.Redis(host='localhost', port=6379, db=0) -r = redis.Redis( - host=os.getenv("REDIS_HOST"), - port=os.getenv("REDIS_PORT"), - password=os.getenv("REDIS_PASSWORD"), - db=0, -) -r.set("n_connected_lc_users", 0) +# r = redis.Redis( +# host=os.getenv("REDIS_HOST"), +# port=os.getenv("REDIS_PORT"), +# password=os.getenv("REDIS_PASSWORD"), +# db=0, +# ) +# r.set("n_connected_lc_users", 0) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ @@ -73,9 +73,9 @@ INSTALLED_APPS = [ "django.contrib.staticfiles", "django.contrib.sites", "django.contrib.sitemaps", - "sslserver", + # "sslserver", "thatcomputerscientist", - "haystack", + # "haystack", "apps.core", "apps.administration", "apps.blog", @@ -83,29 +83,29 @@ INSTALLED_APPS = [ "services.users", "services.stream", "services.pamphlet", - "blog_admin", - "dev_status", - "ignis", - "chat", + # "blog_admin", + # "dev_status", + # "ignis", + # "chat", ] SITE_ID = 1 APPEND_SLASH = False -HAYSTACK_CONNECTIONS = { - "default": { - "ENGINE": "haystack.backends.simple_backend.SimpleEngine", - }, -} - -REST_FRAMEWORK = { - "DEFAULT_AUTHENTICATION_CLASSES": [ - "rest_framework.authentication.BasicAuthentication", - "rest_framework.authentication.SessionAuthentication", - ] -} +# HAYSTACK_CONNECTIONS = { +# "default": { +# "ENGINE": "haystack.backends.simple_backend.SimpleEngine", +# }, +# } + +# REST_FRAMEWORK = { +# "DEFAULT_AUTHENTICATION_CLASSES": [ +# "rest_framework.authentication.BasicAuthentication", +# "rest_framework.authentication.SessionAuthentication", +# ] +# } MIDDLEWARE = [ - "django_hosts.middleware.HostsRequestMiddleware", + # "django_hosts.middleware.HostsRequestMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", @@ -114,24 +114,24 @@ MIDDLEWARE = [ "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", - "whitenoise.middleware.WhiteNoiseMiddleware", + # "whitenoise.middleware.WhiteNoiseMiddleware", + "middleware.i18nmiddleware.I18NMiddleware", "middleware.userprofilemiddleware.UserProfileMiddleware", - "middleware.oldbrowsermiddleware.OldBrowserMiddleware", "middleware.globalmetamiddleware.GlobalMetaMiddleware", - "middleware.ignismiddleware.IgnisMiddleware", - "middleware.uuidmiddleware.UserUUIDMiddleware", - "middleware.i18nmiddleware.I18NMiddleware", - "django_hosts.middleware.HostsResponseMiddleware", + # "middleware.oldbrowsermiddleware.OldBrowserMiddleware", + # "middleware.ignismiddleware.IgnisMiddleware", + # "middleware.uuidmiddleware.UserUUIDMiddleware", + # "django_hosts.middleware.HostsResponseMiddleware", ] -LOCALE_PATHS = [ - os.path.join(BASE_DIR, "locale"), -] +# LOCALE_PATHS = [ +# os.path.join(BASE_DIR, "locale"), +# ] -CONFIGURED_SUBDOMAINS = { - "": "thatcomputerscientist", - "*": "userpages", -} +# CONFIGURED_SUBDOMAINS = { +# "": "thatcomputerscientist", +# "*": "userpages", +# } ROOT_URLCONF = "thatcomputerscientist.urls" @@ -150,7 +150,7 @@ TEMPLATES = [ "django.contrib.messages.context_processors.messages", "apps.blog.context_processors.categories", "apps.blog.context_processors.archives", - "middleware.uuidmiddleware.userTrackingContextProcessor", + # "middleware.uuidmiddleware.userTrackingContextProcessor", ], }, }, @@ -160,19 +160,17 @@ TEMPLATES = [ ASGI_APPLICATION = "thatcomputerscientist.asgi.application" CHANNEL_LAYERS = { + "default": {"BACKEND": "channels.layers.InMemoryChannelLayer"} # "default": { - # "BACKEND": "channels.layers.InMemoryChannelLayer" - # } - "default": { - "BACKEND": "channels_redis.core.RedisChannelLayer", - "CONFIG": { - "hosts": [ - ( - f'redis://:{os.getenv("REDIS_PASSWORD")}@{os.getenv("REDIS_HOST")}:{os.getenv("REDIS_PORT")}' - ) - ], - }, - }, + # "BACKEND": "channels_redis.core.RedisChannelLayer", + # "CONFIG": { + # "hosts": [ + # ( + # f'redis://:{os.getenv("REDIS_PASSWORD")}@{os.getenv("REDIS_HOST")}:{os.getenv("REDIS_PORT")}' + # ) + # ], + # }, + # }, } # Database @@ -204,21 +202,21 @@ AUTH_PASSWORD_VALIDATORS = [ }, ] -CACHES = { - "default": { - "BACKEND": "django_redis.cache.RedisCache", - "LOCATION": f"redis://{os.getenv('REDIS_HOST')}:{os.getenv('REDIS_PORT')}", - "OPTIONS": { - "CLIENT_CLASS": "django_redis.client.DefaultClient", - "PASSWORD": os.getenv("REDIS_PASSWORD"), - }, - } -} -from django.core.cache import cache +# CACHES = { +# "default": { +# "BACKEND": "django_redis.cache.RedisCache", +# "LOCATION": f"redis://{os.getenv('REDIS_HOST')}:{os.getenv('REDIS_PORT')}", +# "OPTIONS": { +# "CLIENT_CLASS": "django_redis.client.DefaultClient", +# "PASSWORD": os.getenv("REDIS_PASSWORD"), +# }, +# } +# } +# from django.core.cache import cache # clear the cache -for key in cache.keys("presence_*"): - cache.delete(key) +# for key in cache.keys("presence_*"): +# cache.delete(key) SESSION_ENGINE = "django.contrib.sessions.backends.cache" @@ -248,12 +246,12 @@ STATICFILES_DIRS = [ DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" -EMAIL_USE_TLS = True -# EMAIL_HOST = os.getenv('MAIL_HOST') -EMAIL_HOST = os.getenv("ORACLE_SMTP_HOST") -EMAIL_PORT = 587 -EMAIL_HOST_USER = os.getenv("EMAIL_USER") -EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PASSWORD") +# EMAIL_USE_TLS = True +# # EMAIL_HOST = os.getenv('MAIL_HOST') +# EMAIL_HOST = os.getenv("ORACLE_SMTP_HOST") +# EMAIL_PORT = 587 +# EMAIL_HOST_USER = os.getenv("EMAIL_USER") +# EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PASSWORD") -USERNAME_SMTP = os.getenv("ORACLE_SMTP_USER") -PASSWORD_SMTP = os.getenv("ORACLE_SMTP_PASSWORD") +# USERNAME_SMTP = os.getenv("ORACLE_SMTP_USER") +# PASSWORD_SMTP = os.getenv("ORACLE_SMTP_PASSWORD") diff --git a/thatcomputerscientist/urls.py b/thatcomputerscientist/urls.py index ad9dee50..76f41dbe 100644 --- a/thatcomputerscientist/urls.py +++ b/thatcomputerscientist/urls.py @@ -17,24 +17,25 @@ Including another URLconf from django.conf import settings from django.conf.urls.static import static from django.contrib import admin -from django.contrib.sitemaps.views import sitemap + +# from django.contrib.sitemaps.views import sitemap from django.urls import include, path -from .sitemaps import ( - CategorySitemap, - GithubSitemap, - PostSitemap, - StaticViewSitemap, - TagSitemap, -) - -sitemaps = { - "posts": PostSitemap, - "categories": CategorySitemap, - "tags": TagSitemap, - "static": StaticViewSitemap, - "github": GithubSitemap, -} +# from .sitemaps import ( +# CategorySitemap, +# GithubSitemap, +# PostSitemap, +# StaticViewSitemap, +# TagSitemap, +# ) + +# sitemaps = { +# "posts": PostSitemap, +# "categories": CategorySitemap, +# "tags": TagSitemap, +# "static": StaticViewSitemap, +# "github": GithubSitemap, +# } handler404 = "thatcomputerscientist.error_handler.custom_404" |
